text
stringlengths
184
4.48M
import * as Tabs from '@radix-ui/react-tabs'; import SearchApp from './SearchApp'; import { useState } from 'react'; import SelectBar from './selectBar'; import '@radix-ui/themes/styles.css'; import { TextField } from '@radix-ui/themes' import { MagnifyingGlassIcon } from '@radix-ui/react-icons' interface SideBarProps { onPathsChange: (newPaths: any[]) => void; } // Componente que renderiza a sidebar com as tabs // Componente que renderiza a barra de seleรงรฃo para calcular os caminhos e outras informaรงรตes do diagrama - รฉ uma collapsed side bar export default function SideBar({ onPathsChange }: SideBarProps) { const [paths, setPaths] = useState<any[]>([]); async function handlePathsChange(newPaths: any[]) { setPaths(newPaths); onPathsChange(newPaths); }; return ( <div> <Tabs.Root className="flex flex-col h-screen w-[400px] shadow-[0_2px_10px] shadow-blackA4" defaultValue="tab1" > <Tabs.List className="shrink-0 flex border-b border-mauve6" aria-label="Manage your account"> <Tabs.Trigger className="bg-white px-5 h-[45px] flex-1 flex items-center justify-center text-[15px] leading-none text-mauve11 select-none first:rounded-tl-md last:rounded-tr-md hover:text-blue-600 data-[state=active]:text-blue-600 data-[state=active]:shadow-[inset_0_-1px_0_0,0_1px_0_0] data-[state=active]:shadow-current data-[state=active]:focus:relative data-[state=active]:focus:shadow-[0_0_0_2px] data-[state=active]: outline-none cursor-default" value="tab1" > Routes </Tabs.Trigger> <Tabs.Trigger className="bg-white px-5 h-[45px] flex-1 flex items-center justify-center text-[15px] leading-none text-mauve11 select-none first:rounded-tl-md last:rounded-tr-md hover:text-blue-600 data-[state=active]:text-blue-600data-[state=active]:shadow-[inset_0_-1px_0_0,0_1px_0_0] data-[state=active]:shadow-current data-[state=active]:focus:relative data-[state=active]:focus:shadow-[0_0_0_2px] data-[state=active]: outline-none cursor-default" value="tab2" > Export </Tabs.Trigger> <Tabs.Trigger className="bg-white px-5 h-[45px] flex-1 flex items-center justify-center text-[15px] leading-none text-mauve11 select-none first:rounded-tl-md last:rounded-tr-md hover:text-blue-600 data-[state=active]:text-blue-600data-[state=active]:shadow-[inset_0_-1px_0_0,0_1px_0_0] data-[state=active]:shadow-current data-[state=active]:focus:relative data-[state=active]:focus:shadow-[0_0_0_2px] data-[state=active]: outline-none cursor-default" value="tab3" > Info </Tabs.Trigger> </Tabs.List> <Tabs.Content className="grow p-5 bg-white rounded-b-md outline-none focus:shadow-[0_0_0_2px] focus:shadow-black" value="tab1" > <SearchApp onPathsChange={handlePathsChange}></SearchApp> </Tabs.Content> <Tabs.Content className="grow p-5 bg-white rounded-b-md outline-none focus:shadow-[0_0_0_2px] focus:shadow-black" value="tab2" > <div className="flex flex-col items-center mt-5"> <button className="rounded px-[15px] text-[15px] leading-none font-medium h-[35px] bg-green4 text-green11 hover:bg-green5 focus:shadow-[0_0_0_2px] focus:shadow-green7 outline-none cursor-default mb-2"> PDF </button> <button className="rounded px-[15px] text-[15px] leading-none font-medium h-[35px] bg-green4 text-green11 hover:bg-green5 focus:shadow-[0_0_0_2px] focus:shadow-green7 outline-none cursor-default"> PNG </button> </div> </Tabs.Content> <Tabs.Content className="grow p-5 bg-white rounded-b-md outline-none focus:shadow-[0_0_0_2px] focus:shadow-black" value="tab3" > <div className="flex flex-col items-center mt-5"> <p className="mb-5 text-mauve11 text-[15px] leading-normal"> Info related to the diagrams created. </p> </div> </Tabs.Content> </Tabs.Root> </div > ); }
# Preserving and Resetting State ## ๋“ค์–ด๊ฐ€๋ฉด์„œ state๋Š” ์ปดํฌ๋„ŒํŠธ ๊ฐ„์— ๊ฒฉ๋ฆฌ๋œ๋‹ค. React๋Š” UI ํŠธ๋ฆฌ์—์„œ ์–ด๋–ค ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์–ด๋–ค state์— ์†ํ•˜๋Š”์ง€๋ฅผ ์ถ”์ . state๋ฅผ ์–ธ์ œ ๋ณด์กด(preserve)ํ•˜๊ณ  ์–ธ์ œ ์ดˆ๊ธฐํ™”(reset)ํ• ์ง€๋ฅผ ์ œ์–ดํ•  ์ˆ˜ ์žˆ์Œ. ## state๋Š” ํŠธ๋ฆฌ์˜ ํ•œ ์œ„์น˜์— ๋ฌถ์ž…๋‹ˆ๋‹ค(state๋Š” ๋ Œ๋” ํŠธ๋ฆฌ์—์„œ์˜ ์ปดํฌ๋„ŒํŠธ์˜ ์œ„์น˜์— ๋”ฐ๋ผ ์œ ์ง€๋˜๋ฉฐ ์‚ญ์ œ๋œ๋‹ค.) React๋Š” UI์˜ ์ปดํฌ๋„ŒํŠธ ๊ตฌ์กฐ์— ๋Œ€ํ•œ ๋ Œ๋” ํŠธ๋ฆฌ๋ฅผ ๋นŒ๋“œํ•จ. ์ปดํฌ๋„ŒํŠธ์— state๋ฅผ ๋ถ€์—ฌํ•  ๋•Œ, state๊ฐ€ ์ปดํฌ๋„ŒํŠธ ๋‚ด๋ถ€์— โ€œ์กด์žฌโ€ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•  ์ˆ˜ ์žˆ์Œ. **ํ•˜์ง€๋งŒ state๋Š” ์‹ค์ œ๋กœ React ๋‚ด๋ถ€์—์„œ ์œ ์ง€๋จ.** **React๋Š” ๋ Œ๋”๋ง ํŠธ๋ฆฌ์—์„œ ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ์˜ ์œ„์น˜์— ๋”ฐ๋ผ, (๋ฆฌ์•กํŠธ๊ฐ€) ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ๊ฐ state๋ฅผ ์˜ฌ๋ฐ”๋ฅธ ์ปดํฌ๋„ŒํŠธ์™€ ์—ฐ๊ฒฐํ•จ.** ์—ฌ๊ธฐ์—๋Š” \<Counter /> JSX ํƒœ๊ทธ๊ฐ€ ํ•˜๋‚˜๋งŒ ์žˆ์ง€๋งŒ ๋‘ ๊ฐœ์˜ ๋‹ค๋ฅธ ์œ„์น˜์—์„œ ๋ Œ๋”๋ง๋ฉ๋‹ˆ๋‹ค: ```javascript import { useState } from "react"; export default function App() { const counter = <Counter />; return ( <div> {counter} {counter} </div> ); } function Counter() { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = "counter"; if (hover) { className += " hover"; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1>{score}</h1> <button onClick={() => setScore(score + 1)}>Add one</button> </div> ); } ``` ํŠธ๋ฆฌ๋กœ ํ‘œ์‹œ๋˜๋Š” ๋ชจ์Šต์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค: ![](https://react-ko.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fpreserving_state_tree.dark.png&w=828&q=75) **์ด ์นด์šดํ„ฐ๋Š” ๊ฐ ํŠธ๋ฆฌ์—์„œ ๊ณ ์œ ํ•œ ์œ„์น˜์— ๋ Œ๋”๋ง๋˜๊ธฐ ๋•Œ๋ฌธ์— ๋‘ ๊ฐœ์˜ ๊ฐœ๋ณ„ ์นด์šดํ„ฐ** ์ผ๋ฐ˜์ ์œผ๋กœ React๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์ด๋Ÿฌํ•œ ์œ„์น˜์— ๋Œ€ํ•ด ์ƒ๊ฐํ•  ํ•„์š”๋Š” ์—†์ง€๋งŒ, ์ž‘๋™ ๋ฐฉ์‹์„ ์ดํ•ดํ•˜๋Š” ๊ฒƒ์ด ์œ ์šฉํ•  ์ˆ˜ ์žˆ์Œ. React์—์„œ ํ™”๋ฉด์˜ ๊ฐ ์ปดํฌ๋„ŒํŠธ๋Š” ์™„์ „ํžˆ ๋ถ„๋ฆฌ๋œ state๋ฅผ ๊ฐ€์ง. ์˜ˆ๋ฅผ ๋“ค์–ด, ๋‘ ๊ฐœ์˜ Counter ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋‚˜๋ž€ํžˆ ๋ Œ๋”๋งํ•˜๋ฉด ๊ฐ๊ฐ ๋…๋ฆฝ์ ์ธ score ๋ฐ hover state๋ฅผ ๊ฐ–๊ฒŒ ๋จ. ๋‘ counter๋ฅผ ๋ชจ๋‘ ํด๋ฆญํ•ด ๋ณด๋ฉด ์„œ๋กœ ์˜ํ–ฅ์„ ๋ฏธ์น˜์ง€ ์•Š๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Œ. counter ํ•˜๋‚˜๊ฐ€ ์—…๋ฐ์ดํŠธ๋˜๋ฉด ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ์— ๋Œ€ํ•œ state๋งŒ ์—…๋ฐ์ดํŠธ๋จ. **React๋Š” ํŠธ๋ฆฌ์˜ ๊ฐ™์€ ์œ„์น˜์— ๊ฐ™์€ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ Œ๋”๋งํ•˜๋Š” ํ•œ ๊ทธ state๋ฅผ ์œ ์ง€ํ•จ.** ์ด๋ฅผ ํ™•์ธํ•˜๋ ค๋ฉด ๋‘ ์นด์šดํ„ฐ๋ฅผ ๋ชจ๋‘ ์ฆ๊ฐ€์‹œํ‚จ ๋‹ค์Œ โ€œ๋‘ ๋ฒˆ์งธ counter ๋ Œ๋”๋งโ€ ์ฒดํฌ๋ฐ•์Šค๋ฅผ ์„ ํƒ ํ•ด์ œํ•˜์—ฌ ๋‘ ๋ฒˆ์งธ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ œ๊ฑฐํ•œ ๋‹ค์Œ ๋‹ค์‹œ ์„ ํƒํ•˜์—ฌ ์ถ”๊ฐ€. ```javascript import { useState } from "react"; export default function App() { const [showB, setShowB] = useState(true); return ( <div> <Counter /> {showB && <Counter />} <label> <input type="checkbox" checked={showB} onChange={(e) => { setShowB(e.target.checked); }} /> Render the second counter </label> </div> ); } function Counter() { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = "counter"; if (hover) { className += " hover"; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1>{score}</h1> <button onClick={() => setScore(score + 1)}>Add one</button> </div> ); } ``` **๋‘ ๋ฒˆ์งธ counter ๋ Œ๋”๋ง์„ ์ค‘์ง€ํ•˜๋Š” ์ˆœ๊ฐ„ state๊ฐ€ ์™„์ „ํžˆ ์‚ฌ๋ผ์ง€๋Š” ๊ฒƒ์— ์ฃผ๋ชฉ.** React๊ฐ€ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ œ๊ฑฐํ•˜๋ฉด ๊ทธ state๊ฐ€ ์‚ฌ๋ผ์ง€๊ธฐ ๋•Œ๋ฌธ. โ€œ๋‘ ๋ฒˆ์งธ counter ๋ Œ๋”๋งโ€์„ ์„ ํƒํ•˜๋ฉด ๋‘ ๋ฒˆ์งธ Counter์™€ ๊ทธ state๊ฐ€ ์ฒ˜์Œ๋ถ€ํ„ฐ ์ดˆ๊ธฐํ™”๋˜๊ณ (score = 0) DOM์— ์ถ”๊ฐ€๋จ. React๋Š” ์ปดํฌ๋„ŒํŠธ๊ฐ€ UI ํŠธ๋ฆฌ์˜ ํ•ด๋‹น ์œ„์น˜์—์„œ ๋ Œ๋”๋ง๋˜๋Š” ๋™์•ˆ ์ปดํฌ๋„ŒํŠธ์˜ state๋ฅผ ์œ ์ง€. **์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ œ๊ฑฐ๋˜๊ฑฐ๋‚˜ ๊ฐ™์€ ์œ„์น˜์— ๋‹ค๋ฅธ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ Œ๋”๋ง๋˜๋ฉด React๋Š” ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ์˜ state๋ฅผ ์‚ญ์ œ.** ## ๋™์ผํ•œ ์œ„์น˜์˜ ๋™์ผํ•œ ์ปดํฌ๋„ŒํŠธ๋Š” state๋ฅผ ์œ ์ง€ํ•ฉ๋‹ˆ๋‹ค ๋‹ค์Œ ์˜ˆ์ œ์—๋Š” ๋‘ ๊ฐœ์˜ ์„œ๋กœ ๋‹ค๋ฅธ \<Counter /> ํƒœ๊ทธ๊ฐ€ ์žˆ์Œ: ```javascript import { useState } from "react"; export default function App() { const [isFancy, setIsFancy] = useState(false); return ( <div> {isFancy ? <Counter isFancy={true} /> : <Counter isFancy={false} />} <label> <input type="checkbox" checked={isFancy} onChange={(e) => { setIsFancy(e.target.checked); }} /> Use fancy styling </label> </div> ); } function Counter({ isFancy }) { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = "counter"; if (hover) { className += " hover"; } if (isFancy) { className += " fancy"; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1>{score}</h1> <button onClick={() => setScore(score + 1)}>Add one</button> </div> ); } ``` **์ฒดํฌ๋ฐ•์Šค๋ฅผ ์„ ํƒํ•˜๊ฑฐ๋‚˜ ์„ ํƒ ์ทจ์†Œํ•ด๋„ ์นด์šดํ„ฐ state๋Š” ์žฌ์„ค์ •๋˜์ง€ ์•Š๋Š”๋‹ค. isFancy๊ฐ€ true์ด๋“  false์ด๋“ , ๋ฃจํŠธ App ์ปดํฌ๋„ŒํŠธ์—์„œ ๋ฐ˜ํ™˜๋œ div์˜ ์ฒซ ๋ฒˆ์งธ ์ž์‹์—๋Š” ํ•ญ์ƒ \<Counter />๊ฐ€ ์žˆ์Œ.** ![](https://react-ko.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fpreserving_state_same_component.dark.png&w=1200&q=75) - Counter๊ฐ€ ๋™์ผ ์œ„์น˜์— ์žˆ์œผ๋ฏ€๋กœ App์˜ state๋ฅผ ์—…๋ฐ์ดํŠธํ•ด๋„ Counter๋Š” ์žฌ์„ค์ •๋˜์ง€ ์•Š์Œ **๊ฐ™์€ ์œ„์น˜์— ์žˆ๋Š” ๊ฐ™์€ ์ปดํฌ๋„ŒํŠธ์ด๋ฏ€๋กœ React์˜ ๊ด€์ ์—์„œ ๋ณด๋ฉด ๊ฐ™์€ ์นด์šดํ„ฐ** - ์ฐธ๊ณ : React์—์„œ ์ค‘์š”ํ•œ ๊ฒƒ์€ JSX ๋งˆํฌ์—…์ด ์•„๋‹ˆ๋ผ UI ํŠธ๋ฆฌ์—์„œ์˜ ์œ„์น˜๋ผ๋Š” ๊ฒƒ์„ ๊ธฐ์–ตํ•˜๋ผ. - ์ด ์ปดํฌ๋„ŒํŠธ์—๋Š” if ๋‚ด๋ถ€์™€ ์™ธ๋ถ€์— ์„œ๋กœ ๋‹ค๋ฅธ \<Counter /> JSX ํƒœ๊ทธ๊ฐ€ ์žˆ๋Š” ๋‘ ๊ฐœ์˜ return์ ˆ์ด ์žˆ์Œ: ```javascript import { useState } from "react"; export default function App() { const [isFancy, setIsFancy] = useState(false); if (isFancy) { return ( <div> <Counter isFancy={true} /> <label> <input type="checkbox" checked={isFancy} onChange={(e) => { setIsFancy(e.target.checked); }} /> Use fancy styling </label> </div> ); } return ( <div> <Counter isFancy={false} /> <label> <input type="checkbox" checked={isFancy} onChange={(e) => { setIsFancy(e.target.checked); }} /> Use fancy styling </label> </div> ); } function Counter({ isFancy }) { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = "counter"; if (hover) { className += " hover"; } if (isFancy) { className += " fancy"; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1>{score}</h1> <button onClick={() => setScore(score + 1)}>Add one</button> </div> ); } ``` - checkbox๋ฅผ ์„ ํƒํ•˜๋ฉด state๊ฐ€ ์žฌ์„ค์ •๋  ๊ฒƒ์œผ๋กœ ์˜ˆ์ƒํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ๊ทธ๋ ‡์ง€ ์•Š์Œ. - ์ด ๋‘ \<Counter /> ํƒœ๊ทธ๊ฐ€ ๋ชจ๋‘ ๊ฐ™์€ ์œ„์น˜์— ๋ Œ๋”๋ง๋˜๊ธฐ ๋•Œ๋ฌธ. - **React๋Š” ํ•จ์ˆ˜์—์„œ ์กฐ๊ฑด์„ ์–ด๋””์— ๋ฐฐ์น˜ํ–ˆ๋Š”์ง€ ์•Œ์ง€ ๋ชปํ•จ. ๋‹จ์ง€ ๋ฐ˜ํ™˜ํ•˜๋Š” ํŠธ๋ฆฌ๋งŒ ๋ณผ ์ˆ˜ ์žˆ์„ ๋ฟ** - ๋‘ ๊ฒฝ์šฐ ๋ชจ๋‘ App ์ปดํฌ๋„ŒํŠธ๋Š” \<Counter />๋ฅผ ์ฒซ ๋ฒˆ์งธ ์ž์‹์œผ๋กœ ๊ฐ€์ง„ \<div>๋ฅผ ๋ฐ˜ํ™˜. - React์—์„œ ์ด ๋‘ ์นด์šดํ„ฐ๋Š” ๋ฃจํŠธ์˜ ์ฒซ ๋ฒˆ์งธ ์ž์‹์˜ ์ฒซ ๋ฒˆ์งธ ์ž์‹์ด๋ผ๋Š” ๋™์ผํ•œ โ€œ์ฃผ์†Œโ€๋ฅผ ๊ฐ€์ง. - React๋Š” **๋กœ์ง์„ ์–ด๋–ป๊ฒŒ ๊ตฌ์„ฑํ•˜๋“  ์ƒ๊ด€์—†์ด** ์ด์ „ ๋ Œ๋”๋ง๊ณผ ๋‹ค์Œ ๋ Œ๋”๋ง ์‚ฌ์ด์—์„œ ์ด ๋ฐฉ๋ฒ•์œผ๋กœ ์ด๋“ค์„ ์ผ์น˜์‹œํ‚ฌ ์ˆ˜ ์žˆ์Œ. ## ๋™์ผํ•œ ์œ„์น˜์˜ ๋‹ค๋ฅธ ์ปดํฌ๋„ŒํŠธ๋Š” state๋ฅผ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค ์•„๋ž˜ ์˜ˆ์ œ์—์„œ ํ™•์ธ๋ž€์„ ์„ ํƒํ•˜๋ฉด \<Counter/>๊ฐ€ \<p>๋กœ ๋ฐ”๋€œ: ```javascript import { useState } from "react"; export default function App() { const [isPaused, setIsPaused] = useState(false); return ( <div> {isPaused ? <p>See you later!</p> : <Counter />} <label> <input type="checkbox" checked={isPaused} onChange={(e) => { setIsPaused(e.target.checked); }} /> Take a break </label> </div> ); } function Counter() { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = "counter"; if (hover) { className += " hover"; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1>{score}</h1> <button onClick={() => setScore(score + 1)}>Add one</button> </div> ); } ``` ์—ฌ๊ธฐ์„œ๋Š” ๊ฐ™์€ ์œ„์น˜์—์„œ ์„œ๋กœ ๋‹ค๋ฅธ ์ปดํฌ๋„ŒํŠธ ์œ ํ˜• ์‚ฌ์ด๋ฅผ ์ „ํ™˜. ์ฒ˜์Œ์— \<div>์˜ ์ฒซ ๋ฒˆ์งธ ์ž์‹์—๋Š” Counter๊ฐ€ ์žˆ์—ˆ์Œ. ํ•˜์ง€๋งŒ p๋ฅผ ๋„ฃ์—ˆ์„ ๋•Œ React๋Š” UI ํŠธ๋ฆฌ์—์„œ Counter๋ฅผ ์ œ๊ฑฐํ•˜๊ณ  ๊ทธ state๋ฅผ ์†Œ๋ฉธ์‹œํ‚ด. ![](https://react-ko.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fpreserving_state_diff_pt1.dark.png&w=1920&q=75) ![](https://react-ko.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fpreserving_state_diff_pt2.dark.png&w=1920&q=75) **๋˜ํ•œ ๊ฐ™์€ ์œ„์น˜์— ๋‹ค๋ฅธ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ Œ๋”๋งํ•˜๋ฉด ์ „์ฒด ํ•˜์œ„ ํŠธ๋ฆฌ์˜ state๊ฐ€ ์žฌ์„ค์ •๋จ.** ```javascript import { useState } from "react"; export default function App() { const [isFancy, setIsFancy] = useState(false); return ( <div> {isFancy ? ( <div> <Counter isFancy={true} /> </div> ) : ( <section> <Counter isFancy={false} /> </section> )} <label> <input type="checkbox" checked={isFancy} onChange={(e) => { setIsFancy(e.target.checked); }} /> Use fancy styling </label> </div> ); } function Counter({ isFancy }) { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = "counter"; if (hover) { className += " hover"; } if (isFancy) { className += " fancy"; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1>{score}</h1> <button onClick={() => setScore(score + 1)}>Add one</button> </div> ); } ``` ํ™•์ธ๋ž€์„ ํด๋ฆญํ•˜๋ฉด counter state๊ฐ€ ์žฌ์„ค์ •๋จ. Counter๋ฅผ ๋ Œ๋”๋งํ•˜๋”๋ผ๋„ div์˜ ์ฒซ ๋ฒˆ์งธ ์ž์‹์€ div์—์„œ section์œผ๋กœ ๋ณ€๊ฒฝ๋จ. ์ž์‹ div๊ฐ€ DOM์—์„œ ์ œ๊ฑฐ๋˜๋ฉด ๊ทธ ์•„๋ž˜์˜ ์ „์ฒด ํŠธ๋ฆฌ(์นด์šดํ„ฐ ๋ฐ ํ•ด๋‹น state ํฌํ•จ)๋„ ํ•จ๊ป˜ ์ œ๊ฑฐ๋จ. ![](https://react-ko.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fpreserving_state_diff_same_pt1.dark.png&w=1920&q=75) ![](https://react-ko.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fpreserving_state_diff_same_pt2.dark.png&w=1920&q=75) **๋ฆฌ๋ Œ๋”๋ง ์‚ฌ์ด์— state๋ฅผ ์œ ์ง€ํ•˜๋ ค๋ฉด ํŠธ๋ฆฌ์˜ ๊ตฌ์กฐ๊ฐ€ โ€œ์ผ์น˜โ€ํ•ด์•ผ ํ•œ๋‹ค. ๊ตฌ์กฐ๊ฐ€ ๋‹ค๋ฅด๋ฉด React๋Š” ํŠธ๋ฆฌ์—์„œ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ œ๊ฑฐํ•  ๋•Œ state๋ฅผ ํŒŒ๊ดดํ•˜๊ธฐ ๋•Œ๋ฌธ.** - ์ฐธ๊ณ : **๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ์ปดํฌ๋„ŒํŠธ ํ•จ์ˆ˜ ์ •์˜๋ฅผ ์ค‘์ฒฉํ•ด์„œ๋Š” ์•ˆ๋จ.** - ์—ฌ๊ธฐ์„œ๋Š” MyTextField ์ปดํฌ๋„ŒํŠธ ํ•จ์ˆ˜๊ฐ€ MyComponent ์•ˆ์— ์ •์˜๋˜์–ด ์žˆ์Œ. ```javascript import { useState } from "react"; export default function MyComponent() { const [counter, setCounter] = useState(0); function MyTextField() { const [text, setText] = useState(""); return <input value={text} onChange={(e) => setText(e.target.value)} />; } return ( <> <MyTextField /> <button onClick={() => { setCounter(counter + 1); }} > Clicked {counter} times </button> </> ); } ``` - ๋ฒ„ํŠผ์„ ํด๋ฆญํ•  ๋•Œ๋งˆ๋‹ค ์ž…๋ ฅ state๊ฐ€ ์‚ฌ๋ผ์ง! **์ด๋Š” MyComponent๋ฅผ ๋ Œ๋”๋งํ•  ๋•Œ๋งˆ๋‹ค ๋‹ค๋ฅธ MyTextField ํ•จ์ˆ˜๊ฐ€ ์ƒ์„ฑ๋˜๊ธฐ ๋•Œ๋ฌธ.** - ๊ฐ™์€ ์œ„์น˜์— ๋‹ค๋ฅธ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ Œ๋”๋งํ•˜๊ธฐ ๋•Œ๋ฌธ์— React๋Š” ์•„๋ž˜์˜ ๋ชจ๋“  state๋ฅผ ์ดˆ๊ธฐํ™” -> ๋ฒ„๊ทธ์™€ ์„ฑ๋Šฅ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒ. - ์ด ๋ฌธ์ œ๋ฅผ ๋ฐฉ์ง€ํ•˜๋ ค๋ฉด ํ•ญ์ƒ ์ปดํฌ๋„ŒํŠธ ํ•จ์ˆ˜๋ฅผ ์ตœ์ƒ์œ„ ์ˆ˜์ค€์—์„œ ์„ ์–ธํ•˜๊ณ  ์ •์˜๋ฅผ ์ค‘์ฒฉํ•˜์ง€ ๋งˆ๋ผ. ## ๋™์ผํ•œ ์œ„์น˜์—์„œ state ์žฌ์„ค์ •ํ•˜๊ธฐ ๊ธฐ๋ณธ์ ์œผ๋กœ React๋Š” ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๊ฐ™์€ ์œ„์น˜์— ์žˆ๋Š” ๋™์•ˆ ์ปดํฌ๋„ŒํŠธ์˜ state๋ฅผ ๋ณด์กด. ์ผ๋ฐ˜์ ์œผ๋กœ ์ด๊ฒƒ์€ ์‚ฌ์šฉ์ž๊ฐ€ ์›ํ•˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ ๊ธฐ๋ณธ ๋™์ž‘์œผ๋กœ ์ ํ•ฉ. ํ•˜์ง€๋งŒ ๋•Œ๋กœ๋Š” ์ปดํฌ๋„ŒํŠธ์˜ state๋ฅผ ๋ฆฌ์…‹ํ•˜๊ณ  ์‹ถ์„ ๋•Œ๊ฐ€ ์žˆ์Œ. ๋‘ ๋ช…์˜ ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ๊ฐ ํ„ด ๋™์•ˆ ์ ์ˆ˜๋ฅผ ์ถ”์ ํ•  ์ˆ˜ ์žˆ๋Š” ์ด ์•ฑ์„ ์˜ˆ๋กœ ๋“ค์–ด๋ณด์ž. ```javascript import { useState } from "react"; export default function Scoreboard() { const [isPlayerA, setIsPlayerA] = useState(true); return ( <div> {isPlayerA ? <Counter person="Taylor" /> : <Counter person="Sarah" />} <button onClick={() => { setIsPlayerA(!isPlayerA); }} > Next player! </button> </div> ); } function Counter({ person }) { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = "counter"; if (hover) { className += " hover"; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1> {person}'s score: {score} </h1> <button onClick={() => setScore(score + 1)}>Add one</button> </div> ); } ``` ํ˜„์žฌ ํ”Œ๋ ˆ์ด์–ด๋ฅผ ๋ณ€๊ฒฝํ•˜๋ฉด ์ ์ˆ˜๊ฐ€ ๋ณด์กด๋จ. ๋‘ Counter๋Š” ๊ฐ™์€ ์œ„์น˜์— ํ‘œ์‹œ๋˜๋ฏ€๋กœ React๋Š” person prop์ด ๋ณ€๊ฒฝ๋œ ๋™์ผํ•œ Counter๋กœ ๊ฐ„์ฃผ. ํ•˜์ง€๋งŒ ๊ฐœ๋…์ ์œผ๋กœ ์ด ์•ฑ์—์„œ๋Š” ๋‘ ๊ฐœ์˜ ๋ณ„๋„ ์นด์šดํ„ฐ๊ฐ€ ์žˆ์–ด์•ผ. UI์—์„œ ๊ฐ™์€ ์œ„์น˜์— ํ‘œ์‹œ๋  ์ˆ˜๋„ ์žˆ์ง€๋งŒ ํ•˜๋‚˜๋Š” Taylor์˜ ์นด์šดํ„ฐ์ด๊ณ  ๋‹ค๋ฅธ ํ•˜๋‚˜๋Š” Sarah์˜ ์นด์šดํ„ฐ. ์ „ํ™˜ํ•  ๋•Œ state๋ฅผ ์žฌ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•์—๋Š” ๋‘ ๊ฐ€์ง€๊ฐ€ ์žˆ์Œ: 1. ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋‹ค๋ฅธ ์œ„์น˜์— ๋ Œ๋”๋งํ•˜๊ธฐ 2. **๊ฐ ์ปดํฌ๋„ŒํŠธ์— key๋กœ ๋ช…์‹œ์ ์ธ ์•„์ด๋ดํ‹ฐํ‹ฐ๋ฅผ ๋ถ€์—ฌ** ### Option 1: ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋‹ค๋ฅธ ์œ„์น˜์— ๋ Œ๋”๋งํ•˜๊ธฐ ์ด ๋‘ Counter๋ฅผ ๋…๋ฆฝ์ ์œผ๋กœ ๋งŒ๋“ค๋ ค๋ฉด ๋‘ ๊ฐœ์˜ ๋‹ค๋ฅธ ์œ„์น˜์— ๋ Œ๋”๋งํ•˜๋ฉด ๋จ. ```javascript import { useState } from "react"; export default function Scoreboard() { const [isPlayerA, setIsPlayerA] = useState(true); return ( <div> {isPlayerA && <Counter person="Taylor" />} {!isPlayerA && <Counter person="Sarah" />} <button onClick={() => { setIsPlayerA(!isPlayerA); }} > Next player! </button> </div> ); } function Counter({ person }) { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = "counter"; if (hover) { className += " hover"; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1> {person}'s score: {score} </h1> <button onClick={() => setScore(score + 1)}>Add one</button> </div> ); } ``` ์ฒ˜์Œ์—๋Š” isPlayerA๊ฐ€ true. ๋”ฐ๋ผ์„œ ์ฒซ ๋ฒˆ์งธ ์œ„์น˜์—๋Š” Counter state๊ฐ€ ํฌํ•จ๋˜๊ณ  ๋‘ ๋ฒˆ์งธ ์œ„์น˜๋Š” ๋น„์–ด ์žˆ์Œ. โ€Next playerโ€ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด ์ฒซ ๋ฒˆ์งธ ์œ„์น˜๋Š” ์ง€์›Œ์ง€์ง€๋งŒ ๋‘ ๋ฒˆ์งธ ์œ„์น˜์—๋Š” ์ด์ œ Counter๊ฐ€ ํฌํ•จ๋จ. ๊ฐ Counter์˜ state๋Š” DOM์—์„œ ์ œ๊ฑฐ๋  ๋•Œ๋งˆ๋‹ค ์†Œ๋ฉธ๋จ. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ๋ฒ„ํŠผ์„ ํด๋ฆญํ•  ๋•Œ๋งˆ๋‹ค ์ดˆ๊ธฐํ™”๋จ. ์ด ์†”๋ฃจ์…˜์€ ๊ฐ™์€ ์œ„์น˜์— ๋ช‡ ๊ฐœ์˜ ๋…๋ฆฝ์ ์ธ ์ปดํฌ๋„ŒํŠธ๋งŒ ๋ Œ๋”๋งํ•  ๋•Œ ํŽธ๋ฆฌ. **์ด ์˜ˆ์‹œ์—์„œ๋Š” ๋‘ ๊ฐœ๋งŒ ์žˆ์œผ๋ฏ€๋กœ JSX์—์„œ ๋‘ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณ„๋„๋กœ ๋ Œ๋”๋งํ•˜๋Š” ๊ฒƒ์ด ๋ฒˆ๊ฑฐ๋กญ์ง€ ์•Š์Œ.** ### Option 2: key๋กœ state ์žฌ์„ค์ •ํ•˜๊ธฐ ์ปดํฌ๋„ŒํŠธ์˜ state๋ฅผ ์žฌ์„ค์ •ํ•˜๋Š” ๋” ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ•. ๋ชฉ๋ก์„ ๋ Œ๋”๋งํ•  ๋•Œ key๋ฅผ ๋ณธ ์ ์ด ์žˆ์„ ๊ฒƒ. **key๋Š” ๋ชฉ๋ก์—๋งŒ ์‚ฌ์šฉ๋˜๋Š” ๊ฒƒ์ด ์•„๋‹˜! key๋ฅผ ์‚ฌ์šฉํ•ด React๊ฐ€ ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ตฌ๋ถ„ํ•˜๋„๋ก ํ•  ์ˆ˜ ์žˆ์Œ.** **๊ธฐ๋ณธ์ ์œผ๋กœ React๋Š” ๋ถ€๋ชจ ๋‚ด์˜ ์ˆœ์„œ(โ€œ์ฒซ ๋ฒˆ์งธ counterโ€, โ€œ๋‘ ๋ฒˆ์งธ counterโ€)๋ฅผ ์‚ฌ์šฉํ•ด ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ตฌ๋ถ„.** ํ•˜์ง€๋งŒ key๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ด๊ฒƒ์ด ์ฒซ ๋ฒˆ์งธ counter๋‚˜ ๋‘ ๋ฒˆ์งธ counter๊ฐ€ ์•„๋‹ˆ๋ผ **ํŠน์ • counter(์˜ˆ: Taylor์˜ counter)์ž„์„ React์— ์•Œ๋ฆด ์ˆ˜ ์žˆ์Œ.** ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด React๋Š” ํ…Œ์ผ๋Ÿฌ์˜ counter๊ฐ€ ํŠธ๋ฆฌ์— ์–ด๋””์— ๋‚˜ํƒ€๋‚˜๋“  ์•Œ ์ˆ˜ ์žˆ์Œ! ๋‹ค์Œ ์˜ˆ์ œ์—์„œ๋Š” ๋‘ \<Counter />๊ฐ€ JSX์—์„œ ๊ฐ™์€ ์œ„์น˜์— ํ‘œ์‹œ๋˜์ง€๋งŒ state๋ฅผ ๊ณต์œ ํ•˜์ง€ ์•Š์Œ ```javascript import { useState } from "react"; export default function Scoreboard() { const [isPlayerA, setIsPlayerA] = useState(true); return ( <div> {isPlayerA ? ( <Counter key="Taylor" person="Taylor" /> ) : ( <Counter key="Sarah" person="Sarah" /> )} <button onClick={() => { setIsPlayerA(!isPlayerA); }} > Next player! </button> </div> ); } function Counter({ person }) { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = "counter"; if (hover) { className += " hover"; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1> {person}'s score: {score} </h1> <button onClick={() => setScore(score + 1)}>Add one</button> </div> ); } ``` ํ…Œ์ผ๋Ÿฌ์™€ ์‚ฌ๋ผ ์‚ฌ์ด๋ฅผ ์ „ํ™˜ํ•ด๋„ state๊ฐ€ ์œ ์ง€๋˜์ง€ ์•Š์Œ. ์„œ๋กœ ๋‹ค๋ฅธ key๋ฅผ ๋ถ€์—ฌํ–ˆ๊ธฐ ๋•Œ๋ฌธ. key๋ฅผ ์ง€์ •ํ•˜๋ฉด React๊ฐ€ ๋ถ€๋ชจ ๋‚ด ์ˆœ์„œ๊ฐ€ ์•„๋‹Œ key ์ž์ฒด๋ฅผ ์œ„์น˜์˜ ์ผ๋ถ€๋กœ ์‚ฌ์šฉํ•˜๋„๋ก ์ง€์‹œ. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— **JSX์—์„œ ๊ฐ™์€ ์œ„์น˜์— ๋ Œ๋”๋งํ•˜๋”๋ผ๋„ React์˜ ๊ด€์ ์—์„œ ๋ณด๋ฉด ๋‘ ์นด์šดํ„ฐ๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ์นด์šดํ„ฐ.** ๊ฒฐ๊ณผ์ ์œผ๋กœ state๋ฅผ ๊ณต์œ ํ•˜์ง€ ์•Š์Œ. ์นด์šดํ„ฐ๊ฐ€ ํ™”๋ฉด์— ๋‚˜ํƒ€๋‚  ๋•Œ๋งˆ๋‹ค ๊ทธ state๊ฐ€ ์ƒ์„ฑ๋จ. ์นด์šดํ„ฐ๊ฐ€ ์ œ๊ฑฐ๋  ๋•Œ๋งˆ๋‹ค ๊ทธ state๋Š” ์†Œ๋ฉธ๋จ. ๋‘ ์นด์šดํ„ฐ ์‚ฌ์ด๋ฅผ ํ† ๊ธ€ํ•˜๋ฉด state๊ฐ€ ๊ณ„์† ์ดˆ๊ธฐํ™”๋จ. - ์ฐธ๊ณ : **ํ‚ค๋Š” ์ „์—ญ์œผ๋กœ ๊ณ ์œ ํ•˜์ง€๋Š” ์•Š๋‹ค๋Š” ์ ์„ ๊ธฐ์–ตํ•˜๋ผ. ํ‚ค๋Š” ๋ถ€๋ชจ ๋‚ด์—์„œ์˜ ์œ„์น˜๋งŒ ์ง€์ •ํ•จ.** ## ํ‚ค๋กœ form ์žฌ์„ค์ •ํ•˜๊ธฐ ํ‚ค๋กœ state๋ฅผ ์žฌ์„ค์ •ํ•˜๋Š” ๊ฒƒ์€ form์„ ๋‹ค๋ฃฐ ๋•Œ ํŠนํžˆ ์œ ์šฉ. ์ด ์ฑ„ํŒ… ์•ฑ์—์„œ \<Chat> ์ปดํฌ๋„ŒํŠธ๋Š” ํ…์ŠคํŠธ input state๋ฅผ ํฌํ•จ. ```javascript import { useState } from "react"; import Chat from "./Chat.js"; import ContactList from "./ContactList.js"; export default function Messenger() { const [to, setTo] = useState(contacts[0]); return ( <div> <ContactList contacts={contacts} selectedContact={to} onSelect={(contact) => setTo(contact)} /> <Chat contact={to} /> </div> ); } const contacts = [ { id: 0, name: "Taylor", email: "taylor@mail.com" }, { id: 1, name: "Alice", email: "alice@mail.com" }, { id: 2, name: "Bob", email: "bob@mail.com" }, ]; ``` ์ž…๋ ฅ๋ž€์— ๋ฌด์–ธ๊ฐ€๋ฅผ ์ž…๋ ฅํ•œ ๋‹ค์Œ โ€œ์•จ๋ฆฌ์Šคโ€ ๋˜๋Š” โ€œ๋ฐฅโ€์„ ๋ˆŒ๋Ÿฌ ๋‹ค๋ฅธ ์ˆ˜์‹ ์ž๋ฅผ ์„ ํƒ -> \<Chat>์ด ํŠธ๋ฆฌ์˜ ๋™์ผํ•œ ์œ„์น˜์— ๋ Œ๋”๋ง๋˜๋ฏ€๋กœ ์ž…๋ ฅ state๊ฐ€ ์œ ์ง€๋˜๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Œ. ๋งŽ์€ ์•ฑ์—์„œ ์ด๋Ÿฌํ•œ ๋™์ž‘์ด ๋ฐ”๋žŒ์งํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, ์ฑ„ํŒ… ์•ฑ์—์„œ๋Š” ๊ทธ๋ ‡์ง€ ์•Š์Œ. ์‚ฌ์šฉ์ž๊ฐ€ ์‹ค์ˆ˜๋กœ ํด๋ฆญํ•ด์„œ ์ด๋ฏธ ์ž…๋ ฅํ•œ ๋ฉ”์‹œ์ง€๋ฅผ ์—‰๋šฑํ•œ ์‚ฌ๋žŒ์—๊ฒŒ ๋ณด๋‚ด๋Š” ๊ฒƒ์„ ์›์น˜ ์•Š์„ ๊ฒƒ. ์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋ ค๋ฉด key๋ฅผ ์ถ”๊ฐ€. ```javascript <Chat key={to.id} contact={to} /> ``` ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋‹ค๋ฅธ ์ˆ˜์‹ ์ž๋ฅผ ์„ ํƒํ•˜๋ฉด Chat ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๊ทธ ์•„๋ž˜ ํŠธ๋ฆฌ์˜ ๋ชจ๋“  state๋ฅผ ํฌํ•จํ•˜์—ฌ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋‹ค์‹œ ์ƒ์„ฑ. ๋˜ํ•œ React๋Š” DOM ์—˜๋ฆฌ๋จผํŠธ๋ฅผ ์žฌ์‚ฌ์šฉํ•˜๋Š” ๋Œ€์‹  ๋‹ค์‹œ ์ƒ์„ฑ. ์ด์ œ ์ˆ˜์‹ ์ž๋ฅผ ์ „ํ™˜ํ•˜๋ฉด ํ•ญ์ƒ ํ…์ŠคํŠธ ํ•„๋“œ๊ฐ€ ์ง€์›Œ์งˆ ๊ฒƒ. - ์ฐธ๊ณ : ์ œ๊ฑฐ๋œ ์ปดํฌ๋„ŒํŠธ์— ๋Œ€ํ•œ state ๋ณด์กด - ์‹ค์ œ ์ฑ„ํŒ… ์•ฑ์—์„œ๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ์ด์ „ ์ˆ˜์‹ ์ž๋ฅผ ๋‹ค์‹œ ์„ ํƒํ•  ๋•Œ ์ž…๋ ฅ state๋ฅผ ๋ณต๊ตฌํ•˜๊ณ  ์‹ถ์„ ๊ฒƒ. ๋” ์ด์ƒ ํ‘œ์‹œ๋˜์ง€ ์•Š๋Š” ์ปดํฌ๋„ŒํŠธ์˜ state๋ฅผ โ€˜์‚ด์•„์žˆ๊ฒŒโ€™ ์œ ์ง€ํ•˜๋Š” ๋ช‡ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ์Œ. - ํ˜„์žฌ ์ฑ„ํŒ…๋งŒ ๋ Œ๋”๋งํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๋ชจ๋“  ์ฑ„ํŒ…์„ ๋ Œ๋”๋งํ•˜๋˜ ๋‹ค๋ฅธ ๋ชจ๋“  ์ฑ„ํŒ…์€ CSS๋กœ ์ˆจ๊ธธ ์ˆ˜ ์žˆ์Œ. ์ฑ„ํŒ…์€ ํŠธ๋ฆฌ์—์„œ ์ œ๊ฑฐ๋˜์ง€ ์•Š์œผ๋ฏ€๋กœ ๋กœ์ปฌ state๊ฐ€ ์œ ์ง€๋จ. ์ด ์†”๋ฃจ์…˜์€ ๊ฐ„๋‹จํ•œ UI์— ์ ํ•ฉ. **ํ•˜์ง€๋งŒ ์ˆจ๊ฒจ์ง„ ํŠธ๋ฆฌ๊ฐ€ ํฌ๊ณ  ๋งŽ์€ DOM ๋…ธ๋“œ๋ฅผ ํฌํ•จํ•˜๋Š” ๊ฒฝ์šฐ ์†๋„๊ฐ€ ๋งค์šฐ ๋А๋ ค์งˆ ์ˆ˜ ์žˆ์Œ.** - ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ์—์„œ ๊ฐ ์ˆ˜์‹ ์ž์— ๋Œ€ํ•œ ๋ณด๋ฅ˜ ์ค‘์ธ ๋ฉ”์‹œ์ง€๋ฅผ state๋ฅผ ๋Œ์–ด์˜ฌ๋ ค์„œ ๋ณด๊ด€ํ•  ์ˆ˜ ์žˆ์Œ. ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์ž์‹ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ œ๊ฑฐ๋˜๋”๋ผ๋„ ์ค‘์š”ํ•œ ์ •๋ณด๋ฅผ ๋ณด๊ด€ํ•˜๋Š” ๊ฒƒ์€ ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ์ด๋ฏ€๋กœ ๋ฌธ์ œ๊ฐ€ ๋˜์ง€ ์•Š์Œ. **์ด๊ฒƒ์ด ๊ฐ€์žฅ ์ผ๋ฐ˜์ ์ธ ํ•ด๊ฒฐ์ฑ….** - React state ์™ธ์— ๋‹ค๋ฅธ ์†Œ์Šค๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ์Œ. ์˜ˆ๋ฅผ ๋“ค์–ด, ์‚ฌ์šฉ์ž๊ฐ€ ์‹ค์ˆ˜๋กœ ํŽ˜์ด์ง€๋ฅผ ๋‹ซ์•„๋„ ๋ฉ”์‹œ์ง€ ์ดˆ์•ˆ์ด ์œ ์ง€๋˜๊ธฐ๋ฅผ ์›ํ•  ์ˆ˜ ์žˆ์Œ. **์ด๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด Chat ์ปดํฌ๋„ŒํŠธ๊ฐ€ localStorage์—์„œ ์ฝ์–ด์„œ state๋ฅผ ์ดˆ๊ธฐํ™”ํ•˜๊ณ  ์ดˆ์•ˆ๋„ ์ €์žฅํ•˜๋„๋ก ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.** - ์–ด๋–ค ์ „๋žต์„ ์„ ํƒํ•˜๋“  ์•จ๋ฆฌ์Šค์™€์˜ ์ฑ„ํŒ…์€ ๋ฐฅ๊ณผ์˜ ์ฑ„ํŒ…๊ณผ ๊ฐœ๋…์ ์œผ๋กœ ๊ตฌ๋ณ„๋˜๋ฏ€๋กœ ํ˜„์žฌ ์ˆ˜์‹ ์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ \<Chat> ํŠธ๋ฆฌ์— key๋ฅผ ๋ถ€์—ฌํ•˜๋Š” ๊ฒƒ์ด ํ•ฉ๋ฆฌ์ .
package masterspringsecurity.domain.dto.product.request; import jakarta.validation.constraints.DecimalMin; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import lombok.*; import java.io.Serializable; import java.math.BigDecimal; @Builder @AllArgsConstructor @NoArgsConstructor @Getter @Setter @ToString public class ProductRequest implements Serializable { @NotBlank(message = "field name is required") private String name; @NotNull @DecimalMin(value = "0.01", message = "field price is required") private BigDecimal price; @NotNull(message = "field categoryId is required") @Min(value = 1) private Long categoryId; }
import React, { useRef } from "react"; import logo from "../../asst/default-person.png"; import { AiFillCloseCircle } from "react-icons/ai"; import { useDispatch, useSelector } from "react-redux"; import Skeleton, { SkeletonTheme } from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; import "./search.scss"; import { checkroomExist, searchUser } from "../../redux/chatSlice"; const Search = ({ opensearch, setopensearch, searchref }) => { const inputref = useRef(null); const state = useSelector((state) => state.chatSlice); const dispatch = useDispatch(); const skelloadin = [1, 2, 1, 1, 1, 1, 1]; const handlesearch = (e) => { e.preventDefault(); dispatch(searchUser(inputref.current.value)); }; const checkrooms = (id) => { dispatch(checkroomExist(id)); }; return ( <div className={opensearch ? `search_menu ` : "search_menu close"} ref={searchref} > <div className="search_menu_content"> <AiFillCloseCircle onClick={() => setopensearch(false)} /> <form> <input type="text" placeholder="Enter Name or Email" ref={inputref} /> <button onClick={handlesearch}>Search</button> </form> <div className="content"> {state.searchloading ? ( skelloadin.map((it, i) => { return ( <div className="item skel" key={i}> <SkeletonTheme baseColor="rgba(233, 231, 231,0.95)" highlightColor="white" className="sekelparent" > <Skeleton count={1} className="sekelcircle skel" /> <Skeleton count={2} className="sekelline skel" /> </SkeletonTheme> </div> ); }) ) : state.searchuser.length > 0 ? ( state.searchuser.map((per, i) => { return ( <div className="item" key={per._id} onClick={() => checkrooms(per._id)} > <div className="img"> <img src={per.image} alt="person img" onError={(e) => { e.target.src = logo; }} /> </div> <div className="name"> <p className="title">{per.name}</p> <p className="email">{per.email}</p> </div> </div> ); }) ) : ( <p> no user Found</p> )} </div> </div> </div> ); }; export default Search;
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\BroadcastMessage; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class RealTimeNotification extends Notification implements ShouldBroadcast { use Queueable; public $message; /** * Create a new notification instance. * * @return void */ public function __construct($message) { $this->message=$message; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['broadcast']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { return (new MailMessage) ->line('The introduction to the notification.') ->action('Notification Action', url('/')) ->line('Thank you for using our application!'); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return BroadcastMessage */ public function toBroadcast($notifiable) { return new BroadcastMessage([ 'message'=>"$this->message (User $notifiable->name)" ]); } }
# Name: Lucas Robertson # Class: CSC 466-01 (Fall 2018) # Filename: C45Util.py # Description: Provides utilities for parsing schema xml and csv data files import numpy as np import xml.etree.ElementTree as et from C45Node import C45Node SPLIT_ITERATIONS = 10 # For 10 fold cross evaluation SPLIT_RATIO = 10 # Parses a .csv file containing rows of election data # Returns a dictionary with the structure: # { 'Bush Approval': array(['Approve', 'Disapprove', 'Approve', ...]), # ... # } def parse_data(file_name): data = np.genfromtxt(file_name, delimiter=',', dtype=str, skip_header=3) headers = np.genfromtxt(file_name, delimiter=',', dtype=str, skip_footer=len(data) + 2) dict = {} for i in range(len(headers)): dict[headers[i]] = data[:, i] return dict # Parses an .xml schema file and returns all attribute labels # and options (unique). # Returns a dictionary with the structure: # { 'Bush Approval': array(['Approve', 'Disapprove']), # 'Race': array(['Black', 'White', 'Other']), # ... # } def parse_attr(file_name): xml = et.parse(file_name).getroot().getchildren() attrs = {} for variable in xml: if variable.tag == "Category": continue class_name = variable.attrib['name'] attrs[class_name] = [child.attrib['name'] for child in variable.getchildren()] return attrs # Parses an .xml schema file and returns the categorizable variable # and class labels. # Returns a tuple with the structure: # ('Vote', ['Obama', 'Mccain']) def parse_categ(file_name, use_numbers=False): xml = et.parse(file_name).getroot().find("Category") class_label = xml.attrib['name'] if use_numbers: return class_label, [child.attrib['type'] for child in xml.getchildren()] else: return class_label, [child.attrib['name'] for child in xml.getchildren()] # Parses a .csv attribute restrictions file and returns them as an array def parse_rest(rest_file, data_file): val = np.genfromtext(rest_file, delimiter=',', dtype=int) word = np.genfromtest(data_file, delimiter=',', dtype=str, max_rows=1) return dict(zip(word, val)) # Restricts attributes in data dictionary def rest_attr(data, rest): for word in rest: if word in data.keys(): data.pop(word) def get_categ_label(csv_filename): csv_file = open(csv_filename, 'r') label = '' for i in range(3): label = csv_file.readline() return label.strip(' \t\n\r') # Converts a dataset using strings to represent a value to using numbers # based off of a dictionary of attributes. def sanitize_data(attr, data, categ): for a in attr.keys(): tempData = data[a] tempAttr = attr[a] if tempData[0].isdigit(): tempData = tempData.astype(int) else: for i in range(len(tempData)): tempData[i] = tempAttr.index(tempData[i]) data[a] = tempData.astype(int) data[a] = data[a] - 1 tempData = data[categ[0]] if not tempData[0].isdigit(): for i in range(len(tempData)): tempData[i] = categ[1].index(tempData[i]) data[categ[0]] = tempData.astype(int) data[categ[0]] = data[categ[0]] - 1 return data # Returns: # [ # { # training: {"gender": [...], "age": [...]}, # validation: {"gender": [...], "age": [...]} # }, # { # ... # }, # ... # ] def split_data(input_data): datasets = [] for i in range(SPLIT_ITERATIONS): datasets.append(__build_set(input_data)) return datasets # Builds one set of training and validation data from 'input_data' def __build_set(input_data): training = {} validation = {} set_size = len(input_data.values()[0]) validation_count = set_size // SPLIT_RATIO rand_indexes = [] while len(rand_indexes) < validation_count: rand_index = np.random.randint(set_size) if rand_index in rand_indexes: continue rand_indexes.append(rand_index) for key in input_data: validation[key] = [input_data[key][i] for i in rand_indexes] training[key] = np.delete(input_data[key], rand_indexes) return { "training": training, "validation": validation } def tree_from_xml(xml_filename): xml = et.parse(xml_filename).getroot().getchildren()[0] return C45Node(xml) def itemize_entry(data, idx): entry = {} for key in data: entry[key] = data[key][idx] return entry
import { FunctionComponent } from "react"; import { Button } from "@mui/material"; import Card from "@mui/material/Card"; import CardContent from "@mui/material/CardContent"; import Typography from "@mui/material/Typography"; import CardActions from "@mui/material/CardActions"; import DeleteIcon from "@mui/icons-material/Delete"; import DeleteOutlineOutlinedIcon from "@mui/icons-material/DeleteOutlineOutlined"; import { JournalInterface } from "components/JournalDiary/Interface/JournalInterface"; import Tooltip from "@mui/material/Tooltip"; interface Props { journalDetail: JournalInterface; onClick: (id: number) => void; } const JournalCard: FunctionComponent<Props> = ({ journalDetail, onClick }) => { return ( <Card sx={{ minWidth: 275 }}> <CardContent> <Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom> {journalDetail.name} </Typography> <Typography variant="body2">{journalDetail.description}</Typography> </CardContent> <CardActions sx={{ display: "flex", justifyContent: "space-between" }}> <Button size="small" onClick={() => onClick(journalDetail.id)}> Expand </Button> <Button> <Tooltip title="Delete"> <DeleteOutlineOutlinedIcon color="error" /> </Tooltip> </Button> </CardActions> </Card> ); }; export default JournalCard;
import { Button, Col, Container, Form, FormControl, Nav, Navbar, NavDropdown, Row } from "react-bootstrap" import { ReactSVG } from "react-svg" import { NavLink } from "react-router-dom"; import { useDispatch, useSelector } from "react-redux"; import { getUserData, logout } from "../../storeAsyncActions/account"; import { useEffect, useState } from "react"; import { search } from "../../storeAsyncActions/movies"; import { getMoviesAction } from "../../store/moviesReducer"; import { getDataAction } from "../../store/authReducer"; const Header = () => { const [searchKeyword, setSearchKeyword] = useState('') const dispatch = useDispatch() const userData = useSelector((state) => { return state.userInfo.userData }) const handleChange = (e) => { setSearchKeyword(e.target.value) } const submitForm = () => { search(searchKeyword).then(res => { const payload = { movies: res } dispatch(getMoviesAction(payload)) }) } useEffect(() => { if (localStorage.getItem('userToken') !== undefined && localStorage.getItem('userToken') !== "undefined") { getUserData(localStorage.getItem('userToken')).then(res => { const payload = { userData: res } dispatch(getDataAction(payload)) }) } }, [userData?.id]) return ( <Navbar collapseOnSelect bg="dark" expand="lg"> <Container fluid> <Navbar.Brand href="/trending"> <NavLink to={{ pathname: "trending" }}> <ReactSVG beforeInjection={(svg) => { svg.classList.add('svg-class-name') svg.setAttribute('style', 'width: 100px; height: 40px') }} src={process.env.PUBLIC_URL + "/imoviIcon.svg"} /> </NavLink> </Navbar.Brand> <Navbar.Toggle aria-controls="navbarScroll" /> <Navbar.Collapse id="navbarScroll"> <Nav className="me-auto my-2 my-lg-0" style={{ maxHeight: '100px' }} navbarScroll > <Nav.Item className="p-1"> <NavLink onClick={() => { const payload = { movies: [] } dispatch(getMoviesAction(payload)) }} to={{ pathname: '/trending' }} style={{ textDecoration: 'none', color: 'grey' }}> Trending <i style={{ marginLeft: '5px', marginRight: '5px', display: 'inline' }} className="fa-solid fa-bolt"></i> </NavLink> </Nav.Item> {userData?.id ? <> <Nav.Item className="p-1"> <NavLink to={{ pathname: '/favourites' }} style={{ textDecoration: 'none', color: 'grey' }}> Favourites <i style={{ marginLeft: '5px', marginRight: '5px', display: 'inline' }} className="fa-solid fa-bookmark"></i> </NavLink> </Nav.Item> <Nav.Item className="p-1"> <NavLink to={{ pathname: '/history' }} style={{ textDecoration: 'none', color: 'grey' }}> History <i style={{ marginLeft: '5px', marginRight: '5px', display: 'inline' }} className="fa-solid fa-clock-rotate-left"></i> </NavLink> </Nav.Item> <Nav.Item className="p-1"> <NavLink to={{ pathname: '/profile' }} style={{ textDecoration: 'none', color: 'grey' }}> {userData.username} <i style={{ marginLeft: '5px', marginRight: '5px', display: 'inline' }} className="fa-solid fa-address-card"></i> </NavLink> </Nav.Item> </> : <></> } </Nav> <Form className="d-flex" onSubmit={(e) => { e.preventDefault() submitForm() }} > <FormControl type="search" placeholder="Search" className="me-2" aria-label="Search" onChange={(e) => { handleChange(e) }} /> <NavLink as={Col} to={{ pathname: '/search' }}> <Button variant="outline-success" onClick={() => { submitForm() }} type='submit'>Search</Button> </NavLink> {userData?.id ? <> <Button as={Row} onClick={() => logout(dispatch)} variant="secondary" className="mx-2"> logout <i style={{ marginLeft: '5px', display: 'inline' }} className="fa-solid fa-door-open"></i> </Button> </> : <> <NavLink as={Col} to={{ pathname: '/login' }}> <Button as={Col} variant="secondary" className="mx-2"> login <i style={{ marginLeft: '5px', display: 'inline' }} className="fa-solid fa-right-to-bracket"></i> </Button> </NavLink> </>} </Form> </Navbar.Collapse> </Container> </Navbar > ) } export default Header
import React, { useState } from 'react' import { auth } from '../Firebase' import { useHistory } from 'react-router-dom' export default function Login() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const history = useHistory(); const handleSubmit = async(e) => { e.preventDefault() try { const result = await auth.signInWithEmailAndPassword(email, password) window.M.toast({ html: `Welcome ${result.user.email}`, classes: 'green' }) history.push("/success") } catch (error) { window.M.toast({ html: error.message, classes: 'green' }) } } return ( <div className="center container" style={{maxWidth:"500px"}}> <h1>Please Login</h1> <form onSubmit={(e) => handleSubmit(e)}> <div className="input-field "> <input type="email" placeholder="Enter your email" onChange={(e) => setEmail(e.target.value)} /> <input type="password" placeholder="Enter your password" onChange={(e) => setPassword(e.target.value)} /> </div> <button type="submit" className="btn blue">Login</button> </form> </div> ) }
# Folksonomy API A light REST API designed for the Open Food Facts Folksonomy Engine. * Design documents: https://wiki.openfoodfacts.org/Folksonomy_Engine * API endpoint: https://api.folksonomy.openfoodfacts.org/ * API Documentation with interactive "try-out": https://api.folksonomy.openfoodfacts.org/docs * Browser extension to try it live: https://github.com/openfoodfacts/folksonomy_frontend * Moderators can access it on Open Food Facts without any extension. The UI has not yet been deployed on Open Products Facts, Open Pet Food Facts or Open Beauty Facts, but has been proven to work, thanks to the extension # Dependencies The code is written in Python 3.x and uses [FastAPI](https://fastapi.tiangolo.com/) framework. PostgreSQL is used as the backend database. # Dev You should create unit tests for each new feature or API change (see [test_main.py](https://github.com/openfoodfacts/folksonomy_api/blob/main/tests/test_main.py)). To run tests just launch: ```bash pytest ``` # Generating an OpenAPI document FastAPI is based on [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (previously known as Swagger) and [JSON Schema](https://json-schema.org/). FastAPI allows to generate an OpenAPI document (JSON) that you can reuse in various services (to automatically generate client libraries for example). To generate an OpenAPI document you can either: * download it at https://api.folksonomy.openfoodfacts.org/openapi.json * or generate it: ```bash ./generate_openapi_json.py ``` # How to install Folksonomy Engine on your local machine 1. Install Python 3.8+ 2. Install pip 3. Install PostgreSQL 13+ 4. Follow the steps in [INSTALL.md](https://github.com/openfoodfacts/folksonomy_api/blob/main/INSTALL.md) to install requirements and for creating a db user 5. Make a copy of [local_settings_example.py](https://github.com/openfoodfacts/folksonomy_api/blob/main/local_settings_example.py) and rename it to *local_settings.py* 6. Change parameters accordingly in *local_settings.py* 7. That's all! ## Deployment [Deployment at Open Food Facts - Folksonomy Section](https://openfoodfacts.github.io/openfoodfacts-infrastructure/folksonomy/)
import org.palladiosimulator.pcm.repository.CompositeDataType import tools.vitruv.applications.pcmumlclass.DefaultLiterals import tools.vitruv.applications.pcmumlclass.TagLiterals import "http://www.eclipse.org/uml2/5.0.0/UML" as uml import "http://palladiosimulator.org/PalladioComponentModel/5.2" as pcm reactions: umlCompositeDataTypeClassReactions in reaction to changes in uml execute actions in pcm // The following reactions and routines synchronize a pcm::CompositeDataType in a pcm::Repository // with an uml::Class in the datatypes uml::Package corresponding to the repository. // // The correspondence is instantiated from this side when the uml::Class is inserted in the datatypes package. // The correspondence is deleted when the uml::Class is deleted. // // Related files: // PcmCompositeDataType.reactions // UmlCompositeDataTypeGeneralization.reactions // CompositeDataTypeConceptTest reaction CompositeDatyTypeClassInserted { after element uml::Class inserted in uml::Package[packagedElement] with newValue.package === affectedEObject call insertCorrespondingCompositeDataType(newValue, affectedEObject) } routine insertCorrespondingCompositeDataType(uml::Class umlClass, uml::Package umlPackage) { match { val pcmRepository = retrieve optional pcm::Repository corresponding to umlPackage tagged TagLiterals. REPOSITORY_TO_DATATYPES_PACKAGE } update { if (pcmRepository.isPresent) { detectOrCreateCorrespondingCompositeDataType(umlClass, umlPackage) moveCorrespondingCompositeDataType(umlClass, umlPackage) } else { deleteCorrespondingCompositeDataType(umlClass) } } } routine detectOrCreateCorrespondingCompositeDataType(uml::Class umlClass, uml::Package umlPackage) { match { val pcmRepository = retrieve asserted pcm::Repository corresponding to umlPackage tagged TagLiterals. REPOSITORY_TO_DATATYPES_PACKAGE require absence of pcm::CompositeDataType corresponding to umlClass tagged TagLiterals.COMPOSITE_DATATYPE__CLASS } update { val candidates = pcmRepository.dataTypes__Repository.filter(CompositeDataType).filter [ type | type.entityName == umlClass.name ] switch (candidates.size) { case 0: createCorrespondingCompositeDataType(umlClass, umlPackage) case 1: addCorrespondenceForExistingCompositeDataType(candidates.head, umlClass) default: { logger.warn(DefaultLiterals.WARNING_MULTIPLE_COMPOSITE_DATA_TYPE_CANDIDATES + umlClass) addCorrespondenceForExistingCompositeDataType(candidates.head, umlClass) } } } } routine createCorrespondingCompositeDataType(uml::Class umlClass, uml::Package umlPackage) { match { val pcmRepository = retrieve asserted pcm::Repository corresponding to umlPackage tagged TagLiterals. REPOSITORY_TO_DATATYPES_PACKAGE } create { val pcmCompositeType = new pcm::CompositeDataType } update { pcmCompositeType.entityName = umlClass.name addCorrespondenceBetween(pcmCompositeType, umlClass, TagLiterals.COMPOSITE_DATATYPE__CLASS) } } routine addCorrespondenceForExistingCompositeDataType(pcm::CompositeDataType pcmCompositeType, uml::Class umlClass) { match { require absence of pcm::CompositeDataType corresponding to umlClass tagged TagLiterals.COMPOSITE_DATATYPE__CLASS require absence of uml::Class corresponding to pcmCompositeType tagged TagLiterals.COMPOSITE_DATATYPE__CLASS } update { addCorrespondenceBetween(pcmCompositeType, umlClass, TagLiterals.COMPOSITE_DATATYPE__CLASS) } } routine moveCorrespondingCompositeDataType(uml::Class umlClass, uml::Package umlPackage) { match { val pcmCompositeType = retrieve asserted pcm::CompositeDataType corresponding to umlClass tagged TagLiterals. COMPOSITE_DATATYPE__CLASS val pcmRepository = retrieve asserted pcm::Repository corresponding to umlPackage tagged TagLiterals. REPOSITORY_TO_DATATYPES_PACKAGE } update { pcmRepository.dataTypes__Repository += pcmCompositeType } } reaction CompositeDataTypeClassRemoved { after element uml::Class removed from uml::Package[packagedElement] with oldValue.package !== affectedEObject call removeCorrespondingCompositeType(oldValue, affectedEObject) } routine removeCorrespondingCompositeType(uml::Class umlClass, uml::Package umlPackage) { match { val pcmCompositeType = retrieve pcm::CompositeDataType corresponding to umlClass tagged TagLiterals. COMPOSITE_DATATYPE__CLASS val pcmRepository = retrieve pcm::Repository corresponding to umlPackage tagged TagLiterals. REPOSITORY_TO_DATATYPES_PACKAGE } update { pcmRepository.dataTypes__Repository -= pcmCompositeType } } reaction CompositeDataTypeClassDeleted { after element uml::Class deleted call deleteCorrespondingCompositeDataType(affectedEObject) } routine deleteCorrespondingCompositeDataType(uml::Class umlClass) { match { val pcmCompositeType = retrieve pcm::CompositeDataType corresponding to umlClass tagged TagLiterals. COMPOSITE_DATATYPE__CLASS } update { removeCorrespondenceBetween(pcmCompositeType, umlClass, TagLiterals.COMPOSITE_DATATYPE__CLASS) removeObject(pcmCompositeType) } } reaction CompositeDataTypeClassNameChanged { after attribute replaced at uml::Class[name] with affectedEObject.name == newValue call changeNameOfCorrespondingCompositeDataType(affectedEObject, newValue) } routine changeNameOfCorrespondingCompositeDataType(uml::Class umlClass, String newName) { match { val pcmCompositeType = retrieve pcm::CompositeDataType corresponding to umlClass tagged TagLiterals. COMPOSITE_DATATYPE__CLASS } update { pcmCompositeType.entityName = newName } }
// // ProgreesView.swift // MonnifyiOSSDK // // Created by Nnaemeka Abah on 18/04/2022. // Copyright ยฉ 2022 Monnify. All rights reserved. // import Foundation import UIKit @IBDesignable class CardProgressView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .white self.addSubview(loadingIndicator) } convenience init() { self.init(frame: .zero) } required init?(coder: NSCoder) { super.init(coder: coder) self.addSubview(loadingIndicator) layoutSubviews() } let loadingIndicator: ProgressView = { let progress = ProgressView(colors: [.appGrdOrangeStart, .appGrdOrangeEnd, .appGrdOrangeStart], lineWidth: 3) progress.translatesAutoresizingMaskIntoConstraints = false return progress }() override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = 5 self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.11 self.layer.shadowOffset = CGSize(width: 0, height: 10) self.layer.shadowRadius = 14 self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale NSLayoutConstraint.activate([ loadingIndicator.centerXAnchor .constraint(equalTo: self.centerXAnchor), loadingIndicator.centerYAnchor .constraint(equalTo: self.centerYAnchor), loadingIndicator.widthAnchor .constraint(equalToConstant: 28), loadingIndicator.heightAnchor .constraint(equalTo: self.loadingIndicator.widthAnchor) ]) } @IBInspectable var isAnimating: Bool = false { didSet { loadingIndicator.isAnimating = isAnimating } } } @IBDesignable class ProgressView: UIView { // MARK: - Properties let colors: [UIColor] let lineWidth: CGFloat // MARK: - Initialization init(frame: CGRect, colors: [UIColor], lineWidth: CGFloat) { self.colors = colors self.lineWidth = lineWidth super.init(frame: frame) self.backgroundColor = .clear } convenience init(colors: [UIColor], lineWidth: CGFloat) { self.init(frame: .zero, colors: colors, lineWidth: lineWidth) } required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.frame.width / 2 let path = UIBezierPath(ovalIn: CGRect( x: 0, y: 0, width: self.bounds.width, height: self.bounds.width ) ) shapeLayer.path = path.cgPath } private lazy var shapeLayer: ProgressShapeLayer = { return ProgressShapeLayer(strokeColor: colors.first!, lineWidth: lineWidth) }() // MARK: - Animations func animateStroke() { let startAnimation = StrokeAnimation( type: .start, beginTime: 0.25, fromValue: 0.0, toValue: 1.0, duration: 0.75 ) let endAnimation = StrokeAnimation( type: .end, fromValue: 0.0, toValue: 1.0, duration: 0.75 ) let strokeAnimationGroup = CAAnimationGroup() strokeAnimationGroup.duration = 1 strokeAnimationGroup.repeatDuration = .infinity strokeAnimationGroup.animations = [startAnimation, endAnimation] shapeLayer.add(strokeAnimationGroup, forKey: nil) let colorAnimation = StrokeColorAnimation( colors: colors.map { $0.cgColor }, duration: strokeAnimationGroup.duration * Double(colors.count) ) shapeLayer.add(colorAnimation, forKey: nil) self.layer.addSublayer(shapeLayer) } func animateRotation() { let rotationAnimation = RotationAnimation( direction: .z, fromValue: 0, toValue: CGFloat.pi * 2, duration: 2, repeatCount: .greatestFiniteMagnitude ) self.layer.add(rotationAnimation, forKey: nil) } var isAnimating: Bool = false { didSet { if isAnimating { self.animateStroke() self.animateRotation() } else { self.shapeLayer.removeFromSuperlayer() self.layer.removeAllAnimations() } } } } class ProgressShapeLayer: CAShapeLayer { public init(strokeColor: UIColor, lineWidth: CGFloat) { super.init() self.strokeColor = strokeColor.cgColor self.lineWidth = lineWidth self.fillColor = UIColor.clear.cgColor self.lineCap = .round } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #define PHILOSOPHERS 5 pthread_mutex_t mutex; pthread_cond_t cond[PHILOSOPHERS]; /* one per philosopher */ pthread_mutex_t print_lock; /* protects against output interleaving */ void space(int s) { pthread_mutex_lock(&print_lock); int i; for (i = 0; i < s * 10; i++) printf(" "); } typedef struct { int num_loops; int thread_id; } arg_t; enum states{THINKING, EATING, HUNGRY} state[PHILOSOPHERS]; /* state of each philosopher */ int left(int p) { return (p + PHILOSOPHERS -1) % PHILOSOPHERS; } int right(int p) { return (p + 1) % PHILOSOPHERS; } void think() { return; } void eat() { return; } int update_state(int p){ if (state[p] == HUNGRY && state[left(p)] != EATING && state[right(p)] != EATING) { state[p] = EATING; pthread_cond_signal(&cond[p]); } return 0; } void put_forks(int p){ pthread_mutex_lock(&mutex); state[p] = THINKING; update_state(left(p)); /* update_state neighbors */ update_state(right(p)); pthread_mutex_unlock(&mutex); } void get_forks(int p){ pthread_mutex_lock (&mutex); /* enter cs, lock mutex */ state[p] = HUNGRY; /* set philosopher's state to HUNGRY */ update_state(p); /* update_state philosopher */ while (state[p] == HUNGRY){ /* loop while philosopher is hungry */ pthread_cond_wait(&cond[p],&mutex); } pthread_mutex_unlock(&mutex); /* exit cs, unlock mutex */ } void *philosopher(void *arg) { arg_t *args = (arg_t *) arg; space(args->thread_id); printf("%d: start\n", args->thread_id); pthread_mutex_unlock(&print_lock); int i; for (i = 0; i < args->num_loops; i++) { space(args->thread_id); printf("%d: think\n", args->thread_id); pthread_mutex_unlock(&print_lock); think(); get_forks(args->thread_id); space(args->thread_id); printf("%d: eat\n", args->thread_id); pthread_mutex_unlock(&print_lock); eat(); put_forks(args->thread_id); space(args->thread_id); printf("%d: done\n", args->thread_id); pthread_mutex_unlock(&print_lock); } return NULL; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: dining_philosophers <num_loops>\n"); exit(1); } printf("dining: started\n"); pthread_mutex_init(&mutex, NULL); pthread_mutex_init(&print_lock, NULL); int i; for (i = 0; i < PHILOSOPHERS; i++) pthread_cond_init(&cond[i], NULL); //Sem_init(&print_lock, 1); pthread_t p[PHILOSOPHERS]; arg_t a[PHILOSOPHERS]; for (i = 0; i < PHILOSOPHERS; i++) { a[i].num_loops = atoi(argv[1]); a[i].thread_id = i; pthread_create(&p[i], NULL, philosopher, &a[i]); state[i] = THINKING; } for (i = 0; i < PHILOSOPHERS; i++) pthread_join(p[i], NULL); printf("dining: finished\n"); return 0; }
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%> <html> <tiles:insertDefinition name="baseLayout"> <tiles:putAttribute name="body"> <div class="inside-banner"> <div class="container"> <span class="pull-right"><a href="<c:url value="/index"/>">Home</a> / Requested Appointments</span> <h2><spring:message code="appointment.header" text="Requested Appointments" /></h2> </div> </div> <!-- banner --> <div class="container"> <div class="spacer"> <div class="row register"> <div class="col-lg-12 col-sm-12 col-xs-12 "> <div class="table-responsive"> <table class="table table-hover"> <tr class="active"> <th><spring:message code="appointment.property" text="Property Name" /></th> <th><spring:message code="appointment.address" text="Property Address" /></th> <th><spring:message code="appointment.owner" text="From Who" /></th> <th><spring:message code="appointment.appointment" text="Appointment" /></th> <th><spring:message code="appointment.date" text="Date" /></th> <th></th> <th></th> </tr> <c:forEach var="appointment" items="${appointments}"> <tr class="active"> <td>${appointment.property.name}</td> <td>${appointment.property.address}</td> <td>${appointment.buyer.firstName}</td> <td>${appointment.appointmentComment}</td> <td>${appointment.appointmentDate}</td> <td><a href="<c:url value="/property/propertyList?id=${appointment.property.id}"/>">View Property</a></td> <td> <c:choose> <c:when test="${appointment.getAppointmentStatus() == 'PENDING'}"> <a href="approve?id=${appointment.id}&status=1">Approve</a> <a href="approve?id=${appointment.id}&status=0">Cancel</a> </c:when> <c:otherwise> ${appointment.appointmentStatus} </c:otherwise> </c:choose> </td> </tr> </c:forEach> </table> </div> </div> </div> </div> </div> </tiles:putAttribute> </tiles:insertDefinition> </html>
import { DataStoreLevel, EventLogLevel, MessageStoreLevel } from '../src/index-stores.js'; /** * Class that manages store implementations for testing. * This is intended to be extended as the single point of configuration * that allows different store implementations to be swapped in * to test compatibility with default/built-in store implementations. */ export class TestStores { /** * Overrides test stores with given implementation. * If not given, default implementation will be used. */ static override(overrides) { TestStores.messageStore = overrides === null || overrides === void 0 ? void 0 : overrides.messageStore; TestStores.dataStore = overrides === null || overrides === void 0 ? void 0 : overrides.dataStore; TestStores.eventLog = overrides === null || overrides === void 0 ? void 0 : overrides.eventLog; } /** * Initializes and return the stores used for running the test suite. */ static get() { var _a, _b, _c; (_a = TestStores.messageStore) !== null && _a !== void 0 ? _a : (TestStores.messageStore = new MessageStoreLevel({ blockstoreLocation: 'TEST-MESSAGESTORE', indexLocation: 'TEST-INDEX' })); (_b = TestStores.dataStore) !== null && _b !== void 0 ? _b : (TestStores.dataStore = new DataStoreLevel({ blockstoreLocation: 'TEST-DATASTORE' })); (_c = TestStores.eventLog) !== null && _c !== void 0 ? _c : (TestStores.eventLog = new EventLogLevel({ location: 'TEST-EVENTLOG' })); return { messageStore: TestStores.messageStore, dataStore: TestStores.dataStore, eventLog: TestStores.eventLog }; } } //# sourceMappingURL=test-stores.js.map
import { z } from '@botpress/sdk' import { User } from '@linear/sdk' import { assert, Equals } from 'tsafe/assert' export const targets = z.object({ issue: z.record(z.string()).optional(), }) type TransformDatesToStrings<T> = { [K in keyof T]: T[K] extends Date | undefined ? string : T[K] } type LinearUserProfile = Pick< TransformDatesToStrings<User>, | 'admin' | 'archivedAt' | 'avatarUrl' | 'createdAt' | 'description' | 'displayName' | 'guest' | 'email' | 'isMe' | 'url' | 'timezone' | 'name' > & { linearId: string } export const UserProfile = z.object({ linearId: z.string().describe('Linear User ID'), admin: z.boolean().describe('Indicates if the user is an admin of the organization'), archivedAt: z.string().datetime().optional().describe('Date when the user was archived'), avatarUrl: z.string().url().optional(), createdAt: z.string().datetime().describe('Date when the user was created'), description: z.string().optional().describe('A short description of the user, either its title or bio'), displayName: z.string().describe("The user's display (nick) name. Unique within each organization"), guest: z .boolean() .describe('Whether the user is a guest in the workspace and limited to accessing a subset of teams'), email: z.string(), isMe: z.boolean().describe('Whether the user is the currently authenticated user'), url: z.string().describe("User's profile URL"), timezone: z.string().optional().describe('The local timezone of the user'), name: z.string().describe("The user's full name"), }) export const LinearIds = z .object({ creatorId: z.string().optional().describe('The internal Linear User ID of the user who created the issue'), labelIds: z.array(z.string()).optional().describe('The internal Linear Label IDs associated with the issue'), issueId: z.string().describe('The internal Linear Issue ID'), teamId: z.string().optional().describe('The internal Linear Team ID'), projectId: z.string().optional().describe('The internal Linear Project ID'), assigneeId: z.string().optional().describe('The internal Linear Assignee ID'), subscriberIds: z.array(z.string()).optional().describe('The internal Linear Subscriber User IDs'), }) .optional() .describe('The Linear IDs of the referenced entities') export const issueSchema = z.object({ id: z.string().describe('The issue ID on Linear'), identifier: z.string().describe("Issue's human readable identifier (e.g. XXX-123)"), number: z.number().describe('The issue number on Linear, such as "123" in XXX-123'), title: z.string().describe('The issue title on Linear'), description: z .string() .optional() .describe('A markdown description of the issue. Images and videos are inlined using markdown links.'), priority: z.number().describe('Priority of the issue, such as "1" for "Urgent", 0 for "No Priority"'), estimate: z.number().optional().describe('The estimate of the issue in points'), url: z.string().describe('The URL of the issue on Linear'), createdAt: z.string().datetime().describe('The ISO date the issue was created'), updatedAt: z.string().datetime().describe('The ISO date the issue was last updated'), }) export const LinearIssue = z.object({ title: z.string().describe('The issue title on Linear, such as "Fix the bug'), number: z.number().describe('The issue number on Linear, such as "123" in XXX-123'), teamName: z .string() .optional() .describe('The name of the Linear team the issue currently belongs to, such as "Customer Support"'), teamKey: z .string() .optional() .describe('The key of the Linear team the issue currently belongs to, such as "XXX" in XXX-123'), createdAt: z.string().datetime().describe('The ISO date the issue was created'), updatedAt: z.string().datetime().describe('The ISO date the issue was last updated'), status: z.string().describe('The issue State name (such as "In Progress"'), priority: z.number().describe('Priority of the issue, such as "1" for "Urgent", 0 for "No Priority"'), description: z .string() .optional() .describe('A markdown description of the issue. Images and videos are inlined using markdown links.'), labels: z.array(z.string()).optional().describe('Label names'), linearIds: LinearIds, userId: z .string() .optional() .describe( 'The Botpress User ID of the individual who initiated the issue. If not provided, it indicates the issue was generated by the bot.' ), conversationId: z.string().describe('Botpress Conversation ID of the issue'), }) assert<Equals<z.infer<typeof UserProfile>, LinearUserProfile>>()
from django.contrib import admin from .models import Group, Post class GroupAdmin(admin.ModelAdmin): list_display = ( 'pk', 'title', 'slug', 'description', ) list_editable = ('description',) search_fields = ('title',) list_filter = ('slug',) empty_value_display = '-ะฟัƒัั‚ะพ-' prepopulated_fields = {'slug': ('title',)} admin.site.register(Group, GroupAdmin) class PostAdmin(admin.ModelAdmin): list_display = ( 'pk', 'text', 'pub_date', 'author', 'group', ) list_editable = ('group',) search_fields = ('text',) list_filter = ('pub_date',) empty_value_display = '-ะฟัƒัั‚ะพ-' admin.site.register(Post, PostAdmin)
/* * File: CheckerboardKarel.java * ---------------------------- * When you finish writing it, the CheckerboardKarel class should draw * a checkerboard using beepers, as described in Assignment 1. You * should make sure that your program works for all of the sample * worlds supplied in the starter folder. */ import stanford.karel.*; public class CheckerboardKarel extends SuperKarel { /* addLastBeeper makes Karel check for a beeper in * the spot he is currently in. If no beeper is found, * he will place one on the row along the wall. */ private void addLastBeeper() { turnAround(); move(); if(noBeepersPresent()) { turnAround(); move(); putBeeper(); } else { turnAround(); move(); } } /* goBack will make Karel go back to left wall. */ private void goBack() { turnAround(); while(frontIsClear()) { move(); } if(frontIsBlocked()) { turnRight(); } } /* oddLayer will make Karel put beepers on * every other space on every odd numbered row */ private void oddLayer() { while(frontIsClear()) { putBeeper(); move(); if(frontIsClear()) { move(); } } addLastBeeper(); } /* evenLayer will make Karel put beepers on * every other space on every even numbered row */ private void evenLayer() { while(frontIsClear()) { move(); if(frontIsClear()) { putBeeper(); move(); } } addLastBeeper(); } public void run() { while(frontIsClear()) { oddLayer(); goBack(); if(frontIsClear()) { move(); turnRight(); evenLayer(); goBack(); if(frontIsClear()) { move(); turnRight(); } } } } }
๏ปฟusing System.ComponentModel.DataAnnotations; namespace bookStore_project.DTO_s { public class BookDTO { //DTO are typically used to communicate with the client public string Title { get; set; } //The DataType attribute on ReleaseDate specifies the type of the data (Date). //With this attribute: //1. The user isn't required to enter time information in the date field. //2. Only the date is displayed, not time information. [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } public string Description { get; set; } public string Author { get; set; } public string Genre { get; set; } public double Price { get; set; } public string ImageUrl { get; set; } } }
<template> <a-card title="ๅŸบ็ก€็”จๆณ•" :bordered="false"> <div style="max-width: 260px"> <ele-table-select :allow-clear="true" placeholder="่ฏท้€‰ๆ‹ฉ" value-key="userId" label-key="nickname" v-model:value="selectedValue" :table-config="tableConfig" :overlay-style="{ width: '520px', maxWidth: '80%' }" :disabled="disabled" :init-value="initValue" @select="onSelect" > <!-- ่ง’่‰ฒๅˆ— --> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'roles'"> <a-tag v-for="item in record.roles" :key="item.roleId" color="blue"> {{ item.roleName }} </a-tag> </template> </template> </ele-table-select> </div> <div class="ele-cell" style="margin-top: 15px"> <div style="line-height: 22px">&nbsp;็ฆ็”จ๏ผš</div> <div class="ele-cell-content"> <a-radio-group v-model:value="disabled" name="disabled"> <a-radio :value="false">ๅฆ</a-radio> <a-radio :value="true">ๆ˜ฏ</a-radio> </a-radio-group> </div> </div> <div style="margin-top: 12px"> <a-button type="primary" @click="setInitValue">ๅ›žๆ˜พๆ•ฐๆฎ</a-button> </div> </a-card> </template> <script setup> import { ref, reactive } from 'vue'; import { pageUsers } from '@/api/system/user'; const selectedValue = ref(); // ่กจๆ ผ้…็ฝฎ const tableConfig = reactive({ datasource: ({ page, limit, where, orders }) => { return pageUsers({ ...where, ...orders, page, limit }); }, columns: [ { title: '็”จๆˆท่ดฆๅท', dataIndex: 'username', sorter: true, showSorterTooltip: false }, { title: '็”จๆˆทๅ', key: 'nickname', dataIndex: 'nickname', sorter: true, showSorterTooltip: false }, { title: 'ๆ€งๅˆซ', dataIndex: 'sexName', width: 80, sorter: true, showSorterTooltip: false }, { title: '่ง’่‰ฒ', key: 'roles' } ], toolbar: false, pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], size: 'small', rowSelection: { columnWidth: 38, fixed: 'left' }, scroll: { x: 480 } }); // ็ฆ็”จ const disabled = ref(false); // ๅ›žๆ˜พๅ€ผ const initValue = ref(); /* ๅ›žๆ˜พๆ•ฐๆฎ */ const setInitValue = () => { //selectedValue.value = 14; initValue.value = { userId: 14, nickname: '็ฎก็†ๅ‘˜' }; }; /* ้€‰ไธญไบ‹ไปถ */ const onSelect = (item) => { console.log('item:', item); }; </script>
package org.nocountry.walam.main.model.dto; import jakarta.validation.Valid; import jakarta.validation.constraints.*; import lombok.Builder; import lombok.Data; import org.nocountry.walam.main.model.entity.User; import java.io.Serializable; import java.util.List; @Data @Builder public class AccountDTO implements Serializable { private Integer id; @NotBlank @Size(max = 20) @Pattern(regexp = "^[0-9]+$") private String numberAccount; @NotBlank @Size(max = 22) @Pattern(regexp = "^[0-9]+$") private String cvu; @NotBlank @DecimalMin(value = "0.00") @DecimalMax(value = "999999999.99") private Double balance; @Valid private List<TransactionDTO> transactions; }
{% extends "base.html" %} {% block content %} {% load markdown_to_html %} <h1>ะšะฐั‚ะฐะปะพะณ ะบะฐั€ั‚ะพั‡ะตะบ Anki ะดะปั ะธะฝั‚ะตั€ะฒะฐะปัŒะฝะพะณะพ ะฟะพะฒั‚ะพั€ะตะฝะธั</h1> <p>ะ—ะดะตััŒ ะฒั‹ ะผะพะถะตั‚ะต ะฒั‹ะฑั€ะฐั‚ัŒ ะบะฐั€ั‚ะพั‡ะบะธ ะดะปั ะธะทัƒั‡ะตะฝะธั</p> <p>ะะฐะนะดะตะฝะพ ะบะฐั€ั‚ะพั‡ะตะบ: {{ page_obj.paginator.count }}</p> {% comment %} ะŸะฐะณะธะฝะฐั†ะธั ะฝะฐั‡ะฐะปะพ {% endcomment %} <div class="col-12">{% include "includes/pagination.html" %}</div> {% comment %} ะŸะฐะณะธะฝะฐั†ะธั ะบะพะฝะตั† {% endcomment %} <p> <div class="container mt-3 col-auto"> <form method="GET" action="{% url 'catalog' %}"> <div class="row"> <div class="input-group mb-3"> <input type="text" required id="input_search" class="search-box" placeholder="ะคะธะปัŒั‚ั€ ะฟะพ ะฒะพะฟั€ะพัะฐะผ ะธ ะพั‚ะฒะตั‚ะฐะผ..." aria-label="ะคะธะปัŒั‚ั€ ะฟะพ ะฒะพะฟั€ะพัะฐะผ ะธ ะพั‚ะฒะตั‚ะฐะผ..." name="search_query" value="{{ request.GET.search_query }}"> <button class="close-icon" type="reset"></button> <button class="btn btn-outline-secondary" style="background-color: #1b5589" type="submit"> <i class="bi bi-search"></i> </button> </div> </div> <div class="row"> <div>ะกะพั€ั‚ะธั€ะพะฒะบะธ:</div> <div class="col-sm-2"> <select class="form-select" name="order" w-25> <option value="desc" {% if request.GET.order == 'desc' %}selected{% endif %}>ะŸะพ ัƒะฑั‹ะฒะฐะฝะธัŽ</option> <option value="asc" {% if request.GET.order == 'asc' %}selected{% endif %}>ะŸะพ ะฒะพะทั€ะฐัั‚ะฐะฝะธัŽ</option> </select> </div> {% comment %} <div class="col-sm-10"> <button type="submit" class="btn btn-secondary" style="background-color: #1b5589" name="sort" value="upload_date">ะŸะพ ะดะฐั‚ะต</button> <button type="submit" class="btn btn-secondary" style="background-color: #1b5589" name="sort" value="views">ะŸะพ ะฟั€ะพัะผะพั‚ั€ะฐะผ</button> <button type="submit" class="btn btn-secondary" style="background-color: #1b5589" name="sort" value="adds">ะŸะพ ะดะพะฑะฐะฒะปะตะฝะธัะผ</button> </div> {% endcomment %} <div class="col-sm-10"> <div class="btn-group" role="group" aria-label="ะ‘ะฐะทะพะฒะฐั ะณั€ัƒะฟะฟะฐ ะฟะตั€ะตะบะปัŽั‡ะฐั‚ะตะปะตะน ั€ะฐะดะธะพ"> <input type="radio" class="btn-check" name="sort" id="sortUploadDate" value="upload_date" autocomplete="off" onclick="this.form.submit()" {% if request.GET.sort == 'upload_date' %}checked{% endif %}> <label class="btn btn-outline-primary" for="sortUploadDate">ะŸะพ ะดะฐั‚ะต</label> <input type="radio" class="btn-check" name="sort" id="sortViews" value="views" autocomplete="off" onclick="this.form.submit()" {% if request.GET.sort == 'views' %}checked{% endif %}> <label class="btn btn-outline-primary" for="sortViews">ะŸะพ ะฟั€ะพัะผะพั‚ั€ะฐะผ</label> <input type="radio" class="btn-check" name="sort" id="sortAdds" value="adds" autocomplete="off" onclick="this.form.submit()" {% if request.GET.sort == 'adds' %}checked{% endif %}> <label class="btn btn-outline-primary" for="sortAdds">ะŸะพ ะดะพะฑะฐะฒะปะตะฝะธัะผ</label> </div> </div> </div> </form> </div> </p> {% for card in cards %} {% include "includes/card_preview.html" %} {% endfor %} {% comment %} ะŸะฐะณะธะฝะฐั†ะธั ะฝะฐั‡ะฐะปะพ {% endcomment %} <div class="col-12">{% include "includes/pagination.html" %}</div> {% comment %} ะŸะฐะณะธะฝะฐั†ะธั ะบะพะฝะตั† {% endcomment %} {% endblock content %}
import type { LinkProps as NextLinkProps } from 'next/link' import NextLink from 'next/link' import { useRouter } from 'next/router' import type { AnchorHTMLAttributes, PropsWithChildren } from 'react' import { useCallback } from 'react' export type LinkProps = PropsWithChildren< NextLinkProps & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> > export function Link({ children, href, as, replace, scroll, shallow, prefetch, locale, title, passHref, ...anchorProps }: LinkProps) { const router = useRouter() const onClick = useCallback( (e) => { if (router.asPath === href) { e.preventDefault() } }, [router, href] ) return ( <NextLink {...{ href, as, replace, scroll, shallow, prefetch, locale }} scroll={false} passHref={passHref} > <a role="link" title={title} tabIndex={0} onClick={onClick} {...anchorProps} > {children} </a> </NextLink> ) }
In this chapter we present a one-way automaton model that has the same expressive power as two-way transducers. We begin by defining {register transducers}, which are automata that use registers to store parts of their output. We have already seen register transducers in Chapter~\ref{sec:hilbert} -- in a more general setting, for arbitrary algebras -- and we have even proved in Corollary~\ref{cor:register-automata-equivalence} that their equivalence is decidable for the specific algebra of words with concatenation that we use in this chapter. To make this chapter self-contained, we give a stand-alone definition below. Register transducers, as defined below, will turn out to be strictly more powerful than two-way transducers, but a model with the same expressive power as two-way transducers will be recovered by placing a certain {copyless restriction} on the register updates. \begin{definition} \label{def:sst} A \emph{register transducer} consists of: \begin{itemize} \item finite \emph{input and output alphabets} $\Sigma$ and $\Gamma$; \item a finite set of \emph{states} $Q$; \item a finite set of \emph{registers} $R$; \item an \emph{initial configuration} in $Q \times (R \to \Gamma^*)$; \item a \emph{transition function} $$ \delta : Q \times \Sigma \to Q \times \underbrace{(R \to (R + \Gamma)^*)}_{\text{register update}}$$ \item an \emph{output function} $$ out : Q \to (R + \Gamma)^*$$ \end{itemize} \end{definition} The automaton is run as follows. Define a \emph{register valuation} to be any function from registers to words over the output alphabet $\Gamma$, and define a \emph{register update} to be any function from registers to words over the alphabet $R + \Gamma$. There is an action of updates on valuations \begin{align*} (v \in \text{register valuations}, \tau \in \text{register update}) \quad \mapsto \quad v\cdot \tau \in \text{register valuations} \end{align*} where $v \cdot\tau$ is obtained from $\tau$ by replacing each register name with its contents under $\tau$. A \emph{configuration} of the automaton is defined to be a pair (state, register valuation). The automaton begins in the initial configuration. When reading an input letter $a$, the automaton uses its transition function to determine its new state and the register update. More formally, the configuration is updated as follows: \begin{align*} (q,v) \cdot a \eqdef (p, v\tau) \qquad \text{where $\delta(q,a)=(p,\tau)$} . \end{align*} After the entire word has been processed, with the last configuration being $(q,v)$, the automaton outputs $out(q)$, with register names replaced by their contents in $v$. \begin{example}\label{ex:two-way} Here is an automaton where the input and output alphabets are $\set{a}$, and the recognised function is $a^n \mapsto a^{5+ 3 \cdot 2^n}$. The automaton has one register and one state. The initial configuration stores the word $a$ in the unique register. When reading an input letter, the unique register $r$ is updated by $r:=rr$. The output function maps the unique state to $aaaaarrr$. The function recognised by this register transducer is not recognised by any two-way transducer. There reason is that the function has exponential growth, while a two-way transducer has necessarily at most linear blowup, because a position in the input word can be visited at most once for each state. \end{example} \paragraph*{Copyless restriction.} As argued in Example~\ref{ex:two-way}, register transducers can have exponential growth, and therefore are not in general equivalent to deterministic two-way transducers. To recover equivalence with two-way transducers, we use the \emph{copyless restriction} (also known as the \emph{single use restriction}) described in the following picture: \mypicc{32} In other words, a register update is copyless if every vertex in the left column has outdegree at most one. The intuition is that the register contents are physical objects and can only be moved around and not duplicated. \begin{definition} A \emph{streaming string transducer}\footnote{The model and name of streaming string transducers comes from~\cite{Alur:2010gc}, although similar and essentially equivalent models have been known before in the literature on attribute grammars, e.g.~attributed tree transducers from~\cite{:1981vj}. } is a register transducer where the transition function produces only copyless register updates. \end{definition} The output function need not be copyless. Requiring it to be copyless would not weaken the model, though, because the output function is applied only once. For example, if the output function uses each register at most $k$ times, then by taking $k$ disjoint copies of the registers we can make the output function copyless. The goal of this chapter is to prove that streaming string transducers are equivalent to deterministic two-way transducers. \begin{theorem}\label{thm:sst-two-way} Streaming string transducers recognise the same word-to-word functions as deterministic two-way transducers \end{theorem} The above theorem was proved by Alur and Cerny in~\cite{Alur:2010gc}. A similar result (using a model of streaming string transducers with lookahead) can also be recovered from earlier work of Bloem, Engelfriet and Hogeboom: (a) \mso transductions are equivalent to deterministic two-way transducers~\cite{Engelfriet:2001kv}; and (b) \mso transductions are equivalent (even over trees) to a certain kind of attribute transducers~\cite{Bloem:2000wq}. We begin by describing the proof strategy. Our goal is to prove the equality \begin{align}\label{eq:sst} \underbrace{\sstfun}_{\substack{\text{functions recognised by} \\ \text{streaming string transducers}}} = \underbrace{\twofun.}_{\substack{\text{functions recognised by} \\ \text{deterministic two-way transducers}}} \end{align} As in the proof of Theorem~\ref{thm:two-way-seq-comp}, we write $\ratfun$ for the class of rational functions. In Section~\ref{sec:sst-rational-equivalence}, we prove the following inclusions \begin{align*} \sstfun \quad \stackrel{\text{Lemma~\ref{lem:sst-to-two-way}}} \subseteq \quad \twofun \circ \ratfun \qquad\text{and} \qquad \sstfun \circ \ratfun \stackrel{\text{Lemma~\ref{lem:two-way-to-sst}}} \supseteq \twofun. \end{align*} In other words, every streaming string transducer can be recognised by a deterministic two-way automaton with preprocessing by a rational function, and likewise in the opposite direction. Rational functions are easily seen to be closed under composition, using a straightforward product construction, see Exercise~\ref{zad:two-way-rat-comp-1}. Combining the inclusions from Lemmas~\ref{lem:sst-to-two-way} and~\ref{lem:two-way-to-sst}, and using closure of rational functions under composition, we get \begin{align}\label{eq:sst-precomp} \sstfun \circ \ratfun = \twofun \circ \ratfun. \end{align} To finish the proof of Theorem~\ref{thm:sst-two-way}, it suffices to show that both streaming string transducers and deterministic two-way transducers are closed under preprocessing with rational functions. For deterministic two-way transducers, this was shown in Theorem~\ref{thm:two-way-seq-comp} from Chapter~\ref{sec:two-way}. For streaming string transducers, this will be done in Lemma~\ref{lem:sst-precompose}, which is the most challenging construction in this chapter. Combining these results, we get \begin{align*} \sstfun \quad \stackrel{\text{Lemma~\ref{lem:sst-precompose}}} = \quad \sstfun \circ \ratfun \stackrel{\eqref{eq:sst-precomp}} = \twofun \circ \ratfun \quad \stackrel{\text{Theorem~\ref{thm:two-way-seq-comp}}} = \quad \twofun \end{align*} which completes the proof of Theorem~\ref{thm:sst-two-way}. It remains to prove Lemmas~\ref{lem:sst-to-two-way},~\ref{lem:two-way-to-sst} and~\ref{lem:sst-precompose}. \section{Equivalence after rational preprocessing} \label{sec:sst-rational-equivalence} In this section, we prove that streaming string transducers and deterministic two-way transducers are equivalent if we allow rational preprocessing \begin{lemma}\label{lem:sst-to-two-way} Every streaming string transducer can be decomposed as a rational function followed by a deterministic two-way transducer. In other words \begin{align*} \sstfun \subseteq \twofun \circ \ratfun. \end{align*} \end{lemma} \begin{proof} Fix a streaming string transducer. A run of the transducer looks like this: \mypicc{44} It is not hard to see that there is a rational -- in fact left-to-right sequential -- transducer which transforms an input word \mypicc{45} to a word describing the corresponding sequence of register updates: \mypicc{46} By using the above rational transducer as a preprocessor, to prove the lemma it is enough to find a deterministic two-way transducer which inputs a tree that describes the register updates, and outputs the final value. To do this, we use a depth-first search through the tree as explained in the following picture \mypicc{47} It is easy to implement a depth-first search using a deterministic two-way automaton. One simply has to remember the current register and the direction from which it came. \end{proof} \begin{lemma}\label{lem:two-way-to-sst} Every deterministic two-way transducer can be decomposed as a rational function followed by a streaming string transducer. In other words \begin{align*} \twofun \subseteq \sstfun \circ \ratfun. \end{align*} \end{lemma} \begin{proof} As in the proof of Theorem~\ref{thm:two-way-compose}, it is more convenient to use a definition of two-way transducers where the initial configuration is (initial state, end of input marker $\dashv$). Consider the configuration graph of the two-way automaton over a given input word, as in the following picture: \mypicc{28} We begin with a naive idea, which will not work because of the copyless restriction. For a vertex in the configuration graph, define its \emph{segment} to be the (unique, by determinism) path that begins in the configuration, and is cut off at the first visit to the same column as the source configuration, as in the following picture: \mypicc{29} The segment might accept/reject/loop without returning to the column of the source configuration. The naive idea would be to store for each state $q$ the output word that is found by reading the labels on the segment of the configuration that has state $q$ in last read position. The problem with this construction is that it violates the copyless restriction, because configurations can have more than one incoming edge, and therefore the labels of one segment can be shared by several longer segments. Like in the proof of Theorem~\ref{thm:two-way-compose}, the solution is to restrict the configuration graph to edges that are reachable from the initial configuration. As shown in Lemma~\ref{lem:two-way-reachable}, a rational function can be used to restrict the configuration graph to reachable configurations, so that the result looks like this: \mypicc{30} When only reachable edges are used, the indegree is at most one, because otherwise the automaton would loop, which cannot happen by the assumption that it defines a total function. Using the naive idea, one can write a streaming string transducer which inputs a configuration graph with only reachable edges -- represented as a word over a finite alphabet in any natural way -- and outputs the label of the segment corresponding to the initial configuration. \end{proof} \section{Lookahead removal} \label{sec:pre-comp-sst} In this section we show that functions recognised by register transducers and streaming string transducers are closed under pre-composition with rational functions. A different perspective on this result is that register transducers and streaming string transducers would not become more expressive if equipped with an oracle that gives regular information about the input word to the left and right of the head. Since the information about the word to the left of the head can be stored in the state, the interesting part of the oracle is the one that talks about the word to the right of the head. In other words, in this section we show that lookahead can be eliminated from the transducers without affecting expressive power. \begin{lemma}\label{lem:lookahead-register} Functions recognised by register transducers are closed under pre-composition with rational functions. \end{lemma} \begin{proof} Consider functions \begin{align*} \xymatrix{\Sigma^* \ar[r]^{\blue f} & \blue \Gamma^* \ar[r]^{\red g} & \red \Delta^*} \end{align*} such that $\blue f$ is rational and $\red g$ is recognised by a register automaton. We use the following colour coding. The first alphabet $\Sigma$ is written in black. \blue{Blue} is used for the states and output alphabet of $\blue f$. \red{Red} is for the states and output alphabet of $\red g$. A run of the composition $\red g \circ \blue f $ looks like this: \mypicc{38} The register transducer for the composition $\red f \circ \blue g$ stores a function \begin{align*} \text{states of lookahead $\blue f$} \qquad \to \qquad \text{configurations of $\red g$} \end{align*} which maps a state $\blue q$ of $\blue f$ to the configuration that would be used by $\red g$ assuming that $\blue q$ is the state of the lookahead $\blue f$ after reading the unread part of the input (in a right-to-left pass). Such a function can be represented by using \begin{align*} \text{(number of states in lookahead $\blue f$)} \times \text{(number of registers in $\red g$)} \end{align*} registers; and the representation can be updated in the transition function. After reading the entire word, the transducer for the composition looks at the value of the function under the initial state of $\blue f$, and then applies the output function of $\red g$. \end{proof} The construction in the above lemma cannot be used for streaming string transducers because it violates the copyless restriction. The violation comes from merging states in the right-to-left sequential function $\blue f$. For example, suppose that the state transformation of $\blue f$ over some input letter $a \in \Sigma$ looks like this: \mypicc{36} Then the register transducer described in the proof of Lemma~\ref{lem:lookahead-register} would duplicate the information stored for state $\blue{q_1}$, using it for both $\blue{q_0}$ and $\blue{q_1}$. To eliminate lookahead for streaming string transducers, we use a data structure, called a transformation forest, which stores register updates organised in a forest structure so that composition can be done without copying. We describe this data structure below. \paragraph*{Composing register updates.} We begin with defining a composition operation on register updates. Here is the picture: \mypicc{33} The composition operation is defined so that if $\tau,\sigma$ are two register updates and $v$ is a register valuation, then \begin{align*} v \cdot (\tau \cdot \sigma) = (v \cdot \tau) \cdot \sigma. \end{align*} Using the above composition, we can view the set of register updates -- for a fixed set of register names and output alphabet -- as a monoid. \paragraph*{Transformation forests.} Suppose that $M$ is a monoid and $Q$ is a finite set. (Our intended application is that $S$ is the monoid of register updates for some streaming string transducer, but the abstract definition requires less notation.) Define a \emph{transformation forest} (over $M$ and $Q$) to be any labelled forest of the following form: \mypicc{64} We now describe how transformation forests can be composed. Suppose that we have two transformation forests $\tau$ and $\sigma$, as illustrated below: \mypicc{65} Their composition $\tau\sigma$ is obtained by doing the following steps. \begin{enumerate} \item To each root of $\sigma$ we can associate a unique leaf of $\tau$ with the same label, because roots of $\sigma$ have different labels and all labels appear in leaves of $\tau$. Merge each root of $\sigma$ with the associated leaf of $\tau$: \mypicc{66} \item Eliminate nodes that do not reach any node leaf of $\sigma$: \mypicc{67} \item Contract into a single edge every path that uses only nodes with unary branching (except the source and target): \mypicc{68} The label of a contracted path is the product, in the semigroup $S$, of the labels of edges on the path before the contraction. \end{enumerate} It is not hard to see that this operation is associative, i.e.~ \begin{align*} \tau (\sigma \rho) = (\tau \sigma) \rho. \end{align*} Also, there is a neutral element, namely the transformation forest where each leaf is a root (and there are no edges). Therefore, the set of transformation forests is a monoid, which we denote by $M^{[Q]}$. The reader might recognise transformation forests from Lemma~\ref{lem:mcnaughton-trees} from Chapter~\ref{sec:determinisation}. In that lemma, the monoid $M$ had two elements ``accepting'' and ``non-accepting''. In this chapter, $M$ will be the infinite monoid of copyless register updates. \paragraph*{Lookahead elimination for streaming string transducers.} Equipped with the data structure of transformation forests, we are ready to prove the copyless variant of Lemma~\ref{lem:lookahead-register}. \begin{lemma} \label{lem:sst-precompose} Functions recognised by streaming string transducers are closed under pre-composition with rational functions. In other words \begin{align*} \sstfun = \sstfun \circ \ratfun. \end{align*} \end{lemma} \begin{proof} The left-to-right inclusion is immediate, since the identity is a rational function. For the converse inclusion, recall the following equality \begin{align*} \ratfun \quad = \underbrace{\seqfun}_{\substack{\text{left-to-right}\\ \text{sequential functions}}} \circ \underbrace{\seqfunrev}_{\substack{\text{right-to-left}\\ \text{sequential functions}}} \end{align*} from Theorem~\ref{thm:rational-functions}. Since both streaming string transducers and left-to-right sequential functions are instances of left-to-right automata, a straightforward product construction can be used to yield the inclusion \begin{align*} \sstfun \supseteq \sstfun \circ \seqfun \end{align*} Therefore, in order to prove the lemma it suffices to show \begin{align*} \sstfun = \sstfun \circ \seqfunrev. \end{align*} Here we cannot use a simple product construction, because we compose automata that move in different directions. The rest of the proof is devoted to proving the above inclusion. We use the same notation and colour convention as in the proof of Lemma~\ref{lem:lookahead-register}. Let \begin{align*} \xymatrix{\Sigma^* \ar[r]^{\blue f} & \blue \Gamma^* \ar[r]^{\red g} & \red \Delta^*} \end{align*} be functions such that $\blue f$ is right-to-left sequential and $\red g$ is a streaming string transducer. Our goal is to design a streaming string transducer that recognises the composition $\red g \circ \blue f$. To make notation lighter, we assume that $\blue f$ has empty end-of-input words. This assumption can be lifted without greater conceptual difficulty. \paragraph*{Overview of the construction.} The idea is that instead of storing register valuations, the streaming string transducer for $\red g \circ \blue f$ will store register updates, organised in a transformation forest. To illustrate this idea, consider the configuration graph of the right-to-left sequential function $\blue f$ over an input word $w \in \Sigma^*$, as shown in the following picture: \mypicc{39} Nodes of the configuration graph are labelled by states of $\blue f$ and edges are labelled by output words of $\blue f$. Because the $\blue f$ is right-to-left deterministic, the configuration graph is a forest, with the roots in the first column. The output of $\blue f$ is obtained by reading from left to right the labels on the path that goes from the unique leaf with the initial state of $\blue f$ to the unique root that is its ancestor. (We use the assumption that the end-of-input words are empty; otherwise we would need to add one more column at the left end of the picture.) The automaton recognising the composition $\red g \circ \blue f$ will store in its configuration a transformation forest \begin{align*} t \in \underbrace{(\text{register updates of $\red g$})}_{\substack{\text{monoid of copyless register}\\ \text{updates for registers and }\\ \text{output alphabet of $\red g$}}}\ \! ^{[\text{states of $\blue f$}]}. \end{align*} The nodes of this transformation forest will correspond to the leaves of the configuration graph, their closest common ancestors, and the roots that are reachable from leaves, as represented by the big yellow circles below: \mypicc{56} For a path connecting two adjacent yellow nodes, the transformation forest $t$ will store the register update done by $\red g$ on that path. To describe the automaton in more detail, we begin by discussing how copyless register updates, and therefore also transformation forests over the monoid of copyless register updates, can be stored in the configuration of a streaming string transducer. \paragraph*{Storing register updates.} Recall the graphical representation of register updates that was used when defining the copyless restriction. A copyless register update can be stored by a streaming string transducer like this: \mypicc{37} In general, to store a copyless register update we need a bounded number of bits to store the tree structure of the update plus \begin{align*} 2 \cdot \text{(number of registers in $\red g$)} \end{align*} registers to store the output words used in the update. To store a transformation forest \begin{align*} t \in (\text{register updates of $\red g$})^{[\text{states of $\blue f$}]}. \end{align*} we use a bounded number of bits to store the structure of the forest and its labelling by states of $\blue f$, plus \begin{align*} \underbrace{2 \cdot \text{(number of registers in $\red g$)}}_{\substack{\text{registers to store}\\ \text{a register update}}} \cdot \underbrace{2 \cdot \text{(states in $\blue f$)}}_{\substack{\text{number of edges in}\\ \text{a transformation forest}}} \end{align*} registers to store the register updates. The following claim says that transformation forests can be updated in a copyless way. \begin{claim}\label{claim:represent-transformation} Fix a transformation forest \begin{align*} s \in (\text{register updates of $\red g$})^{[\text{states of $\blue f$}]}. \end{align*} Then the function \begin{align*} t \in (\text{register updates of $\red g$})^{[\text{states of $\blue f$}]} \quad \mapsto \quad ts \in (\text{register updates of $\red g$})^{[\text{states of $\blue f$}]} \end{align*} can be done using a copyless register update. \end{claim} \begin{proof} Almost by definition, copyless register updates can be composed using a copyless register update. The same is true when composing transformation forests $ts$, because each label from $t$ and each label from $s$ is used at most once in the composition. In fact, copyless register updates can be seen as a special case of transformation forests, see Exercise~\ref{zad:sst-transformation-forest}. \end{proof} \paragraph*{The automaton.} Before describing the automaton, let us introduce some notation that will be used in its definition and correctness proof. Let $\blue q$ be a state of $\blue f$ and let $\red p$ be a state of $\red g$. Define $\blue{f_q}$ to be the right-to-left sequential function obtained from $\blue f$ by changing the initial state to $\blue q$ and define $[\red p, w, \blue q]$ to be the run of $\red g$ -- viewed as a sequence of transitions -- which begins in state $\red p$ and reads the word $\blue {f_q}(w)$. We have the following equality, which is obtained by unravelling the definitions: \begin{align}\label{eq:sst-bracket-comp} [\red p, w a, \blue q] = [\red p, w, a \blue q] \cdot [\red p (\blue{f_q}(a)), a, \blue q] \qquad \text{for every $w \in \Sigma^*$ and $a \in \Sigma$}. \end{align} In the above, we write $\_\blue q$ and $\red p\_$ for the state transformations of the automata underlying $\blue f$ and $\red g$. Equipped with the above notation, we are ready to define the streaming string transducer recognising the composition $\red g \circ \blue f$. After reading an input word $w \in \Sigma^*$, the transducer will store a transformation forest \begin{align*} t_w \in (\text{register updates of $\red g$})^{[\text{states of $\blue f$}]} \end{align*} whose intuitive meaning was described at the beginning of the proof. The transformation forest $t_w$ is stored as described before Claim~\ref{claim:represent-transformation}, and it satisfies the following invariant: \begin{enumerate} \item[(*)] Let $\blue q$ be a state of $\blue f$ and let $\pi$ be the unique root-to-leaf path in $t_w$ that ends in a leaf with label $\blue q$. Then the composition of register updates labelling $\pi$ is the same as the register update done by the run $[\text{initial state of $\red g$}, w, \blue q]$. \end{enumerate} To update its configuration, the transducer will also store in its finite state space the function $\delta_w$ defined by \begin{align*} \blue q \in \text{states of $\blue f$} \quad \mapsto \quad \text{target state of the run $[\text{initial state of $\red g$}, w, \blue q]$} \end{align*} Using~\eqref{eq:sst-bracket-comp}, it is not hard to see how $\delta_{wa}$ can be computed from $\delta_{w}$ and an input letter $a$. It remains to show how to update the transformation forest $t_w$. Initially, $t_\varepsilon$ is a forest with no edges and one leaf per state of $\blue f$, like this\mypicc{70}and therefore the invariant (*) is satisfied because $\pi$ is the empty path which yields an identity register update. When reading a letter $a$, the transformation forest is updated as follows. The new transformation forest $t_{wa}$ is defined to be the composition -- in the monoid of transformation forests -- of $t_w$ with the following transformation forest:\mypicc{69} Using the equality~\eqref{eq:sst-bracket-comp}, it is not hard to check that $t_{wa}$ satisfies the invariant. Furthermore, the update can be done while preserving the copyless discipline, by Claim~\ref{claim:represent-transformation}. It remains to define the output function so that the automaton recognises the composition $\red g \circ \blue f$. By the invariant, once the automaton has finished processing an input $w$, by looking at the transformation forest $t_w$ we can recover the register update $\tau$ that is done by the run of $\red{g}$ on $\blue f(w)$, i.e.~the run \begin{align*} [\text{initial state of $\red g$},\ w, \text{ initial state of $\blue f$}]. \end{align*} To get the output of $\red g \circ \blue f$ on $w$, it remains to apply $\tau$ to the empty register valuation, and finally apply the output function of $\red g$ to the resulting register valuation. All of this can be done using the register representation of the transformation forest $t_w$. \end{proof}
import { expect } from 'chai'; import Region from '../../database/objects/region.db'; import dbSingleton from '../../database/dbSingleton'; import regionTableResource from '../resources/region.db.resource'; describe('Region table', function () { let table: Region; let createdRegion: Model.Region; before(() => { table = dbSingleton.get().region; }); describe('Region details', function () { let regions: Api.Region.Res.Get[]; before(async () => { regions = await table.get(); }); it('should get a list of regions', function () { expect(regions).to.exist; expect(regions).to.be.a('array').with.length.greaterThan(0); }); it('should have the correct columns', function () { let region = regions[0]; expect(region).to.haveOwnProperty('id'); expect(region).to.haveOwnProperty('name'); }); }); describe('Add region', function () { it('should add the region to the table', async function () { const result = await table.create({ name: regionTableResource.regionToAdd }); expect(result.name).to.equal(regionTableResource.regionToAdd); createdRegion = result; }); }); describe('Edit region', async function () { it('should update a region', async function () { const result = await table.update(createdRegion.id, { name: regionTableResource.regionToUpdate }); expect(result.id).to.equal(createdRegion.id); expect(result.name).to.equal(regionTableResource.regionToUpdate); createdRegion = result; }); }); after(async function () { await table.deleteForTestOnly(createdRegion.id); }); });
from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, password, **extra_fields): """ Create and save a User with the given email and password. """ user = self.model(**extra_fields) if not password: user.set_password(None) user.save() return user user.set_password(password) user.save() return user def create_superuser(self, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(password, **extra_fields)
<?php namespace App\Http\Controllers\Admin; use App\Http\Requests\EquipmentModRequest; use Backpack\CRUD\app\Http\Controllers\CrudController; /** * Class EquipmentModCrudController. * * @property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud */ class EquipmentModCrudController extends CrudController { use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation; use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation; use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation; use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation; use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation; public function setup() { $this->crud->setModel(\App\EquipmentMod::class); $this->crud->setRoute(config('backpack.base.route_prefix').'/equipment-mod'); $this->crud->setEntityNameStrings('equipment mod', 'equipment mods'); } protected function setupListOperation() { $this->crud->addColumns(['mod_name']); // make these the only columns in the table $this->crud->addColumn([ 'name' => 'character', // The db column name 'label' => 'Character', // Table column heading 'type' => 'relationship', 'entity' => 'character', // the method that defines the relationship in your Model 'attribute' => 'name', // foreign key attribute that is shown to user 'model' => App\Character::class, // foreign key model 'searchLogic' => function ($query, $column, $searchTerm) { $query->orWhereHas('character', function ($q) use ($searchTerm) { $q->where('name', 'like', '%'.$searchTerm.'%'); }); }, ]); $this->crud->addColumn([ 'name' => 'equipment', // The db column name 'label' => 'Equipment', // Table column heading 'type' => 'relationship', 'entity' => 'equipment', // the method that defines the relationship in your Model 'attribute' => 'name', // foreign key attribute that is shown to user 'model' => App\Equipment::class, // foreign key model 'searchLogic' => function ($query, $column, $searchTerm) { $query->orWhereHas('equipment', function ($q) use ($searchTerm) { $q->where('name', 'like', '%'.$searchTerm.'%'); }); }, ]); $this->crud->addColumns(['mod_tier', 'mod_index']); $this->crud->addFilter([ 'type' => 'dropdown', 'name' => 'class', 'label' => 'Class', ], [ 1 => 'Engineer', 2 => 'Scout', 3 => 'Driller', 4 => 'Gunner', ], function ($value) { // if the filter is active $this->crud->addClause('where', 'character_id', $value); }); $this->crud->addFilter([ 'type' => 'dropdown', 'name' => 'equipment', 'label' => 'Equipment', ], [ 1 => 'Reinforced Power Drills', 2 => 'Satchel Charge', 3 => 'Platform Gun', 4 => 'LMG Gun Platform', 5 => 'Zipline Launcher', 6 => 'Shield Generator', 7 => 'Grappling Hook', 8 => 'Flare Gun', 9 => 'Engineering Suit', 10 => 'Light Scouting Suit', 11 => 'Heavy Drill Suit', 12 => 'Reinforced Impact Suit', ], function ($value) { // if the filter is active $this->crud->addClause('where', 'equipment_id', $value); }); } protected function setupCreateOperation() { $this->crud->setValidation(EquipmentModRequest::class); $this->crud->addField([ 'name' => 'mod_name', 'label' => 'Mod Name', 'type' => 'text', 'tab' => 'Base Info', ]); $this->crud->addField([ 'type' => 'select', 'name' => 'character_id', // the relationship name in your Model 'entity' => 'character', // the relationship name in your Model 'attribute' => 'name', // attribute on Article that is shown to admin 'model' => \App\Character::class, 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'equipment_id', // The db column name 'label' => 'Equipment', // Table column heading 'type' => 'relationship', 'entity' => 'equipment', // the method that defines the relationship in your Model 'attribute' => 'name', // foreign key attribute that is shown to user 'model' => \App\Equipment::class, // foreign key model 'tab' => 'Base Info', ]); $this->crud->addField([ // select_from_array 'name' => 'mod_tier', 'label' => 'Mod Tier', 'type' => 'select_from_array', 'options' => [1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5], 'allows_null' => false, 'default' => '', 'tab' => 'Base Info', ]); $this->crud->addField([ // select_from_array 'name' => 'mod_index', 'label' => 'Mod Index', 'type' => 'select_from_array', 'options' => ['A' => 'A', 'B' => 'B', 'C' => 'C'], 'allows_null' => false, 'default' => '', 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'description', 'label' => 'Text Description', 'type' => 'textarea', 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'icon', 'label' => 'Icon', 'type' => 'text', 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'mod_type', 'label' => 'Mod Type', 'type' => 'text', 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'credits_cost', 'label' => 'Credits Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'magnite_cost', 'label' => 'Magnite Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'bismor_cost', 'label' => 'Bismor Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'umanite_cost', 'label' => 'Umanite Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'croppa_cost', 'label' => 'Croppa Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'enor_pearl_cost', 'label' => 'Enor Pearl Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'jadiz_cost', 'label' => 'Jadiz Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'json_stats', 'label' => 'JSON Stats', 'type' => 'textarea', 'tab' => 'Stats', ]); } protected function setupUpdateOperation() { $this->crud->addField([ 'name' => 'mod_name', 'label' => 'Mod Name', 'type' => 'text', 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'id', 'label' => 'id', 'type' => 'text', 'attributes' => [ 'readonly' => 'readonly', ], 'tab' => 'Base Info', ]); $this->crud->addField([ 'type' => 'select', 'name' => 'character_id', // the relationship name in your Model 'entity' => 'character', // the relationship name in your Model 'attribute' => 'name', // attribute on Article that is shown to admin 'model' => \App\Character::class, 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'equipment_id', // The db column name 'label' => 'Equipment', // Table column heading 'type' => 'relationship', 'entity' => 'equipment', // the method that defines the relationship in your Model 'attribute' => 'name', // foreign key attribute that is shown to user 'model' => \App\Equipment::class, // foreign key model 'tab' => 'Base Info', ]); $this->crud->addField([ // select_from_array 'name' => 'mod_tier', 'label' => 'Mod Tier', 'type' => 'select_from_array', 'options' => [1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5], 'allows_null' => false, 'default' => '', 'tab' => 'Base Info', ]); $this->crud->addField([ // select_from_array 'name' => 'mod_index', 'label' => 'Mod Index', 'type' => 'select_from_array', 'options' => ['A' => 'A', 'B' => 'B', 'C' => 'C'], 'allows_null' => false, 'default' => '', 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'description', 'label' => 'Text Description', 'type' => 'textarea', 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'icon', 'label' => 'Icon', 'type' => 'text', 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'mod_type', 'label' => 'Mod Type', 'type' => 'text', 'tab' => 'Base Info', ]); $this->crud->addField([ 'name' => 'credits_cost', 'label' => 'Credits Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'magnite_cost', 'label' => 'Magnite Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'bismor_cost', 'label' => 'Bismor Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'umanite_cost', 'label' => 'Umanite Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'croppa_cost', 'label' => 'Croppa Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'enor_pearl_cost', 'label' => 'Enor Pearl Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'jadiz_cost', 'label' => 'Jadiz Cost', 'type' => 'number', 'tab' => 'Cost', ]); $this->crud->addField([ 'name' => 'json_stats', 'label' => 'JSON Stats', 'type' => 'textarea', 'tab' => 'Stats', ]); } }
# 1 - ็ฝ‘็ปœๅฑ‚ๆ•ฐ้—ฎ้ข˜ - ็ฝ‘็ปœๅฑ‚ๆ•ฐ๏ผš่พ“ๅ…ฅๅฑ‚ + ้š่—ๅฑ‚ + ่พ“ๅ‡บๅฑ‚ - ๅ…จ่ฟžๆŽฅๅฑ‚ๆ•ฐ๏ผšไป…่ฎก็ฎ—ๅ…จ่ฟžๆŽฅๅฑ‚ - ReLUๅฑ‚ๆ•ฐ๏ผšๅ…จ่ฟžๆŽฅๅฑ‚ๆ•ฐ - 1๏ผˆๆœ€ๅŽไธ€ไธชไธชๅ…จ่ฟžๆŽฅๅฑ‚ไธๅธฆReLU๏ผ‰ - ไพ‹ๅฆ‚๏ผš1ๅฑ‚่พ“ๅ…ฅๅฑ‚ + 2ๅฑ‚้š่—ๅฑ‚ + 1ๅฑ‚่พ“ๅ‡บๅฑ‚ใ€‚็ฝ‘็ปœๅฑ‚ๆ•ฐ=4๏ผŒๅ…จ่ฟžๆŽฅๅฑ‚ๆ•ฐ=3๏ผŒReLUๅฑ‚ๆ•ฐ=2 # 2 - ๅˆ›ๅปบ็ฝ‘็ปœๅฑ‚ ๅˆ›ๅปบๅ…จ่ฟžๆŽฅๅฑ‚๏ผš ``` import torch.nn as nn fc = nn.Linear(ๅทฆ่พน่Š‚็‚นๆ•ฐ, ๅณ่พน่Š‚็‚นๆ•ฐ) ``` ่ฟ›่กŒ่ฟ็ฎ—๏ผš ``` y = fc(x) ``` ่ฟ›่กŒๅธฆๆœ‰ReLU็š„ๅ…จ่ฟžๆŽฅ่ฎก็ฎ—๏ผš ``` relu = nn.ReLU() # Create ReLU Instance, remember () x = fc(x) y = relu(x) # or y = nn.ReLU()(x), remember double () ``` ๅˆ›ๅปบ็ฝ‘็ปœ็ฑป๏ผš ``` class Net(nn.Module): def __init__(self): super(Net, self).__init__() # ๅฎšไน‰ๅ…จ่ฟžๆŽฅๅฑ‚ def forward(self, x): # ่ฟ›่กŒๅธฆๆœ‰ReLU็š„ๅ…จ่ฟžๆŽฅ่ฎก็ฎ— return x ``` ๅˆ›ๅปบ็ฝ‘็ปœๅฎžไพ‹๏ผš ``` net = Net() ``` # 3 - ่ฎญ็ปƒ ## ็”Ÿๆˆๆ•ฐๆฎ้›† ``` torch.randn(x, y) ``` randnๆœ‰ไธคไธชๅ‚ๆ•ฐ๏ผŒ่ฏดๆ˜Žไผš็”Ÿๆˆไธ€ไธชไบŒ็ปดๅผ ้‡ใ€‚ ``` x_train = torch.randn(10, 5) y_train = torch.randn(10, 4) ``` ่ฟ™้‡Œ๏ผŒ่พ“ๅ…ฅๅฑ‚5ไธช่Š‚็‚น๏ผŒ่พ“ๅ‡บๅฑ‚4ไธช่Š‚็‚นใ€‚ 10ๆ˜ฏไป€ไนˆๆ„ๆ€๏ผŸๆ˜ฏๆ•ฐๆฎ้›†ๅฎน้‡ไธบ10็š„ๆ„ๆ€ใ€‚ไธ€ๅฎš่ฆๆŠŠxๅ’Œy็š„็ฌฌไธ€็ปดๅบฆไฝœไธบๆ•ฐๆฎ้›†็š„ไธชๆ•ฐ๏ผˆๅฎน้‡๏ผ‰๏ผŒ่ฟ™ๆ ท`pytorch`็š„`nn.MSELoss`ๅ’Œ`optim.SGD`ๆ‰ไผšๆ”ฏๆŒใ€‚ ## ๅฎšไน‰ๆŸๅคฑๅ‡ฝๆ•ฐๅ’Œไผ˜ๅŒ–ๅ™จ ``` import torch.nn as nn import torch.optim as optim criterion = nn.MSELoss() optimizer = optim.SGD(net.parameters(), lr=0.01) ``` criterionๅฎž่ดจๅฐฑๆ˜ฏLossๅ‡ฝๆ•ฐ๏ผŒoptimizerๅฎž่ดจๅฐฑๆ˜ฏ่‡ชๅŠจ็š„ๆขฏๅบฆไธ‹้™ๆฑ‚ๅฏผๅ™จใ€‚`net.parameters()`ไผš่ฟ”ๅ›žๆƒ้‡็Ÿฉ้˜ต็š„่ฟญไปฃๅ™จใ€‚ ## ่ฎญ็ปƒ่ฟญไปฃ็š„้€š็”จๆ€่ทฏ ็”จ็ฝ‘็ปœ็คบไพ‹่ฟ›่กŒ้ข„ๆต‹๏ผš ``` y_hat = net(x_train) ``` ่ฎก็ฎ—ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผš ``` loss = criterion(y_hat, y_train) ``` ๅๅ‘ไผ ๆ’ญ้€š็”จๅ†™ๆณ•๏ผš ``` optimizer.zero_grad() loss.backward() optimizer.step() ``` ่Žทๅ–Loss็š„ๆ ‡้‡ๅ€ผ๏ผš ``` loss.item() ``` ่ฟญไปฃ็š„ไปฃ็ ๏ผš ```python for epoch in range(1000): # ๅ‰ๅ‘ไผ ๆ’ญ y_hat = net(x_train) loss = criterion(y_hat, y_train) # ๅๅ‘ไผ ๆ’ญ optimizer.zero_grad() loss.backward() optimizer.step() if epoch % 100 == 0: print('Epoch [%s/%s], Loss: %s' % (epoch + 1, 1000, loss.item())) # loss.item()ๆ˜ฏ็”จๆฅ่Žทๅ–ๅผ ้‡lossไธญ็š„ๅ•ไธชๆ•ฐๅ€ผ็š„ๅ‡ฝๆ•ฐใ€‚ ``` ๆ€่ทฏ๏ผš - ็”จ็ฝ‘็ปœๅšไธ€ๆฌก้ข„ๆต‹ - ่ฎก็ฎ—Lossๅ‡ฝๆ•ฐ - ๆธ…็ฉบๆขฏๅบฆ - ๅๅ‘ไผ ๆ’ญ - ๆขฏๅบฆไธ‹้™ # 4 - ไฝฟ็”จ่ฎญ็ปƒๆˆๆžœ ๅˆ›ๅปบๆต‹่ฏ•้›†๏ผš ``` x_test = torch.randn(5, 5) ``` ไธๅธฆๆขฏๅบฆ๏ผˆๅŠ ๅฟซ่ฟ็ฎ—้€Ÿๅบฆใ€้˜ฒๆญข็ ดๅๆจกๅž‹๏ผ‰ๅœฐไฝฟ็”จๆจกๅž‹่ฟ›่กŒ้ข„ๆต‹๏ผš ``` with torch.no_grad(): ``` ็ป“ๆžœ๏ผš ``` with torch.no_grad(): output = net(x_test) print(output) ``` # 5 - ๆŸๅคฑๅ‡ฝๆ•ฐๅ’Œไผ˜ๅŒ–ๅ™จ็š„้€‰ๆ‹ฉ ```python criterion = nn.MSELoss() # ้€‚็”จไบŽๅ›žๅฝ’ไปปๅŠก criterion = nn.CrossEntropyLoss() # ้€‚็”จไบŽๅˆ†็ฑปไปปๅŠก ``` ```python optimizer = optim.SGD(net.parameters(), lr=0.01) # Adamๆ•ˆๆžœไธๅฅฝๆ—ถ๏ผŒๅฐ่ฏ•ไฝฟ็”จ optimizer = optim.Adam(net.parameters(), lr=0.01) # ๆ•ˆๆžœๆ›ดๅฅฝ๏ผŒๆ›ด้€š็”จ ```
# Create GKE cluster using Terraform - Nginx Ingress & TLS - OIDC Workload Identity ## Create GKE cluster using Terraform ```bash # Authenticate with your GCP account gcloud auth login # List available GCP projects gcloud projects list # Set your desired GCP project gcloud config set project <project_id> # Initialize Terraform terraform init # Apply Terraform configuration to create GKE cluster terraform apply # Configure `kubectl` to connect to the newly created GKE cluster gcloud container clusters get-credentials <cluster_name> --region <region> --project <project_id> ``` ## Deploy Ingress Controller ```bash # Install Nginx Ingress Controller kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.0.0/deploy/static/provider/cloud/deploy.yaml ``` ## Create Public and Private load balancers ```bash # Apply example service configuration kubectl apply -f k8s/1-example # Get service details kubectl get svc ``` ## Auto-Scaling ```bash # Check current nodes kubectl get nodes # Apply example deployment configuration with autoscaling kubectl apply -f k8s/2-example # Monitor pods kubectl get pods kubectl describe pods nginx-v2-<pod_id> # Monitor nodes for autoscaling kubectl get nodes ``` ## Create an Ingress using Nginx Ingress ```bash # Check Nginx Ingress Controller service kubectl get svc -n ingress # Apply example Ingress configuration kubectl apply -f k8s/3-example # Monitor pods kubectl get pods # Monitor Ingress kubectl get ing # Test Ingress curl --resolve "echo.eternalamit5.pvt:80:<ingress_ip>" http://echo.eternalamit5.pvt/ ``` ## Secure the Ingress with TLS & Cert-manager ```bash k# Apply Cert-manager kubectl apply -f k8s/4-example # Monitor pods kubectl get pods # Monitor Ingress and Certificates kubectl get ing kubectl get Certificate # Describe Certificate resources for details kubectl describe Certificate kubectl describe CertificateRequest kubectl describe Order kubectl describe Challenge # Verify Ingress and Certificate kubectl get ing kubectl get Certificate # Verify DNS resolution dig echo.eternalamit5.com ``` ## Test Workload Identity ```bash # Apply example workload identity configuration kubectl apply -f k8s/5-example # Check pods in dev namespace kubectl get pods -n dev # Enter Azure CLI pod kubectl exec -it azure-cli-<pod_id> -n dev -- sh # Authenticate with Azure CLI using federated token az login --federated-token "$(cat $AZURE_FEDERATED_TOKEN_FILE)" --service-principal -u $AZURE_CLIENT_ID -t $AZURE_TENANT_ID # List storage blobs (example) az storage blob list -c test --account-name <storage_account_name> # Clean up workload identity resources kubectl delete -f k8s/5-example ```
package org.team4.view.manager.manage.book; import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.TableColumn; import org.team4.maintaindb.MaintainDatabase; import org.team4.model.items.Item; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JLabel; import java.awt.Font; import java.util.ArrayList; import javax.swing.JScrollPane; import javax.swing.JButton; public class ManageBookPanel extends JPanel { private static final long serialVersionUID = 1L; private BookViewTableModel bookViewTableModel; private ArrayList<Item> allBooks = new ArrayList<>(); private JPanel panel; private JButton updateButton; /** * Create the panel. */ public ManageBookPanel() { allBooks = MaintainDatabase.getInstance().getBookDatabase().getAllBooks(); initComponents(); } private void initComponents() { setBounds(100, 100, 976, 627); setLayout(new BorderLayout()); panel = new JPanel(); panel.setLayout(null); add(panel, BorderLayout.CENTER); JLabel titleLabel = new JLabel("Manage Books"); titleLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 18)); titleLabel.setBounds(422, 23, 132, 22); panel.add(titleLabel); addScrollPane(); } private void addScrollPane() { bookViewTableModel = new BookViewTableModel(this.allBooks); JTable bookTable = new JTable(bookViewTableModel); TableColumn rentColumn = bookTable.getColumnModel().getColumn(6); JComboBox<Boolean> comboBox = new JComboBox<>(new Boolean[]{true, false}); rentColumn.setCellEditor(new DefaultCellEditor(comboBox)); JScrollPane scrollPane = new JScrollPane(bookTable); scrollPane.setBounds(30, 58, 917, 527); panel.add(scrollPane); updateButton = new JButton("Update"); updateButton.setBounds(823, 592, 117, 29); panel.add(updateButton); } public JButton getUpdateButton() { return this.updateButton; } public void updateSelectedBooks() { int rowCount = bookViewTableModel.getRowCount(); for (int i = 0; i < rowCount; i++) { Boolean rentableStatus = (Boolean) bookViewTableModel.getValueAt(i, 6); Item book = allBooks.get(i); book.setRentable(rentableStatus); } // Now, update the CSV with changed fields try { MaintainDatabase.getInstance().getBookDatabase().update(); } catch (Exception ex) { ex.printStackTrace(); } } }
#ifndef CARDWIDGET_H #define CARDWIDGET_H #include <QLabel> #include <QPixmap> #include "clienttypes.h" #include "OverlayWidget.h" #include "Logging.h" QT_BEGIN_NAMESPACE class QResizeEvent; QT_END_NAMESPACE class ImageLoaderFactory; class ImageLoader; class CardWidget_Overlay; class CardWidget : public QLabel { Q_OBJECT public: explicit CardWidget( const CardDataSharedPtr& cardDataSharedPtr, ImageLoaderFactory* imageLoaderFactory, const QSize& defaultSize, const Logging::Config& loggingConfig = Logging::Config(), QWidget* parent = 0 ); CardDataSharedPtr getCardData() const { return mCardDataSharedPtr; } void setDefaultSize( const QSize& size ); void setZoomFactor( float zoomFactor ); void loadImage(); void setPreselectable( bool enabled ); bool isPreselectable() const { return mPreselectable; } void setPreselected( bool enabled ); bool isPreselected() const { return mPreselected; } void setDimmed( bool enabled ); bool isDimmed() const { return mDimmed; } void setHighlighted( bool enabled ); bool isHighlighted() const { return mHighlighted; } void setSelectedByOpponent( bool enabled ); bool isSelectedByOpponent() const { return mSelectedByOpponent; } void setSelectedByPlayer( bool enabled ); bool isSelectedByPlayer() const { return mSelectedByPlayer; } // Resets all above traits to false. void resetTraits(); signals: void preselectRequested(); void selectRequested(); void moveRequested(); protected: virtual void mousePressEvent( QMouseEvent* event ) override; virtual void mouseDoubleClickEvent( QMouseEvent* event ) override; virtual void mouseMoveEvent( QMouseEvent* event ) override; virtual void enterEvent( QEvent* event ) override; virtual void leaveEvent( QEvent* event ) override; virtual bool event( QEvent* event ) override; private slots: void handleImageLoaded( int multiverseId, const QImage &image ); private: void updateScaling(); void updateOverlay(); CardDataSharedPtr mCardDataSharedPtr; ImageLoaderFactory* const mImageLoaderFactory; ImageLoader* mImageLoader; QSize mDefaultSize; float mZoomFactor; // A copy of the original-sized pixmap obtained from ImageLoader. QPixmap mPixmap; // The string for the default tooltip. QString mToolTipStr; bool mPreselectable; bool mPreselected; bool mDimmed; bool mHighlighted; bool mSelectedByOpponent; bool mSelectedByPlayer; bool mMouseWithin; CardWidget_Overlay* mOverlay; Logging::Config mLoggingConfig; std::shared_ptr<spdlog::logger> mLogger; }; // This would be a nested class within CardWidget but Qt doesn't allow // nested QObject classes. class CardWidget_Overlay : public OverlayWidget { Q_OBJECT public: CardWidget_Overlay( CardWidget* parent ); bool inPreselectRegion( const QPoint& pos ) const; protected: virtual void resizeEvent( QResizeEvent* resizeEvent ) override; virtual void paintEvent( QPaintEvent* ) override; private: // Pointer to parent CardWidget where properties can be queried. const CardWidget * const mParentCardWidget; QRect mPreselectRect; // Cached painting calculations. QRectF mPreselectRectF; QRadialGradient mBackgroundRadialGradient; QRectF mIconRectF; QRectF mPinTopRectF; QRectF mPinHandleRectF; QPainterPath mPinBasePath; QPainterPath mPinPath; QRectF mBannerRectF; }; #endif // CARDWIDGET_H
import { NgModule } from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { RouterModule, Routes } from "@angular/router"; import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http"; import { AppComponent } from "./app.component"; import { LoginComponent } from "./login/login.component"; import { RegisterComponent } from "./register/register.component"; import { Protected1Component } from "./protected1/protected1.component"; import { Protected2Component } from "./protected2/protected2.component"; import { FormsModule } from "@angular/forms"; import { AuthInterceptor } from "./interceptors/auth.interceptor"; import { AuthService } from "./services/auth.service"; const routes: Routes = [ { path: "login", component: LoginComponent }, { path: "register", component: RegisterComponent }, { path: "protected1", component: Protected1Component }, { path: "protected2", component: Protected2Component }, ]; @NgModule({ declarations: [ AppComponent, LoginComponent, RegisterComponent, Protected1Component, Protected2Component, ], imports: [ BrowserModule, FormsModule, /* We have to implement the useHash option becoz we have our api from our express application and then we the routes from the angular application, we don't want them to conflict */ RouterModule.forRoot(routes, { useHash: true }), HttpClientModule, ], providers: [ AuthService, { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }, ], bootstrap: [AppComponent], }) export class AppModule {}
(* evidence.ml: Evidence calculations by various methods. Copyright (C) 2011 Will M. Farr <w-farr@northwestern.edu> 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 <http://www.gnu.org/licenses/>. *) (** Various algorithms for computing the Bayesian evidence from an MCMC sample. *) (** Input type for the [Make] functor. *) module type MCMC_OUT = sig (** Parameters in the MCMC. *) type params (** [to_coords params] returns a float array representing the parameters. *) val to_coords : params -> float array end (** Output type for the [Make] functor. *) module type EVIDENCE = sig (** Parameters. *) type params (** MCMC samples. *) type sample = params Mcmc.mcmc_sample (** Embedded kD tree. *) module Kd : (Kd_tree.KD_TREE with type o = sample) (** Construct a kD tree. *) val kd_tree_of_samples : sample array -> float array -> float array -> Kd.tree (** Directly integrate evidence within the region enclosed by the given samples. *) val evidence_direct : ?n : int -> sample array -> float (** Directly integrate the evidence using the previously-created tree of samples. *) val evidence_direct_tree : ?n : int -> Kd.tree -> float (** Integrate evidence using harmonic mean. *) val evidence_harmonic_mean : sample array -> float (** Integrate evidence using Lebesque integral of 1/L, within the rectangular parameter region between the given arrays. *) val evidence_lebesgue : ?n : int -> ?eps : float -> sample array -> float end module Make(MO : MCMC_OUT) : EVIDENCE with type params = MO.params = struct type params = MO.params type sample = params Mcmc.mcmc_sample module Kd = Kd_tree.Make( struct type t = sample let coord ({Mcmc.value = v} : t) = MO.to_coords v end) let kd_tree_of_samples samps = Kd.tree_of_objects (Array.to_list samps) let rec length_at_least n = function | [] -> n = 0 | _ :: xs -> (n <= 0) || (length_at_least (n-1) xs) let rec depth = function | Kd.Empty -> 0 | Kd.Cell(_, _, _, left, right) -> 1 + (max (depth left) (depth right)) let rec collect_subvolumes nmax = function | Kd.Empty -> [] | Kd.Cell(objs, _, _, left, right) as c -> if not (length_at_least nmax objs) then [c] else List.rev_append (collect_subvolumes nmax left) (collect_subvolumes nmax right) let log_likelihood {Mcmc.like_prior = {Mcmc.log_likelihood = ll}} = ll let log_prior {Mcmc.like_prior = {Mcmc.log_prior = lp}} = lp let log_posterior s = (log_likelihood s) +. (log_prior s) let posterior s = exp (log_posterior s) let compare_inverse_like s1 s2 = Pervasives.compare (~-.(log_likelihood s1)) (~-.(log_likelihood s2)) let evidence_harmonic_mean samples = let linv = ref 0.0 and n = Array.length samples in for i = 0 to n - 1 do linv := !linv +. 1.0/.(exp (log_likelihood samples.(i))) done; (float_of_int n)/.(!linv) let median_sample (f : sample -> float) samples = let n = List.length samples and ssamp = List.fast_sort (fun s1 s2 -> Pervasives.compare (f s1) (f s2)) samples in if n mod 2 = 0 then 0.5*.((f (List.nth ssamp (n/2 - 1))) +. (f (List.nth ssamp (n/2)))) else f (List.nth ssamp (n/2)) let mean_sample (f : sample -> float) samples = let (n, sum) = List.fold_left (fun (n,sum) samp -> (n+1, sum +. (f samp))) (0, 0.0) samples in sum /. (float_of_int n) let compare_samples s1 s2 = let {Mcmc.value = v1} = s1 and {Mcmc.value = v2} = s2 in Pervasives.compare (MO.to_coords v1) (MO.to_coords v2) let rev_remove_dups comp l = let rec rev_remove_dups_loop removed remaining = match remaining with | [] -> removed | [x] -> x :: removed | x :: (y :: _ as ys) -> if comp x y = 0 then rev_remove_dups_loop removed ys else rev_remove_dups_loop (x :: removed) ys in rev_remove_dups_loop [] l let array_to_list_remove_dups samples = let l = Array.to_list samples in let lsort = List.sort compare_samples l in rev_remove_dups compare_samples lsort let evidence_direct_tree ?(n = 64) tree = let sub_vs = collect_subvolumes n tree in List.fold_left (fun integral c -> match c with | Kd.Cell(objs, _, _, _, _) -> let (low,high) = Kd.bounds_of_objects objs in let vol = Kd.bounds_volume low high and post = mean_sample posterior objs in integral +. vol*.post | _ -> raise (Invalid_argument "evidence_direct: bad cell in integral accumulation")) 0.0 sub_vs let evidence_direct ?(n = 64) samples = let lsamples = array_to_list_remove_dups samples in let (low,high) = Kd.bounds_of_objects lsamples in evidence_direct_tree ~n:n (Kd.tree_of_objects lsamples low high) let collect_samples_up_to_eps eps samps = let rec collect_samples_loop collected_samples = function | [] -> List.rev collected_samples | [x] -> List.rev (x :: collected_samples) | x :: ((y :: _) as ys) -> let ilx = exp (~-.(log_likelihood x)) and ily = exp (~-.(log_likelihood y)) in let delta = ily -. ilx in assert(delta >= 0.0); if delta > eps then List.rev (x :: collected_samples) else collect_samples_loop (x :: collected_samples) ys in collect_samples_loop [] (List.fast_sort compare_inverse_like (Array.to_list samps)) let mean_inv_like samps = let tot_il = List.fold_left (fun il samp -> il +. (exp (~-.(log_likelihood samp)))) 0.0 samps in tot_il /. (float_of_int (List.length samps)) let remove_dups_rev l = let rec remove_dups_loop removed = function | [] -> removed | [x] -> x :: removed | x :: (y :: _ as ys) -> if log_likelihood x = log_likelihood y then remove_dups_loop removed ys else remove_dups_loop (x :: removed) ys in remove_dups_loop [] l let evidence_lebesgue ?(n = 64) ?(eps = 0.1) samples = let samples = collect_samples_up_to_eps eps samples in let mean_il = mean_inv_like samples in let samples = remove_dups_rev samples in let (low,high) = Kd.bounds_of_objects samples in let t = Kd.tree_of_objects samples low high in let vols = collect_subvolumes n t in let prior_mass = List.fold_left (fun pm cell -> match cell with | Kd.Cell(objs, _, _, _, _) -> let (low,high) = Kd.bounds_of_objects objs in let vol = Kd.bounds_volume low high and prior = exp (median_sample log_prior objs) in pm +. prior*.vol | _ -> raise (Failure "prior_mass in evidence_lebesgue: bad cell")) 0.0 vols in prior_mass /. mean_il end
%(BEGIN_QUESTION) % Copyright 2010, Tony R. Kuphaldt, released under the Creative Commons Attribution License (v 1.0) % This means you may do almost anything with this work of mine, so long as you give me proper credit Read and outline the ``Use of Line Reactors'' section of the ``Variable-Speed Motor Controls'' chapter in your {\it Lessons In Industrial Instrumentation} textbook. Note the page numbers where important illustrations, photographs, equations, tables, and other relevant details are found. Prepare to thoughtfully discuss with your instructor and classmates the concepts and examples explored in this reading. \underbar{file i03841} %(END_QUESTION) %(BEGIN_ANSWER) %(END_ANSWER) %(BEGIN_NOTES) DC and AC motor drives alike produce lots of electrical noise due to the PWM switching of their power transistors. Fourier proved that any cyclic waveform is equivalent to a sum of harmonic frequencies, therefore motor drives produce harmonics on their power lines. These harmonics may cause transformer core heating, resonance with power-factor correction capacitors, and even conductor overheating in the case of three-phase systems where triplen harmonics (3rd, 6th, 9th, 12th) add in the neutral of Wye-connected systems and circulate in the phase elements of Delta-connected systems. \vskip 10pt Series inductors may be used as low-pass filters to keep harmonics contained to the VFD. Such line reactors may be placed in the drive's input conductors as well as on the drive's output conductors. Line reactors also help to limit fault currents in the event of short-circuited wiring! \vskip 20pt \vbox{\hrule \hbox{\strut \vrule{} {\bf Suggestions for Socratic discussion} \vrule} \hrule} \begin{itemize} \item{} Explain how reactors help mitigate problems caused by harmonic frequencies generated by motor drives. \item{} Explain why one might choose to install an input line reactor in a VFD system. What, specifically, is being protected by this reactor? \item{} Explain why one might choose to install an output line reactor in a VFD system. What, specifically, is being protected by this reactor? \item{} Will the presence of a line reactor affect a VFD's ability to {\it brake} the motor using DC injection? \item{} Will the presence of a line reactor affect a VFD's ability to {\it dynamically brake} the motor? \item{} Will the presence of a line reactor affect a VFD's ability to {\it regeneratively brake} the motor? \item{} Will the presence of a line reactor affect a VFD's ability to {\it plug} the motor? \item{} Explain what will happen to a VFD-controlled motor if one of the inductors in an input line reactor were to fail open. \item{} Explain what will happen to a VFD-controlled motor if one of the inductors in an output line reactor were to fail open. \end{itemize} %INDEX% Reading assignment: Lessons In Industrial Instrumentation, line reactors in motor speed control circuits %(END_NOTES)
import { Box, Button, Container, Image, HStack, Icon, Heading, } from "@chakra-ui/react"; import { useEffect, useState } from "react"; import { Link } from "react-scroll"; import pizza from "../../assets/images/favicon.png"; import { FiShoppingCart } from "react-icons/fi"; export default function Header() { const [backgroundColor, setBackgroundColor] = useState("transparent"); const pages = [ { name: "Home", path: "/", }, { name: "Menu", path: "menu", }, { name: "About", path: "about", }, { name: "Contact", path: "contact", }, ]; const handleScroll = () => { const scroll = window.scrollY; const headerHeight = document.getElementById("header").offsetHeight; scroll > headerHeight ? setBackgroundColor("linear(to-b, black, blackAlpha.300)") : setBackgroundColor("transparent"); }; useEffect(() => { window.addEventListener("scroll", handleScroll); }, [window.scrollY]); return ( <Box w="full" top={0} paddingY={5} id="header" as="header" position="fixed" zIndex="sticky" bgGradient={backgroundColor} transition="all 800ms ease" backdropFilter={backgroundColor === "transparent" ? "none" : "blur(7px)"} > <Container maxW="container.xl" id="header"> <HStack maxW="container.xl" justify="space-between"> <Link to="/" smooth={true}> <HStack spacing={3} cursor="pointer"> <Image src={pizza} alt="Logo" w="50" h="50" /> <Heading color="brand.primary" letterSpacing={1} fontSize='3xl' textShadow='dark-lg'> Terra Pizza </Heading> </HStack> </Link> <HStack spacing="4.5rem" as="nav" display={{ base: "none", lg: "flex" }} fontFamily="title" > {pages.map(({ name, path }) => ( <Button variant="unstyled" fontSize='lg' key={name} color={backgroundColor === 'transparent' ? '' : 'whiteAlpha.900'}> <Link to={path} duration={1250} smooth={true} spy={true} > {name} </Link> </Button> ))} </HStack> </HStack> </Container> </Box> ); }
import React, { useEffect, useState } from "react"; import BlogDetails from "../components/BlogDetails"; import BlogForms from "../components/BlogForms"; import { useThoughtsContext } from "../hooks/useBlogsContext"; const Home = () => { const { blogs, dispatch } = useThoughtsContext(); const [loading, setLoading] = useState(true); // Add loading state useEffect(() => { const fetchBlog = async () => { try { const response = await fetch( process.env.REACT_APP_API_URL + "/api/blogs" ); const json = await response.json(); if (response.ok) { dispatch({ type: "SET_BLOGS", payload: json }); } } catch (error) { console.error("An error occurred while fetching blogs"); } finally { setLoading(false); } }; fetchBlog(); }, []); return ( <div className="flex flex-col p-10 items-center"> <BlogForms /> <div className=""> {loading ? ( <p className="text-3xl m-10">Loading...</p> ) : ( blogs && blogs.map((blog) => <BlogDetails key={blog._id} blog={blog} />) )} </div> </div> ); }; export default Home;
import 'package:flutter/material.dart'; class ChartBar extends StatelessWidget { final String label; final double spentAmount; final double spentPercentage; ChartBar(this.label, this.spentAmount, this.spentPercentage); @override Widget build(BuildContext context) { return LayoutBuilder(builder: (context, constraints) { return Column( children: <Widget>[ Container( height: constraints.maxHeight * 0.15, child: FittedBox(child: Text('\$${spentAmount.toStringAsFixed(0)}')), ), SizedBox( height: constraints.maxHeight * 0.05, ), Container( height: constraints.maxHeight * 0.6, width: 10, child: Stack(children: <Widget>[ Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey, width: 1), color: Color.fromRGBO(220, 220, 220, 1), borderRadius: BorderRadius.circular(10))), FractionallySizedBox( heightFactor: spentPercentage, child: Container( decoration: BoxDecoration( color: Theme.of(context).primaryColor, borderRadius: BorderRadius.circular(10)))) ])), SizedBox( height: constraints.maxHeight * 0.05, ), Container( height: constraints.maxHeight * 0.15, child: FittedBox(child: Text(label)) ) ], ); }); } }
package vn.funix.fx22541.asm02.models; import java.util.ArrayList; import java.util.List; public class Customer extends User { protected final List<Account> accounts; public Customer(String name, String customerId) { super(name, customerId); this.accounts = new ArrayList<>(); } public boolean isCustomerPremium() { for (Account account : accounts ) { if (account.isAccountPremium()) { return true; } } return false; } public boolean isAccountExisted(Account newAccount) { return accounts.contains(newAccount); } public void addAccount(String accountNumber, double initialAmount) { if (!isAccountExisted(getAccountByAccountNumber(accountNumber))) { accounts.add(new Account(accountNumber, initialAmount)); } } public double getTotalBalanceAccount() { double totalBalance = 0; for (Account acc : accounts) { totalBalance += acc.getAccountBalance(); } return totalBalance; } public Account getAccountByAccountNumber(String accNo) { for (Account account : accounts) { if (account.getAccountNumber().equals(accNo)) { return account; } } return null; } public void displayInformation() { String premium = "Normal"; int order = 1; if (isCustomerPremium()) { premium = "Premium"; } System.out.println("+---------+-----------------------------------+--------+"); System.out.printf("%12s |%10s| %8s | %,18.2fฤ‘%n", getCustomerId(), getName().toUpperCase(), premium, getTotalBalanceAccount()); for (Account account : accounts) { System.out.printf("%d%11s | %8s %,28.2fฤ‘%n", order++, account.getAccountNumber(),"", account.getAccountBalance()); } } }
use anyhow::{bail, Context, Result}; use reqwest::header::{HeaderMap, ACCEPT, AUTHORIZATION}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum DomainRecordResponse { Ok { domain_record: DomainRecord }, Error { id: String, message: String }, } #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum DomainRecordsResponse { Ok { domain_records: Vec<DomainRecord>, links: serde_json::Value, meta: serde_json::Value, }, Error { id: String, message: String, }, } #[derive(Serialize, Deserialize, Debug)] pub struct DomainRecord { pub id: i64, pub name: String, pub data: String, pub ttl: i32, #[serde(rename = "type")] pub kind: String, } pub struct ApiClient { http: reqwest::Client, } impl ApiClient { pub fn new(token: &str) -> Self { let mut headers = HeaderMap::new(); headers.insert( ACCEPT, "application/json" .parse() .expect("Faile to set default Accept header"), ); headers.insert( AUTHORIZATION, format!("Bearer {token}") .parse() .expect("Failed to set default Authorization header"), ); Self { http: reqwest::Client::builder() .default_headers(headers) .build() .expect("Failed to build HTTP client"), } } pub async fn get_records( &self, domain: &str, per_page: Option<u16>, kind: Option<&str>, name: Option<&str>, ) -> Result<Vec<DomainRecord>> { let mut url = format!("https://api.digitalocean.com/v2/domains/{domain}/records"); let mut params = Vec::new(); if let Some(per_page) = per_page { params.push(format!("per_page={per_page}")); } if let Some(kind) = kind { params.push(format!("type={kind}")); } if let Some(name) = name { params.push(format!("name={name}")); } if !params.is_empty() { url.push('?'); url.push_str(&params.join("&")); } let response = self .http .get(url) .send() .await .context("Failed to send GET request (get_records)")? .text() .await .context("Failed to fetch GET response (get_records)")?; log::debug!("get_records: {response}"); let response = serde_json::from_str(&response) .context("Failed to parse GET response (get_records)")?; match response { DomainRecordsResponse::Ok { domain_records, .. } => Ok(domain_records), DomainRecordsResponse::Error { id, message } => bail!("{}: {}", id, message), } } pub async fn update_record( &self, domain: &str, id: i64, name: &str, kind: &str, data: &str, ttl: u32, ) -> Result<DomainRecord> { let response = self .http .put(format!( "https://api.digitalocean.com/v2/domains/{domain}/records/{id}" )) .json(&serde_json::json!({ "name": name, "type": kind, "data": data, "ttl": ttl, })) .send() .await .context("Failed to send PUT request (update_record)")? .text() .await .context("Failed to fetch PUT response (update_record)")?; log::debug!("update_record: {response}"); let response = serde_json::from_str(&response) .context("Failed to parse PUT response (create_record)")?; match response { DomainRecordResponse::Ok { domain_record } => Ok(domain_record), DomainRecordResponse::Error { id, message } => bail!("{}: {}", id, message), } } pub async fn create_record( &self, domain: &str, name: &str, kind: &str, data: &str, ttl: u32, ) -> Result<DomainRecord> { let response = self .http .post(format!( "https://api.digitalocean.com/v2/domains/{domain}/records/" )) .json(&serde_json::json!({ "name": name, "type": kind, "data": data, "ttl": ttl, })) .send() .await .context("Failed to send POST request (create_record)")? .text() .await .context("Failed to fetch POST response (create_record)")?; log::debug!("create_record: {response}"); let response = serde_json::from_str(&response) .context("Failed to parse POST response (create_record)")?; match response { DomainRecordResponse::Ok { domain_record } => Ok(domain_record), DomainRecordResponse::Error { id, message } => bail!("{}: {}", id, message), } } }
/** Copyright 2004, 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Addendum: * The original version of this file belongs to the retired Apache HiveMind * project: http://hivemind.apache.org/hivemind1/index.html * The original files can be found in hivemind-1.1.jar in package org.apache.hivemind.order * * The original version has been modified entirely by Riena committers such: * - removed dependencies from HiveMind * - added generics, uses extended for loops, .. * - adapted to Riena/Eclipse coding conventions */ package org.eclipse.riena.core.util; import java.util.List; import org.eclipse.riena.core.test.RienaTestCase; import org.eclipse.riena.core.test.collect.NonUITestCase; import org.eclipse.riena.core.util.Orderer.OrdererFailure; /** * Tests for the {@link org.apache.hivemind.order.Orderer}. * * @author Howard Lewis Ship */ @NonUITestCase public class OrdererTest extends RienaTestCase { public void testNoDependencies() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", null, null); o.add("BARNEY", "barney", null, null); o.add("WILMA", "wilma", null, null); o.add("BETTY", "betty", null, null); final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("FRED").list("BARNEY").list("WILMA").list("BETTY"), l); } public void testPrereq() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", "wilma", null); o.add("BARNEY", "barney", "betty", null); o.add("BETTY", "betty", null, null); o.add("WILMA", "wilma", null, null); final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("WILMA").list("FRED").list("BETTY").list("BARNEY"), l); } public void testPostreq() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", null, "barney,wilma"); o.add("BARNEY", "barney", null, "betty"); o.add("BETTY", "betty", null, null); o.add("WILMA", "wilma", null, null); final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("FRED").list("BARNEY").list("BETTY").list("WILMA"), l); } public void testPrePostreq() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", null, "barney,wilma"); o.add("BARNEY", "barney", "wilma", "betty"); o.add("BETTY", "betty", null, null); o.add("WILMA", "wilma", null, null); final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("FRED").list("WILMA").list("BARNEY").list("BETTY"), l); } public void testUnknownPrereq() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", "charlie", "barney,wilma"); o.add("BARNEY", "barney", "wilma", "betty"); o.add("BETTY", "betty", null, null); o.add("WILMA", "wilma", null, null); final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("FRED").list("WILMA").list("BARNEY").list("BETTY"), l); // TODO check logging: expect logging for charlie -> fred } public void testUnknownPostreq() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", null, "barney,wilma"); o.add("BARNEY", "barney", "wilma", "betty"); o.add("BETTY", "betty", null, "dino"); o.add("WILMA", "wilma", null, null); final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("FRED").list("WILMA").list("BARNEY").list("BETTY"), l); // TODO Check logging: Unknown cartoon character dependency 'dino' (for 'betty').", null, null); } public void testCyclePre() { try { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", "wilma", null); o.add("BARNEY", "barney", "betty", null); o.add("BETTY", "betty", "fred", null); o.add("WILMA", "wilma", "barney", null); final List<String> l = o.getOrderedObjects(); fail(); } catch (final OrdererFailure e) { assertTrue(e.getMessage().contains("between 'wilma'")); } // assertListsEqual(new Object[] { "WILMA", "FRED", "BETTY", "BARNEY" }, l); } public void testCyclePost() { try { final Orderer<String> o = new Orderer<String>(); o.add("WILMA", "wilma", null, "betty"); o.add("FRED", "fred", null, "barney"); o.add("BARNEY", "barney", null, "wilma"); o.add("BETTY", "betty", null, "fred"); final List<String> l = o.getOrderedObjects(); fail(); } catch (final OrdererFailure e) { assertTrue(e.getMessage().contains("between 'fred' and 'betty'")); } // assertListsEqual(new Object[] { "FRED", "BARNEY", "WILMA", "BETTY" }, l); } public void testDupe() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "flintstone", null, null); o.add("BARNEY", "rubble", null, null); // interceptLogging(); try { o.add("WILMA", "flintstone", null, null); fail(); } catch (final OrdererFailure e) { assertTrue(e.getMessage().contains("'flintstone'")); } // List<String> l = o.getOrderedObjects(); // // assertListsEqual(new Object[] { "FRED", "BARNEY" }, l); } public void testPreStar() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", "*", null); o.add("BARNEY", "barney", "betty", null); o.add("WILMA", "wilma", "betty", null); o.add("BETTY", "betty", null, null); final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("BETTY").list("BARNEY").list("WILMA").list("FRED"), l); } public void testPreStartDupe() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", "*", null); o.add("BARNEY", "barney", "*", null); o.add("WILMA", "wilma", "betty", null); o.add("BETTY", "betty", null, null); try { final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("BARNEY").list("BETTY").list("WILMA").list("FRED"), l); fail(); } catch (final OrdererFailure e) { assertTrue(e.getMessage().contains( "More than one trailer. Conflicting 'fred' (ordered unknown) and 'barney' (last)")); } } public void testPostStar() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", null, "wilma"); o.add("BARNEY", "barney", null, "*"); o.add("WILMA", "wilma", null, "betty"); o.add("BETTY", "betty", null, null); final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("BARNEY").list("FRED").list("WILMA").list("BETTY"), l); } public void testPostStarDupe() { final Orderer<String> o = new Orderer<String>(); o.add("FRED", "fred", null, "wilma"); o.add("BARNEY", "barney", null, "*"); o.add("WILMA", "wilma", null, "*"); o.add("BETTY", "betty", null, null); try { final List<String> l = o.getOrderedObjects(); assertEquals(Literal.list("BARNEY").list("FRED").list("WILMA").list("BETTY"), l); fail(); } catch (final OrdererFailure e) { assertTrue(e.getMessage().contains( "More than one leader. Conflicting 'barney' (ordered unknown) and 'wilma' (first)")); } } public void testNoObjects() { final Orderer<String> o = new Orderer<String>(); final List<String> l = o.getOrderedObjects(); assertEquals(0, l.size()); } }
/// This module defines the fee computation protocol for Soroban. /// /// This is technically not part of the Soroban host and is provided here for /// the sake of sharing between the systems that run Soroban host (such as /// Hcnet core or Soroban RPC service). /// Rough estimate of the base size of any transaction result in the archives /// (independent of the transaction envelope size). pub const TX_BASE_RESULT_SIZE: u32 = 300; /// Estimate for any `TtlEntry` ledger entry pub const TTL_ENTRY_SIZE: u32 = 48; const INSTRUCTIONS_INCREMENT: i64 = 10000; const DATA_SIZE_1KB_INCREMENT: i64 = 1024; // minimum effective write fee per 1KB pub const MINIMUM_WRITE_FEE_PER_1KB: i64 = 1000; /// These are the resource upper bounds specified by the Soroban transaction. pub struct TransactionResources { /// Number of CPU instructions. pub instructions: u32, /// Number of ledger entries the transaction reads. pub read_entries: u32, /// Number of ledger entries the transaction writes (these are also counted /// as entries that are being read for the sake of the respective fees). pub write_entries: u32, /// Number of bytes read from ledger. pub read_bytes: u32, /// Number of bytes written to ledger. pub write_bytes: u32, /// Size of the contract events XDR. pub contract_events_size_bytes: u32, /// Size of the transaction XDR. pub transaction_size_bytes: u32, } /// Fee-related network configuration. /// /// This should be normally loaded from the ledger, with exception of the /// `fee_per_write_1kb`, that has to be computed via `compute_write_fee_per_1kb` /// function. #[derive(Debug, Default, PartialEq, Eq)] pub struct FeeConfiguration { /// Fee per `INSTRUCTIONS_INCREMENT=10000` instructions. pub fee_per_instruction_increment: i64, /// Fee per 1 entry read from ledger. pub fee_per_read_entry: i64, /// Fee per 1 entry written to ledger. pub fee_per_write_entry: i64, /// Fee per 1KB read from ledger. pub fee_per_read_1kb: i64, /// Fee per 1KB written to ledger. This has to be computed via /// `compute_write_fee_per_1kb`. pub fee_per_write_1kb: i64, /// Fee per 1KB written to history (the history write size is based on /// transaction size and `TX_BASE_RESULT_SIZE`). pub fee_per_historical_1kb: i64, /// Fee per 1KB of contract events written. pub fee_per_contract_event_1kb: i64, /// Fee per 1KB of transaction size. pub fee_per_transaction_size_1kb: i64, } /// Network configuration used to determine the ledger write fee. /// /// This should be normally loaded from the ledger. #[derive(Debug, Default, PartialEq, Eq)] pub struct WriteFeeConfiguration { // Write fee grows linearly until bucket list reaches this size. pub bucket_list_target_size_bytes: i64, // Fee per 1KB write when the bucket list is empty. pub write_fee_1kb_bucket_list_low: i64, // Fee per 1KB write when the bucket list has reached // `bucket_list_target_size_bytes`. pub write_fee_1kb_bucket_list_high: i64, // Write fee multiplier for any additional data past the first // `bucket_list_target_size_bytes`. pub bucket_list_write_fee_growth_factor: u32, } /// Change in a single ledger entry with parameters relevant for rent fee /// computations. /// /// This represents the entry state before and after transaction has been /// applied. pub struct LedgerEntryRentChange { /// Whether this is persistent or temporary entry. pub is_persistent: bool, /// Size of the entry in bytes before it has been modified, including the /// key. /// `0` for newly-created entires. pub old_size_bytes: u32, /// Size of the entry in bytes after it has been modified, including the /// key. pub new_size_bytes: u32, /// Live until ledger of the entry before it has been modified. /// Should be less than the current ledger for newly-created entires. pub old_live_until_ledger: u32, /// Live until ledger of the entry after it has been modified. pub new_live_until_ledger: u32, } /// Rent fee-related network configuration. /// /// This should be normally loaded from the ledger, with exception of the /// `fee_per_write_1kb`, that has to be computed via `compute_write_fee_per_1kb` /// function. #[derive(Debug, Default, PartialEq, Eq)] pub struct RentFeeConfiguration { /// Fee per 1KB written to ledger. /// This is the same field as in `FeeConfiguration` and it has to be /// computed via `compute_write_fee_per_1kb`. pub fee_per_write_1kb: i64, /// Fee per 1 entry written to ledger. /// This is the same field as in `FeeConfiguration`. pub fee_per_write_entry: i64, /// Denominator for the total rent fee for persistent storage. /// /// This can be thought of as the number of ledgers of rent that costs as /// much, as writing the entry for the first time (i.e. if the value is /// `1000`, then we would charge the entry write fee for every 1000 ledgers /// of rent). pub persistent_rent_rate_denominator: i64, /// Denominator for the total rent fee for temporary storage. /// /// This has the same semantics as `persistent_rent_rate_denominator`. pub temporary_rent_rate_denominator: i64, } /// Computes the resource fee for a transaction based on the resource /// consumption and the fee-related network configuration. /// /// This can handle unsantized user inputs for `tx_resources`, but expects /// sane configuration. /// /// Returns a pair of `(non_refundable_fee, refundable_fee)` that represent /// non-refundable and refundable resource fee components respectively. pub fn compute_transaction_resource_fee( tx_resources: &TransactionResources, fee_config: &FeeConfiguration, ) -> (i64, i64) { let compute_fee = compute_fee_per_increment( tx_resources.instructions, fee_config.fee_per_instruction_increment, INSTRUCTIONS_INCREMENT, ); let ledger_read_entry_fee: i64 = fee_config.fee_per_read_entry.saturating_mul( tx_resources .read_entries .saturating_add(tx_resources.write_entries) .into(), ); let ledger_write_entry_fee = fee_config .fee_per_write_entry .saturating_mul(tx_resources.write_entries.into()); let ledger_read_bytes_fee = compute_fee_per_increment( tx_resources.read_bytes, fee_config.fee_per_read_1kb, DATA_SIZE_1KB_INCREMENT, ); let ledger_write_bytes_fee = compute_fee_per_increment( tx_resources.write_bytes, fee_config.fee_per_write_1kb, DATA_SIZE_1KB_INCREMENT, ); let historical_fee = compute_fee_per_increment( tx_resources .transaction_size_bytes .saturating_add(TX_BASE_RESULT_SIZE), fee_config.fee_per_historical_1kb, DATA_SIZE_1KB_INCREMENT, ); let events_fee = compute_fee_per_increment( tx_resources.contract_events_size_bytes, fee_config.fee_per_contract_event_1kb, DATA_SIZE_1KB_INCREMENT, ); let bandwidth_fee = compute_fee_per_increment( tx_resources.transaction_size_bytes, fee_config.fee_per_transaction_size_1kb, DATA_SIZE_1KB_INCREMENT, ); let refundable_fee = events_fee; let non_refundable_fee = compute_fee .saturating_add(ledger_read_entry_fee) .saturating_add(ledger_write_entry_fee) .saturating_add(ledger_read_bytes_fee) .saturating_add(ledger_write_bytes_fee) .saturating_add(historical_fee) .saturating_add(bandwidth_fee); (non_refundable_fee, refundable_fee) } // Helper for clamping values to the range of positive i64, with // invalid cases mapped to i64::MAX. trait ClampFee { fn clamp_fee(self) -> i64; } impl ClampFee for i64 { fn clamp_fee(self) -> i64 { if self < 0 { // Negatives shouldn't be possible -- they're banned in the logic // that sets most of the configs, and we're only using i64 for XDR // sake, ultimately I think compatibility with java which only has // signed types -- anyway we're assuming i64::MAX is more likely the // safest in-band default-value for erroneous cses, since it's more // likely to fail a tx, than to open a "0 cost tx" DoS vector. i64::MAX } else { self } } } impl ClampFee for i128 { fn clamp_fee(self) -> i64 { if self < 0 { i64::MAX } else { i64::try_from(self).unwrap_or(i64::MAX) } } } /// Computes the effective write fee per 1 KB of data written to ledger. /// /// The computed fee should be used in fee configuration for /// `compute_transaction_resource_fee` function. /// /// This depends only on the current ledger (more specifically, bucket list) /// size. pub fn compute_write_fee_per_1kb( bucket_list_size_bytes: i64, fee_config: &WriteFeeConfiguration, ) -> i64 { let fee_rate_multiplier = fee_config .write_fee_1kb_bucket_list_high .saturating_sub(fee_config.write_fee_1kb_bucket_list_low) .clamp_fee(); let mut write_fee_per_1kb: i64; if bucket_list_size_bytes < fee_config.bucket_list_target_size_bytes { // Convert multipliers to i128 to make sure we can handle large bucket list // sizes. write_fee_per_1kb = num_integer::div_ceil( (fee_rate_multiplier as i128).saturating_mul(bucket_list_size_bytes as i128), (fee_config.bucket_list_target_size_bytes as i128).max(1), ) .clamp_fee(); // no clamp_fee here write_fee_per_1kb = write_fee_per_1kb.saturating_add(fee_config.write_fee_1kb_bucket_list_low); } else { write_fee_per_1kb = fee_config.write_fee_1kb_bucket_list_high; let bucket_list_size_after_reaching_target = bucket_list_size_bytes.saturating_sub(fee_config.bucket_list_target_size_bytes); let post_target_fee = num_integer::div_ceil( (fee_rate_multiplier as i128) .saturating_mul(bucket_list_size_after_reaching_target as i128) .saturating_mul(fee_config.bucket_list_write_fee_growth_factor as i128), (fee_config.bucket_list_target_size_bytes as i128).max(1), ) .clamp_fee(); write_fee_per_1kb = write_fee_per_1kb.saturating_add(post_target_fee); } write_fee_per_1kb.max(MINIMUM_WRITE_FEE_PER_1KB) } /// Computes the total rent-related fee for the provided ledger entry changes. /// /// The rent-related fees consist of the fees for TTL extensions and fees for /// increasing the entry size (with or without TTL extensions). /// /// This cannot handle unsantized inputs and relies on sane configuration and /// ledger changes. This is due to the fact that rent is managed automatically /// wihtout user-provided inputs. pub fn compute_rent_fee( changed_entries: &[LedgerEntryRentChange], fee_config: &RentFeeConfiguration, current_ledger_seq: u32, ) -> i64 { let mut fee: i64 = 0; let mut extended_entries: i64 = 0; let mut extended_entry_key_size_bytes: u32 = 0; for e in changed_entries { fee = fee.saturating_add(rent_fee_per_entry_change(e, fee_config, current_ledger_seq)); if e.old_live_until_ledger < e.new_live_until_ledger { extended_entries = extended_entries.saturating_add(1); extended_entry_key_size_bytes = extended_entry_key_size_bytes.saturating_add(TTL_ENTRY_SIZE); } } // The TTL extensions need to be written to the ledger. As they have // constant size, we can charge for writing them independently of the actual // entry size. fee = fee.saturating_add( fee_config .fee_per_write_entry .saturating_mul(extended_entries), ); fee = fee.saturating_add(compute_fee_per_increment( extended_entry_key_size_bytes, fee_config.fee_per_write_1kb, DATA_SIZE_1KB_INCREMENT, )); fee } // Size of half-open range (lo, hi], or None if lo>hi fn exclusive_ledger_diff(lo: u32, hi: u32) -> Option<u32> { hi.checked_sub(lo) } // Size of closed range [lo, hi] or None if lo>hi fn inclusive_ledger_diff(lo: u32, hi: u32) -> Option<u32> { exclusive_ledger_diff(lo, hi).map(|diff| diff.saturating_add(1)) } impl LedgerEntryRentChange { fn entry_is_new(&self) -> bool { self.old_size_bytes == 0 && self.old_live_until_ledger == 0 } fn extension_ledgers(&self, current_ledger: u32) -> Option<u32> { let ledger_before_extension = if self.entry_is_new() { current_ledger.saturating_sub(1) } else { self.old_live_until_ledger }; exclusive_ledger_diff(ledger_before_extension, self.new_live_until_ledger) } fn prepaid_ledgers(&self, current_ledger: u32) -> Option<u32> { if self.entry_is_new() { None } else { inclusive_ledger_diff(current_ledger, self.old_live_until_ledger) } } fn size_increase(&self) -> Option<u32> { self.new_size_bytes.checked_sub(self.old_size_bytes) } } fn rent_fee_per_entry_change( entry_change: &LedgerEntryRentChange, fee_config: &RentFeeConfiguration, current_ledger: u32, ) -> i64 { let mut fee: i64 = 0; // If there was a difference-in-expiration, pay for the new ledger range // at the new size. if let Some(rent_ledgers) = entry_change.extension_ledgers(current_ledger) { fee = fee.saturating_add(rent_fee_for_size_and_ledgers( entry_change.is_persistent, entry_change.new_size_bytes, rent_ledgers, fee_config, )); } // If there were some ledgers already paid for at an old size, and the size // of the entry increased, those pre-paid ledgers need to pay top-up fees to // account for the change in size. if let (Some(rent_ledgers), Some(entry_size)) = ( entry_change.prepaid_ledgers(current_ledger), entry_change.size_increase(), ) { fee = fee.saturating_add(rent_fee_for_size_and_ledgers( entry_change.is_persistent, entry_size, rent_ledgers, fee_config, )); } fee } fn rent_fee_for_size_and_ledgers( is_persistent: bool, entry_size: u32, rent_ledgers: u32, fee_config: &RentFeeConfiguration, ) -> i64 { // Multiplication can overflow here - unlike fee computation this can rely // on sane input parameters as rent fee computation does not depend on any // user inputs. let num = (entry_size as i64) .saturating_mul(fee_config.fee_per_write_1kb) .saturating_mul(rent_ledgers as i64); let storage_coef = if is_persistent { fee_config.persistent_rent_rate_denominator } else { fee_config.temporary_rent_rate_denominator }; let denom = DATA_SIZE_1KB_INCREMENT.saturating_mul(storage_coef); num_integer::div_ceil(num, denom.max(1)) } fn compute_fee_per_increment(resource_value: u32, fee_rate: i64, increment: i64) -> i64 { let resource_val: i64 = resource_value.into(); num_integer::div_ceil(resource_val.saturating_mul(fee_rate), increment.max(1)) }
import { AppBar, makeStyles, Toolbar } from '@material-ui/core'; import { push } from 'connected-react-router'; import { useCallback, useState, VFC } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import logo from '../../assets/img/header_logo.png'; import { RootState } from '../../reducks/store/store'; import { getIsSignedIn } from '../../reducks/users/selectors'; import { ClosableDrawer } from './ClosableDrawer'; import { HeaderMenus } from './HeaderMenus'; const useStyles = makeStyles({ root: { flexGrow: 1, }, menuBar: { backgroundColor: '#fff', color: '#444', }, toolBar: { margin: '0 auto', maxWidth: 1024, width: '100%', }, iconButtons: { margin: '0 0 0 auto', }, }); export const Header: VFC = () => { const classes = useStyles(); const dispatch = useDispatch(); const selector = useSelector((state: RootState) => state); // ใƒญใ‚ฐใ‚คใƒณ็Šถๆ…‹ใ‚’ๅ–ๅพ— const isSignedIn = getIsSignedIn(selector); // ใƒ‰ใƒญใƒฏใƒผใฎ้–‹้–‰็Šถๆ…‹ const [open, setopen] = useState<boolean>(false); /** * ใƒ‰ใƒญใƒฏใƒผใƒกใƒ‹ใƒฅใƒผใ‚’้–‹้–‰ใ™ใ‚‹. * * @param event */ const handleDrawerToggle = useCallback((e) => { // Tabใ‹Shiftใ‚’ๆŠผใ—ใฆใ‚‚้–‰ใ˜ใชใ„ใ‚ˆใ†ใซ if (e.type === 'keydown' && (e.key === 'Tab' || e.key === 'Shift')) { return; } setopen(!open); }, [open, setopen]); return ( <header className={classes.root}> <AppBar position='fixed' className={classes.menuBar}> <Toolbar className={classes.toolBar}> <img src={logo} alt='logo' width='100px' onClick={() => dispatch(push('/'))} /> {isSignedIn && ( <div className={classes.iconButtons}> <HeaderMenus handleDrawerToggle={handleDrawerToggle}/> </div> )} </Toolbar> <ClosableDrawer open={open} onClose={handleDrawerToggle} /> </AppBar> </header> ); };
import React, { Fragment, useState } from "react"; import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown"; import { useDispatch } from "react-redux"; import { changeTheme } from "../../../theme/themeSlice"; import { useTranslation } from "react-i18next"; import { ECMenuItem } from "../../../components/ECMenuItem"; import { ECMenu } from "../../../components/ECMenu"; import { ECMenuButton } from "../../../components/ECMenuButton"; import { useAppTheme } from "../../../theme/useAppTheme"; export const SelectThemeMenu = () => { const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null); const open = Boolean(anchorElement); const dispatch = useDispatch(); const { t } = useTranslation("navigation"); const handleOnClose = () => { setAnchorElement(null); }; const { palette } = useAppTheme(); return ( <Fragment> <ECMenuButton fontSize={12} variant="text" aria-controls={open ? "theme-menu" : undefined} aria-haspopup="true" aria-expanded={open ? "true" : undefined} id="theme-button" onAction={(event) => { setAnchorElement(event?.currentTarget); }} endIcon={<KeyboardArrowDownIcon />} labelColor={palette.primary.light} label={t("theme")} /> <ECMenu open={open} id="theme-menu" anchorEl={anchorElement} MenuListProps={{ "aria-labelledby": "theme-button", }} onClose={handleOnClose} > <ECMenuItem label={t("lightTheme")} onAction={async () => { handleOnClose(); setTimeout(() => { dispatch(changeTheme("light")); }, 100); }} /> <ECMenuItem label={t("darkTheme")} onAction={() => { handleOnClose(); setTimeout(() => { dispatch(changeTheme("dark")); }, 100); }} /> </ECMenu> </Fragment> ); };
# 11.1 Integrating Network Changes into CI/CD Pipelines **Automated Testing for Network Configurations:** 1. **Test Automation Tools:** - Choose appropriate tools for automating tests on network configurations. - Examples include NAPALM, Ansible, or custom scripts. 2. **Unit Testing:** - Create unit tests to validate individual components of network configurations. - Test router configurations, firewall rules, and other network elements in isolation. 3. **Integration Testing:** - Perform integration tests to validate the interaction between different network components. - Test end-to-end communication and connectivity. 4. **Configuration Validation:** - Use tools to validate the syntax and semantics of configuration files. - Ensure that configurations comply with network device specifications. 5. **Performance Testing:** - Implement performance tests to assess the impact of configuration changes on network performance. - Evaluate bandwidth, latency, and packet loss. 6. **Security Testing:** - Integrate security testing into the CI/CD pipeline to identify vulnerabilities. - Check for misconfigurations that may pose security risks. **Integrating Network Changes into CI/CD Pipelines:** 1. **Version Control Integration:** - Connect CI/CD pipelines to the version control system (e.g., Git). - Trigger pipeline execution upon code commits. 2. **Automated Builds:** - Automatically build network configurations from source code. - Use tools like Ansible or custom scripts for configuration generation. 3. **Testing Stage:** - Include a dedicated testing stage in the CI/CD pipeline. - Execute automated tests on network configurations. 4. **Deployment Stage:** - Define deployment stages for different environments (development, testing, production). - Use automated deployment tools to apply configurations to network devices. 5. **Rollback Mechanism:** - Implement a rollback mechanism in case of failed deployments. - Automatically revert to the previous known-good configuration. 6. **Monitoring and Notifications:** - Integrate monitoring tools to track the status of network devices. - Set up notifications for pipeline success or failure. **Example Scenario:** 1. **Configure CI/CD Pipeline:** - Define CI/CD pipeline stages in a CI/CD tool (e.g., Jenkins, GitLab CI). - Set up triggers to start the pipeline on code commits. 2. **Automate Configuration Build:** - Use Ansible to automate the generation of network configurations. - Ensure that configuration files are created based on the committed code. 3. **Implement Testing Stages:** - Create stages for unit testing, integration testing, and performance testing. - Use NAPALM or similar tools to execute tests on network configurations. 4. **Deployment Stage:** - Define deployment stages for different environments. - Use Ansible or another automation tool to apply configurations to network devices. 5. **Rollback Mechanism:** - Implement a rollback playbook in Ansible to revert configurations in case of deployment failure. - Trigger the rollback process automatically if needed. 6. **Monitoring and Notifications:** - Integrate monitoring tools like Nagios or Prometheus to track the status of network devices. - Configure notifications to alert the team in case of pipeline failures.
<script setup> import {ref,reactive} from "vue" const form = ref("form") let prevData = [] if(localStorage.getItem("data")) { prevData = JSON.parse(localStorage.getItem("data")) }else{ prevData = [] } const data = reactive([ ...prevData, ]) console.log( prevData) const emit = defineEmits(['response']) const handleSubmit = () => { const information = { firstName:form._rawValue[0].value, lastName:form._rawValue[1].value, address:form._rawValue[2].value, dateOfBirth:form._rawValue[3].value, gender:form._rawValue[4].value, note:form._rawValue[5].value, } data.push(information) emit('response', data) localStorage.setItem("data",JSON.stringify(data)) window.location.reload(); } const checkValidity = (event) =>{ console.log(event.target.validity) if(!event.target.validity){ e.target.setCustomValidity("Please input data without special characters or digits"); } } </script> <template> <div class=" container-fluid d-flex flex-column col-md-5 col-md-offset-5 w-50 min-vh-100 justify-content-center align-items-center" > <div class="row my-auto "> <h1>VuiForm</h1> <form class="form-horizontal col-12 col-offset-12" @submit.prevent="handleSubmit" ref="form"> <div class="form-row"> <div class="form-group col-md-12 mb-2"> <label for="firstName" class="form-label">First name</label> <input type="text" class="form-control" id="firstName" placeholder="First Name" required autocomplete="off" @change="checkValidity" pattern="[A-Za-z]+"> <small class="form-text text-muted">Please don't use special characters or digits</small> </div> <div class="form-group col-md-12 mb-2"> <label for="lastName">Last Name</label> <input type="text" class="form-control" id="lastName" placeholder="Last Name" required autocomplete="off" @change="checkValidity" pattern="[A-Za-z]+"> <small class="form-text text-muted">Please don't use special characters or digits</small> </div> <div class="form-group col-md-8"> <label for="address">Address</label> <input type="text" class="form-control" id="address" placeholder="1234 Main St" required autocomplete="off"> </div> <div class="form-group col-md-12"> <label for="dateOfBirth">Date Of Birth</label> <input type="date" class="form-control" id="dateOfBirth" placeholder="Last Name" autocomplete="off"> </div> </div> <div class="form-row"> <div class="form-group col-md-5 mt-2"> <select id="gender" class="form-control"> <option value="" disabled selected>Choose Gender</option> <option value="Male">Male</option> <option value="Female">Female</option> </select> </div> <div class="form-group col-md-10 mt-2"> <textarea id="note" class = "form-control" rows = "3" placeholder = "Notes" ></textarea> </div> </div> <button type="submit" class="btn btn-primary mt-2" @submit="handleSubmit">Submit</button> </form> </div> </div> </template> <style scoped> h1{ margin-bottom: 0.5in !important; } textarea { resize: none; } </style>
"""Lab 07.05 - Binary Search Tree (Cases 1, 2, 3)""" class BSTNode: """BSTNode""" def __init__(self, data) -> None: """Initiation""" self.data = int(data) self.left = None self.right = None def set_data(self, data): """Setting Data""" self.data = int(data) def set_left(self, left_node): """Left Side""" self.left = left_node def set_right(self, right_node): """Right Side""" self.right = right_node def get_data(self): """Return Data""" return self.data def get_left(self): """Return Left""" return self.left def get_right(self): """Return Right""" return self.right class BST: """BST""" def __init__(self) -> None: """Initiation""" self.root = None def get_root(self): """Getting Root""" return self.root def set_root(self, root): """Setting Root""" self.root = root def insert(self, data): """Insert""" self.root = self._insert(self.root, data) def _insert(self, root, data): """Insertion""" if root is None: return BSTNode(data) if data < root.data: root.left = self._insert(root.left, data) elif data > root.data: root.right = self._insert(root.right, data) return root def preorder(self): """Pre-Order""" self._preorder(self.root) print() def _preorder(self, root): """Showing Output""" if root: print("->", root.data, end=" ") self._preorder(root.left) self._preorder(root.right) def is_empty(self): """Empty""" return self.root is None def inorder(self): """In-order""" self._inorder(self.root) print() def _inorder(self, root): """Show-Output""" if root: self._inorder(root.left) print("->", root.data, end=" ") self._inorder(root.right) def postorder(self): """Post-Order""" self._postorder(self.root) print() def _postorder(self, root): """Show Output only Post-Order""" if root: self._postorder(root.left) self._postorder(root.right) print("->", root.data, end=" ") def traverse(self): """Traversing and Show Output""" if self.is_empty(): return print("This is an empty binary search tree.") print('Preorder: ', end='') self.preorder() print('Inorder: ', end='') self.inorder() print('Postorder: ', end='') self.postorder() def _find_min(self, root): """Using""" if self.is_empty(): return None cur = root while cur.getleft: cur = cur.left return cur.data def find_min(self): """Finding Minimum""" return self._find_min(self.root) def find_max(self): """Using""" return self._find_max(self.root) def _find_max(self, root): """Finding Maximum""" if self.is_empty(): return None cur = root while cur.right: cur = cur.right return cur.data def delete(self, data): """delete""" self.root = self._delete(self.root, data) def _delete(self, root, data): """recursive delete function""" if root is None: print("Delete Error, %s is not found in Binary Search Tree." % data) return None if data < root.get_data(): root.set_left(self._delete(root.get_left(), data)) elif data > root.get_data(): root.set_right(self._delete(root.get_right(), data)) else: #เน‚เธซเธ™เธ”เธ—เธตเนˆเธ•เน‰เธญเธ‡เธเธฒเธฃเธฅเธš if root.get_left() is None: return root.get_right() elif root.get_right() is None: return root.get_left() #เน‚เธซเธ™เธ”เธ—เธตเนˆเธกเธตเธ—เธฑเน‰เธ‡เธ‹เน‰เธฒเธขเนเธฅเธฐเธ‚เธงเธฒ #เธซเธฒเน‚เธซเธ™เธ”เธ—เธตเนˆเน€เธ›เน‡เธ™ inorder (เน‚เธซเธ™เธ”เธ—เธตเนˆเธ™เน‰เธญเธขเธ—เธตเนˆเธชเธธเธ”เนƒเธ™เธ•เน‰เธ™เธ—เธฒเธ‡เธ‚เธงเธฒ) root.set_data(self._find_min(root.get_right())) # เนƒเธซเน‰ เธฅเธš inorder root.set_right(self._delete(root.get_right(), root.get_data())) return root def main(): """Data Structures and Algorithms Lab - Binary Search Tree""" my_bst = BST() while 1: text = input() if text == "Done": break condition, data = text.split(": ") if condition == "I": my_bst.insert(int(data)) elif condition == "D": my_bst.delete(int(data)) else: print("Invalid Condition") my_bst.traverse() main()
{% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <!-- Begin Page Content --> <div class="container-fluid"> <!-- Page Heading <nav class="navbar navbar-main navbar-expand-lg px-0 mx-4 shadow-none border-radius-xl " id="navbarBlur" data-scroll="false"> <div class="container-fluid py-1 px-3"> <nav aria-label="breadcrumb"> <ol class="breadcrumb bg-transparent mb-0 pb-0 pt-1 px-0 me-sm-6 me-5"> <li class="breadcrumb-item text-sm"><a class="opacity-5 text-white" href="javascript:;">Home</a> </li> <li class="breadcrumb-item text-sm text-white active" aria-current="page">Profile Update</li> </ol> </nav> <div class="collapse navbar-collapse mt-sm-0 mt-2 me-md-0 me-sm-4" id="navbar"> <div class="ms-md-auto pe-md-3 d-flex align-items-center"> <div class="input-group"> <span class="input-group-text text-body"><i class="fas fa-search" aria-hidden="true"></i></span> <input type="text" class="form-control" placeholder="Type here..."> </div> </div> <ul class="navbar-nav justify-content-end"> <li class="nav-item d-flex align-items-center"> <a href="{% url 'logout' %}" class="nav-link text-white font-weight-bold px-0"> <i class="fa fa-sign-out me-sm-1"></i> <span class="d-sm-inline d-none">Logout</span> </a> </li> <li class="nav-item d-xl-none ps-3 d-flex align-items-center "> <a href="javascript:;" class="nav-link text-white p-0" id="iconNavbarSidenav"> <div class="sidenav-toggler-inner"> <i class="sidenav-toggler-line bg-white"></i> <i class="sidenav-toggler-line bg-white"></i> <i class="sidenav-toggler-line bg-white"></i> </div> </a> </li> <li class="nav-item dropdown pe-2 px-3 d-flex align-items-center"> <a href="javascript:;" class="nav-link text-white p-0" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false"> <i class="fa fa-user cursor-pointer"><span class="mx-2 ">{{user.username}}</span></i> </a> <ul class="dropdown-menu dropdown-menu-end px-2 py-3 me-sm-n4" aria-labelledby="dropdownMenuButton"> <li class="mb-2"> <a class="dropdown-item border-radius-md" href="{% url 'profile' %}"> <div class="d-flex py-1"> <div class="my-auto"> <i class="fa fa-user cursor-pointer pe-3" class="avatar avatar-sm me-3 "></i> </div> <div class="d-flex flex-column justify-content-center"> <h6 class="text-sm font-weight-normal mb-1"> <span class="font-weight-bold">Profile</span> </h6> </div> </div> </a> </li> <li class="mb-2"> <a class="dropdown-item border-radius-md" href="{% url 'change-password'%}"> <div class="d-flex py-1"> <div class="my-auto"> <i class="fa fa-key cursor-pointer pe-3" class="avatar avatar-sm me-3 "></i> </div> <div class="d-flex flex-column justify-content-center"> <h6 class="text-sm font-weight-normal mb-1"> <span class="font-weight-bold">Change Password</span> </h6> </div> </div> </a> </li> </li> </ul> </li> </ul> </div> </div> </nav> --> <!-- Main Content Here --> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <div class="row"> <div class="col-lg-3"></div> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <!-- Page heading --> <h1 class="h4 text-gray-900 mb-4">Update Your Profile!</h1> </div> <!-- Profile update form --> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <!-- Username --> <div class="form-group"> <label for="{{ user_form.username.id_for_label }}">Username</label> <input type="text" class="form-control" id="{{ user_form.username.id_for_label }}" name="{{ user_form.username.name }}" value="{{ user_form.username.value }}" placeholder="Enter username" readonly> </div> <!-- First Name --> <div class="form-group"> <label for="{{ user_form.first_name.id_for_label }}">First Name</label> <input type="text" class="form-control" id="{{ user_form.first_name.id_for_label }}" name="{{ user_form.first_name.name }}" value="{{ user_form.first_name.value }}" placeholder="Enter first name"> </div> <!-- Last Name --> <div class="form-group"> <label for="{{ user_form.last_name.id_for_label }}">Last Name</label> <input type="text" class="form-control" id="{{ user_form.last_name.id_for_label }}" name="{{ user_form.last_name.name }}" value="{{ user_form.last_name.value }}" placeholder="Enter last name"> </div> <!-- Email Address --> <div class="form-group"> <label for="{{ user_form.email.id_for_label }}">Email Address</label> <input type="email" class="form-control" id="{{ user_form.email.id_for_label }}" name="{{ user_form.email.name }}" value="{{ user_form.email.value }}" placeholder="Enter email address"> </div> <!-- Phone Number --> <div class="form-group"> <label for="{{ profile_form.phone_number.id_for_label }}">Phone Number</label> <input type="text" class="form-control" id="{{ profile_form.phone_number.id_for_label }}" name="{{ profile_form.phone_number.name }}" value="{{ profile_form.phone_number.value }}" placeholder="Enter phone number"> </div> <div class="d-grid gap-2 col-6 mx-auto"> <button type="submit" class="btn btn-success btn-block align-self-center text-center ">Update</button> </div> </form> <hr> <div class="text-center"> <!-- Back link --> <a class="small" href="{% url 'profile' %}">Back</a> </div> </div> </div> </div> </div> </div> </div> <!-- /.container-fluid --> {% endblock content %}
package com.github.benoitf.devfile.extractor.entity; import static java.util.stream.Collectors.toCollection; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.persistence.CascadeType; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.MapKeyColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity(name = "DevfileComponent") @Table(name = "devfile_component") public class ComponentImpl { @Id @GeneratedValue @Column(name = "id") private Long generatedId; @Column(name = "component_id", nullable = false) private String componentId; @ElementCollection(fetch = FetchType.EAGER) @CollectionTable( name = "devfile_component_preferences", joinColumns = @JoinColumn(name = "devfile_component_id")) @MapKeyColumn(name = "preference_key") @Convert(converter = SerializableConverter.class) @Column(name = "preference") @JsonDeserialize(using = PreferencesDeserializer.class) private Map<String, Serializable> preferences; @Column(name = "alias") private String alias; @Column(name = "type", nullable = false) private String type; @Column(name = "registry_url") private String registryUrl; @Column(name = "reference") private String reference; @Column(name = "reference_content") private String referenceContent; @ElementCollection(fetch = FetchType.EAGER) @CollectionTable( name = "devfile_component_selector", joinColumns = @JoinColumn(name = "devfile_component_id")) @MapKeyColumn(name = "selector_key") @Column(name = "selector") private Map<String, String> selector; @Column(name = "image") private String image; @Column(name = "memory_limit") private String memoryLimit; @Column(name = "memory_request") private String memoryRequest; @Column(name = "cpu_limit") private String cpuLimit; @Column(name = "cpu_request") private String cpuRequest; @Column(name = "mount_sources") private Boolean mountSources; @Column(name = "automount_secrets") private Boolean automountWorkspaceSecrets; @ElementCollection(fetch = FetchType.EAGER) @CollectionTable( name = "devfile_component_command", joinColumns = @JoinColumn(name = "devfile_component_id")) @Column(name = "command") private List<String> command; @ElementCollection(fetch = FetchType.EAGER) @CollectionTable( name = "devfile_component_arg", joinColumns = @JoinColumn(name = "devfile_component_id")) @Column(name = "args") private List<String> args; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "devfile_component_id") private List<EntrypointImpl> entrypoints; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "devfile_component_id") private List<VolumeImpl> volumes; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "devfile_component_id") private List<EnvImpl> env; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "devfile_component_id") private List<EndpointImpl> endpoints; public ComponentImpl() {} public ComponentImpl(String type, String id) { this.type = type; this.componentId = id; } public ComponentImpl(String type, String id, Map<String, String> preferences) { this.type = type; this.componentId = id; if (preferences != null) { this.preferences = new HashMap<>(preferences); } } public ComponentImpl( String type, String id, String reference, String referenceContent, Map<String, String> selector, List<? extends EntrypointImpl> entrypoints) { this.type = type; this.componentId = id; this.reference = reference; this.referenceContent = referenceContent; if (selector != null) { this.selector = new HashMap<>(selector); } if (entrypoints != null) { this.entrypoints = entrypoints.stream().map(EntrypointImpl::new).collect(toCollection(ArrayList::new)); } } public ComponentImpl( String type, String alias, String id, Map<String, Serializable> preferences, String registryUrl, String reference, String referenceContent, Map<String, String> selector, List<? extends EntrypointImpl> entrypoints, String image, String memoryLimit, String memoryRequest, String cpuLimit, String cpuRequest, Boolean mountSources, Boolean automountWorkspaceSecrets, List<String> command, List<String> args, List<? extends VolumeImpl> volumes, List<? extends EnvImpl> env, List<? extends EndpointImpl> endpoints) { this.alias = alias; this.type = type; this.componentId = id; this.registryUrl = registryUrl; if (preferences != null) { this.preferences = new HashMap<>(preferences); } this.reference = reference; this.referenceContent = referenceContent; if (selector != null) { this.selector = new HashMap<>(selector); } if (entrypoints != null) { this.entrypoints = entrypoints.stream().map(EntrypointImpl::new).collect(toCollection(ArrayList::new)); } this.image = image; this.memoryLimit = memoryLimit; this.memoryRequest = memoryRequest; this.cpuLimit = cpuLimit; this.cpuRequest = cpuRequest; this.mountSources = mountSources; this.automountWorkspaceSecrets = automountWorkspaceSecrets; this.command = command; this.args = args; if (volumes != null) { this.volumes = volumes.stream().map(VolumeImpl::new).collect(toCollection(ArrayList::new)); } if (env != null) { this.env = env.stream().map(EnvImpl::new).collect(toCollection(ArrayList::new)); } if (endpoints != null) { this.endpoints = endpoints.stream().map(EndpointImpl::new).collect(toCollection(ArrayList::new)); } } public ComponentImpl(ComponentImpl component) { this( component.getType(), component.getAlias(), component.getId(), component.getPreferences(), component.getRegistryUrl(), component.getReference(), component.getReferenceContent(), component.getSelector(), component.getEntrypoints(), component.getImage(), component.getMemoryLimit(), component.getMemoryRequest(), component.getCpuLimit(), component.getCpuRequest(), component.getMountSources(), component.getAutomountWorkspaceSecrets(), component.getCommand(), component.getArgs(), component.getVolumes(), component.getEnv(), component.getEndpoints()); } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getId() { return componentId; } public void setId(String id) { this.componentId = id; } public String getRegistryUrl() { return registryUrl; } public void setRegistryUrl(String registryUrl) { this.registryUrl = registryUrl; } public Map<String, Serializable> getPreferences() { if (preferences == null) { preferences = new HashMap<>(); } return preferences; } public void setPreferences(Map<String, Serializable> preferences) { this.preferences = preferences; } public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public String getReferenceContent() { return referenceContent; } public void setReferenceContent(String referenceContent) { this.referenceContent = referenceContent; } public Map<String, String> getSelector() { if (selector == null) { selector = new HashMap<>(); } return selector; } public void setSelector(Map<String, String> selector) { this.selector = selector; } public List<EntrypointImpl> getEntrypoints() { if (entrypoints == null) { entrypoints = new ArrayList<>(); } return entrypoints; } public void setEntrypoints(List<EntrypointImpl> entrypoints) { this.entrypoints = entrypoints; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getMemoryLimit() { return memoryLimit; } public void setMemoryLimit(String memoryLimit) { this.memoryLimit = memoryLimit; } public String getMemoryRequest() { return memoryRequest; } public void setMemoryRequest(String memoryRequest) { this.memoryRequest = memoryRequest; } public String getCpuLimit() { return cpuLimit; } public void setCpuLimit(String cpuLimit) { this.cpuLimit = cpuLimit; } public String getCpuRequest() { return cpuRequest; } public void setCpuRequest(String cpuRequest) { this.cpuRequest = cpuRequest; } public Boolean getMountSources() { return mountSources; } public void setMountSources(Boolean mountSources) { this.mountSources = mountSources; } public Boolean getAutomountWorkspaceSecrets() { return automountWorkspaceSecrets; } public void setAutomountWorkspaceSecrets(Boolean automountWorkspaceSecrets) { this.automountWorkspaceSecrets = automountWorkspaceSecrets; } public List<String> getCommand() { if (command == null) { command = new ArrayList<>(); } return command; } public void setCommand(List<String> command) { this.command = command; } public List<String> getArgs() { if (args == null) { args = new ArrayList<>(); } return args; } public void setArgs(List<String> args) { this.args = args; } public List<VolumeImpl> getVolumes() { if (volumes == null) { volumes = new ArrayList<>(); } return volumes; } public void setVolumes(List<VolumeImpl> volumes) { this.volumes = volumes; } public List<EnvImpl> getEnv() { if (env == null) { env = new ArrayList<>(); } return env; } public void setEnv(List<EnvImpl> env) { this.env = env; } public List<EndpointImpl> getEndpoints() { if (endpoints == null) { endpoints = new ArrayList<>(); } return endpoints; } public void setEndpoints(List<EndpointImpl> endpoints) { this.endpoints = endpoints; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ComponentImpl)) { return false; } ComponentImpl component = (ComponentImpl) o; return getMountSources() == component.getMountSources() && getAutomountWorkspaceSecrets() == component.getAutomountWorkspaceSecrets() && Objects.equals(generatedId, component.generatedId) && Objects.equals(alias, component.alias) && Objects.equals(type, component.type) && Objects.equals(componentId, component.componentId) && Objects.equals(registryUrl, component.registryUrl) && Objects.equals(reference, component.reference) && Objects.equals(referenceContent, component.referenceContent) && Objects.equals(image, component.image) && Objects.equals(memoryLimit, component.memoryLimit) && Objects.equals(getPreferences(), component.getPreferences()) && Objects.equals(getSelector(), component.getSelector()) && Objects.equals(getEntrypoints(), component.getEntrypoints()) && Objects.equals(getCommand(), component.getCommand()) && Objects.equals(getArgs(), component.getArgs()) && Objects.equals(getVolumes(), component.getVolumes()) && Objects.equals(getEnv(), component.getEnv()) && Objects.equals(getEndpoints(), component.getEndpoints()); } @Override public int hashCode() { return Objects.hash( generatedId, alias, type, componentId, registryUrl, reference, referenceContent, image, memoryLimit, getPreferences(), getSelector(), getEntrypoints(), getMountSources(), getAutomountWorkspaceSecrets(), getCommand(), getArgs(), getVolumes(), getEnv(), getEndpoints()); } @Override public String toString() { return "ComponentImpl{" + "id='" + componentId + '\'' + ", alias='" + alias + '\'' + ", type='" + type + '\'' + ", preferences=" + preferences + ", registryUrl='" + registryUrl + '\'' + ", reference='" + reference + '\'' + ", referenceContent='" + referenceContent + '\'' + ", selector=" + selector + ", entrypoints=" + entrypoints + ", image='" + image + '\'' + ", memoryLimit='" + memoryLimit + '\'' + ", mountSources=" + mountSources + ", automountWorkspaceSecrets=" + automountWorkspaceSecrets + ", command=" + command + ", args=" + args + ", volumes=" + volumes + ", env=" + env + ", endpoints=" + endpoints + '}'; } }
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class AddPage extends StatefulWidget { const AddPage({Key? key}) : super(key: key); @override State<AddPage> createState() => _AddPageState(); } enum options { PANORAMA,CAMERA, GBS } class _AddPageState extends State<AddPage> { late int id; late String type; late String price; String? groupValue; bool _panoramaValue = false; bool _cameraValue = false; bool _gpsValue = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: IconButton( icon: Icon( Icons.arrow_back_ios, color: Colors.teal.shade500, ), onPressed: () => Navigator.pop(context), ), title: Text( 'Add', style: GoogleFonts.cairo( fontWeight: FontWeight.bold, color: Colors.teal.shade500, fontSize: 24, ), ), centerTitle: true, backgroundColor: Colors.transparent, elevation: 0, ), body: Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 50), child: ListView( children: [ TextField( onChanged: (String value) { print('value $value'); setState(() { id = value as int; }); print('id $id'); }, keyboardType: TextInputType.number, decoration: InputDecoration( focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.teal.shade500), borderRadius: BorderRadius.circular(10), ), hintText: 'Year Of Release', prefixIcon: Icon( Icons.date_range, color: Colors.teal.shade500, ), border: OutlineInputBorder( borderSide: const BorderSide( color: Colors.grey, width: 1, ), borderRadius: BorderRadius.circular(10), ), ), ), const SizedBox( height: 20, ), TextField( onChanged: (String value) { print('value $value'); setState(() { type = value; }); print('type: $type'); }, style: GoogleFonts.nunito(), enabled: true, textAlign: TextAlign.start, textDirection: TextDirection.ltr, decoration: InputDecoration( focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.teal.shade500), borderRadius: BorderRadius.circular(10), ), hintText: 'Vehicle Type', hintStyle: GoogleFonts.nunito(fontWeight: FontWeight.bold), hintMaxLines: 1, hintTextDirection: TextDirection.ltr, prefixIcon: Icon( Icons.car_repair_rounded, color: Colors.teal.shade500, ), border: OutlineInputBorder( borderSide: const BorderSide( color: Colors.grey, width: 1, ), borderRadius: BorderRadius.circular(10), ), ), ), const SizedBox( height: 20, ), TextField( style: GoogleFonts.nunito(), onChanged: (String value) { print("value : $value"); setState(() { price = value; }); print("price: $price"); }, keyboardType: TextInputType.number, enabled: true, textAlign: TextAlign.start, textDirection: TextDirection.ltr, decoration: InputDecoration( focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.teal.shade500), borderRadius: BorderRadius.circular(10), ), hintText: 'Vehicle Price', hintStyle: GoogleFonts.nunito(fontWeight: FontWeight.bold), hintMaxLines: 1, hintTextDirection: TextDirection.ltr, prefixIcon: Icon( Icons.monetization_on, color: Colors.teal.shade500, ), border: OutlineInputBorder( borderSide: const BorderSide( color: Colors.grey, width: 1, ), borderRadius: BorderRadius.circular(10), ), ), ), const SizedBox( height: 20, ), Text( 'Sold OR Not !', style: GoogleFonts.cairo(fontWeight: FontWeight.bold, fontSize: 18), ), Row( children: [ Expanded( child: RadioListTile( activeColor: Colors.teal.shade500, title: Text('Sold'), value: 'Sold', groupValue: groupValue, onChanged: (String? value) { setState(() => groupValue = value); print('Sold : $value'); })), Expanded( child: RadioListTile( activeColor: Colors.teal.shade500, title: Text('Not Sold'), value: 'Not Sold', groupValue: groupValue, onChanged: (String? value) { setState(() => groupValue = value); print('Not Sold : $value'); }, ), ), ], ), const SizedBox( height: 20, ), Text( 'Other Options ! ', style: GoogleFonts.cairo(fontWeight: FontWeight.bold, fontSize: 18), ), CheckboxListTile( activeColor: Colors.teal.shade500, title: Text( options.PANORAMA.name, style: GoogleFonts.cairo(), ), value: _panoramaValue, onChanged: (bool? value) { if (value != null) { setState(() => _panoramaValue = value); } }, ), CheckboxListTile( activeColor: Colors.teal.shade500, title: Text( options.CAMERA.name, style: GoogleFonts.cairo(), ), value: _cameraValue, onChanged: (bool? value) { if (value != null) { setState(() => _cameraValue = value); } }, ), CheckboxListTile( activeColor: Colors.teal.shade500, title: Text( options.GBS.name, style: GoogleFonts.cairo(), ), value: _gpsValue, onChanged: (bool? value) { if (value != null) { setState(() => _gpsValue = value); } }, ), const SizedBox( height: 30, ), ElevatedButton( style: ElevatedButton.styleFrom( minimumSize: const Size(double.infinity, 50), primary: Colors.teal.shade500, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topRight: Radius.circular(20), bottomLeft: Radius.circular(20), ), ), ), onPressed: () { Navigator.pushReplacementNamed(context, '/list_page', arguments: { 'id': id, 'type': type, 'price': price, 'groupValue': groupValue, }); }, child: Text( 'SAVE', style: GoogleFonts.nunito( fontWeight: FontWeight.bold, ), ), ), ], ), ), ); } }
<template> <div class="vue-page"> <div class="ctrl"> <el-button type="primary" @click="onClickTest01()">ๆต‹่ฏ•JS:ๆ— ๅฃฐๆ˜Žๆ–‡ไปถ</el-button> <el-button type="primary" @click="onClickTest02()">ๆต‹่ฏ•JS:ๆœ‰ๅฃฐๆ˜Žๆ–‡ไปถ</el-button> <el-button type="primary" @click="onClickTest03()">ๆต‹่ฏ•JS:IIFEๆ— ๅฃฐๆ˜Žๆ–‡ไปถ</el-button> </div> <div class="panel-warn"> <div class="item">1.<a href="javascript:void(0)" @click="onClickOpenWindowByUrl('https://segmentfault.com/a/1190000009247663')">ๅฆ‚ไฝ•็ผ–ๅ†™ไธ€ไธชd.tsๆ–‡ไปถ</a> </div> <div class="item">2.<a href="javascript:void(0)" @click="onClickOpenWindowByUrl('https://zhuanlan.zhihu.com/p/285270177')">ไบ†ไธ่ตท็š„ tsconfig.json ๆŒ‡ๅ—</a> </div> <div class="item">3.<a href="javascript:void(0)" @click="onClickOpenWindowByUrl('https://juejin.cn/post/6987735091925483551')">ไธ€ๆ–‡่ฏปๆ‡‚TS็š„(.d.ts)ๆ–‡ไปถ</a> </div> <div class="item">4.<a href="javascript:void(0)" @click="onClickOpenWindowByUrl('https://segmentfault.com/a/1190000019768261')">TypeScriptๆœ€ไฝณๅฎž่ทต๏ผšๆ˜ฏๅฆไฝฟ็”จnoImplicitAny</a> </div> <div class="item">5.<a href="javascript:void(0)" @click="onClickOpenWindowByUrl('https://www.jianshu.com/p/47c29865b3a4')">tsconfig.json้…็ฝฎ่ฏฆ่งฃ</a> </div> </div> </div> </template> <script lang="ts" setup> import ModalTool from '@/common/ui/ModalTool' /*่‹ฅtsconfig.json็š„compilerOptions.strict้…็ฝฎไธบtrue๏ผˆไธฅๆ ผๆจกๅผ๏ผ‰ 1.IDEไผšๆ้†’๏ผšๆ— ๆณ•ๆ‰พๅˆฐๆจกๅ—โ€œxxxโ€็š„ๅฃฐๆ˜Žๆ–‡ไปถ 2.ไธ่ฟ‡ๆž„ๅปบๅฏไปฅ้€š่ฟ‡๏ผŒไปฃ็ ๅฏไปฅๆญฃๅธธๆ‰ง่กŒ ๅฆๅค–๏ผŒ่‹ฅๅผ•็”จไบ†็ฌฌไธ‰ๆ–นjsๆ–‡ไปถ๏ผŒๆœ€ๅฅฝๆŠŠ้กน็›ฎไธญ็š„tsconfig.json็š„compilerOptions.noImplicitAny้…็ฝฎไธบfalse๏ผŒๅฆๅˆ™IDEไผšๆœ‰ๅพˆๅคšๅผ‚ๅธธๆ้†’ */ import xiao from '@/jsexec/xiao' import xuan from '@/jsexec/xuan' import xing from '@/jsexec/xing' function onClickTest01() { //ๆ— ็ฑปๅž‹ๅฎšไน‰็š„๏ผŒๅฐ†ๆ‰€ๆœ‰็š„่งฃๆžไธบany ModalTool.ShowDialogInfo("็ป“ๆžœ", xiao.sayHello("xiao")) } function onClickTest02() { //ๆœ‰็ฑปๅž‹ๅฎšไน‰็š„๏ผŒๅฐ†ๆ˜Ž็กฎๆŒ‡ๅ‡บๅ‚ๆ•ฐๅŠ่ฟ”ๅ›žๅ€ผ็š„็ฑปๅž‹ ModalTool.ShowDialogInfo("็ป“ๆžœ", xuan.sayHello("xuan")) } function onClickTest03() { let x = new xing() ModalTool.ShowDialogInfo("็ป“ๆžœ", x.sayHello("xing")) } function onClickOpenWindowByUrl(url: string) { window.EPre.openChildWin("...", url) } </script> <style lang="scss" scoped> .vue-page { display: flex; flex-direction: column; padding: 5px; .ctrl { display: flex; flex-direction: row; } } </style>
/** * Represents a function to find the object with the maximum value of a given key in a list of objects. */ import { AbstractContextData } from '../../context'; import { TypeGuard } from '../../utils'; import ICommand, { isCommand } from '../ICommand'; import IFunction from './IFunction'; export default class MaxObject implements IFunction<object | undefined> { /** * Unique identifier for the function. */ id = 'maxObject'; /** * A type guard instance for object type. */ typeGuard: TypeGuard = new TypeGuard(['object']); /** * The list of objects to iterate over or a command that returns a list of objects. */ private readonly objects: (ICommand<object> | object)[] | ICommand<object[]>; /** * The key that should be used to find the object with the maximum value. */ private readonly key: string; /** * Creates an instance of MaxObject function. * @param objects The list of objects to iterate over or a command that returns a list of objects. * @param key The key that should be used to find the object with the maximum value. */ constructor(objects: (ICommand<object> | object)[] | ICommand<object[]>, key: string) { this.objects = objects; this.key = key; } /** * Validates if the given value is an object. * @param value The object to validate. * @param operandName The name of the operand being validated. * @returns A promise that resolves if the object is valid, otherwise throws an error. */ private async validateObject(value: object, operandName: string): Promise<void> { await this.typeGuard.evaluate(value, this.id, operandName); } /** * Executes the function to find the object with the maximum value of a given key in a list of objects. * @param context The context data. * @returns A promise that resolves to the object with the maximum value of the given key in the list of objects. */ async execute(context: AbstractContextData): Promise<object | undefined> { const values = (isCommand(this.objects) ? await this.objects.execute(context) : this.objects) as object[]; const result = await Promise.all( values.map(async (value, index) => { const toEvaluate = (isCommand(value) ? await value.execute(context) : value) as object; await this.validateObject(toEvaluate, `values[${index}]`); return toEvaluate; }) ).catch((err) => { throw err; }); if (result.length === 0) { return undefined; } return result.reduce((prev, curr) => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return prev[this.key] > curr[this.key] ? prev : curr; }); } /** * Returns a string representation of the function. * @returns A string representation of the function. */ toString(): string { const str = isCommand(this.objects) ? this.objects.toString() : this.objects.map((e) => e.toString()).join(`, `); return `${this.id}(${str}, ${this.key})`; } }
import React, { useState } from "react"; import { Carousel, CarouselItem, CarouselControl, CarouselIndicators, } from "reactstrap"; import "../../css/app.css"; const items = [ { src: require("../../images/Deals.png").default, altText: "Deals", caption: "Great deals in April! Don't loss your chance!", }, { src: require("../../images/Quote.png").default, altText: "Quote", caption: "Quote of April", }, { src: require("../../images/NewRelease.png").default, altText: "New Release", caption: "", }, ]; const ImageCarousel = (props) => { const [activeIndex, setActiveIndex] = useState(0); const [animating, setAnimating] = useState(false); const next = () => { if (animating) return; const nextIndex = activeIndex === items.length - 1 ? 0 : activeIndex + 1; setActiveIndex(nextIndex); }; const previous = () => { if (animating) return; const nextIndex = activeIndex === 0 ? items.length - 1 : activeIndex - 1; setActiveIndex(nextIndex); }; const goToIndex = (newIndex) => { if (animating) return; setActiveIndex(newIndex); }; const slides = items.map((item) => { return ( <CarouselItem className="carouselItem" onExiting={() => setAnimating(true)} onExited={() => setAnimating(false)} key={item.src} > <img className="carouselImage" src={item.src} alt={item.altText} /> </CarouselItem> ); }); return ( <Carousel className="carouselCont" activeIndex={activeIndex} next={next} previous={previous} > <CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={goToIndex} /> {slides} <CarouselControl direction="prev" directionText="Previous" onClickHandler={previous} /> <CarouselControl direction="next" directionText="Next" onClickHandler={next} /> </Carousel> ); }; export default ImageCarousel;
import { makeMap } from './makeMap' export { makeMap } export * from './patchFlags' export { isGloballyWhitelisted } from './globalsWhitelist' // ๅฏผๅ‡บไธ€ไธช็ฉบๅฏน่ฑก export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__ ? Object.freeze({}) : {} // ๅฏผๅ‡บไธ€ไธช็ฉบๆ•ฐ็ป„ export const EMPTY_ARR: [] = [] // ๅฏผๅ‡บไธ€ไธช็ฉบๅ‡ฝๆ•ฐ export const NOOP = () => {} /** * Always return false. */ export const NO = () => false // ๅˆคๆ–ญไผ ๅ…ฅ็š„ๅญ—็ฌฆไธฒ็š„ๅ‰ไธคไธชๅญ—็ฌฆๆ˜ฏๅฆไธบ 'on' export const isOn = (key: string) => key[0] === 'o' && key[1] === 'n' export const extend = <T extends object, U extends object>( a: T, b: U ): T & U => { for (const key in b) { ;(a as any)[key] = b[key] } return a as any } const hasOwnProperty = Object.prototype.hasOwnProperty export const hasOwn = ( val: object, key: string | symbol ): key is keyof typeof val => hasOwnProperty.call(val, key) export const isArray = Array.isArray // ๅˆคๆ–ญไผ ๅ…ฅ็š„ๅ‚ๆ•ฐๆ˜ฏๅฆๆ˜ฏๅ‡ฝๆ•ฐ export const isFunction = (val: unknown): val is Function => typeof val === 'function' // ๅˆคๆ–ญไผ ๅ…ฅ็š„ๅ‚ๆ•ฐๆ˜ฏๅฆๆ˜ฏๅญ—็ฌฆไธฒ export const isString = (val: unknown): val is string => typeof val === 'string' // ๅˆคๆ–ญไผ ๅ…ฅ็š„ๅ‚ๆ•ฐๆ˜ฏๅฆๆ˜ฏ symbol export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol' // ๅˆคๆ–ญไผ ๅ…ฅ็š„ๅ‚ๆ•ฐๆ˜ฏๅฆๆ˜ฏๅฏน่ฑก export const isObject = (val: unknown): val is Record<any, any> => val !== null && typeof val === 'object' // ๅˆคๆ–ญไผ ๅ…ฅ็š„ๅ‚ๆ•ฐๆ˜ฏๅฆๆ˜ฏ Promise export function isPromise<T = any>(val: unknown): val is Promise<T> { return isObject(val) && isFunction(val.then) && isFunction(val.catch) } export const objectToString = Object.prototype.toString // ๅฏผๅ‡บไผ ๅ…ฅๅ‚ๆ•ฐ็š„็ฑปๅž‹ๅญ—็ฌฆไธฒ export const toTypeString = (value: unknown): string => objectToString.call(value) // ๅฏผๅ‡บไผ ๅ…ฅๅ‚ๆ•ฐ็š„ๅŽŸๅง‹็ฑปๅž‹ export function toRawType(value: unknown): string { return toTypeString(value).slice(8, -1) } // ๅˆคๆ–ญไผ ๅ…ฅ็š„ๅ‚ๆ•ฐๆ˜ฏๅฆๆ˜ฏๆ™ฎ้€šๅฏน่ฑก export const isPlainObject = (val: unknown): val is object => toTypeString(val) === '[object Object]' // ๅˆคๆ–ญๆ˜ฏๅฆๆ˜ฏ ้ข„็•™ prop export const isReservedProp = /*#__PURE__*/ makeMap( 'key,ref,' + 'onVnodeBeforeMount,onVnodeMounted,' + 'onVnodeBeforeUpdate,onVnodeUpdated,' + 'onVnodeBeforeUnmount,onVnodeUnmounted' ) const camelizeRE = /-(\w)/g export const camelize = (str: string): string => { return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : '')) } const hyphenateRE = /\B([A-Z])/g export const hyphenate = (str: string): string => { return str.replace(hyphenateRE, '-$1').toLowerCase() } export const capitalize = (str: string): string => { return str.charAt(0).toUpperCase() + str.slice(1) } // compare whether a value has changed, accounting for NaN. export const hasChanged = (value: any, oldValue: any): boolean => value !== oldValue && (value === value || oldValue === oldValue)
/** * @mxmlc -target-player=10.0.0 -debug */ /** * Katakana / Hiragana learning tool * Jukka Paasonen */ package sandbox { import flash.display.*; import flash.events.*; import flash.geom.*; import flash.media.Sound; import flash.text.*; import org.paazio.utils.Numbers; import org.paazio.lang.Japanese; [SWF(backgroundColor = '0x042836', frameRate = '33', width = '900', height = '700')] public class KanaLearner extends Sprite { [Embed(source = "../assets/maru_hira-kata-roma_only.ttf", fontFamily = "maru")] public var Maru:String; // Settings private var colors:Object = { fill: 0xFBFBFB, outline: 0x000000, text: 0x2B2B2B, hover: 0xCBCBCB }; private var locations:Object = { bTop: 50, bLeft: 20, bMargin: 2 }; private var volume:Number = 60; private var gridCont:Sprite; private var gSound:Sound = new Sound(); private var playSound:Boolean = false; private var points:Number = 0; private var started:Date; private var usedItems:Array = []; public function KanaLearner() { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; stage.quality = StageQuality.MEDIUM; loaderInfo.addEventListener(Event.INIT, onInit); } private function onInit(event:Event):void { drawGradientBack(); } private function drawGradientBack():void { var gra:Graphics = graphics; gra.clear(); var fillType:String = GradientType.RADIAL; var colors:Array = [0xDCB51B, 0xC6B9B0]; var alphas:Array = [100, 100]; var ratios:Array = [0, 0xFF]; var spreadMethod:String = SpreadMethod.REFLECT; var interpolationMethod:String = InterpolationMethod.LINEAR_RGB; var focalPointRatio:Number = 0.9; var matrix:Matrix = new Matrix(); matrix.createGradientBox(stage.stageWidth / 2, stage.stageHeight / 2, Math.PI); gra.beginGradientFill(fillType, colors, alphas, ratios, matrix, spreadMethod, interpolationMethod, focalPointRatio); gra.drawRect(0, 0, stage.stageWidth, stage.stageHeight); gra.endFill(); } private function createKanaButton(parent:Sprite, txtIndex:String, txtObj:Object, bWidth:Number, bHeight:Number, colors:Object):Sprite { var backg:Sprite = new Sprite(); drawShape4(backg.graphics, bWidth, bHeight, bWidth / 2, bHeight / 2, colors, 5, 4); var txtfmt:TextFormat = new TextFormat(); txtfmt.align = TextFormatAlign.LEFT; txtfmt.bold = false; txtfmt.color = colors.text; txtfmt.font = "maru"; txtfmt.leftMargin = 0; txtfmt.rightMargin = 0; txtfmt.size = 14; //trace(txtIndex + " Txtfiled depth should be " + backg.getNextHighestDepth()); var field:TextField = new TextField(); field.autoSize = TextFieldAutoSize.LEFT; field.background = false; field.border = false; field.condenseWhite = true; field.embedFonts = true; field.maxChars = 3; field.mouseWheelEnabled = false; field.multiline = false; field.selectable = true; field.text = txtObj[txtIndex]; field.wordWrap = true; field.defaultTextFormat = txtfmt; backg.addChild(field); /* backg.onRelease = function() { trace(charkey); //playKanaSound(charkey); }; */ return backg; } // xPos, yPos give the center of the shape private function drawShape4(mc:Graphics, xPos:Number, yPos:Number, width:Number, height:Number, colors:Object, four:Number, eight:Number):void { // lineStyle(thickness:Number, rgb:Number, alpha:Number, pixelHinting:Boolean, noScale:String, capsStyle:String, jointStyle:String, miterLimit:Number) mc.lineStyle(1, colors.outline, 100); // beginFill(rgb:Number, [alpha:Number]) // beginGradientFill(fillType:String, colors:Array, alphas:Array, ratios:Array, matrix:Object, [spreadMethod:String], [interpolationMethod:String], [focalPointRatio:Number]) mc.beginFill(colors.fill, 100); mc.moveTo(xPos + width, yPos); // curveTo(controlX:Number, controlY:Number, anchorX:Number, anchorY:Number) mc.curveTo(width + xPos, Math.tan(Math.PI / eight) * height + yPos, Math.sin(Math.PI / four) * width + xPos, Math.sin(Math.PI / four) * height + yPos); mc.curveTo(Math.tan(Math.PI / eight) * width + xPos, height + yPos, xPos, height + yPos); mc.curveTo(-Math.tan(Math.PI / eight) * width + xPos, height + yPos, -Math.sin(Math.PI / four) * width + xPos, Math.sin(Math.PI / four) * height + yPos); mc.curveTo(-width + xPos, Math.tan(Math.PI / eight) * height + yPos, -width + xPos, yPos); mc.curveTo(-width + xPos, -Math.tan(Math.PI / eight) * height + yPos, -Math.sin(Math.PI / four) * width + xPos, -Math.sin(Math.PI / four) * height + yPos); mc.curveTo(-Math.tan(Math.PI / eight) * width + xPos, -height + yPos, xPos, -height + yPos); mc.curveTo(Math.tan(Math.PI / eight) * width + xPos, -height + yPos, Math.sin(Math.PI / four) * width + xPos, -Math.sin(Math.PI / four) * height + yPos); mc.curveTo(width + xPos, -Math.tan(Math.PI / eight) * height + yPos, width + xPos, yPos); mc.endFill(); } // xPos, yPos give the upper left corner private function drawBox4(mc:Graphics, xPos:Number, yPos:Number, height:Number, width:Number, colors:Object, doOutline:Boolean):void { if (doOutline) { mc.lineStyle(1, colors.outline, 100); } else { mc.beginFill(colors.fill, 100); } mc.moveTo(xPos, yPos); mc.lineTo(xPos + width, yPos); mc.lineTo(xPos + width, yPos + height); mc.lineTo(xPos, yPos + height); mc.lineTo(xPos, yPos); if (!doOutline) { mc.endFill(); } } } } /* // Create buttons for selecting kana type. var hiragana_bt:MovieClip = createButton(createEmptyMovieClip("hiragana_bt", getNextHighestDepth()), 90, 20, colors, "Hiragana"); var katakana_bt:MovieClip = createButton(createEmptyMovieClip("katakana_bt", getNextHighestDepth()), 90, 20, colors, "Katakana"); var romaji_bt:MovieClip = createButton(createEmptyMovieClip("romaji_bt", getNextHighestDepth()), 90, 20, colors, "Romaji"); hiragana_bt._y = locations.bTop; katakana_bt._y = hiragana_bt._y + hiragana_bt._height + locations.bMargin; romaji_bt._y = katakana_bt._y + katakana_bt._height + locations.bMargin; hiragana_bt._x = locations.bLeft; katakana_bt._x = locations.bLeft; romaji_bt._x = locations.bLeft; // Create "preview" field for the character we are asking var preview:MovieClip = createEmptyMovieClip("preview", getNextHighestDepth()); preview._y = locations.bTop; preview._x = locations.bLeft + hiragana_bt._width + locations.bMargin * 10; preview = createButton(preview, 80, 80, colors, "..."); // Text field for points and time var points:TextField = createTextField("points", getNextHighestDepth(), romaji_bt._y + locations.bMargin, locations.bLeft, 400, 60); //points.text = "Halloota talloon"; // Create start button var start_bt:MovieClip = createEmptyMovieClip("start_bt", getNextHighestDepth()); start_bt._y = locations.bTop; start_bt._x = preview._x + preview._width + locations.bMargin * 10; start_bt = createButton(start_bt, 120, 20, colors, "Start testing"); // ####################################################################### // Button and other "on" based actions hiragana_bt.onPress = chooseKanaSet; katakana_bt.onPress = chooseKanaSet; romaji_bt.onPress = chooseKanaSet; gSound.onSoundComplete = function() { trace("Sound completed"); }; start_bt.onRelease = function() { started = new Date(); _visible = false; }; // ####################################################################### // Functions function chooseKanaSet():void { var kana:String = _name.split("_")[0]; trace(kana); gridCont.removeMovieClip(); gridCont = createCharGrid(_root[kana], _root, 2, 25, 22, colors); gridCont._x = preview._x + preview._width + locations.bMargin * 10; gridCont._y = locations.bTop; } function createCharGrid(kana:Object, parent:MovieClip, margin:Number, bWidth:Number, bHeight:Number, colors:Object):MovieClip { var cont:MovieClip = parent.createEmptyMovieClip("cont", parent.getNextHighestDepth()); var s:Number = 0; var k:Number = 0; for (var i in kana) { var clip:MovieClip = createKanaButton(cont, i, kana, bWidth, bHeight, colors); clip._x = k * (clip._width + margin); //trace("clip._width : " + clip._width); clip._y = s * (clip._height + margin); //trace("clip._height : " + clip._height); // Count the x location multiplier for next round if (s < 4) { if (i.substr(0, 1) == "y") { s += 2; } else if (i == "wa0") { s += 4; } else { s++; } } else { s = 0; } // Count the y location multiplier for nex round. if (i.substr(1, 1) == "o") { k++; } } return cont; } function createButton(clip:MovieClip, bWidth:Number, bHeight:Number, colors:Object, createText:String):MovieClip { // Create containers for the fill and for the outlines. //trace("Default value of createText is undefined, but now it is " + createText); var bgCont:MovieClip = clip.createEmptyMovieClip("bgfill", clip.getNextHighestDepth()); var ouCont:MovieClip = clip.createEmptyMovieClip("outline", clip.getNextHighestDepth()); if (createText != undefined) { var txtBt:TextField = clip.createTextField("txt", clip.getNextHighestDepth(), 0, 0, bWidth, bHeight); txtBt.text = createText; txtBt.size = Math.round(clip._height / 2); } // Draw background drawBox4(bgCont, 0, 0, bHeight, bWidth, colors, false); drawBox4(ouCont, 0, 0, bHeight, bWidth, colors, true); // When mouseover, change fill color. Change back when rollout. clip.onRollOver = function() { var clTr:ColorTransform = bgfill.transform.colorTransform; clTr.rgb = colors.hover; bgfill.transform.colorTransform = clTr; //trace("RollOver of " + this + ", clTr.rgb : " + clTr.rgb); }; clip.onRollOut = function() { var clTr:ColorTransform = bgfill.transform.colorTransform; clTr.rgb = colors.fill; bgfill.transform.colorTransform = clTr; //trace("RollOut of " + this + ", clTr.rgb : " + clTr.rgb); }; return clip; } function playKanaSound(sndId:String):void { // Play the sound which pronounces the character released. gSound.attachSound(sndId); gSound.start(); } function showRandKana(preview:TextField, kanaset:Object, usedItems:Array):void { var objKeys:Array = new Array(); // Push keys in array. Terrible way to go. for (var i in kanaset) { for (var s in usedItems) { if (usedItems[s] == kanaset[i]) { continue; } } objKeys.push(i); } // Select random index var inx:String = kanaset[Numbers.random(0, objKeys.length)]; // Set the text preview.text = kanaset[inx]; // Add the current to the used list usedItems.push(inx); } */
#include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266mDNS.h> #include <WiFiUdp.h> #include <NTPClient.h> #include <ArduinoOTA.h> #include <FS.h> ESP8266WiFiMulti wifiMulti; const char* dns_name = "heizungssteuerung"; // time client WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org"); //Week Days String weekDays[7]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; //Month names String months[12]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; void printWifiStatus(); void connectWiFi(); void initWiFi() { Serial.println("Starting WiFi"); wifiMulti.addAP("NetFrame", "87934hzft9oeu4389nv8o437893hf978"); wifiMulti.addAP("JCBS-WLAN", "K1,12Wviaa,dgeM,KGzw."); wifiMulti.addAP("Movement2", "12345678"); WiFi.mode(WIFI_STA); connectWiFi(); } void connectWiFi() { // WiFi.scanNetworks will return the number of networks found int n = WiFi.scanNetworks(); Serial.println("scan done"); if (n == 0) { Serial.println("no networks found"); } else { Serial.print(n); Serial.println(" networks found"); for (int i = 0; i < n; ++i) { // Print SSID and RSSI for each network found Serial.print(i + 1); Serial.print(": "); Serial.print(WiFi.SSID(i)); Serial.print(" ("); Serial.print(WiFi.RSSI(i)); Serial.print(")"); Serial.println((WiFi.encryptionType(i) == AUTH_OPEN)?" ":"*"); delay(10); } } Serial.println(); // Connect to Wi-Fi using wifiMulti (connects to the SSID with strongest connection) Serial.println("Connecting Wifi..."); if(wifiMulti.run() != WL_CONNECTED) { Serial.println("Connection failed"); return; } Serial.println(); Serial.println("WiFi connected"); printWifiStatus(); Serial.println(); if(MDNS.begin(dns_name)) { Serial.println("DNS gestartet, erreichbar unter: "); Serial.println("http://" + String(dns_name) + ".local/"); } else Serial.println("Error setting up MDNS responder!"); // Initialize a NTPClient to get time timeClient.setTimeOffset(3600); timeClient.begin(); Serial.println(); } void initOTA() { // Start ArduionOTA Serial.println("starting OTA"); ArduinoOTA.setHostname(dns_name); ArduinoOTA.onStart([]() { Serial.println("Start"); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); Serial.println("OTA started"); Serial.println(); } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); } void reconnectWiFi() { if(WiFi.status() == WL_CONNECTED) return; connectWiFi(); } // Initialize SPIFFS void initFS() { Serial.println("Starting Filesystem"); if (!SPIFFS.begin()) { Serial.println("An error has occurred while mounting SPIFFS"); } else{ Serial.println("SPIFFS mounted successfully"); } }
package com.epam.kubernetes_intensive.service; import com.epam.kubernetes_intensive.dao.PostRepository; import com.epam.kubernetes_intensive.model.Post; import lombok.extern.log4j.Log4j; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import java.util.HashMap; import java.util.List; @Slf4j @Service public class PostService { private final RestTemplate restTemplate; private final PostRepository postRepository; private final String userServiceUrl; @Autowired public PostService(RestTemplate restTemplate, PostRepository postRepository, @Value("${user.service.url}") String userServiceUrl) { this.restTemplate = restTemplate; this.postRepository = postRepository; this.userServiceUrl = userServiceUrl; } public Post getPostById(Long id) { return postRepository.findById(id).orElseThrow(() -> new RuntimeException( String.format("Post with id = {} doesn't exist", id) )); } public List<Post> getAllPosts() { return postRepository.findAll(); } @Transactional public void deleteById(Long id) { Post post = postRepository.findById(id).orElseThrow(() -> new RuntimeException( String.format("Post with id = {} doesn't exist", id) )); postRepository.deleteById(id); updateNumberOfPost(post.getUserId(), false); } @Transactional public void createPost(Post post) { postRepository.save(post); updateNumberOfPost(post.getUserId(), true); } public Post updatePost(Post post) { Post post1 = postRepository.save(post); log.info("POST WAS UPDATED -> "+post1); System.out.println("POST WAS UPDATED -> "+post1); return post1; } private void updateNumberOfPost(Long userId, boolean isPositive) { String uriString = UriComponentsBuilder.fromHttpUrl(userServiceUrl + userId) .queryParam("isPositive", isPositive).toUriString(); restTemplate.put(uriString, HttpMethod.PUT); } }
from django.db import transaction from django.shortcuts import get_object_or_404 from djoser.serializers import UserSerializer from drf_extra_fields.fields import Base64ImageField from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from recipes.models import (Favorite, Ingredient, IngredientInRecipe, Recipe, ShoppingCart, Tag) from users.models import Follow, User class CustomUserSerializer(UserSerializer): is_subscribed = serializers.SerializerMethodField( method_name='get_is_subscribed' ) class Meta: model = User fields = ( 'username', 'id', 'email', 'first_name', 'last_name', 'is_subscribed' ) def get_is_subscribed(self, author): request = self.context.get('request') return (request and request.user.is_authenticated and author.following.filter(user=request.user).exists()) class FollowSerializer(serializers.ModelSerializer): class Meta: model = Follow fields = ('user', 'author') validators = [ UniqueTogetherValidator( queryset=Follow.objects.all(), fields=('user', 'author'), message=('ะ’ั‹ ัƒะถะต ะฟะพะดะฟะธัะฐะฝั‹ ะฝะฐ ัั‚ะพั‚ ะฐะบะบะฐัƒะฝั‚') ), ] def validate_following(self, value): if self.context['request'].user == value: raise serializers.ValidationError( 'ะะตะปัŒะทั ะฟะพะดะฟะธัั‹ะฒะฐั‚ัŒัั ะฝะฐ ัะฐะผะพะณะพ ัะตะฑั!' ) return value class RecipeShortSerializer(serializers.ModelSerializer): class Meta: model = Recipe fields = ( 'id', 'name', 'image', 'cooking_time' ) class SubscriptionSerializer(serializers.ModelSerializer): is_subscribed = serializers.SerializerMethodField( method_name='get_is_subscribed' ) recipes = serializers.SerializerMethodField(method_name='get_recipe') recipes_count = serializers.SerializerMethodField( method_name='get_recipe_count' ) class Meta: model = User fields = ( 'email', 'id', 'username', 'first_name', 'last_name', 'is_subscribed', 'recipes', 'recipes_count' ) def get_request(self): return self.context.get('request') def get_is_subscribed(self, obj): return obj.following.filter( user=self.get_request().user ).exists() def get_recipe(self, obj): limit = self.get_request().GET.get('recipes_limit') recipes = obj.author.all() if limit: recipes = recipes[:int(limit)] return RecipeShortSerializer(recipes, many=True, context={'request': self.get_request()} ).data def get_recipe_count(self, obj): return obj.author.all().count() class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = '__all__' class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class IngredientInRecipeSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='ingredient.id') name = serializers.ReadOnlyField(source='ingredient.name') measurement_unit = serializers.ReadOnlyField( source='ingredient.measurement_unit') class Meta: model = IngredientInRecipe fields = ('id', 'name', 'measurement_unit', 'amount') class AddIngredientSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=Ingredient.objects.all()) amount = serializers.IntegerField() class Meta: model = IngredientInRecipe fields = ('id', 'amount') class RecipeSerializer(serializers.ModelSerializer): author = CustomUserSerializer(read_only=True) tags = TagSerializer(many=True, read_only=True) ingredients = IngredientInRecipeSerializer(source='ingredient_in_recipe', read_only=True, many=True) image = Base64ImageField() is_favorited = serializers.SerializerMethodField( method_name='get_is_favorited') is_in_shopping_cart = serializers.SerializerMethodField( method_name='get_is_in_shopping_cart') class Meta: model = Recipe fields = ( 'id', 'name', 'author', 'image', 'ingredients', 'text', 'tags', 'cooking_time', 'is_favorited', 'is_in_shopping_cart' ) def get_request(self, obj, model): request = self.context.get('request') return (request and request.user.is_authenticated and model.objects.filter(user=request.user, recipe=obj).exists()) def get_is_favorited(self, obj): return self.get_request(obj, Favorite) def get_is_in_shopping_cart(self, obj): return self.get_request(obj, ShoppingCart) class AddRecipeSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField( queryset=Tag.objects.all(), many=True) image = Base64ImageField() ingredients = AddIngredientSerializer(many=True) author = CustomUserSerializer(read_only=True) cooking_time = serializers.IntegerField() class Meta: model = Recipe fields = ('id', 'tags', 'author', 'ingredients', 'name', 'image', 'text', 'cooking_time') def validate_ingredient(self, value): ingredient = value if not ingredient: raise serializers.ValidationError( 'ะ—ะฐะฟะพะปะฝะธั‚ะต ะฟะพะปะต ะธะฝะณั€ะตะดะธะตะฝั‚ะพะฒ' ) ingredients_list = [] for item in ingredient: ingredients = get_object_or_404(Ingredient, id=item['id']) if ingredients in ingredients_list: raise serializers.ValidationError( 'ะ˜ะฝะณั€ะตะดะธะตะฝั‚ั‹ ะฝะต ะดะพะปะถะฝั‹ ะฟะพะฒั‚ะพั€ัั‚ัŒัั' ) if int(item['amount']) <= 1: raise serializers.ValidationError( 'ะšะพะปะธั‡ะตัั‚ะฒะพ ะธะฝะณั€ะตะดะธะตะฝั‚ะพะฒ ะดะพะปะถะฝะพ ะฑั‹ั‚ัŒ ะฑะพะปัŒัˆะต ะพะดะฝะพะณะพ' ) ingredients_list.append(ingredients) return value def validate_tags(self, value): tags = value if not tags: raise serializers.ValidationError( 'ะ—ะฐะฟะพะปะฝะธั‚ะต ะฟะพะปะต ั‚ะตะณะฐ' ) tag_list = [] for tag in tags: if tag in tag_list: raise serializers.ValidationError( 'ะขะตะณ ะดะพะปะถะตะฝ ะฑั‹ั‚ัŒ ัƒะฝะธะบะฐะปัŒะฝั‹ะผ' ) tag_list.append(tag) return value def validate_cooking_time(self, data): if data <= 0: raise serializers.ValidationError( 'ะ’ั€ะตะผั ะฟั€ะธะณะพั‚ะพะฒะปะตะฝะธะต ะฝะต ะผะตะฝัŒัˆะต ะผะธะฝัƒั‚ั‹' ) return data def to_representation(self, instance): return RecipeSerializer(instance).data @transaction.atomic def create_ingredients(self, ingredients, recipe): IngredientInRecipe.objects.bulk_create( [IngredientInRecipe( ingredient=ingredient.get('id'), recipe=recipe, amount=ingredient.get('amount'), ) for ingredient in ingredients] ) @transaction.atomic def create(self, validated_data): tags = validated_data.pop('tags') ingredients = validated_data.pop('ingredients') recipe = Recipe.objects.create(author=self.context['request'].user, **validated_data) recipe.tags.set(tags) self.create_ingredients(ingredients, recipe) return recipe @transaction.atomic def update(self, instance, validated_data): ingredients = validated_data.pop('ingredients') tags = validated_data.pop('tags') instance.ingredients.clear() self.create_ingredients(ingredients, instance) instance.tags.clear() instance.tags.set(tags) return super().update(instance, validated_data)
๏ปฟ<?xml version="1.0" encoding="utf-8"?> <html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" MadCap:lastBlockDepth="6" MadCap:lastHeight="12224" MadCap:lastWidth="1220"> <head> <link href="../Resources/Stylesheets/help_ie.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="navigation"> <table style="WIDTH: 100%;" width="100%"> <tr valign="bottom"> <td width="95%" align="left" valign="bottom" style="font-family: Arial;font-size: 12pt;"><em style="font-style: italic;"></em>BioSARBrowser</td> </tr> <tr align="left" valign="top"> <td style="font-family: Arial;font-size: 12pt;"> <hr /><b>User</b><strong>'s Guide</strong> </td> </tr> </table> </div> <h1>Creating a Form</h1> <p>You must have privileges to create new forms. &#160;If you do not have the required privileges, contact your system administrator.</p> <p><span style="font-size: 11pt; font-weight: bold;">To create a new form:</span> </p> <ol> <li>From the Form&#160;Management interface, click on <b>Create New Form</b>.</li> </ol> <p> <img src="../Resources/Images/BioSARBrowser images/create a new form button.gif" /> </p> <ol MadCap:continue="true"> <li>Enter a Name and Description for the new form in the designated fields.</li> </ol> <p> <img src="../Resources/Images/BioSARBrowser images/form description.gif" /> </p> <ol MadCap:continue="true"> <li>Click <b>Save Changes</b>. The newly-created form appears: </li> </ol> <p> <img src="../Resources/Images/BioSARBrowser images/test form.gif" /> </p> <p><b style="font-size: 14pt;">Selecting a Base Table </b> </p> <p>A base table is the table on which the new form is based. The base table is always the first table in any form, and all additional tables included in the form must be linked to that base table. When defining a search form, you can select any table in the visible schemas as the base table. Only one base table can be chosen for a form. The list of child tables changes based on the base table you select. </p> <p style="font-size: 11pt;font-weight: bold;">To select a base table:</p> <ol> <li>Click <b>Select Base Table</b> in the newly-created form. The Choose Base Table window appears:<br /><br /><img src="../Resources/Images/BioSARBrowser images/base_table_select_532x456.gif" /><br /></li> <li>Select a <b>Schema</b> from the Schema list. The Base Table list automatically populates based on the schema you select.</li> <li>Select the <b>Base Table</b> from the Base Table list. <br /><img src="../Resources/Images/BioSARBrowser images/base table selected.gif" /><br /></li> <li>Click <b>Save Changes</b>. The new base table displays, as shown in the example below. <br /><br /><img src="../Resources/Images/BioSARBrowser images/base_table.gif" /></li> </ol> <p><span style="font-size: 14pt;font-weight: bold;">Selecting Fields In a Table</span> </p> <p>After selecting a base table, you select the fields you want visible to the form user. You also define the conditions when the fields are visible. </p> <p style="font-size: 11pt;font-weight: bold;">To select fields in a table:</p> <ol> <li>Click <b>Edit</b> in the Fields column of the relevant table. A page listing all available fields appears, as in the example below. <br /><br /><img src="../Resources/Images/BioSARBrowser images/pick_fields.gif" /><br />Three columns, representing different views display to the right of Field names and Descriptions in the table. These columns are as follows: <blockquote><p>โ€ข <b>Query</b>: Visible in the Query form and used to search.</p><p>โ€ข <b>List</b>: Visible in the Results List form in which multiple records are viewed simultaneously.</p><p>โ€ข <b>Detail</b>: Visible when a single record is viewed at a time.</p></blockquote></li> <li>Select the checkboxes in the appropriate columns to indicate the fields you want to display for a particular view.</li> <li>Click <b>Save Changes</b>. </li> </ol> <p><b style="font-size: 14pt;">Selecting Child Tables</b> </p> <p style="font-size: 11pt;font-weight: bold;">To select a child table:</p> <ol> <li>After selecting the Parent table, click <b>Select Child Table</b>. The Choose Child Table window appears:</li> </ol> <p> <img src="../Resources/Images/BioSARBrowser images/child table.gif" /> </p> <ol MadCap:continue="true"> <li>Select the child table and click <b>Save Changes</b>.</li> <li>Follow the steps in "Selecting Fields in a Table" to customize the visible fields in the form.</li> </ol> <p><b style="font-size: 14pt;">Displaying Fields in Forms</b> </p> <p>After selecting the fields to display in a table, you define how the selected fields will display in a form. </p> <p><b>Note</b>: You can modify the options for only those fields you have selected as visible in your form.</p> <p><span style="font-size: 11pt; font-weight: bold;">To define table fields displayed in forms:</span> </p> <ol> <li>Click <b>Edit</b> in the Field Options column for the table whose fields you want to define. <br /><img src="../Resources/Images/BioSARBrowser images/field options.gif" /><br /></li> <li>The list of selected fields, along with the display options, appears. <br /><img src="../Resources/Images/BioSARBrowser images/field options2.gif" /><br /></li> <li>Select the display options you want to define. </li> </ol> <p><![CDATA[ ]]><b>Note</b>: Some fields cannot be customized. &#160;There is only one option for display. &#160;In these instances, no choice is provided.</p> <ol MadCap:continue="true"> <li>Enter the desired dimensions for each field in each view. </li> </ol> <p><i><b style="font-style: normal;">Note</b>:</i>When configuring column-width values, remember that with default font settings, you need 7 points for each character you want to display. For example, to display a 12 character registration number, the column width should be set to 84. The content of the table cell is truncated to a fixed number of characters based on the configured width of the column, and a conversion factor based on the font type and size. The default font for table cell data is <b>Lucida Console 9 pt</b>, which is an equi-spaced font. The truncated text will be followed by "โ€ฆ" and the full text of the cell value will be displayed as a tip when the mouse pointer moves over the truncated value.<i></i></p> <ol MadCap:continue="true"> <li>Select <b>Show</b> corresponding to a field, to make this field visible to users in the specified view.</li> <li>Click <b>Save Changes</b> to save your changes. </li> </ol> <p><b style="font-size: 14pt;">Field Display Options</b> </p> <p>The field display options are as follows: </p> <ul style="list-style-type: square;"> <li><b>Structure</b>: Displays a structure window. This option is available in Search view.</li> <li><b>ChemDraw Plug-in</b>: Displays a CDX file, which can be edited using the ChemDraw toolbar. This option is available in List and Detail views.</li> <li><b>Graphic</b>: Displays a graphic. An IN-LINE graphic appears in the current window. NEW WINDOW means a link to the graphic will be displayed. Clicking on the link will open the graphic in a new window. This option is available in List and Detail views.</li> <li><b>Static GIF</b>: Displays a GIF image, which displays an image of the structure. The image cannot be edited. This is only available if the field in the database is base64. This option is available in List and Detail views. This option is not available if the field is set to one of the following types: CDX_BLOB, SMILES, MOLFILE or CDXML.</li> <li><b>Hyperlink</b>: Lets you access files or web pages on remote servers. However, in the results window, only the word 'link' is displayed, instead of the actual URL. Click on the link to open a file, or web page. The Hyperlink option is available in List and Detail views.</li> <li><b>Text Box</b>: Displays a text box. This option is available in Search view. 6 Form Management.</li> <li><b>Text Area</b>: Lets you enter multiple lines of text. This option is available in Search view.</li> <li><b>TextBoxAllowList</b>: Lets you browse to a list of files and use that as the entry, or enter multiple values delimited by commas, tabs, or linefeeds. These values can be pasted from Excel, or a text file. This option is available in Search view.</li> <li><b>DatePicker</b>: Includes a calendar icon allowing easy input of dates. This option is available in Search view.</li> <li><b>Date</b>: Validates as date. This option is available in Search view.</li> <li><b>URL</b>: Lets you create hyperlinks using Hyperlink and Link Text fields, based on the data contained in the form. This option is available in List and Detail views.</li> <li><b>Link Text</b>: Lets you create hyperlinks using Hyperlink and URL fields, based on the data contained in the form. This option is available in List and Detail views. </li> </ul> <p style="font-weight: bold;">Augmented Hyperlinks</p> <p>The augmented hyperlink functionality lets you create hyperlinks based on data contained in the form. </p> <p>The fields, Hyperlink, URL, and Link text are used to create augmented hyperlinks. To create augmented hyperlinks, you can combine these fields in three ways:</p> <ul style="list-style-type: square;"> <li><b>Hyperlink selected, URL blank, Link Text blank</b>: This method requires the entire URL to be stored in the database.</li> <li><b>Hyperlink selected, URL entered, Link Text blank</b>: This method displays the value of the column and the link navigates to the URL entered in the URL box. For example, if you make regid a link, it will display the actual regid.</li> <li><b>Hyperlink selected, URL entered, Link Text Entered</b>: This method displays the link text, instead of the value. </li> </ul> <p><i><b style="font-style: normal;">Note</b></i>: The base ID of the base table cannot display as a link. However, the ID is available for use when creating a link to another field.</p> <p><b>Note</b>: Links that contain replacement values in a child table cannot be displayed in the base table. The link must be created in the child table of the form. Values from the parent table can exist in child tables of a form. </p> <p><b style="font-size: 14pt;">Masks</b> </p> <p>You can use format masks, in some fields, to format the output of the fields and display the results. The format models described below can be used in the Format Mask field when building your form. </p> <p><b>Conversion Formats</b> <![CDATA[ ]]></p> <p>Several of the conversion functions, such as: TO_CHAR, TO_DATE, and TO_NUMBER use format models to determine the format of the converted data. Format models convert strings to dates, and strings to numbers. The default format for dates as character values is DD-MON-YY. However, if you want, you can specify your own default date format with the NLS_DATE_FORMAT parameter, as follows: NLS_DATE_FORMAT = `MM/DD/YYYY'.</p> <p>The following table describes the various <b>Date Format Masks</b>:</p> <table style="width: 100%;border-collapse: separate;border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;margin-left: 0;margin-right: auto;"> <col style="width: 119px;" /> <col style="width: 50%;" /> <tbody> <tr> <td style="font-weight: bold;border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Mask</td> <td style="font-weight: bold;border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Description</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">SCC or CC</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">CC represents a century in A.D. SCC format is used to represent centuries in B.C. A B.C. century is prefaced with a hyphen (-).</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">SYYYY or YYYY</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">YYYY represents a four-digit year. SYYYY format is used to represent a B.C. year. A B.C. year is prefaced with a hyphen (-).</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">IYYY </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The four-digit ISO standard year.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">YYY or YY or Y </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The last three, two, or one digits of the year. The default value is the last three, two, or one digit of the current year.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">IYY or IY or I</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The last three, two, or one digits of the ISO standard year. The default value is the last three, two, or one digit of the current ISO standard year.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Y,YYY</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The four-digit year with a comma.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">SYEAR or YEAR or SYear or Year </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The year spelled out. The S prefix places a negative sign in front of B.C. dates.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">RR </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The last two digits of the year. This format is used to display years in centuries other than our own.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">BC or AD </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The B.C. or A.D. indicator, without periods.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">B.C. or A.D.</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The B.C. or A.D. indicator, with periods.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Q </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The quarter of the year, from 1 through 4. January through March are in the first quarter, April through June in second quarter.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">MM</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The number of the month in the year, from 01 through 12. January is month number 01, September is 09.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">RM</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The Roman numeral representation of the month number, from I through XII. January is I, September is IX.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">MONTH or Month </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The name of the month, either in upper- or mixed-case format.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">MON or Mon</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The abbreviated name of the month, as in JAN for January.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">WW</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">WW The week in the year, from 1 through 53.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">IW</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The week in the year, from 1 through 52 or 1 through 53, based on the ISO standard.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">W</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The week in the month, from 1 through 5. Week 1 starts on the first day of the month and ends on the seventh.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">DDD</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The day in the year, from 1 through 366.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">DD</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The day in the month, from 1 through 31.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">D</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The day in the week, from 1 through 7. The first day is defined by the NLS_TERRITORY initialization parameter for the database instance.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">DAY or Day </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The name of the day in upperor mixed-case format.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">DY</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The abbreviated name of the day, as in TUE for Tuesday.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">J</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The Julian day format of the date (counted as the number of days since January 1, 4712 B.C., the earliest date supported by the Oracle RDBMS).</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">AM or PM</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The meridian indicator (morning or evening) without periods.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">A.M. or P.M. </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The meridian indicator (morning or evening) with periods.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">HH or HH12 </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The hour in the day, from 1 through 12.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">HH24</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The hour in the day, from 0 through 23.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">MI</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The minutes component of the date's time, from 0 through 59.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">SS</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The seconds component of the date's time, from 0 through 59.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">SSSSS</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The number of seconds since midnight of the time component. Values range from 1 through 86399, with each hour comprising 3600 seconds.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">TH</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The suffix that converts a number to its ordinal format. For example, 4 becomes 4th and 1 becomes 1st. This element can appear only at the end of the entire format mask. The return value is always in English, regardless of the date language.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">SP</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The suffix that converts a number to its spelled format. For example, 4 becomes FOUR, 1 becomes ONE, and 221 becomes TWO HUNDRED TWENTY ONE. This element can appear only at the end of the entire format mask. The return value is always in English, regardless of the date language.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">SPTH</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The suffix that converts a number to its spelled and ordinal format. For example, 4 becomes FOURTH and 1 becomes FIRST. This element can appear only at the end of the entire format mask. The return value is always in English, regardless of the date language.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">FX</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The element that requires exact pattern matching between data and format model. FX stands for Format eXact.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">FM</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">The element that toggles suppression of blanks in output from conversion. FM stands for Fill Mode.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Other text</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Any punctuation, such as a comma (,) or slash (/) or hyphen (-), will be reproduced in the formatted output of the conversion. You can also include text within double quotes ("). This text will be represented as entered in the converted value. See examples in TO_CHAR for an illustration of this element.</td> </tr> </tbody> </table> <p style="font-weight: bold;">Using Text in Dates</p> <p>Two parameters determine the type of text returned in dates, such as MONTH, MON, DAY, DY, AM, and PM. These parameters are: </p> <ul style="list-style-type: square;"> <li>The National Language Support parameters, NLS_DATE_LANGUAGE and NLS_LANGUAGE </li> <li>The optional date language argument you can pass to both TO_CHAR and TO_DATE. </li> </ul> <p>Some examples of date format masks composed with the above format elements are:</p> <ul style="list-style-type: square;"> <li>'Month DD, YYYY' </li> <li>'MM/DD/YY Day A.M.' </li> <li>'Year Month Day HH24:MI:SS' </li> <li>'J' โ€ข 'SSSSS-YYYY-MM-DD' </li> <li>'"A beautiful summer morning on the "DDth" day of "Month' </li> </ul> <p style="font-weight: bold;">Number Format Models </p> <p>The number formats are used in TO_CHAR and TO_NUMBER. The number format in TO_CHAR translates a numeric value to a VARCHAR2 data type. The number format in TO_NUMBER translates a VARCHAR2 value to a numeric data type. A number format mask can comprise one or more elements from the table shown below. The resulting format of the character string or the converted numeric value will reflect the combination of the format elements.</p> <p>Format elements with a description starting with "Prefix:" can be used only at the beginning of the complete format mask. Format elements with a description starting with "Suffix:" can be used only at the end of the complete format mask. </p> <p>The following table describes the number <b>Format Model Elements</b>:</p> <table style="width: 100%;border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;margin-left: 0;margin-right: auto;"> <col style="width: 88px;" /> <col /> <tbody> <tr> <td style="font-weight: bold;border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Format Elements</td> <td style="font-weight: bold;border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Description</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">9</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Represents a significant digit to be returned. Leading zeros in a number are displayed, or treated, as blanks.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">0</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Represents a significant digit to be returned. Leading zeros in a number are displayed, or treated, as zeros.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">$ </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Puts a dollar sign in front of the number. It is used as a prefix.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">B</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Returns a zero value as blanks, even if the format element was used to show a leading zero. It is used as a prefix.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">MI</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Places a minus sign (-) after the number, if it is negative. For positive values, it returns a trailing space. It is used as a suffix.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">S</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Places a plus sign (+) in front of a positive number and a minus sign (-) before a negative number. It is used as a prefix.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">PR</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Places angle brackets (&lt; and &gt;) around a negative value. For positive values, it places leading and trailing spaces around the number. It is used as a suffix.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">D</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Specifies the location of the decimal point in the returned value. All format elements to the left of the D will format the integer component of the value. All format elements to the right of the D will format the fractional part of the value. The character used for the decimal character is determined by the database initialization parameter NLS_NUMERIC_CHARAC TERS.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">G</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Specifies the location of the group separator in the returned value in the same ways as a comma is used to separate thousands, as in 6,734. The character used for the group separator is determined by the database initialization parameter NLS_NUMERIC_CHARAC TERS.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">C</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Specifies the location of the ISO currency symbol in the returned value.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">L</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Specifies the location of the local currency symbol, such as $, in the returned value.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">, (comma) </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Specifies that a comma is returned in that location in the return value.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">. (period) </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Specifies that a period is returned in that location in the return value.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">V</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Multiplies the number to the left of the V, in the format model by 10, raised to the nth power, where n is the number of 9s found after the V in the format model.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">EEEE</td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Specifies that the value be returned in scientific notation. It is used as a suffix.</td> </tr> <tr> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">RN or rn </td> <td style="border-left-style: solid;border-left-width: 1px;border-left-color: #808080;border-right-style: solid;border-right-width: 1px;border-right-color: #808080;border-top-style: solid;border-top-width: 1px;border-top-color: #808080;border-bottom-style: solid;border-bottom-width: 1px;border-bottom-color: #808080;">Specifies that the return value be converted to upper- or lowercase Roman numerals. The range of valid numbers for conversion to Roman numerals is between 1 and 3999. The value must be an integer.</td> </tr> </tbody> </table> <p>Some examples of numeric format masks built from these elements, are as follows:</p> <ul style="list-style-type: square;"> <li>9.999EEEE</li> <li>00V99</li> <li>S9,999,999</li> <li>00009MI </li> <li>999D99</li> <li>9G999G999 </li> <li>L999.99 </li> </ul> <p><b style="font-size: 14pt;">Display Order of Fields </b> </p> <p>You can display the order of fields as displayed in forms.</p> <p><span style="font-size: 11pt; font-weight: bold;">To display the order of fields to be displayed in forms: </span> </p> <ol> <li>Click the appropriate view option in the Field Order column of the relevant table. <br /><img src="../Resources/Images/BioSARBrowser images/field order.gif" /><br /></li> <li>A table listing all chosen fields displays:<br /><img src="../Resources/Images/BioSARBrowser images/order.gif" /></li> </ol> <ol MadCap:continue="true"> <li>Click the arrows to the right of a field name to move a field higher, or lower, on the form.</li> <li>Click <b>Save Changes</b>. </li> </ol> <p><b style="font-size: 14pt;"><span style="background-color: #ffffff;">Selecting Integration Options</span> <![CDATA[ ]]></b> </p> <p>The Integration tab lets you export the data displayed in forms to either an Excel spreadsheet or ChemFinder BioViz. </p> <p>When exporting data to Excel, you can choose one of the following options:</p> <ul style="list-style-type: square;"> <li>MERGED_CHILD: Puts data of child table into a single cell.</li> <li>PARENT_REPEATED: Puts data of child table into individual cells, repeating the parent table data in each row.</li> <li>PARENT_NOT_REPEATED: Puts data of child table into individual cells, without the parent data in each row. </li> </ul> <p><b>Note</b>: The system administrator can configure the <b>cfserver.ini</b> file so that a particular report option is available for all users, and users are unable to select a different export option from the one configured.</p> <p><b style="font-size: 14pt;">Selecting Users and Roles</b> </p> <p>With appropriate privileges, you can select specific users, and roles, to have access to a form. You can assign users and roles to a form using the Security tab of the form. </p> <p style="font-size: 11pt;font-weight: bold;">To add users or roles to the form:</p> <ol> <li>From the Security tab within the form, highlight the appropriate user/role in the <b>All Users and Roles</b> list, for example USER:&#160;SCIENTIST. </li> <li>Click <b>Add</b> to move . This moves the selected user/role to the <b>Permitted Users and Roles</b> list. </li> </ol> <p> <img src="../Resources/Images/BioSARBrowser images/selecting users.gif" /> </p> <ol MadCap:continue="true"> <li>To remove user/role from the <b>Permitted Users and Roles</b> list, highlight the appropriate item in the <b>Permitted Users and Roles</b> list and click <b>Remove</b>.<b></b> <![CDATA[ ]]></li> </ol> <p><b>Note</b>: When roles, or users, are chosen, even if an individual user is missing a role (for example, one to view a specific table in the form), the missing role is granted to the user automatically.</p> <p><b style="font-size: 14pt;">Assigning Forms to Projects</b> </p> <p>Forms can be assigned to any number of projects in the system using the Organization tab. The following image shows the Organization tab of a form:</p> <p> <img src="../Resources/Images/BioSARBrowser images/form_edit_org.gif" /> </p> <p style="font-size: 11pt;font-weight: bold;">To assign a form to a project:</p> <ol> <li>Click the Organization tab of the form you want to assign to a project.</li> <li>Click the <b>Add to Private Category</b> or <b>Add to Public Category</b> link to display the tree view window containing the list of projects.</li> <li>Navigate to the appropriate project.</li> <li>Click the project to assign the form to it. The selected project is listed under the appropriate form category. </li> </ol> <p><b style="font-size: 14pt;">Changing Project Assignment </b> </p> <p><span style="font-size: 11pt; font-weight: bold;">To change the project assignment to a different project:</span> </p> <ol> <li>Click the move link corresponding to the project name. The tree view window displays.</li> <li>Highlight the project to be newly assigned to the form.</li> <li>Verify that the selected project replaces the existing one. </li> </ol> <p><b style="font-size: 14pt;">Deleting Project Assignment</b> </p> <p style="font-size: 11pt;font-weight: bold;">To delete a project assignment:</p> <ol> <li>Select the project you want to delete in either the Private Form Categories or the Public Form Categories.</li> <li>Click on its corresponding <b>Delete</b> link. The project assignment is deleted.</li> </ol> <p>To learn more about adding, removing, and editing project groups, see โ€œ<a href="Organizing Projects.htm">Organizing Projects</a>โ€.</p> <p><b style="text-decoration: underline;">Related Topics</b> <br /><a href="Form Management.htm">Form Management</a> <br /><a href="BioSARBrowser Introduction.htm">BioSARBrowser</a> </p> </body> </html>
๏ปฟ--- title: Aspose.Cells ใ‚’ไฝฟ็”จใ—ใฆ Word Art ใฎ้€ใ‹ใ—ใ‚’ใƒฏใƒผใ‚ฏใ‚ทใƒผใƒˆใซ่ฟฝๅŠ ใ™ใ‚‹ type: docs weight: 10 url: /ja/java/add-word-art-watermark-to-worksheet-using-aspose-cells/ --- ## **Aspose.Cells - Word ใ‚ขใƒผใƒˆใฎ้€ใ‹ใ—ใ‚’ใƒฏใƒผใ‚ฏใ‚ทใƒผใƒˆใซ่ฟฝๅŠ ** ใƒฏใƒผใƒ‰ใ‚ขใƒผใƒˆใ‚’ไฝฟ็”จใ—ใฆใ€ใ‚นใƒ—ใƒฌใƒƒใƒ‰ใ‚ทใƒผใƒˆใซ็‰นๆฎŠใชใƒ†ใ‚ญใ‚นใƒˆๅŠนๆžœใ‚’่ฟฝๅŠ ใ—ใพใ™ใ€‚ใŸใจใˆใฐใ€ใ‚ฟใ‚คใƒˆใƒซใ‚’ใƒ•ใ‚กใ‚คใƒซใฎไธŠ้ƒจใซๅบƒใ’ใŸใ‚Šใ€ใƒ†ใ‚ญใ‚นใƒˆใ‚’่ฃ…้ฃพใ—ใŸใ‚Šใ€ใƒ†ใ‚ญใ‚นใƒˆใ‚’ใƒ—ใƒชใ‚ปใƒƒใƒˆใฎๅฝข็Šถใซๅˆใ‚ใ›ใŸใ‚Šใ€ใƒ†ใ‚ญใ‚นใƒˆใ‚’่ƒŒๆ™ฏใฎ้€ใ‹ใ—ใจใ—ใฆ Excel ใ‚ทใƒผใƒˆใซ้ฉ็”จใ—ใŸใ‚Šใงใใพใ™ใ€‚ใƒฏใƒผใƒ‰ใ‚ขใƒผใƒˆใฏใ€ใ‚นใƒ—ใƒฌใƒƒใƒ‰ใ‚ทใƒผใƒˆๅ†…ใง็งปๅ‹•ใพใŸใฏ้…็ฝฎใ—ใฆ่ฃ…้ฃพใ‚’่ฟฝๅŠ ใงใใ‚‹ใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆใซใชใ‚Šใพใ™ใ€‚ **Java** {{< highlight "java" >}} Workbook workbook = new Workbook(); //Get the first default sheet Worksheet sheet = workbook.getWorksheets().get(0); //Add Watermark Shape wordart = sheet.getShapes().addTextEffect(MsoPresetTextEffect.TEXT_EFFECT_1, "CONFIDENTIAL", "Arial Black", 50, false, true , 18, 8, 1, 1, 130, 800); //Get the shape's fill format FillFormat wordArtFormat = wordart.getFill(); //Set the transparency wordArtFormat.setTransparency(0.9); //Make the line invisible wordart.setHasLine(false); //Save the file workbook.save(dataDir + "AsposeWatermark_Out.xls"); {{< /highlight >}} ## **ๅฎŸ่กŒไธญใฎใ‚ณใƒผใƒ‰ใ‚’ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰** - [GitHub](https://github.com/aspose-cells/Aspose.Cells-for-Java/releases/tag/Aspose.Cells_Java_for_Apache_POI_SS-v1.0.0) ## **ใ‚ตใƒณใƒ—ใƒซใ‚ณใƒผใƒ‰ใ‚’ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰** - [GitHub](https://github.com/aspose-cells/Aspose.Cells-for-Java/blob/master/Plugins/Aspose_Cells_for_Apache_POI/Aspose-Cells-for-Apache-POI-(Maven)/src/main/java/com/aspose/cells/examples/asposefeatures/worksheets/AddWatermarkToWorksheet.java) {{% alert color="primary" %}} ่ฉณ็ดฐใซใคใ„ใฆใฏใ€ๆฌกใ‚’ๅ‚็…งใ—ใฆใใ ใ•ใ„ใ€‚[ใƒฏใƒผใƒ‰ใ‚ขใƒผใƒˆใฎ้€ใ‹ใ—ใ‚’ใƒฏใƒผใ‚ฏใ‚ทใƒผใƒˆใซ่ฟฝๅŠ ใ™ใ‚‹](/cells/ja/java/add-wordart-watermark-to-worksheet). {{% /alert %}}
"use client"; import React, { useEffect, useState } from "react"; import { createNitterLink } from "../lib"; import ListItem from "./ListItem"; import SubsForm from "./SubsForm"; import { useRouter } from "next/navigation"; import { removeFeedSubscription, deleteFeed } from "@/lib/api"; import { UserFeedsResponse } from "@/@types"; import Button from "./Button"; import Link from "next/link"; interface Props { feed: UserFeedsResponse; username: string; } const SubList = ({ feed, username }: Props) => { const [list, setList] = useState<string[]>(feed.subscriptions || []); const [url, setUrl] = useState(""); const router = useRouter(); useEffect(() => { const url = createNitterLink(list, feed.isNsfw); setUrl(url); }, [list, feed.isNsfw]); const deleteItem = async (name: string) => { const newSubs = list.filter((item) => item !== name); const [ok, err] = await removeFeedSubscription(username, feed.title, { feedId: feed.id, subs: newSubs, }); if (ok) { setList((prev) => prev.filter((item) => item !== name)); } }; const removeFeed = async () => { const [ok, err] = await deleteFeed(username, feed.id); if (ok) { router.push(`/users/${username}`); } }; return ( <> <SubsForm list={list} setList={setList} feedId={feed.id} /> <div className="mx-auto flex w-full max-w-screen-sm flex-col gap-2 rounded-lg border border-gray-600/50 bg-neutral-950 p-4 shadow-sm"> <div className="flex flex-row items-center justify-between"> <p className="text-lg font-semibold"> Users in this Feed{" "} <span className="text-xs font-normal text-slate-300/50"> ({list.length} users) </span> </p> {feed.isNsfw && <p className="text-xs text-slate-300/50">(NSFW)</p>} </div> <ul className=""> {list?.map((item, index) => ( <ListItem key={index} name={item} deleteItem={deleteItem} url={createNitterLink([item], feed.isNsfw)} /> ))} </ul> <div className="flex flex-row items-center justify-between"> <Button as={Link} href={list.length > 0 ? url : ""} aria-disabled={list.length === 0} onClick={(e: React.MouseEvent) => { if (list.length === 0) { e.preventDefault(); } }} target="_blank" rel="noreferrer" > visit </Button> <Button onClick={removeFeed} variant="secondary" className="border-red-500 text-red-500" > delete feed </Button> </div> </div> </> ); }; export default SubList;
import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import "bootstrap/dist/css/bootstrap.min.css" import "bootstrap" import { DropDown } from 'vue3-dropper'; import 'vue3-dropper/dist/base.css'; import Vue3ConfirmDialog from 'vue3-confirm-dialog'; import 'vue3-confirm-dialog/style'; import FloatingVue from 'floating-vue'; import 'floating-vue/dist/style.css' store.subscribe( (mutation, state) => { const ss = window.sessionStorage; ss.setItem('email', JSON.stringify(state.userModule.email)); ss.setItem('boards', JSON.stringify(state.userModule.boards)); }) router.beforeEach((to, from, next) => { // Check if the route requires authentication if (to.meta.requiresAuth) { // Check if the user is authenticated const isAuthenticated = store.getters["userModule/getEmail"] !== null; if (!isAuthenticated) { // Redirect to the login page next('/login'); } else { // Continue to the restricted page next(); } } else { // For routes that don't require authentication, proceed normally next(); } }); const app = createApp(App); app.component('DropDown', DropDown); app.use(Vue3ConfirmDialog).use(FloatingVue).use(store).use(router).mount('#app'); app.component('vue3-confirm-dialog', Vue3ConfirmDialog.default);
package at.srfg.kmt.ehealth.phrs.i18n; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.Locale; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import javax.faces.context.FacesContext; import at.srfg.kmt.ehealth.phrs.presentation.services.VocabularyService; /* <application> <locale-config> <default-locale>en</default-locale> <supported-locale>de</supported-locale> </locale-config> <resource-bundle> <base-name>at.srfg.kmt.ehealth.phrs.i18n.Labels</base-name> <var>text</var> </resource-bundle> </application> */ public class LabelUtil extends ResourceBundle { protected static final String BUNDLE_NAME = "at.srfg.kmt.ehealth.phrs.i18n.messagelabels"; protected static final String BUNDLE_EXTENSION = "properties"; protected static final Control UTF8_CONTROL = new UTF8Control(); public LabelUtil() { // get locale from servlet thread Locale locale = Locale.ENGLISH; try { locale = FacesContext.getCurrentInstance().getViewRoot().getLocale(); } catch (Exception e){ } //Executions.getCurrent(). setParent(ResourceBundle.getBundle(BUNDLE_NAME, locale, UTF8_CONTROL)); } public LabelUtil(Locale locale) { if(locale==null) locale = Locale.ENGLISH; setParent(ResourceBundle.getBundle(BUNDLE_NAME, locale, UTF8_CONTROL)); } /* * lookup */ //static VocabularyService vocabService = new VocabularyService(); public String getLabel(String key){ //need language ? how? String lang = this.getLocale().getLanguage(); String label = VocabularyService.getTermLabel(key, lang); if(label !=null) return label; return super.getString(key); } @Override protected Object handleGetObject(String key) { //TODO can lookup from another source return parent.getObject(key); } @Override public Enumeration getKeys() { return parent.getKeys(); } protected static class UTF8Control extends Control { public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { // The below code is copied from default Control#newBundle() // implementation. // Only the PropertyResourceBundle line is changed to read the file // as UTF-8. String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, BUNDLE_EXTENSION); ResourceBundle bundle = null; InputStream stream = null; if (reload) { URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); } } } else { stream = loader.getResourceAsStream(resourceName); } if (stream != null) { try { bundle = new PropertyResourceBundle(new InputStreamReader( stream, "UTF-8")); } finally { stream.close(); } } return bundle; } } }
<?php declare(strict_types=1); namespace app\common\service; use think\facade\Cache; class WeChat { private $appId; private $appSecret; public function __construct($appId, $appSecret) { $this->appId = $appId; $this->appSecret = $appSecret; } public function getSignPackage() { $jsapiTicket = $this->getJsApiTicket(); $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $timestamp = time(); $nonceStr = $this->createNonceStr(); // ่ฟ™้‡Œๅ‚ๆ•ฐ็š„้กบๅบ่ฆๆŒ‰็…ง key ๅ€ผ ASCII ็ ๅ‡ๅบๆŽ’ๅบ $string = 'jsapi_ticket=' . $jsapiTicket . '&noncestr=' . $nonceStr . '&timestamp=' . $timestamp . '&url=' . $url; $signature = sha1($string); $signPackage = [ "appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ]; return $signPackage; } private function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } private function getJsApiTicket() { if (empty(Cache::get('wx_ticket'))) { $url2 = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", $this->getAccessToken()); $res = $this->httpGet($url2); $res = json_decode($res, true); $ticket = $res['ticket']; if ($ticket) { Cache::set('wx_ticket', $ticket, 7000); } } else { $ticket = Cache::get('wx_ticket'); } return $ticket; } private function getAccessToken() { if (empty(Cache::get('access_token'))) { $res = json_decode($this->httpGet('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appId . '&secret=' . $this->appSecret), true); $access_token = $res['access_token']; if ($access_token) { Cache::set('access_token', $access_token, 3600); } } else { $access_token = Cache::get('access_token'); } return $access_token; } private function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } }
import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { GeneratePassword } from './generate-password'; @Injectable({ providedIn: 'root' }) export class GeneratePasswordService { options = [ { "id": "letters", "library": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPWRSTUVWXYZ", }, { "id": "numbers", "library": "0123456789", }, { "id": "symbols", "library": "!@#$%^&*-_=+\\|:;',.\<>/?~", } ]; constructor() { } getGeneratePassword(dataPassword: GeneratePassword): Observable<GeneratePassword>{ var optionsSelected: Array<string> = []; if (dataPassword.useLetters) { var letters = this.options[0].library.split(''); letters.forEach(letter => { optionsSelected.push(letter); }); } if (dataPassword.useNumbers) { var numbers = this.options[1].library.split(''); numbers.forEach(number => { optionsSelected.push(number); }); } if (dataPassword.useSymbols) { var symbols = this.options[2].library.split(''); symbols.forEach(symbol => { optionsSelected.push(symbol); }); } var newPassword = ""; for (var i = 0; i < dataPassword.length; i++) { newPassword += optionsSelected[Math.floor(Math.random() * optionsSelected.length)]; } dataPassword.password = newPassword; return of(dataPassword); } }
package br.com.fiapsoat.presenters.dto; import br.com.fiapsoat.entities.enums.StatusDoPagamento; import br.com.fiapsoat.entities.pagamento.ConfirmacaoPagamento; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data public class ConfirmacaoPagamentoDTO { @Schema(description = "Nรบmero retornado ao efetuar pedido", example = "1") private Long numeroDoPedido; @Schema(description = "Status do pagamento retornado pela instituiรงรฃo financeira", example = "CONFIRMADO") private StatusDoPagamento statusDoPagamento; public ConfirmacaoPagamento toConfirmacaoPagamento() { ConfirmacaoPagamento c = new ConfirmacaoPagamento(); c.setNumeroDoPedido(getNumeroDoPedido()); c.setStatusDoPagamento(getStatusDoPagamento()); return c; } }
import React, { useState , useRef} from 'react' import { useDispatch, useSelector } from "react-redux"; import axios from "axios" import { useNavigate } from 'react-router-dom' import { useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import {userLogin} from "../../features/authSlice" import * as yup from 'yup'; const schema = yup.object({ email: yup.string().required("email is required").email("invalid email"), password: yup.string().required('Password is required') }) function Login() { const refInput = useRef(null) const navigate = useNavigate() const { isLoggedIn } = useSelector((state) => state.auth); const dispatch = useDispatch(); const { register, handleSubmit, formState:{ errors } } = useForm({ resolver: yupResolver(schema) }); const onLogin = (data) =>{ console.log(data.email) console.log(data.password) dispatch(userLogin( {email: data.email, password: data.password} )) } const loadUser = async () => { try{ const response = await axios.get("http://localhost:3001/user/me") console.log(response.data) }catch(e){ console.log(e) } } return ( <div> <h1> Login </h1> <form onSubmit={handleSubmit(onLogin)}> <input {...register("email")} className={`form-control ${errors.email ? 'is-invalid' : ''}`}/> <p className="invalid-feedback">{errors.email?.message}</p> <input type="password" {...register("password")} className={`form-control ${errors.password ? 'is-invalid' : ''}`} /> <p className="invalid-feedback">{errors.password?.message}</p> <button onClick={loadUser}> me </button> <input type="submit" /> </form> </div> ) } export default Login
import streamlit as st from ucimlrepo import fetch_ucirepo import joblib import numpy as np clf = joblib.load("clf.joblib") aids_clinical_trials_group_study_175 = fetch_ucirepo(id=890) X = aids_clinical_trials_group_study_175.data.features aids_variables = aids_clinical_trials_group_study_175.variables n_variables = len(aids_variables) st.markdown( """ # Predictive Analytics ๐Ÿ‘จโ€๐Ÿ’ป As part of Sushruta's diagnostic offerings, a **highly interpretable linear regression model** has been trained on UCI's AIDS dataset. By finetuning the parameters below, you can generate predictions of how likely a certain profile is to have contracted AIDS, based on a variety of features. Overall, this model has an accuracy of 83.18% on the UCI dataset. The scoring functions and other related training code are available in the iPython notebook training.ipynb """ ) def make_prediction(): X = [] for var in aids_variables["name"][2:]: X.append(int(st.session_state[var])) X = np.array([X]) prediction_prob = clf.score(X, [1]) with st.expander("Sushruta's prediction"): if prediction_prob < 1e-6: st.write(f"The likelihood of AIDS infection according to the model is less than 1e-6.") else: st.write(f"The likelihood of AIDS infection according to the model is {prediction_prob * 100:0.2f}%") with st.form(key="var_values"): for var_idx in range(2, n_variables): name, role, demographic = aids_variables["name"][var_idx], \ aids_variables["type"][var_idx], aids_variables["demographic"][var_idx] label = demographic if demographic else name if role == "Integer": st.slider(label, min_value = min(X[name]) - 5, max_value = min(X[name]) + 5, key=name) elif role == "Binary": st.selectbox(label, options=(1, 0), format_func=lambda x: "Yes" if x == 1 else "No", key=name) elif role == "Continuous": st.number_input(label, min_value = min(X[name]), max_value = min(X[name]), key=name) st.form_submit_button(on_click=make_prediction)
/*********************************************************************** * File : Board.cpp * Author : ้˜่ฉฉ้ˆ B11115010 * ้™ณไป•่ˆˆ B11115011 * ้ญ็พŽ่Šณ B11115014 * Create Date : 2023-05-08 * Editor : ้˜่ฉฉ้ˆ B11115010 * ้™ณไป•่ˆˆ B11115011 * ้ญ็พŽ่Šณ B11115014 * Update Date : 2023-05-17 * Description : This C++ program simulates chess game with Guardians of the Galaxy theme *************************************************************************/ #include "Queen.h" #include <cctype> #include "player.h" // Intent: Create a Queen object with specified color and position. // Pre: The color and position of the Queen are provided. // Pos: Initializes the Queen object with the given color and position. Sets the image URL and color based on the color parameter. Queen::Queen(bool isWhite, Position position) { this->position = position; if (isWhite) { this->imgUrl = ":/images/images/gQueen.png"; this->color = "WHITE"; } else { this->imgUrl = ":/images/images/vQueen.png"; this->color = "BLACK"; } } // Intent: Get the possible legal moves for the Queen. // Pre: The current state of the chessboard is provided. // Pos: Returns a QVector of legal moves for the Queen based on the current state of the chessboard. QVector<Position> Queen::getPossibleMove(Board gBoard) { QVector<Position> legalMoves; Player player(gBoard.board); char piece = this->color == "WHITE" ? 'Q' : 'q'; // Define the four diagonal directions int diagX[] = {-1, -1, 1, 1}; int diagY[] = {-1, 1, -1, 1}; // Check the diagonal directions for (int i = 0; i < 4; i++) { int newX = position.x + diagX[i]; int newY = position.y + diagY[i]; // Keep moving in the diagonal direction until out of bounds or obstruction while(Position(newX, newY).isInRange()) { Position newPos(newX, newY); const char pieceAtNewPosition = player.getPieceAt(newPos); QString pieceAtNewPositionColor = player.getColor(pieceAtNewPosition); // If no piece at the position, add it as a legal move if (pieceAtNewPosition == ' ') { Board tempBoard; // Copy the current board state to the temporary board for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { tempBoard.board[row][col] = player.board[row][col]; } } int oldX = this->position.x; int oldY = this->position.y; tempBoard.board[newY][newX] = piece; tempBoard.board[oldY][oldX] = ' '; Position kingPos = player.getKingPosition(this->color); // Check if the move puts the King in check if (!player.isUnderAttack(this->color, kingPos, tempBoard)) { legalMoves.push_back(newPos); } } else if (pieceAtNewPositionColor != this->color) { Board tempBoard; // Copy the current board state to the temporary board for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { tempBoard.board[row][col] = player.board[row][col]; } } int oldX = this->position.x; int oldY = this->position.y; tempBoard.board[newY][newX] = piece; tempBoard.board[oldY][oldX] = ' '; Position kingPos = player.getKingPosition(this->color); // Check if the move puts the King in check if (!player.isUnderAttack(this->color, kingPos, tempBoard)) { legalMoves.push_back(newPos); } break; } else { break; } newX += diagX[i]; newY += diagY[i]; } } // Define the four straight directions int straightX[] = {-1, 1, 0, 0}; int straightY[] = {0, 0, -1, 1}; // Check the straight directions for (int i = 0; i < 4; i++) { int newX = position.x + straightX[i]; int newY = position.y + straightY[i]; // Keep moving in the straight direction until out of bounds or obstruction while (Position(newX, newY).isInRange()) { Position newPos(newX, newY); char pieceAtNewPosition = player.getPieceAt(newPos); QString pieceAtNewPositionColor = player.getColor(pieceAtNewPosition); if (pieceAtNewPosition == ' ') { Board tempBoard; // Copy the current board state to the temporary board for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { tempBoard.board[row][col] = player.board[row][col]; } } int oldX = this->position.x; int oldY = this->position.y; tempBoard.board[newY][newX] = piece; tempBoard.board[oldY][oldX] = ' '; Position kingPos = player.getKingPosition(this->color); // Check if the move puts the King in check if (!player.isUnderAttack(this->color, kingPos, tempBoard)) { legalMoves.push_back(newPos); } } else if (pieceAtNewPositionColor != this->color) { Board tempBoard; // Copy the current board state to the temporary board for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { tempBoard.board[row][col] = player.board[row][col]; } } char piece = this->color == "WHITE" ? 'B' : 'b'; int oldX = this->position.x; int oldY = this->position.y; tempBoard.board[newY][newX] = piece; tempBoard.board[oldY][oldX] = ' '; Position kingPos = player.getKingPosition(this->color); // Check if the move puts the King in check if (!player.isUnderAttack(this->color, kingPos, tempBoard)) { legalMoves.push_back(newPos); } break; } else { break; } newX += straightX[i]; newY += straightY[i]; } } return legalMoves; } // Intent: Move the Queen to the target position on the provided chessboard. // Pre: The target position and the chessboard are provided. // Pos: Moves the Queen to the target position on the chessboard and updates the last moved piece position. void Queen::move(Board& gBoard, Position targetPos) { char currentPiece = this->color == "WHITE" ? 'Q' : 'q'; gBoard.setPieceAt(targetPos, currentPiece); gBoard.setPieceAt(this->position, ' '); // Update the last moved piece position gBoard.lastMovedPiecePosition = targetPos; } // Intent: Get the possible legal moves for the Queen in a simulation. // Pre: The current state of the chessboard is provided. // Pos: Returns a QVector of legal moves for the Queen based on the current state of the chessboard in a simulation. QVector<Position> Queen::getSimulation(Board gBoard) { QVector<Position> legalMoves; Player player(gBoard.board); char piece = this->color == "WHITE" ? 'Q' : 'q'; // Define the four diagonal directions int diagX[] = {-1, -1, 1, 1}; int diagY[] = {-1, 1, -1, 1}; // Check the diagonal directions for (int i = 0; i < 4; i++) { int newX = position.x + diagX[i]; int newY = position.y + diagY[i]; // Keep moving in the diagonal direction until out of bounds or obstruction while (Position(newX, newY).isInRange()) { Position newPos(newX, newY); const char pieceAtNewPosition = player.getPieceAt(newPos); QString pieceAtNewPositionColor = player.getColor(pieceAtNewPosition); // If no piece at the position, add it as a legal move if (pieceAtNewPosition == ' ') { legalMoves.push_back(newPos); } else if (pieceAtNewPositionColor != this->color) { // If the piece at the position is of a different color, add it as a legal move and stop iterating in this direction legalMoves.push_back(newPos); break; } else { // If the piece at the position is of the same color, stop iterating in this direction break; } newX += diagX[i]; newY += diagY[i]; } } // Define the four straight directions int straightX[] = {-1, 1, 0, 0}; int straightY[] = {0, 0, -1, 1}; // Check the straight directions for (int i = 0; i < 4; i++) { int newX = position.x + straightX[i]; int newY = position.y + straightY[i]; // Keep moving in the straight direction until out of bounds or obstruction while (Position(newX, newY).isInRange()) { Position newPos(newX, newY); char pieceAtNewPosition = player.getPieceAt(newPos); QString pieceAtNewPositionColor = player.getColor(pieceAtNewPosition); if (pieceAtNewPosition == ' ') { legalMoves.push_back(newPos); } else if (pieceAtNewPosition != ' ' && pieceAtNewPositionColor != this->color) { // If the piece at the position is of a different color, add it as a legal move and stop iterating in this direction legalMoves.push_back(newPos); break; } else { // If the piece at the position is of the same color, stop iterating in this direction break; } newX += straightX[i]; newY += straightY[i]; } } return legalMoves; }
<?php namespace App\Controller; use App\Entity\Recipe; // use App\Entity\User; use App\Form\RecipeType; use DateTimeImmutable; use App\Repository\RecipeRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; class RecipeController extends AbstractController { #[Route(path: '/recette', name: 'app_recipe_index')] public function index(Request $request, EntityManagerInterface $em): Response { //permet de recuperer toutes les recettes en BD // $recipes = $repository->findAll(); $recipes = $em->getRepository(Recipe::class)->findAll(); //permet de recuperer toutes les recettes en dessous d'une durรฉe en BD // $recipes = $repository->findRecipeDurationLowerThan(60); // dd($recipes); //version classique // $recipe = new Recipe(); // $recipe->setTitle('Sushi Saumon'); // $recipe->setSlug('sushi-saumon'); // $recipe->setContent('Prenez du riz et du saumon.'); // $recipe->setDuration(156); // $recipe->setCreatedAt(new DateTimeImmutable()); // $recipe->setUpdatedAt(new DateTimeImmutable()); // $em->persist($recipe); //version avec l'utilisation de fluent setter // $recipe2 = new Recipe(); // $userRepo = $em->getRepository(User::class); // $user = $userRepo->find(1); // dd($user); // $recipe2->setTitle('Sushi Au Saumon') // ->setSlug('sushi-au-saumon') // ->setContent('Tu prends du riz et du saumon.') // ->setDuration(45) // ->setImageName('https://th.bing.com/th/id/OIP.YzNBu-r2yymhRgwhGIZ_rgHaJ4?rs=1&pid=ImgDetMain') // ->setCreatedAt(new DateTimeImmutable()) // ->setUpdatedAt(new DateTimeImmutable()) // ->setUser($user); // $em->persist($recipe2); // $recipes[5]->setTitle('Pizza Bolognaise') // ->setSlug('pizza-bolognaise') // ->setContent('Suffis de prendre une pate a pizza et de rajouter de la bolognaise'); // $em->remove($recipes[5]); // $em->flush(); return $this->render('recipe/index.html.twig', [ 'recipes' => $recipes ]); } #[Route(path: '/recette/{slug}-{id}', name: 'app_recipe_show', requirements : ['id'=> '\d+', 'slug'=> '[a-z0-9-]+'])] public function show(Request $request, string $slug, int $id,RecipeRepository $repository): Response { //ca nous permet de recuperer une recette ร  partir du slug donnรฉ en paramรจtre // $recipe1 = $repository->findOneBy(['slug' => $slug]); // dd($recipe1); //ca nous recupere une recette correspondant ร  l'id $recipe = $repository->find($id); if($recipe->getSlug() !== $slug){ return $this->redirectToRoute('app_recipe_show', ['id' => $recipe->getId(), 'slug' => $recipe->getSlug()]); } // dd($recipe); return $this->render('recipe/show.html.twig', [ 'recipe' => $recipe ]); } #[Route(path : '/recette/create', name : 'app_recipe_create')] public function create(Request $request, EntityManagerInterface $em) : Response { $recipe = new Recipe; $form = $this->createForm(RecipeType::class, $recipe); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()){ $recipe->setCreatedAt(new DateTimeImmutable()); $recipe->setUpdatedAt(new DateTimeImmutable()); $em->persist($recipe); $em->flush(); $this->addFlash('success', 'La recette '. $recipe->getTitle() .' a bien รฉtรฉ crรฉรฉe'); return $this->redirectToRoute('app_recipe_index'); } return $this->render('recipe/create.html.twig', [ 'monForm' => $form ]); } #[Route(path: '/recette/{id}/edit', name: 'app_recipe_edit')] public function edit(Recipe $recipe, Request $request, EntityManagerInterface $em): Response { // dd($recipe); //cette methode prend en premier paramรจtre le formulaire que l'on souhaite utiliser //en second paramรจtre elle prend les donnรฉes $form = $this->createForm(RecipeType::class, $recipe); $form->handleRequest($request); // dd($recipe); if($form->isSubmitted() && $form->isValid()){ $recipe->setUpdatedAt(new DateTimeImmutable()); $em->flush(); $this->addFlash('success','La recette a bien รฉtรฉ modifiรฉe'); return $this->redirectToRoute('app_recipe_show', ['id' => $recipe->getId(), 'slug' => $recipe->getSlug()]); } return $this->render('recipe/edit.html.twig', [ 'recipe' => $recipe, 'monForm' => $form ]); } #[Route(path: '/recette/{id}/delete', name: 'app_recipe_delete', requirements : ['id'=> '\d+'])] public function delete(Recipe $recipe, EntityManagerInterface $em): Response{ $titre = $recipe->getTitle(); $em->remove($recipe); $em->flush(); $this->addFlash('info', 'La recette '. $titre . ' a bien รฉtรฉ supprimรฉe'); return $this->redirectToRoute('app_recipe_index'); } }
<!DOCTYPE html> <html> <head> <title>Routing</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script> </head> <body ng-app="MyApp"> <nav> <a href="#/page1">About Us</a> <a href="#/page2">Our Services</a> <a href="#/page3">Contact Us</a> <ng-view></ng-view> </nav> <script type="text/javascript"> var app = angular.module("MyApp", ["ngRoute"]); app.config(function($routeProvider){ $routeProvider .when("/",{ templateUrl : "main.html" }) .when("/page1",{ templateUrl : "page1.html" }) .when("/page2",{ templateUrl : "page2.html" }) .when("/page3",{ templateUrl : "page3.html" }) }) </script> </body> </html>
/* The PyMem_ family: low-level memory allocation interfaces. See objimpl.h for the PyObject_ memory family. */ #ifndef Py_PYMEM_H #define Py_PYMEM_H #include "pyport.h" #ifdef __cplusplus extern "C" { #endif /* BEWARE: Each interface exports both functions and macros. Extension modules should use the functions, to ensure binary compatibility across Python versions. Because the Python implementation is free to change internal details, and the macros may (or may not) expose details for speed, if you do use the macros you must recompile your extensions with each Python release. Never mix calls to PyMem_ with calls to the platform malloc/realloc/ calloc/free. For example, on Windows different DLLs may end up using different heaps, and if you use PyMem_Malloc you'll get the memory from the heap used by the Python DLL; it could be a disaster if you free()'ed that directly in your own extension. Using PyMem_Free instead ensures Python can return the memory to the proper heap. As another example, in PYMALLOC_DEBUG mode, Python wraps all calls to all PyMem_ and PyObject_ memory functions in special debugging wrappers that add additional debugging info to dynamic memory blocks. The system routines have no idea what to do with that stuff, and the Python wrappers have no idea what to do with raw blocks obtained directly by the system routines then. The GIL must be held when using these APIs. */ /* * Raw memory interface */ /* Functions Functions supplying platform-independent semantics for malloc/realloc/ free. These functions make sure that allocating 0 bytes returns a distinct non-NULL pointer (whenever possible -- if we're flat out of memory, NULL may be returned), even if the platform malloc and realloc don't. Returned pointers must be checked for NULL explicitly. No action is performed on failure (no exception is set, no warning is printed, etc). */ PyAPI_FUNC(void *) PyMem_Malloc(size_t); PyAPI_FUNC(void *) PyMem_Realloc(void *, size_t); PyAPI_FUNC(void) PyMem_Free(void *); /* Starting from Python 1.6, the wrappers Py_{Malloc,Realloc,Free} are no longer supported. They used to call PyErr_NoMemory() on failure. */ /* Macros. */ #ifdef PYMALLOC_DEBUG /* Redirect all memory operations to Python's debugging allocator. */ #define PyMem_MALLOC PyObject_MALLOC #define PyMem_REALLOC PyObject_REALLOC #define PyMem_FREE PyObject_FREE #else /* ! PYMALLOC_DEBUG */ /* PyMem_MALLOC(0) means malloc(1). Some systems would return NULL for malloc(0), which would be treated as an error. Some platforms would return a pointer with no memory behind it, which would break pymalloc. To solve these problems, allocate an extra byte. */ /* Returns NULL to indicate error if a negative size or size larger than Py_ssize_t can represent is supplied. Helps prevents security holes. */ #define PyMem_MALLOC(n) (((n) < 0 || (n) > PY_SSIZE_T_MAX) ? NULL \ : malloc((n) ? (n) : 1)) #define PyMem_REALLOC(p, n) (((n) < 0 || (n) > PY_SSIZE_T_MAX) ? NULL \ : realloc((p), (n) ? (n) : 1)) #define PyMem_FREE free #endif /* PYMALLOC_DEBUG */ /* * Type-oriented memory interface * * Allocate memory for n objects of the given type. Returns a new pointer * or NULL if the request was too large or memory allocation failed. Use * these macros rather than doing the multiplication yourself so that proper * overflow checking is always done. */ #define PyMem_New(type, n) \ ( ((n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ ( (type *) PyMem_Malloc((n) * sizeof(type)) ) ) #define PyMem_NEW(type, n) \ ( ((n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ ( (type *) PyMem_MALLOC((n) * sizeof(type)) ) ) /* * The value of (p) is always clobbered by this macro regardless of success. * The caller MUST check if (p) is NULL afterwards and deal with the memory * error if so. This means the original value of (p) MUST be saved for the * caller's memory error handler to not lose track of it. */ #define PyMem_Resize(p, type, n) \ ( (p) = ((n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ (type *) PyMem_Realloc((p), (n) * sizeof(type)) ) #define PyMem_RESIZE(p, type, n) \ ( (p) = ((n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ (type *) PyMem_REALLOC((p), (n) * sizeof(type)) ) /* PyMem{Del,DEL} are left over from ancient days, and shouldn't be used * anymore. They're just confusing aliases for PyMem_{Free,FREE} now. */ #define PyMem_Del PyMem_Free #define PyMem_DEL PyMem_FREE #ifdef __cplusplus } #endif #endif /* !Py_PYMEM_H */
"""Models for Cupcake app.""" from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() DEFAULT_IMAGE = "https://thestayathomechef.com/wp-content/uploads/2017/12/Most-Amazing-Chocolate-Cupcakes-1-small.jpg" class Cupcake(db.Model): """Available Cupcakes Model""" __tablename__ = "cupcakes" id = db.Column(db.Integer, primary_key=True, autoincrement=True) flavor = db.Column(db.Text, nullable=False) size = db.Column(db.Text, nullable=False) rating = db.Column(db.Float, nullable=False) image = db.Column(db.Text, nullable=False, default=DEFAULT_IMAGE) def serialize(self): """Converts Cupcake object data into dictionary""" cupcake_dict = { "id": self.id, "flavor": self.flavor, "rating": self.rating, "size": self.size, "image": self.image } return cupcake_dict def connect_db(app): """Connect to database from Flask app instance.""" db.app = app db.init_app(app)
<template> <div> <div v-if="myCounter === 11 && !submitted"> <b-jumbotron class="myjumbo"> You Scored {{ numCorrect }} / {{ numTotal }} <div> <b-button @click="reload" variant="primary">Retry</b-button> <a href="/"> <b-button>Home</b-button> </a> </div> </b-jumbotron> </div> <div v-else> <b-jumbotron class="myjumbo"> <template v-slot:lead> <b> <u>Question {{ myCounter }} / 10</u> </b> <div v-html="currentQuestion.question"></div> </template> <hr class="my-4" /> <b-list-group class="liststyle"> <b-list-group-item v-for="(answer, index) in answers" :key="index" @click.prevent="[!submitted ? selectAnswer(index) : void 0]" :class="[ !submitted && selectedIndex === index ? 'selected' : submitted && correctIndex === index ? 'correct' : submitted && correctIndex !== index && selectedIndex === index ? 'incorrect' : '', submitted ? 'noHover' : '', ]" > <div v-html="answer"></div> </b-list-group-item> </b-list-group> <div class="btncontainer"> <b-button @click="submitAnswer" :disabled="selectedIndex === null || submitted" variant="primary" href="#" > Submit <i v-if="selectedIndex !== null && !submitted" class="fa fa-arrow-circle-o-right" style="font-size:20px" ></i> </b-button> <b-button @click=" next(); incMyCount(); " variant="success" href="#" :disabled="!submitted" > Next <i v-if="submitted" class="fa fa-arrow-circle-o-right" style="font-size:20px"></i> </b-button> </div> </b-jumbotron> </div> </div> </template> <script> export default { props: { currentQuestion: Object, next: Function, increment: Function, numCorrect: Number, numTotal: Number, index: Number, topic: String, }, data() { return { selectedIndex: null, correctIndex: null, submitted: false, myCounter: 1, }; }, methods: { shuffle(a) { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }, selectAnswer(index) { this.selectedIndex = index; console.log(index); }, submitAnswer() { let isCorrect = false; this.correctIndex = this.answers.indexOf( this.currentQuestion.correct_answer ); if (this.selectedIndex === this.correctIndex) { isCorrect = true; } this.increment(isCorrect); this.submitted = true; }, reload() { location.reload(); }, incMyCount() { this.myCounter += 1; if (this.myCounter == 11) { if (localStorage.getItem(this.topic) !== null) { let retrievedObj = JSON.parse(localStorage.getItem(this.topic)); let oldAvg = parseFloat(retrievedObj.avg); let numTot = parseFloat(retrievedObj.num); console.log("oldAvg: ", oldAvg); console.log("numTot: ", numTot); let newAvg = (oldAvg * numTot + this.numCorrect) / (numTot + 1); console.log(newAvg); let newObj = { avg: newAvg, num: numTot + 1, }; localStorage.setItem(this.topic, JSON.stringify(newObj)); } else { let obj = { avg: this.numCorrect, num: 1, }; localStorage.setItem(this.topic, JSON.stringify(obj)); } } }, }, computed: { answers() { let answers = [...this.currentQuestion.incorrect_answers]; answers.push(this.currentQuestion.correct_answer); answers = this.shuffle(answers); return answers; }, }, watch: { currentQuestion() { this.selectedIndex = null; this.correctIndex = null; this.submitted = false; }, }, }; </script> <style scoped> .btn { margin-top: 50px; margin-left: 10px; margin-right: 10px; } .list-group-item:hover { background: #eeeeee; cursor: pointer; } .list-group-item:hover.selected { background-color: lightblue; } .selected { background-color: lightblue; } .correct { background-color: lightgreen; } .incorrect { background-color: lightcoral; } .noHover { pointer-events: none; } .btncontainer { position: relative; } .myjumbo { padding: 32px 32px; } </style>
import { PDFDocument, rgb } from "pdf-lib"; import { ExpenseInfo } from "./App"; // ghetto debug mode const DEBUG = false; export const OFFSETS = { NAME: [310, 720], COMMITTEE_AND_EVENT: [310, 635], PURPOSE: [310, 574], AMOUNT: [310, 513], DATE_RECEIPT: [440, 450], DATE_TODAY: [440, 385], SIGNATURE_RECIEVER: [310, 319], SIGNATURE_BOARD: [310, 255], COMMENTS: [20, 162], MONEY_CHECKBOX: [22, 125], PAYER_LINE_1: [20, 87], PAYER_LINE_2: [20, 49], }; // Warning - trash code ahead export async function createExpensePDF( expense: ExpenseInfo ): Promise<PDFDocument> { const url = "/invoice.pdf"; const arrayBuffer = await fetch(url).then((res) => res.arrayBuffer()); const pdfDoc = await PDFDocument.load(arrayBuffer); const pages = pdfDoc.getPages(); const page = pages[0]; page.setFontSize(16); if (DEBUG) { for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { page.drawText(`${i} ${j}`); page.moveTo(i * 100, j * 100); } } } const fullName = `${expense.firstName} ${expense.lastName}`; page.setFontColor(rgb(0.8, 0, 0)); page.moveTo(OFFSETS.NAME[0], OFFSETS.NAME[1]); page.drawText(fullName); page.moveTo(OFFSETS.COMMITTEE_AND_EVENT[0], OFFSETS.COMMITTEE_AND_EVENT[1]); page.drawText(expense.committee); page.moveTo(OFFSETS.PURPOSE[0], OFFSETS.PURPOSE[1]); page.drawText(expense.purpose); page.setFontSize(20); const digits_franken = Math.floor(Number(expense.amount)) .toString() .padStart(4, " ") .split(""); const digits_rappen = Number(expense.amount) .toFixed(2) .split(".")[1] .split(""); page.drawText(digits_franken[0], { x: OFFSETS.AMOUNT[0] + 130, y: OFFSETS.AMOUNT[1], }); page.drawText(digits_franken[1], { x: OFFSETS.AMOUNT[0] + 158, y: OFFSETS.AMOUNT[1], }); page.drawText(digits_franken[2], { x: OFFSETS.AMOUNT[0] + 183, y: OFFSETS.AMOUNT[1], }); page.drawText(digits_franken[3], { x: OFFSETS.AMOUNT[0] + 206, y: OFFSETS.AMOUNT[1], }); page.drawText(digits_rappen[0], { x: OFFSETS.AMOUNT[0] + 234, y: OFFSETS.AMOUNT[1], }); page.drawText(digits_rappen[1], { x: OFFSETS.AMOUNT[0] + 256, y: OFFSETS.AMOUNT[1], }); function fillDateInBoxesAt(date_string: string, x: number, y: number) { const date = new Date(date_string); const dateYearDigits = (date.getFullYear() % 100).toString().split(""); const dateMonthDigits = (date.getMonth() + 1) // L M A O .toString() .padStart(2, "0") .split(""); const dateDateDigits = date.getDate().toString().padStart(2, " ").split(""); console.log(dateMonthDigits); page.drawText(dateDateDigits[0] ?? "", { x: x + 0, y, }); page.drawText(dateDateDigits[1] ?? "", { x: x + 22, y, }); page.drawText(dateMonthDigits[0] ?? "", { x: x + 52, y, }); page.drawText(dateMonthDigits[1] ?? "", { x: x + 76, y, }); page.drawText(dateYearDigits[0] ?? "", { x: x + 103, y, }); page.drawText(dateYearDigits[1] ?? "", { x: x + 124, y, }); } fillDateInBoxesAt( expense.dateReceipt, OFFSETS.DATE_RECEIPT[0], OFFSETS.DATE_RECEIPT[1] ); fillDateInBoxesAt( expense.dateToday, OFFSETS.DATE_TODAY[0], OFFSETS.DATE_TODAY[1] ); if (expense.signatureReciever) { page.moveTo(OFFSETS.SIGNATURE_RECIEVER[0], OFFSETS.SIGNATURE_RECIEVER[1]); const signatureRecieverImg = await pdfDoc.embedPng( expense.signatureReciever ); page.drawImage(signatureRecieverImg, { width: 120, height: 40, }); } if (expense.signatureBoard) { page.moveTo(OFFSETS.SIGNATURE_BOARD[0], OFFSETS.SIGNATURE_BOARD[1]); const signatureBoardImg = await pdfDoc.embedPng(expense.signatureBoard); page.drawImage(signatureBoardImg, { width: 120, height: 40, }); } page.moveTo(OFFSETS.MONEY_CHECKBOX[0], OFFSETS.MONEY_CHECKBOX[1]); page.drawText("X"); page.setFontSize(12); page.moveTo(OFFSETS.COMMENTS[0], OFFSETS.COMMENTS[1]); page.drawText(expense.comments); page.moveTo(OFFSETS.PAYER_LINE_1[0], OFFSETS.PAYER_LINE_1[1]); page.drawText(`${fullName}, ${expense.address}`); page.moveTo(OFFSETS.PAYER_LINE_2[0], OFFSETS.PAYER_LINE_2[1]); page.drawText(`${expense.iban}`); return pdfDoc; }
# Ansible Role: Qemu [![CI](https://github.com/skaary/ansible-role-qemu/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/skaary/ansible-role-qemu/actions?query=workflow%3Ci) An Ansible Role that installs [Qemu](https://www.qemu.org) on Linux. ## Installation Download the role directly from git by typing into your terminal: ```bash $ ansible-galaxy install git+https://github.com/skaary/ansible-role-qemu.git ``` or ```bash $ ansible-galaxy install git+https://github.com/skaary/ansible-role-qemu.git,,qemu ``` to change the installed role name from _ansible-role-qemu_ to just _qemu_. Alternatively, install the role via a _requirements.yml_ file, e.g. when installing multiple roles at once. See [ansible galaxy documentation](https://galaxy.ansible.com/docs/using/installing.html#installing-multiple-roles-from-a-file) for more information. ## Example playbook ```yaml - hosts: all roles: - ansible-role-qemu ``` ## Testing the role ### Vagrant Vagrant can be used to test the role in order to graphically see it working in a virtual machine. Make sure Vagrant and VirtualBox are installed: ```bash $ sudo apt install vagrant virtualbox ``` Use the following commands to run vagrant and boot up the virtual machine: ```bash $ cd tests $ vagrant up ``` Use `vagrant destroy` after you are done testing to delete the virtual machine. For more information about Vagrant and its commands, see the [Vagrant documentation](https://www.vagrantup.com/docs/cli). ### Molecule with Docker Molecule can be used to test the role with a docker container. Make sure Molecule is installed: ```bash $ python3 -m pip install --user "molecule[docker]" ``` Use the following commands to run Molecule in order to create the docker container and access the created container: ```bash $ molecule converge && molecule login ``` For more information on how to use Molecule please consult the [Molecule documentation](https://molecule.readthedocs.io/en/latest/getting-started.html). > Note: Python and Docker are required for the use of molecule. For more information, see [Molecule installation](https://molecule.readthedocs.io/en/latest/installation.html). ## License MIT / BSD
import { Board, Engine, Result, VerticalHandler, HorizontalHandler } from './sudoku'; const easy: Board = new Board([ 9, 0, 6, 3, 4, 0, 8, 1, 0, 0, 5, 1, 7, 0, 0, 3, 0, 0, 4, 7, 0, 0, 9, 1, 0, 0, 5, 0, 0, 0, 9, 0, 3, 0, 0, 2, 0, 0, 2, 0, 8, 7, 0, 0, 0, 1, 0, 7, 2, 0, 0, 6, 0, 0, 0, 8, 5, 0, 0, 9, 1, 0, 0, 0, 3, 4, 0, 6, 0, 0, 0, 9, 0, 1, 0, 5, 0, 8, 7, 0, 6, ], 3, 3); const hard: Board = new Board([ 0, 0, 0, 2, 4, 7, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 7, 0, 1, 9, 7, 0, 0, 3, 5, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0, 5, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 9, 0, 8, 6, 0, 5, 0, 0, 0, 0, 0, 4, 0, 3, 0, 9, 0, 8, 0, 0, 0, 0, 0, 9, 0, 7, 0, 3, 0, 0, ], 3, 3); const expert: Board = new Board([ 0, 0, 0, 0, 3, 0, 0, 0, 0, 1, 2, 0, 7, 4, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 4, 0, 0, 5, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0, 0, 6, 1, 0, 2, 8, 0, 0, 0, 9, 0, 0, 0, 0, 2, 4, 6, 0, 0, 0, 0, 8, 3, 0, 0, 0, 7, 0, 0, 0, 0, 0, 9, ], 3, 3); const silly: Board = new Board([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], 3, 3); const large: Board = new Board([ 1, 2, 0, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, 5, 0, 8, 0, 7, 6, 0, 11, 0, 0, 0, 0, 0, 12, 4, 0, 0, 10, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 10, 0, 0, 5, 0, 7, 4, 0, 0, 0, 0, 0, 0, 0, 8, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 3, 9, 8, 0, 0, 12, 0, 4, 0, 5, 6, 9, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 12, 0, 0, 6, 0, 0, 0, 0, 0, 8, 0, 2, 0, 0, 7, ], 4, 3); const huge: Board = new Board([ 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 8, 0, 7, 0, 0, 14, 0, 0, 0, 0, 0, 5, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 9, 0, 0, 13, 0, 0, 0, 16, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 5, 0, 11, 0, 0, 0, 7, 4, 15, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 6, 0, 0, 0, 0, 3, 13, 0, 0, 0, 15, 0, 4, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 5, 0, 0, 0, 0, 6, 0, 11, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 12, 0, 0, 2, 0, 0, 0, 6, 0, 0, 0, 0, 0, 8, 0, 2, 0, 0, 7, 0, 0, 14, 0, 4, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, ], 4, 4); class Guess { private option: number = 0; constructor( private readonly x: number, private readonly y: number, private readonly options: Array<number> ) { } next(): boolean { if (this.option < this.options.length - 1) { ++this.option; return true; } else { return false; } } apply(board: Board): void { // tslint:disable-next-line:max-line-length console.log(`guessing option ${this.option} of ${this.options.length} by applying ${this.options[this.option]} to ${this.x}, ${this.y}`); board.set(this.x, this.y, this.options[this.option]); } undo(board: Board): void { console.log(`undoing ${this.x}, ${this.y}`); board.set(this.x, this.y, 0); } } class Unknown { constructor( readonly x: number, readonly y: number, readonly options: Array<number> ) { } } const board: Board = silly; const engine: Engine = new Engine(board); let attempt: number = 0; let remaining: number; let last: number; let guessing: boolean = false; let guess: Array<Guess> = new Array<Guess>(); const unknown: Array<Unknown> = new Array<Unknown>(); let invalid: boolean = false; type PlayHandler = (x: number, y: number, play: Result) => void; type StrategyMap = { [K: string]: PlayHandler }; const handleValidPlay: PlayHandler = (x: number, y: number, play: Result): void => { board.set(x, y, play.value); if (guessing) { guess.push(new Guess(x, y, new Array<number>())); } }; const handleUnknownPlay: PlayHandler = (x: number, y: number, play: Result): void => { unknown.push(new Unknown(x, y, play.options)); }; const handleInvalidPlay: PlayHandler = (x: number, y: number, play: Result): void => { invalid = true; }; const strategy: StrategyMap = { "valid": handleValidPlay, "unknown": handleUnknownPlay, "invalid": handleInvalidPlay }; let line: string = ''; // โ”Œโ”€โ”€โ”€โ”ฌโ”โ”‚โ”œโ”คโ”ผโ””โ”ดโ”˜โ”˜ const maximum: number = board.options.toString().length; // tslint:disable-next-line:max-line-length const draw: (left: string, separator: string, junction: string, right: string) => string = (left: string, separator: string, junction: string, right: string): string => { let line: string = ''; for (let index: number = 0; index < board.options; ++index) { if (index === 0) { line += left; } else if (index % board.sector.width === 0) { line += junction; } for (let place: number = 0; place < maximum + 2; ++place) { line += separator; } if (index === board.options - 1) { line += right; } } return line; }; let top: string = draw('โ”Œ', 'โ”€', 'โ”ฌ', 'โ”'); let middle: string = draw('โ”œ', 'โ”€', 'โ”ผ', 'โ”ค'); let bottom: string = draw('โ””', 'โ”€', 'โ”ด', 'โ”˜'); const verticalLog: VerticalHandler = (y: number): void => { if (y === 0) { console.log(top); } else if (y % board.sector.height === 0) { console.log(middle); } console.log(line); line = ''; if (y === board.options - 1) { console.log(bottom); } }; const horizontalLog: HorizontalHandler = (x: number, y: number): void => { const current: number = board.get(x, y).toString().length; if (x === 0) { line += 'โ”‚'; } else if (x % board.sector.width === 0) { line += 'โ”‚'; } if (board.get(x, y) === 0) { for (let place: number = 0; place < maximum + 2; ++place) { line += ' ';//'โˆ™'; } } else { for (let place: number = 0; place < maximum + 1 - current; ++place) { line += ' '; } line += board.get(x, y); line += ' '; } if (x === board.options - 1) { line += 'โ”‚'; } }; const evaluate: HorizontalHandler = (x: number, y: number): void => { const play: Result = engine.evaluate(x, y); if (strategy[play.result]) { strategy[play.result](x, y, play); } }; do { console.log('\x1B[2J'); ++attempt; unknown.splice(0, unknown.length); invalid = false; board.scan( (y: number): void => verticalLog(y), (x: number, y: number): void => { evaluate(x, y); horizontalLog(x, y); } ); remaining = board.remaining(); console.log(`After ${attempt} attempts, ${remaining} remain.`); if (guessing && invalid) { console.log('reached a dead end!'); while (guess.length > 0) { const current: Guess = guess.pop(); current.undo(board); if (current.next()) { current.apply(board); guess.push(current); break; } } if (guess.length === 0) { console.log('guessing failed!'); break; } } else if (last && last === remaining) { const canGuess: boolean = unknown.length > 0; if (canGuess) { unknown.sort((red: Unknown, green: Unknown): number => { const primary: number = green.options.length - red.options.length; if (primary !== 0) { return primary; } const secondary: number = green.x - red.x; if (secondary !== 0) { return secondary; } return green.y - red.y; }); const best: Unknown = unknown[0]; const current: Guess = new Guess(best.x, best.y, best.options); if (current.next()) { guessing = true; current.apply(board); guess.push(current); } } else { console.log('giving up!'); break; } } last = remaining; } while (remaining > 0);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Pacifico&display=swap" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css"> <title>home</title> <script> let menu = document.querySelector('#menu-btn'); let navbar = document.querySelector('.header .navbar'); menu.onclick = () =>{ menu.classList.toggle('fa-times'); navbar.classList.toggle('active'); }; window.onscroll = () =>{ menu.classList.remove('fa-times'); navbar.classList.remove('active'); }; var swiper = new Swiper(".home-slider", { loop:true, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, }); var swiper = new Swiper(".reviews-slider", { grabCursor:true, loop:true, autoHeight:true, spaceBetween: 20, breakpoints: { 0: { slidesPerView: 1, }, 700: { slidesPerView: 2, }, 1000: { slidesPerView: 3, }, }, }); let loadMoreBtn = document.querySelector('.packages .load-more .btn'); let currentItem = 3; loadMoreBtn.onclick = () =>{ let boxes = [...document.querySelectorAll('.packages .box-container .box')]; for (var i = currentItem; i < currentItem + 3; i++){ boxes[i].style.display = 'inline-block'; }; currentItem += 3; if(currentItem >= boxes.length){ loadMoreBtn.style.display = 'none'; } } </script> <!-- swiper css link --> <link rel="stylesheet" href="https://unpkg.com/swiper@7/swiper-bundle.min.css" /> <!-- font awesome cdn link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- custom css file link --> <link rel="stylesheet" href="css/style.css"> </head> <body> <header> <div class="inner-width"> <a href="#" class="logo">TRAVEL AND EXPLORE. </a> <i class="menu-toggle-btn fas fa-bars"></i> <nav class="navigation-menu"> <a href="#"><i class="fas fa-home home"></i> Home</a> <a href="#"><i class="fas fa-angle-right about"></i> About</a> <a href="#"><i class="fab fa-buffer works"></i> package</a> <a href="registration.html"><i class="fas fa-user team"></i> register </a> <a href="#"><i class="fas fa-user team"></i> login </a> <a href="#"><i class="fas fa-headset contact"></i> Contact</a> </nav> </header> <section class="home"> <div id="carouselExampleIndicators" class="carousel slide carousel-fade" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="images/home-slide-1.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="images/home-slide-2.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="images/home-slide-3.jpg" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </section> <section class="services"> <h1 class="heading-title"> our services </h1> <div class="box-container"> <div class="box"> <img src="images/icon-1.png" alt=""> <h3>adventure</h3> </div> <div class="box"> <img src="images/icon-2.png" alt=""> <h3>tour guide</h3> </div> <div class="box"> <img src="images/icon-3.png" alt=""> <h3>trekking</h3> </div> <div class="box"> <img src="images/icon-4.png" alt=""> <h3>camp fire</h3> </div> <div class="box"> <img src="images/icon-5.png" alt=""> <h3>off road</h3> </div> <div class="box"> <img src="images/icon-6.png" alt=""> <h3>camping</h3> </div> </div> </section> <section class="home-about"> <div class="image"> <img src="images/about-img.jpg" alt=""> </div> <div class="content"> <h3>about us</h3> <p>โ€œWe live in a wonderful world that is full of beauty, charm and adventure. There is no end to the adventures we can have if only we seek them with our eyes open.โ€</p> <a href="about.php" class="btn">read more</a> </div> </section> <section class="footer"> <div class="box-container"> <div class="box"> <h3>quick links</h3> <a href="home.php"> <i class="fas fa-angle-right"></i> home</a> <a href="about.php"> <i class="fas fa-angle-right"></i> about</a> <a href="package.php"> <i class="fas fa-angle-right"></i> package</a> <a href="book.php"> <i class="fas fa-angle-right"></i> book</a> </div> <div class="box"> <h3>extra links</h3> <a href="#"> <i class="fas fa-angle-right"></i> ask questions</a> <a href="#"> <i class="fas fa-angle-right"></i> about us</a> <a href="#"> <i class="fas fa-angle-right"></i> privacy policy</a> <a href="#"> <i class="fas fa-angle-right"></i> terms of use</a> </div> <div class="box"> <h3>contact info</h3> <a href="#"> <i class="fas fa-phone"></i> +91 9920645772 </a> <a href="#"> <i class="fas fa-envelope"></i> sadhvikoli02@gmail.com </a> <a href="#"> <i class="fas fa-map"></i> mumbai, india - 400061 </a> </div> <div class="box"> <h3>follow us</h3> <a href="#"> <i class="fab fa-facebook-f"></i> facebook </a> <a href="#"> <i class="fab fa-twitter"></i> twitter </a> <a href="#"> <i class="fab fa-instagram"></i> instagram </a> <a href="#"> <i class="fab fa-linkedin"></i> linkedin </a> </div> </div> <div class="credit"> created by <span>Sadhvi Koli</span> </div> </section> <script src="https://unpkg.com/swiper@7/swiper-bundle.min.js"></script> <!-- custom js file link --> <script src="js/script.js"></script> </body> </html>
import { HttpException, Inject, OnModuleInit } from '@nestjs/common' import { ClientGrpc, MessagePattern } from '@nestjs/microservices' import { CreateUserServiceResponse, UserRPCService } from '@telman/protobuf/user' import { RPCServicesEnum } from '@telman/rpc-connector' import { firstValueFrom } from 'rxjs' import { CreateUserDto } from './dto/createUser.dto' import { UpdateUserDto } from './dto/updateUser.dto' export class UserService implements OnModuleInit { private userRpcService: UserRPCService constructor(@Inject(RPCServicesEnum.USER) private userClient: ClientGrpc) {} onModuleInit() { this.userRpcService = this.userClient.getService<UserRPCService>(RPCServicesEnum.USER) } async create(createUserDto: CreateUserDto): Promise<CreateUserServiceResponse> { const res = await firstValueFrom(this.userRpcService.CreateUser({ user: createUserDto, })) return res } async findOneById(id: string) { const user = await firstValueFrom(this.userRpcService.GetUser({ id })) return user } async update(updateUserDto: UpdateUserDto) { //TODO: ะดะพะฑะฐะฒะธั‚ัŒ try-catch ะดะปั ะพะฑั€ะฐะฑะพั‚ะบะธ ะพัˆะธะฑะบะธ ะพั‚ ัะตั€ะฒะธัะฐ try { const updateResponse = await firstValueFrom(this.userRpcService.UpdateUser({ user: { ...updateUserDto }, })) return updateResponse } catch (err) { throw new HttpException('Internal server error', 500) } } async deleteUser(id: string) { const deleteResponse = await firstValueFrom(this.userRpcService.DeleteUser({ id })) return deleteResponse } }
import { StyleSheet, View, FlatList, ActivityIndicator } from "react-native"; import React from "react"; import { Stack, useLocalSearchParams } from "expo-router"; import Colors from "@/src/constants/Colors"; import { Text } from "@/src/components/Themed"; import { useColorScheme } from "@/src/components/useColorScheme"; import OrderListItem from "@/src/components/OrderListItem"; import OrderItemListItem from "@/src/components/OrderItemListItem"; import { useOrderDetails } from "@/src/api/orders"; import { useUpdateOrderStatusSubscription } from "@/src/api/orders/subscriptions"; export default function ProductDetailsScreen() { const { id } = useLocalSearchParams(); const orderId = Array.isArray(id) ? id[0] : id || ""; // Take the first element if it's an array, or use an empty string if it's undefined useUpdateOrderStatusSubscription(parseInt(orderId)); const { data: order, error, isLoading, refetch, } = useOrderDetails(parseInt(orderId)); const colorScheme = useColorScheme(); return ( <View style={styles.container}> {isLoading ? ( <View style={styles.subcontainer}> <ActivityIndicator size="large" color={Colors[colorScheme ?? "light"].tint} /> </View> ) : error ? ( <View style={styles.subcontainer}> <Text>Error: {error.message}</Text> </View> ) : ( <View style={styles.container}> {!order ? ( <View style={styles.subcontainer}> <Text>No order found</Text> </View> ) : ( <> <Stack.Screen options={{ title: "Order #" + order?.id }} /> <OrderListItem order={order} /> <FlatList data={order.order_items} renderItem={({ item }) => ( <OrderItemListItem orderItem={item} /> )} //Styles to the rows and around contentContainerStyle={{ gap: 10, padding: 10 }} //Styles to the columns/between /> </> )} </View> )} </View> ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 10, }, subcontainer: { flex: 1, justifyContent: "center", alignItems: "center", }, });
def does_clinic_have_free_space(): return Vet.space > 0 class Vet: animals = list() space = 5 def __init__(self, name): self.name = name self.animals = list() def does_animal_exist(self, animal_name): return animal_name in self.animals def register_animal(self, animal_name): if not does_clinic_have_free_space(): return "Not enough space" self.animals.append(animal_name) Vet.animals.append(animal_name) Vet.space -= 1 return f"{animal_name} registered in the clinic" def unregister_animal(self, animal_name): if not self.does_animal_exist(animal_name): return f"{animal_name} not in the clinic" self.animals.remove(animal_name) Vet.animals.remove(animal_name) Vet.space += 1 return f"{animal_name} unregistered successfully" def info(self): return f"{self.name} has {len(self.animals)} animals. {Vet.space} space left in clinic"
package com.example.blogwithsecurity.Config; import com.example.blogwithsecurity.Services.UsersDetailsService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class ConfigurationSecurity { private final UsersDetailsService usersDetailsService; @Bean public DaoAuthenticationProvider daoAuthenticationProvider() { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(usersDetailsService); daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder()); return daoAuthenticationProvider; } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf().disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .authenticationProvider(daoAuthenticationProvider()) .authorizeHttpRequests().requestMatchers("/api/v1/auth/register").permitAll(). requestMatchers("api/v1/blogs/get").hasAuthority("ADMIN") .anyRequest().authenticated() .and() .logout().logoutUrl("api/v1/auth/logout") .deleteCookies("JSESSIONID").invalidateHttpSession(true) .and() .httpBasic(); return http.build(); } }
<?php /** * Copyright (c) Enalean, 2022 - Present. All Rights Reserved. * * This file is a part of Tuleap. * * Tuleap 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. * * Tuleap 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 Tuleap. If not, see <http://www.gnu.org/licenses/>. */ namespace Tuleap\Docman\Item; use Tuleap\Docman\REST\v1\Folders\ParentFolderRepresentation; /** * @psalm-immutable */ final class PaginatedParentRowCollection { private int $size; /** * @var ParentFolderRepresentation[] */ private array $paginated_element_collection; /** * @param $paginated_element_collection ParentFolderRepresentation[] */ public function __construct(array $paginated_element_collection, int $size) { $this->paginated_element_collection = $paginated_element_collection; $this->size = $size; } /** * @return ParentFolderRepresentation[] */ public function getPaginatedElementCollection(): array { return $this->paginated_element_collection; } public function getTotalSize(): int { return $this->size; } }
package com.practice.simpleWeb.Security; import com.practice.simpleWeb.Repository.RefreshTokenRepository; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfig { private final JwtProvider jwtProvider; private final RefreshTokenRepository refreshTokenRepository; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .httpBasic().disable() .csrf().disable() .cors().and() .authorizeRequests() .antMatchers("/home", "/member/*") .permitAll() .anyRequest().authenticated() .and() .addFilterBefore(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .build(); } @Bean public PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring() .antMatchers("home", "/member/*"); } }
using Elsa.Mediator.Contexts; using Elsa.Mediator.Contracts; using Elsa.Mediator.Middleware.Command.Contracts; namespace Elsa.Mediator.Middleware.Command.Components; /// <summary> /// A command middleware that invokes the command. /// </summary> public class CommandHandlerInvokerMiddleware : ICommandMiddleware { private readonly CommandMiddlewareDelegate _next; private readonly IServiceProvider _serviceProvider; private readonly IEnumerable<ICommandHandler> _commandHandlers; /// <summary> /// Constructor. /// </summary> public CommandHandlerInvokerMiddleware(CommandMiddlewareDelegate next, IEnumerable<ICommandHandler> commandHandlers, IServiceProvider serviceProvider) { _next = next; _serviceProvider = serviceProvider; _commandHandlers = commandHandlers.DistinctBy(x => x.GetType()).ToList(); } /// <inheritdoc /> public async ValueTask InvokeAsync(CommandContext context) { // Find all handlers for the specified command. var command = context.Command; var commandType = command.GetType(); var resultType = context.ResultType; var handlerType = typeof(ICommandHandler<,>).MakeGenericType(commandType, resultType); var handlers = _commandHandlers.Where(x => handlerType.IsInstanceOfType(x)).ToArray(); if (!handlers.Any()) throw new InvalidOperationException($"There is no handler to handle the {commandType.FullName} command"); if (handlers.Length > 1) throw new InvalidOperationException($"Multiple handlers were found to handle the {commandType.FullName} command"); var handler = handlers.First(); var strategyContext = new CommandStrategyContext(command, handler, _serviceProvider, context.CancellationToken); var strategy = context.CommandStrategy; var executeMethod = strategy.GetType().GetMethod(nameof(ICommandStrategy.ExecuteAsync))!; var executeMethodWithReturnType = executeMethod.MakeGenericMethod(resultType); // Execute command. var task = executeMethodWithReturnType.Invoke(strategy, new object[] { strategyContext }); // Get result of task. var taskWithReturnType = typeof(Task<>).MakeGenericType(resultType); var resultProperty = taskWithReturnType.GetProperty(nameof(Task<object>.Result))!; context.Result = resultProperty.GetValue(task); // Invoke next middleware. await _next(context); } }
import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.apache.log4j.Logger; import org.junit.Assert; public class Steps { private static Logger logger = Logger.getLogger(Steps.class); String providedValue; String resultValue; @Given("^I have \"(.*)\" string$") public void i_have_string(String value) { logger.info("i_have_string invoked, threadId=" + Thread.currentThread().getId()); providedValue = value; sleep(); } @When("^I repeat it (.*) times$") public void repeat_string(int nrOfTimes) { logger.info("repeat_string invoked, threadId=" + Thread.currentThread().getId()); resultValue = ""; for (int i = 0 ; i < nrOfTimes; i++) { resultValue += providedValue; } sleep(); } @Then("^I'll get \"(.*)\" string$") public void get_string(String benchmarkValue) { logger.info("get_string invoked, threadId=" + Thread.currentThread().getId()); Assert.assertEquals("Values are different", benchmarkValue, resultValue); sleep(); } private void sleep() { try { Thread.sleep(3000); } catch (Exception e) { logger.error(e.getMessage()); } } }
import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { MoviesService } from '../../services/movies.service'; import { Router } from '@angular/router'; import { Observable, Subject, takeUntil, tap } from 'rxjs'; import { Movie } from '../../interfaces/movie'; import { FormType } from '../../enums/formType'; import { MovieFormState } from '../../state/movieForm.state'; import { MoviesState } from '../../state/movies.state'; @Component({ selector: 'app-movie-form', templateUrl: './movie-form.component.html', styleUrl: './movie-form.component.scss', }) export class MovieFormComponent implements OnInit, OnDestroy { @Input() movieData?: Movie; movieForm!: FormGroup; movieFormTitle$!: Observable<FormType>; private destroy$ = new Subject<void>(); constructor( private formBuilder: FormBuilder, private moviesService: MoviesService, private movieFormState: MovieFormState, private moviesState: MoviesState, private router: Router ) {} ngOnInit(): void { this.movieForm = this.formBuilder.group({ title: '', overview: '', backdrop_path: '', release_date: '', budget: 0, revenue: 0, popularity: 0, homepage: '', }); this.movieFormTitle$ = this.movieFormState.getMovieFormTitle(); if (this.movieData) { this.movieForm.patchValue(this.movieData); } } onSubmit(): void { const movieObservable = this.movieData ? this.moviesService.patchMovie(this.movieData.id || '', this.movieForm.value) : this.moviesService.postMovie(this.movieForm.value); movieObservable.pipe(takeUntil(this.destroy$)) .pipe( tap(movie => this.moviesState.setSelectedMovie(movie)), tap(() => this.movieFormState.setDisplayState(false)) ) .subscribe((createdMovie) => { this.router.navigate([`movie/${createdMovie.id}`]); }); } onCancel(): void { this.movieFormState.setDisplayState(false); } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.unsubscribe(); } }
import React from "react"; import { useEffect, useState } from "react"; import Logo from "../Logo"; import TodayBox from "../../components/MainPage/TodayBox"; import axios from "axios"; import { useNavigate } from "react-router-dom"; interface Props { toggleMainVisibility: () => void; } interface spot { spotName: string; grade: number; spotId: number; } function TodayMain({ toggleMainVisibility }: Props) { const [spotList, setSpotList] = useState<Array<spot>>([]); const navigate = useNavigate(); useEffect(() => { let now = new Date(); let year = now.getFullYear().toString(); let month = (now.getMonth() + 1).toString().padStart(2, "0"); let day = now.getDate().toString().padStart(2, "0"); let hours = now.getHours().toString(); // console.log(year, month, day, hours); // console.log(typeof year); // console.log(typeof month); // console.log(typeof day); // console.log(typeof hours); axios .get("https://counting-star.com/api/spot/ranking", { params: { baseDateYear: year, baseDateMonth: month, baseDateDay: day, // baseDateHour: hours, baseDateHour: "00", baseDateMinute: "00", limit: 5, }, }) .then(function (response) { console.log("๊ตฌ๋ถ„"); console.log("spotLists์ถœ๋ ฅ"); console.log(response); setSpotList(response.data.data); console.log(spotList); }) .catch(function (error) { console.log(error); }); }, []); //๊ฒ€์ƒ‰ ํ›„ ๊ฒฐ๊ณผ ์ปดํฌ๋„ŒํŠธ ํด๋ฆญํ•˜๋ฉด ํ•ด๋‹น ์ƒ์„ธํŽ˜์ด์ง€๋กœ ์—ฐ๊ฒฐ const navigateToDetail = (spotId: number) => { navigate(`/detail/${spotId}`); }; return ( <> <div className="grid grid-cols-12 gap-4 mb-7"> <div className="col-span-2 "> <Logo /> </div> <div className="col-span-8 "> <p className="text-4xl text-center py-4 font-serif"> ์˜ค๋Š˜์€ ์–ด๋””์— ๋ณ„์ด ๋งŽ์ด ๋œฐ๊นŒ์š”? </p> </div> <div className="col-span-2"></div> </div> <div className="grid grid-cols-12 gap-10 mx-auto my-1 "> {spotList && spotList.map((spot, idx) => ( <div className="col-span-4" key={idx} onClick={() => { navigateToDetail(spot.spotId); }} > <TodayBox spotName={spot.spotName} grade={spot.grade} /> </div> ))} </div> </> ); } export default TodayMain;
'use strict'; // // Data needed for a later exercise // const flights = // '_Delayed_Departure;fao93766109;txl2133758440;11:25+_Arrival;bru0943384722;fao93766109;11:45+_Delayed_Arrival;hel7439299980;fao93766109;12:05+_Departure;fao93766109;lis2323639855;12:30'; // Data needed for first part of the section // const restaurant = { // name: 'Classico Italiano', // location: 'Via Angelo Tavanti 23, Firenze, Italy', // categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'], // starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'], // mainMenu: ['Pizza', 'Pasta', 'Risotto'], // order: function (starterIndex, mainIndex) { // return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]; // }, // }; // const arr = [2, 3, 4]; // const a = arr[0]; // const b = arr[1]; // const c = arr[2]; // const [x, y, z] = arr; // console.log(x, y, z); // console.log(arr); // let [main, secondary] = restaurant.categories; // console.log(main, secondary); // // const temp = main; // // main = secondary; // // secondary = temp; // // console.log(main, secondary); // [main, secondary] = [secondary, main]; // console.log(main, secondary); // //Receive to return values from a function // const [starter, mainCourse] = restaurant.order(2, 0); // console.log(starter, mainCourse); // // Nested destructing // const nested = [2, 4, [5, 6]]; // // const [i, j] = nested; // const [i, , [j, k]] = nested; // console.log(i, j, k); // // Default values // const [p = 1, q = 1, r = 1] = [8, 9]; // console.log(p, q, r); // console.log('------slice method------'); // function func() { // let arr = [23, 56, 87, 32, 75, 13]; // let newArr = arr.slice(2, 4); // console.log(arr); // console.log(newArr); // } // func(); const arr = [2, 3, 4]; const a = arr[0]; const b = arr[1]; const c = arr[2]; const [x, y, z] = arr; console.log(x, y, z); /**************************/ console.log('----------Restaurant---------'); /*********************** */ const restaurant = { name: 'Cafe TJ da Bangalinano', location: 'Vai Angelo Tavanti 23, Firenze, Italy', categories: ['Bangladeshi', 'Italian', 'Pizzeria', 'Vegetarian', 'Organic'], starterMenu: [ 'Chom Chom', 'Rosmalai', 'Rosogolla', 'Doi', 'Sondesh', 'Nan: Butter or Normal', 'Porata', 'Focaccia', 'Bruschetta', 'Garlic Bread', ], mainMenu: [ 'Choui Beef Vuna', 'Rice', 'Beef Akhni', 'Kacchi', 'Chieck Tanduri', 'Kabab', 'Pizza', 'Pasta', 'Risotto', ], order: function (starterIndex, mainIndex) { return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]; }, }; let [first, , , , second] = restaurant.categories; console.log(first, second); [first, second] = [second, first]; console.log(first, second); console.log(restaurant.order(0, 0)); const [starter, mainCourse] = restaurant.order(0, 0); console.log(starter, mainCourse); /********************************** */ console.log('-------Nested-------'); /******************************** */ const nested = [2, 4, [5, 6]]; const [i, , [j, k]] = nested; console.log(i, j, k);
import hmac import hashlib import json from functools import wraps from werkzeug.exceptions import Unauthorized class Signature: """ ๅ‚่€ƒ่…พ่ฎฏไบ‘ๆŽฅๅฃ้‰ดๆƒ https://cloud.tencent.com/document/product/214/1526 t = time.time() secret_id, action = 'wechat_personal', 'send_user_feedback' signature = Signature.gen_signature(action, secret_id, t) Signature.check_right(action, secret_id, t, signature) """ identify_keys = ['secret_id', 'timestamp', 'action'] @classmethod def get_key(cls, key): """ clsๅฎžไพ‹ๅŒ–ๅฏน่ฑก item ๏ผšjsonๅŽ็š„ๅญ—ๅ…ธ key: secret_id """ return json.loads(cls.items).get(key) @classmethod def gen_signature(cls, action, secret_id, timestamp): identify = [ (cls.identify_keys[2], action), (cls.identify_keys[0], secret_id), (cls.identify_keys[1], timestamp), ] identify_str = "&".join(["%s=%s" % (k, v) for k, v in identify]) secret_key = cls.get_key(secret_id).encode("utf-8") return hmac.new(secret_key, identify_str.encode('utf-8'), hashlib.sha1).hexdigest() @classmethod def check_right(cls, action, secret_id, timestamp, signature): cal_signature = cls.gen_signature(action, secret_id, timestamp) return cal_signature == signature @classmethod def get_program_authentication_required(signature_cls): def program_authentication_required(func): """ๅŸบไบŽไปฅไธŠ้‰ดๆƒ็š„่ฃ…้ฅฐๅ™จๆ–นๆณ•""" @wraps(func) def decorated_view(request, *args, **kwargs): identify = request.META.get('HTTP_IDENTIFY', '') try: dic = dict([i.split('=') for i in identify.split('&')]) if not signature_cls.check_right(**dic): raise Unauthorized(description='signature failed:' + str(dic)) except Exception as e: raise Unauthorized(description='signature failed:' + str(e)) return func(*args, **kwargs) return decorated_view return program_authentication_required @classmethod def get_signature_required(signature_cls): def signature_required(*params): def wrapper(func): project, action = params @wraps(func) def decorated_view(request, *args, **kwargs): identify = request.META.get('HTTP_IDENTIFY', '') try: dic = dict([i.split('=') for i in identify.split('&')]) if project != dic.get('secret_id'): raise Unauthorized(description='project error:' + str(dic)) if action != dic.get('action'): raise Unauthorized(description='action error:' + str(dic)) if not signature_cls.check_right(**dic): raise Unauthorized(description='signature failed:' + str(dic)) except Exception as e: raise Unauthorized(description='signature failed:' + str(e)) return func(request, *args, **kwargs) return decorated_view return wrapper return signature_required program_authentication_required = Signature.get_program_authentication_required() signature_required = Signature.get_signature_required()
#PEARSON'S CORRELATION TEST ON STANDARDIZED DATA # SETUP ---- # Libraries library(GGally) #for nice correlation plots library(cowplot) # Local directories plot.dir <- "plots" models_path <- "data/results/full" # Load data produced in covariate ordination plot fit.df <- fst::read_fst(paste0(models_path, "/freeflow_data.fst"), as.data.table = T) scols <- c("COMID", "cov.lat_v", "cov.elev_mean_smo", "cov.area_km2_ws_log", "cov.BFI_cat", "cov.elev_diff", "cov.slope", "cov.pct_wet_all_ws", "cov.pct_ow_ws", "cov.pct_ice_ws", "cov.pct_for_all_cat_rip100m", "cov.canopy_line", "cov.pct_urb_all_ws", "cov.precip_cat", "cov.air_temp_range_cat", "cov.pct_extru_vol_ws") spat.df <- fit.df[,..scols] spat.std <- vegan::decostand(spat.df[,2:ncol(spat.df)], method = "rrank", MARGIN = 2, na.rm = T) spat.df <- cbind.data.frame("COMID" = spat.df$COMID, spat.std); rm(spat.std) tcols <- c("COMID", "cov.antec_air_temp", "cov.air_temp_ws", "cov.SWE_ws", "cov.daylength_hours", "cov.std_mean_flow", "cov.SWE_1Apr", "tim.doy") temp.df <- fit.df[,..tcols] temp.std <- vegan::decostand(temp.df[,2:ncol(temp.df)], method = "rrank", MARGIN = 2, na.rm = T) temp.df <- cbind.data.frame("COMID" = temp.df$COMID, temp.std); rm(temp.std) ycols <- c("tim.year", "tim.doy") times.df <- fit.df[,..ycols] times.df$tim.date <- as.Date(times.df$tim.doy, origin = as.Date(paste0(times.df$tim.year, "-01-01"))) times.df$tim.month <- lubridate::month(times.df$tim.date) times.df$tim.season <- NA times.df$tim.season[times.df$tim.month %in% 1:3] <- "winter" times.df$tim.season[times.df$tim.month %in% 4:6] <- "spring" times.df$tim.season[times.df$tim.month %in% 7:9] <- "summer" times.df$tim.season[times.df$tim.month %in% 10:12] <- "fall" summary(as.factor(times.df$tim.season)) dat.std <- cbind.data.frame("COMID" = temp.df$COMID, times.df, temp.df[,tcols[-1]], spat.df) dat.std <- unique(dat.std); dat.std <- dat.std[,-14] # Rename mat.std colnames for plotting thecols <- c("Tl","Tws","Sws","DL","Qr","SA1","D","Lat","E","A","BFI","Ed","S","W","O","I","F","C","U","P","R","V") colnames(dat.std) <- c("COMID", "year", "doy", "date", "month", "season", thecols) # Correlation plots showing values ---- g1 <- list( cor.sp <- ggcorr(subset(dat.std, season == "spring")[,thecols], method = c("pairwise", "pearson"), label_size = 3, label = T, label_alpha = T) + ggtitle("Spring") + theme(plot.title = element_text(size = 22)), cor.su <- ggcorr(subset(dat.std, season == "summer")[,thecols], method = c("pairwise", "pearson"), label_size = 3, label = T, label_alpha = T) + ggtitle("Summer") + theme(plot.title = element_text(size = 22)), cor.f <- ggcorr(subset(dat.std, season == "fall")[,thecols], method = c("pairwise", "pearson"), label_size = 3, label = T, label_alpha = T) + ggtitle("Fall") + theme(plot.title = element_text(size = 22)), cor.w <- ggcorr(subset(dat.std, season == "winter")[,thecols], method = c("pairwise", "pearson"), label_size = 3, label = T, label_alpha = T) + ggtitle("Winter") + theme(plot.title = element_text(size = 22)) ) #legend.position = "none" png(height = 12, width = 12, units = "in", res = 400, file = paste0(plot.dir, "/FigS1_correl_values.png")) grid.arrange( grobs = g1, widths = c(3, 3), layout_matrix = rbind(c(1, 2), c(3, 4)) ) dev.off() cor.all <- ggcorr(subset(dat.std)[,thecols], method = c("pairwise", "pearson"), label_size = 4, label = T, label_alpha = T) + ggtitle("Year-round") png(paste0(plot.dir, "/correl_values_year-round.png"), width = 9.5, height = 9.5, units = "in", res = 300) plot(cor.all) dev.off()
package com.example.aichatbot; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; EditText type; ImageButton send; List<Message> messages; MessageAdapter messageAdapter; public static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); messages = new ArrayList<>(); recyclerView = findViewById(R.id.recycler_view); type = findViewById(R.id.tb_type); send = findViewById(R.id.btn_send); messageAdapter = new MessageAdapter(messages); recyclerView.setAdapter(messageAdapter); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setStackFromEnd(true); recyclerView.setLayoutManager(linearLayoutManager); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String question = type.getText().toString().trim(); AddToChat(question, Message.sent_by_user); type.setText(""); CallAPI(question); } }); } void AddToChat(String message, String send_by) { runOnUiThread(new Runnable() { @Override public void run() { messages.add(new Message(message, send_by)); messageAdapter.notifyDataSetChanged(); recyclerView.smoothScrollToPosition(messageAdapter.getItemCount()); } }); } void AddRespond(String respond) { messages.remove(messages.size() - 1); AddToChat(respond, Message.sent_by_ai); } void CallAPI(String question) { messages.add(new Message("Typing...", Message.sent_by_ai)); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("model", "gpt-3.5-turbo"); jsonObject.put("prompt", question); jsonObject.put("max_tokens", 4000); jsonObject.put("temperature", 1); } catch (JSONException e) { e.printStackTrace(); } RequestBody body = RequestBody.create(jsonObject.toString(), JSON); Request request = new Request.Builder() .url("https://api.openai.com/v1/chat/completions") .header("Authorization", "Bearer YOUR_OPENAI_API_KEY") .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { AddRespond("Failed to respond due to " + e.getMessage()); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { try { JSONObject _jsonObject = null; if (!response.isSuccessful()) { AddRespond("API request failed with code: " + response.code()); return; } try { String respondBody = response.body().string(); _jsonObject = new JSONObject(respondBody); JSONArray jsonArray = _jsonObject.getJSONArray("choices"); String result = jsonArray.getJSONObject(0).getString("text"); AddRespond(result.trim()); } catch (JSONException e) { e.printStackTrace(); } } finally { if (response.body() != null) { response.body().close(); } } } }); } }
package br.edu.iff.jogoforca.dominio.rodada; import java.util.ArrayList; import java.util.List; import br.edu.iff.bancodepalavras.dominio.letra.Letra; import br.edu.iff.bancodepalavras.dominio.palavra.Palavra; import br.edu.iff.dominio.ObjetoDominioImpl; public class Item extends ObjetoDominioImpl { //ATRIBUTOS public Palavra palavra; private boolean[] posicoesDescobertas; private String palavraArriscada = null; //CONSTRUTORES private Item(long id, Palavra palavra) { super(id); this.palavra = palavra; this.posicoesDescobertas = new boolean[palavra.getTamanho()]; } private Item(long id, Palavra palavra, int[] posicoesDescobertas, String palavraArriscada) { super(id); this.palavra = palavra; this.palavraArriscada = palavraArriscada; for (int i = 0; i < posicoesDescobertas.length; i++ ) { this.posicoesDescobertas[posicoesDescobertas[i]] = true; } } //USAM OS CONSTRUTORES static Item criar(long id, Palavra palavra) { return new Item(id, palavra); } public static Item reconstituir(long id, Palavra palavra, int[] posicoesDescobertas, String palavraArriscada) { return new Item(id, palavra, posicoesDescobertas, palavraArriscada); } //Mร‰TODOS public Palavra getPalavra() { return this.palavra; } public Letra[] getLetrasDescobertas() { List<Letra> listaLetras = new ArrayList<>(); for (int i = 0; i < posicoesDescobertas.length; i++) { if(posicoesDescobertas[i]){ listaLetras.add(palavra.getLetra(i)); } } return listaLetras.toArray(new Letra[listaLetras.size()] ); } public Letra[] getLetrasEncobertas() { List<Letra> listaLetras = new ArrayList<>(); for (int i = 0; i < posicoesDescobertas.length; i++) { if(!posicoesDescobertas[i]){ listaLetras.add(palavra.getLetra(i)); } } return listaLetras.toArray(new Letra[listaLetras.size()]); } public int quantidadeLetrasEncobertas() { int qtd = 0; for (int i = 0; i < posicoesDescobertas.length; i++) { if(!posicoesDescobertas[i]){ qtd++; } } return qtd; } public int calcularPontosLetrasEncobertas(int valorPorLetraEncoberta) { return this.quantidadeLetrasEncobertas() * valorPorLetraEncoberta; } public boolean descobriu() { return acertou() || quantidadeLetrasEncobertas() == 0; } public void exibir(Object contexto) { palavra.exibir(contexto, posicoesDescobertas); } boolean tentar(char codigo){ // se ele chamar a funcao de tentar de palavra e ela n retornar nenhuma posicao acertada, retorna false if (palavra.tentar(codigo).length == 0) return false; //caso ele encontre posicoes acertadas, ele vai rodar esse // vetor de posicoes setando a posicao acertada como true no vetor posicoesDescobertas; for (int posicao : palavra.tentar(codigo)) { posicoesDescobertas[posicao] = true ; } return true; } void arriscar(String palavra) { this.palavraArriscada = palavra; } public String getPalavraArriscada() { return palavraArriscada; } public boolean arriscou(){ return palavraArriscada != null; } public boolean acertou(){ return palavra.toString().equals(palavraArriscada); } }
Docker - Create a docker file - Build the docker file to create an image - Veify image - Inspect image - Push image to repository - Run image - Pull image - Check status with [docker ps] Docker Components Docker components include Docker daemon Docker client Docker Objects Images Containers / Services Network Volumes Docker Registry ********** Docker Basic Commands ********** [ Check the version of Docker ] docker version [ Check the detailed information on the running/stopped containers ] docker info [ Pull an image from docker hub (latest version by default) ] docker pull $mage_name [ Pull specific version of an image from docker hub ] docker pull $image_name:$version [ Verify the downloaded docker images ] docker images [ Remove Docker Image ] docker rmi $image_name [ Check actions on image ] docker history $image_name [ Pull and run image ] docker run $image_name [ Run image with an specific service in background ] docker run --name $service_name -d $image_name [ Search image ] docker search $image_name docker search $image_name | head -$n [ List running containers ] docker ps [ List running/stopped containers ] docker ps -a [ Know the IP address of the running container ] docker inspect $container/service_name [ Stats for a running Container ] docker stats $container|service_name [ Pause/Unpause the processes in a running container ] docker pause $container/service_name_name docker unpause $container/service_name_name [ Start/Stop/Kill the same container ] docker start $container|service_name_name or $id docker stop $container|service_name_name or $id docker kill $container|service_name_name or $id [ Delete a container ] docker rm $container|service_name_name or $id [ Remove all stopped containers ] docker container prune [ Export a container ] docker export $container_name $file_name.tar [ Import a container ] docker import $remote_url/name $file_name.tar [ Stop/Start Docker daemon process (access root required)] service docker stop service docker start [ Check the running status of docker ] service docker status [ Restart Docker service in your system ] service docker restart ********** Docker Installation ********** Prerequisite for installation of Docker on Linux are: 64-bit architecture Linux Linux kernel must be 3.10 or later Here are the steps for installing the community edition in Ubuntu 16.04: Add the GPG key for the official Docker repository to the system: $ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - Now add the Docker repository to APT sources: $ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" Now update the package database with the Docker packages: $ sudo apt-get update Check for the policy: $ apt-cache policy docker-ce Install Docker: $ sudo apt-get install -y docker-ce Check the installed version of Docker: $ sudo docker --version Installation Using Automated Script Are you feeling this procedure lengthy? There is a shortcut to this process. Just run the below command to install Docker curl command $ sudo curl -sSL https://get.docker.io/ | sh ********** Docker Installation for linux MX ********** https://mxlinux.org/wiki/applications/docker/ ********** Uninstall Docker CE ********** This command is used to uninstall Docker CE package in Ubuntu machine. $ sudo apt-get purge docker-ce
import { PromisePool } from "@supercharge/promise-pool"; import { STATUT_CREATION_ORGANISME, STATUT_FIABILISATION_COUPLES_UAI_SIRET, STATUT_FIABILISATION_ORGANISME, } from "shared"; import { createOrganisme, findOrganismeById } from "@/common/actions/organismes/organismes.actions"; import { STATUT_PRESENCE_REFERENTIEL } from "@/common/constants/organisme"; import logger from "@/common/logger"; import { fiabilisationUaiSiretDb, organismesDb, organismesReferentielDb } from "@/common/model/collections"; let nbOrganismesReferentielFiables: number; let nbOrganismesFiabilises: number; let nbOrganismesFermesAFiabiliser: number; /** * Mรฉthode d'application de la fiabilisation pour les diffรฉrents cas : * Organismes du rรฉfรฉrentiel ayant une UAI valide : MAJ le champ fiabilisation_statut des organismes concernรฉs comme FIABLE * Couples ร  fiabiliser : On dรฉplace les effectifs, puis on MAJ le champ fiabilisation_statut des organismes concernรฉs * et on supprime les organismes non fiables restants * Couples identifiรฉs comme non fiables : si on trouve un couple fiable liรฉ ร  ce siret et que l'UAI est fermรฉe dans le rรฉfรฉrentiel alors * si doublons d'effectifs on dรฉplace les effectifs du non fiable vers le fiable et on supprime le non fiable */ export const updateOrganismesFiabilisationUaiSiret = async () => { // Init counters nbOrganismesReferentielFiables = 0; nbOrganismesFiabilises = 0; nbOrganismesFermesAFiabiliser = 0; // Traitement // de l'identification des diffรฉrents statuts de fiabilisation await Promise.all([ updateOrganismesReferentielFiables(), updateOrganismesFiabilises(), updateOrganismesFiablesFermes(), ]); // Log logger.info("> MAJ des statuts de fiabilisation des organismes"); logger.info(" ->", nbOrganismesReferentielFiables, "organismes du rรฉfรฉrentiel mis ร  jour en tant que fiables"); logger.info(" ->", nbOrganismesFiabilises, "organismes mis ร  jour en tant que fiabilisรฉs"); logger.info(" ->", nbOrganismesFermesAFiabiliser, "organismes fiables fermรฉs ร  fiabiliser vers organisme ouvert"); return { nbOrganismesReferentielFiables, nbOrganismesFiabilises, nbOrganismesFermesAFiabiliser, }; }; // #region ORGANISMES REFERENTIEL FIABLES /** * Mรฉthode maj des statuts de fiabilisation FIABLE pour les organismes avec UAI, prรฉsents dans le rรฉfรฉrentiel et encore ouverts */ const updateOrganismesReferentielFiables = async () => { const { modifiedCount } = await organismesDb().updateMany( { uai: { $exists: true }, est_dans_le_referentiel: STATUT_PRESENCE_REFERENTIEL.PRESENT, ferme: false }, { $set: { fiabilisation_statut: STATUT_FIABILISATION_ORGANISME.FIABLE } } ); nbOrganismesReferentielFiables += modifiedCount; }; // #endregion // #region ORGANISMES A FIABILISER /** * Mรฉthode de MAJ des organismes pour les cas ou l'on bien fiabilisรฉ la donnรฉe */ const updateOrganismesFiabilises = async () => { const couplesAFiabiliser = await fiabilisationUaiSiretDb() .find({ type: STATUT_FIABILISATION_COUPLES_UAI_SIRET.A_FIABILISER }) .toArray(); await PromisePool.for(couplesAFiabiliser).process(updateOrganismeForCoupleFiabilise); }; /** * Mรฉthode de MAJ unitaire d'un organisme ร  fiabiliser et de ses effectifs * Pour chaque couple identifiรฉ on va mettre ร  jour l'organisme en question comme รฉtant FIABLE * Enfin on va dรฉplacer les effectifs de l'organisme non fiable vers le fiable * Puis supprimer l'organisme non fiable * @param {*} currentFiabilisationCouple */ const updateOrganismeForCoupleFiabilise = async ({ uai_fiable, siret_fiable }: any) => { // Update de l'organisme liรฉ ร  un couple UAI-SIRET marquรฉ comme A_FIABILISER en FIABLE const { modifiedCount: organismesModifiedCount } = await organismesDb().updateOne( { uai: uai_fiable, siret: siret_fiable }, { $set: { fiabilisation_statut: STATUT_FIABILISATION_ORGANISME.FIABLE } } ); let organismeFiable = await organismesDb().findOne({ uai: uai_fiable, siret: siret_fiable }); if (!organismeFiable) { // Si on ne trouve aucun organisme fiable pour l'uai fiable / siret_fiable c'est qu'on est dans le cas d'un couple d'un lieu // On peut alors crรฉer l'organisme comme รฉtant un organisme "lieu" const organismeLieuToCreate = await createOrganisme({ uai: uai_fiable, siret: siret_fiable, fiabilisation_statut: STATUT_FIABILISATION_ORGANISME.FIABLE, creation_statut: STATUT_CREATION_ORGANISME.ORGANISME_LIEU_FORMATION, // Ajout d'un flag pour identifier que c'est un organisme crรฉรฉ ร  partir d'un lieu }); organismeFiable = await findOrganismeById(organismeLieuToCreate?._id); } nbOrganismesFiabilises += organismesModifiedCount; }; // #endregion /** * Fonction de fiabilisation des organismes fermรฉ si on trouve un unique organisme ouvert liรฉ */ export const updateOrganismesFiablesFermes = async () => { // Rรฉcupรฉration des couples fiables avec lookup sur le rรฉfรฉrentiel via SIRET et รฉtant marquรฉs comme fermรฉs dans le rรฉfรฉrentiel const couplesFiablesFermesDansReferentiel = await organismesDb() .find({ fiabilisation_statut: STATUT_FIABILISATION_ORGANISME.FIABLE, ferme: true }) .toArray(); await PromisePool.for(couplesFiablesFermesDansReferentiel).process(async ({ uai, siret }: any) => { // On recherche s'il existe un organisme ouvert liรฉ ร  l'UAI const organismesReferentielOpen = await organismesReferentielDb() .find({ uai, etat_administratif: "actif" }) .toArray(); // S'il existe un unique organisme ouvert liรฉ on ajoute une fiabilisation if (organismesReferentielOpen.length === 1) { await updateOrganismeForCoupleFiabilise({ uai, uai_fiable: uai, siret, siret_fiable: organismesReferentielOpen[0].siret, }); nbOrganismesFermesAFiabiliser++; } }); };
import { IsEnum, IsInt, IsOptional, IsString } from 'class-validator'; import { JanusRequestEvent } from '../constants/janus-request-event'; import { CreateGameRoomDto } from '../dto'; export class CreateJanusRoomDto { @IsEnum(JanusRequestEvent) request: JanusRequestEvent; @IsInt() publishers: number; @IsOptional() @IsString() pin?: string; @IsString() description?: string; @IsString() admin_key: string; constructor(createGameDto: CreateGameRoomDto, admin_key: string) { this.request = JanusRequestEvent.CREATE; this.description = createGameDto.description; this.publishers = createGameDto.publishers; if (createGameDto?.pin) { this.pin = createGameDto.pin; } this.admin_key = admin_key; } } // export class CreateJanusRoomDto { // @IsEnum(JanusRequestEvent) // @Exclude() // private readonly _request: JanusRequestEvent; // @IsInt() // @Exclude() // private readonly _publishers: number; // @IsOptional() // @IsString() // @Exclude() // private readonly _pin?: string; // @IsString() // @Exclude() // private readonly _description?: string; // @IsString() // @Exclude() // private readonly _admin_key: string; // constructor(createGameDto: CreateGameRoomDto, admin_key: string) { // this._request = JanusRequestEvent.CREATE; // this._description = createGameDto.description; // this._publishers = createGameDto.publishers; // if (createGameDto?.pin) { // this._pin = createGameDto.pin; // } // this._admin_key = admin_key; // } // get request(): JanusRequestEvent { // return this._request; // } // get description(): string { // return this._description; // } // get publishers(): number { // return this._publishers; // } // get pin(): string | null { // return this?._pin; // } // get admin_key(): string { // return this._admin_key; // } // }
import { createContext, useReducer } from "react"; export const themeContext = createContext(); const initialState = { darkMode: false }; const themeReducer = (state, action) => { switch (action.type) { case "toggle": return { darkMode: !state.darkMode }; default: return state; } }; export const ThemeProvider = (props) => { const [state, dispatch] = useReducer(themeReducer, initialState); return ( <themeContext.Provider value={{state, dispatch}}>{props.children}</themeContext.Provider> ); };
ANALYZING TOP WEBSITE PAGES & ENTRY PAGES Basic SELECT *: SELECT * FROM website_pageviews WHERE website_pageview_id < 1000 Identifying all the pageview URL visits for a single user: SELECT * FROM website_pageviews WHERE website_session_id = 6 Selecting the volume of visits for each webpage: SELECT pageview_url, COUNT(DISTINCT website_pageview_id) AS visits FROM website_pageviews WHERE website_pageview_id < 1000 GROUP BY pageview_url ORDER BY visits DESC # pageview_url, visits '/home', '523' '/products', '195' '/the-original-mr-fuzzy', '134' '/cart', '56' '/shipping', '39' '/billing', '34' '/thank-you-for-your-order', '18' Creating and Utilizing a Temporary Table: CREATE TEMPORARY TABLE first_pageview SELECT website_session_id, MIN(website_pageview_id) AS min_pv_id FROM website_pageviews WHERE website_pageview_id < 1000 GROUP BY website_session_id SELECT website_pageviews.pageview_url AS landing_page, -- AKA "entry page" COUNT(DISTINCT first_pageview.website_session_id) AS sessions_hitting_this_lander FROM first_pageview LEFT JOIN website_pageviews ON first_pageview.min_pv_id = website_pageviews.website_pageview_id GROUP BY landing_page ----------------------------------------------------------------------------------------------------------------------- ASSIGNMENTS Assignment 1 - Select the Most-Viewed Website Pages, Ranked by Session Volume: SELECT pageview_url, COUNT(DISTINCT website_session_id) AS sessions FROM website_pageviews WHERE created_at < '2012-06-09' GROUP BY pageview_url ORDER BY sessions DESC # pageview_url, sessions '/home', '10403' '/products', '4239' '/the-original-mr-fuzzy', '3037' '/cart', '1306' '/shipping', '869' '/billing', '716' '/thank-you-for-your-order', '306' Assignment 2 - Select All Entry Pages and Rank them on Entry Volume: -- Step 1: find the first pageview for each session -- Step 2: find the url that the customer saw on that first pageview CREATE TEMPORARY TABLE first_pv_per_session -- this query will return the website session ids and the first pageview id that they saw SELECT website_session_id, MIN(website_pageview_id) AS first_pv FROM website_pageviews WHERE created_at < '2012-06-12' GROUP BY website_session_id; SELECT website_pageviews.pageview_url AS landing_page_url, COUNT(DISTINCT first_pv_per_session.website_session_id) AS sessions_hitting_page FROM first_pv_per_session LEFT JOIN website_pageviews ON first_pv_per_session.first_pv = website_pageviews.website_pageview_id GROUP BY landing_page_url; # landing_page_url, sessions_hitting_page '/home', '10714'
{{!-- The UiTable is designed as a layer-cake of controls whose output is fed to the input of the next tier down. --}} <div class="ui-table" role="region" aria-describedby="{{concat this.tableGuid '-description'}}" > <UiSorter @records={{this.records}} as |Sorter|> <UiFilter @records={{Sorter.sortedRecords}} @filterRules={{this.derivedFilterRules}} @filterMethod={{this.filterMethod}} as |Filter|> <UiPager @records={{Filter.filteredRecords}} as |Pager|> {{!-------------------------- Top Control Bar ----------------------------}} {{#let (component Pager.SizeOptions) (component Pager.Navbar responsive = false pageLinkCount = 3 ) (component Filter.Input filters = this.filters showClearButton = this.showFilterClearButton placeholder = this.filterPlaceholder ) as |PagerSizeOptions PagerNavbar FilterInput|}} {{#if (has-block "topControlBar")}} {{yield (hash PagerSizeOptions = PagerSizeOptions PagerNavbar = PagerNavbar FilterInput = FilterInput pagerDescription = Pager.description ) to="topControlBar"}} {{else}} <UiTable::ControlBar @pagerSizeOptions={{PagerSizeOptions}} @pagerNavbar={{PagerNavbar}} @filterInput={{FilterInput}} @pagerDescription={{Pager.description}} @showPagerSizeOptions={{this.pagingEnabled}} @showFilterInput={{this.filterEnabled}} @showPagerDescription={{this.pagingEnabled}} @showPagerNavbar={{this.pagingEnabled}} /> {{/if}} {{/let}} {{!-------------------------- Table Proper ----------------------------}} <table class="table table-striped table-responsive" ...attributes id="{{this.tableGuid}}" aria-describedby="{{concat this.tableGuid "-description"}}" > {{#if (has-block "caption")}} <caption> {{yield to="caption"}} </caption> {{else if this.caption}} <caption>{{this.caption}}</caption> {{/if}} <thead> {{#if (has-block "thead")}} {{yield (hash Th=(component "ui-table/th" sortCriterion=Sorter.Criterion)) to="thead"}} {{else if this.columns}} <tr> {{#each this.columns as |column|}} <UiTable::Th @label={{column.label}} @propertyName={{column.propertyName}} @sortOn={{column.sortOn}} @sortDirection={{column.sortDirection}} @subSortOn={{column.subSortOn}} @subSortDirection={{column.subSortDirection}} @description={{column.description}} @recordSet={{Filter.filteredRecords}} @sortCriterion={{Sorter.Criterion}} class={{column.thClassName}} /> {{/each}} </tr> {{/if}} </thead> <tbody> {{#if (has-block "row")}} {{#each (if this.pagingEnabled Pager.pageRecords Filter.filteredRecords) as |record rowIndex|}} {{yield record rowIndex to="row"}} {{/each}} {{else if this.columns}} {{#each (if this.pagingEnabled Pager.pageRecords Filter.filteredRecords) as |record rowIndex|}} <tr> {{#each this.columns as |column columnIndex|}} {{#if column.tdComponent}} {{component column.tdComponent column=column record=record rowIndex=rowIndex columnIndex=columnIndex }} {{else}} <td class={{column.tdClassName}}>{{get record column.propertyName}}</td> {{/if}} {{/each}} </tr> {{/each}} {{/if}} </tbody> </table> <div class="sr-only" aria-live="polite" id="{{concat this.tableGuid "-description"}}"> {{#if this.pagingEnabled}}{{Pager.description}}{{/if}} {{Sorter.description}} {{Filter.description}} </div> {{!-------------------------- Bottom Control Bar ----------------------------}} {{#let (component Pager.SizeOptions) (component Pager.Navbar responsive = false pageLinkCount = 3 ) (component Filter.Input filters = this.filters showClearButton = this.showFilterClearButton placeholder = this.filterPlaceholder ) as |PagerSizeOptions PagerNavbar FilterInput|}} {{#if (has-block "bottomControlBar")}} {{yield (hash PagerSizeOptions = PagerSizeOptions PagerNavbar = PagerNavbar FilterInput = FilterInput pagerDescription = Pager.description ) to="bottomControlBar"}} {{else}} <UiTable::ControlBar @pagerSizeOptions={{PagerSizeOptions}} @pagerNavbar={{PagerNavbar}} @filterInput={{FilterInput}} @pagerDescription={{Pager.description}} @showPagerSizeOptions={{false}} @showFilterInput={{false}} @showPagerDescription={{this.pagingEnabled}} @showPagerNavbar={{this.pagingEnabled}} /> {{/if}} {{/let}} </UiPager> </UiFilter> </UiSorter> </div>
/// Unconditionally stops execution. /// /// # Parameters: /// - message: A description of the error to write to the standard error of a hosted environment /// before terminating the program. The default is an empty string. /// - file: The file name to print with `message`. The default is the file where this function /// is called. /// - line: The line number to print along with message. The default is the line where this /// function is called. public fun fatal_error( _ message: String = "", file: String = #file, line: Int = #line ) -> Never { log_failure_description("fatal error", message, in: file, at: line) trap() } /// Checks a necessary condition for making forward progress. /// /// # Parameters: /// - condition: The condition to test. /// - message: A description of the error to write to the standard error of a hosted environment /// before terminating the program if the precondition fails. The default is an empty string. /// - file: The file name to print with `message` if the precondition fails. The default is the /// file where this function is called. /// - line: The line number to print along with message if the precondition fails. The default is /// the line where this function is called. public fun precondition( _ condition: Bool, _ message: String = "", file: String = #file, line: Int = #line ) { if condition { return } log_failure_description("precondition failure", message, in: file, at: line) trap() } /// Logs to the standard error a description of a failure with the given properties iff the program /// is built for executing in a hosted environment. fun log_failure_description(_ title: String, _ message: String, in file: String, at line: Int) { // TODO: select the standard error #if !feature(freestanding) print(file, terminator: ":") print(line, terminator: ": ") if message.is_empty() { print(title) } else { print(title, terminator: ": ") print(message) } #endif } /// Terminates the program abnormally. /// /// This function calls `abort` in a hosted environment or `halt` in free-standing mode. fun trap() -> Never { #if feature(freestanding) halt() #else abort() #endif } /// Halts the execution of the program. /// /// The definition of this function is provided at linking time for use in free-standing mode. /// Programs built for a hosted environment must not call it `halt` and use `trap` instead. @external("halt") fun halt() -> Never
package com.example.scipubwatch.logic; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.*; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.ArrayList; import java.util.List; import static org.openqa.selenium.support.ui.ExpectedConditions.numberOfElementsToBeMoreThan; public class ScraperService { FirefoxDriver driver; WebDriverWait webDriverWait; // selenium 3 public ScraperService(String browserLocation, String driverLocation, int timeout) { driver = getFirefoxDriver(browserLocation, driverLocation); webDriverWait = new WebDriverWait(driver, timeout); // selenium 3 } public void getUrl(String url) { driver.get(url); } public String[] scrape (FindType findType, String text) { List<WebElement> webElementsList = null; if(findType == FindType.FIND_ELEMENT_BY_CLASS_NAME) { webElementsList = driver.findElements(By.className(text)); } else if(findType == FindType.FIND_ELEMENT_BY_ID) { webElementsList = driver.findElements(By.id(text)); } else if(findType == FindType.FIND_ELEMENT_BY_TAG_NAME) { webElementsList = driver.findElements(By.tagName(text)); } else if(findType == FindType.FIND_ELEMENT_BY_XPATH) { webElementsList = driver.findElements(By.xpath(text)); } webElementsList.forEach (webElement -> System.out.println(webElement.getText())); String[] webElements = new String[webElementsList.size()]; int i = 0; for (WebElement webElement : webElementsList) { webElements[i] = webElement.getText(); i++; } return (webElements); } public static FirefoxDriver getFirefoxDriver(String browserLocation, String driverLocation) { System.setProperty("webdriver.firefox.bin", browserLocation); System.setProperty("webdriver.gecko.driver", driverLocation); FirefoxOptions options = new FirefoxOptions(); options.addArguments("--headless"); //ProfilesIni profile = new ProfilesIni(); //FirefoxProfile testprofile = profile.getProfile("debanjan"); //FirefoxOptions opt = new FirefoxOptions(); //opt.setProfile(testprofile); options.setProfile(new FirefoxProfile()); FirefoxDriver driver = new FirefoxDriver(options); return(driver); } public void stopFirefoxDriver() { driver.quit(); } public void clickButtonById(String id) { driver.findElement(By.id(id)).click(); } public void waitUntilNumberOfElementsToBeMoreThan(FindType findType, String identificator, int number) { if (findType == FindType.FIND_ELEMENT_BY_CLASS_NAME) { webDriverWait.until(numberOfElementsToBeMoreThan(By.className(identificator), number)); } else if (findType == FindType.FIND_ELEMENT_BY_ID) { webDriverWait.until(numberOfElementsToBeMoreThan(By.id(identificator), number)); } else if (findType == FindType.FIND_ELEMENT_BY_TAG_NAME) { webDriverWait.until(numberOfElementsToBeMoreThan(By.tagName(identificator), number)); } else if (findType == FindType.FIND_ELEMENT_BY_XPATH) { webDriverWait.until(numberOfElementsToBeMoreThan(By.xpath(identificator), 20)); } } public List<String[]> scrapeAndGet (FindType findType, String text) { List<WebElement> webElementsList = null; if(findType == FindType.FIND_ELEMENT_BY_CLASS_NAME) { webElementsList = driver.findElements(By.className(text)); } else if(findType == FindType.FIND_ELEMENT_BY_ID) { webElementsList = driver.findElements(By.id(text)); } else if(findType == FindType.FIND_ELEMENT_BY_TAG_NAME) { webElementsList = driver.findElements(By.tagName(text)); } else if(findType == FindType.FIND_ELEMENT_BY_XPATH) { webElementsList = driver.findElements(By.xpath(text)); } List<String[]> data = new ArrayList<>(); webElementsList.forEach (webElement -> data.add(webElement.getText().split("\n"))); return(data); } public void scrollBy(int quantity) { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollBy(0, "+String.valueOf(quantity)+")", ""); } public enum FindType { FIND_ELEMENT_BY_CLASS_NAME, FIND_ELEMENT_BY_ID, FIND_ELEMENT_BY_TAG_NAME, FIND_ELEMENT_BY_XPATH } }