text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="author" content="Kreasis" /> <meta name="description" content="Portafolio" /> <meta name="keywords" content="HTML, CSS, , Javascript, Reactjs" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <link rel="stylesheet" href="index.css" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" /> <link rel="icon" type="image/x-icon" href="images/lightsaber.png" /> <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=Quicksand:wght@500&family=Rubik+Dirt&family=Share+Tech+Mono&display=swap" rel="stylesheet" /> <title>Kreasis's Portafolio</title> </head> <body> <!-- Nav Bar --> <nav class="navbar navbar-expand-md navbar-light"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbar-toggler" aria-controls="navbar-toggler" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbar-toggler"> <a class="navbar-brand" href="#" ><img src="images/icono.png" alt="Logo" /></a> <ul class="navbar-nav d-flex justify-content-center align-items-center" > <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#about">Sobre mí</a> </li> <li class="nav-item"> <a class="nav-link" href="#projects">Proyectos</a> </li> <li class="nav-item"> <a class="nav-link" href="#testimonial">Testimonios</a> </li> <li class="nav-item"> <a class="nav-link" href="#contact">Contacto</a> </li> </ul> </div> </div> </nav> <!-- Hero --> <section class="hero align-items-stretch"> <div class="hero-principal d-flex flex-column justify-content-center align-items-center" > <img src="images/Richards.jpg" class="rounded-circle img-fluid shadow" width="200" alt="Chelo-Richards" /> <h1>Hola, soy Chelini</h1> <h2>Hago cosas bonitas en la Web :3</h2> </div> <div class="hero-inferior"> <img src="images/hero-inferior.svg" class="hero-inferior-imagen img-fluid" alt="pc" /> </div> </section> <!-- Sobre mí --> <section class="sobre-mi seccion-oscura" id="about"> <div class="contenedor mx-auto"> <h2 class="seccion-titulo">Conoce a Chelini</h2> <p class="seccion-texto text-center"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ac mollis ipsum, non volutpat elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur tincidunt gravida elit et eleifend. Donec tincidunt fermentum ante, eget eleifend sem feugiat id. Maecenas in turpis diam. Suspendisse scelerisque dapibus ligula, non ultrices neque facilisis vitae. Ut ac neque aliquet, finibus odio a, pellentesque felis. Etiam sit amet hendrerit elit. Curabitur eu placerat nibh. Integer faucibus nisl volutpat, tristique massa eu, dictum purus. </p> </div> </section> <!-- Experiencia --> <section class="experiencia seccion-clara"> <div class="container text-center"> <div class="row"> <div class="columna col-12 col-md-4"> <i class="bi bi-laptop"></i> <p class="experiencia-titulo">Desarrollo Web</p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ac mollis ipsum, non volutpat elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas </p> <div class="badges-contenedor"> <span class="badge text-bg-primary">HTML</span> <span class="badge text-bg-primary">CSS</span> <span class="badge text-bg-primary">JS</span> <span class="badge text-bg-primary">ReactJs</span> </div> </div> <div class="columna col-12 col-md-4"> <i class="bi bi-laptop"></i> <p class="experiencia-titulo">Articulos</p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ac mollis ipsum, non volutpat elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas </p> <div class="badges-contenedor"> <span class="badge text-bg-primary">Escribir</span> <span class="badge text-bg-primary">Editar</span> <span class="badge text-bg-primary">Blogs</span> </div> </div> <div class="columna col-12 col-md-4"> <i class="bi bi-laptop"></i> <p class="experiencia-titulo">Estudios</p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ac mollis ipsum, non volutpat elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas </p> <div class="badges-contenedor"> <span class="badge bg-primary">FreeCodeCamp</span> <span class="badge bg-primary">Python</span> <span class="badge bg-primary">Desarrollo Web</span> </div> </div> </div> </div> </section> <!-- Proyectos --> <section class="proyectos-recientes seccion-clara d-flex flex-column" id="projects"> <h2 class="seccion-titulo text-negro text-center">Mis Proyectos</h2> <h3 class="seccion-descripcion text-center"> Estos son algunos de mis proyectos creados recientemente </h3> <!-- Galeria de Proyectos --> <div class="container proyectos-contenedor text-center"> <div class="row"> <div class="col-12 col-md-6 col-lg-4"> <div class="proyecto"> <img src="images/proyecto1.png" alt="proyecto1" /> <div class="overlay"> <p>Proyecto 1</p> <div class="iconos-contenedor"> <a href="https://github.com/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-github"></i ></a> <a href="https://www.freecodecamp.org/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-laptop"></i ></a> </div> </div> </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="proyecto"> <img src="images/proyecto2.png" alt="proyecto1" /> <div class="overlay"> <p>Proyecto 2</p> <div class="iconos-contenedor"> <a href="https://github.com/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-github"></i ></a> <a href="https://www.freecodecamp.org/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-laptop"></i ></a> </div> </div> </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="proyecto"> <img src="images/proyecto3.png" alt="proyecto1" /> <div class="overlay"> <p>Proyecto 3</p> <div class="iconos-contenedor"> <a href="https://github.com/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-github"></i ></a> <a href="https://www.freecodecamp.org/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-laptop"></i ></a> </div> </div> </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="proyecto"> <img src="images/proyecto4.png" alt="proyecto1" /> <div class="overlay"> <p>Proyecto 4</p> <div class="iconos-contenedor"> <a href="https://github.com/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-github"></i ></a> <a href="https://www.freecodecamp.org/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-laptop"></i ></a> </div> </div> </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="proyecto"> <img src="images/proyecto5.png" alt="proyecto1" /> <div class="overlay"> <p>Proyecto 5</p> <div class="iconos-contenedor"> <a href="https://github.com/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-github"></i ></a> <a href="https://www.freecodecamp.org/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-laptop"></i ></a> </div> </div> </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="proyecto"> <img src="images/proyecto6.png" alt="proyecto1" /> <div class="overlay"> <p>Proyecto 6</p> <div class="iconos-contenedor"> <a href="https://github.com/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-github"></i ></a> <a href="https://www.freecodecamp.org/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-laptop"></i ></a> </div> </div> </div> </div> </div> </div> <a href="https://github.com/" rel="noopener noreferrer" target="_blank" class="mx-auto"> <button type="button" class="btn btn-info"> VER MÁS PROYECTOS <i class="bi bi-arrow-right-circle-fill"></i></button ></a> </section> <!-- Articulos --> <section class="articulos justify-content-start"> <h2 class="seccion-titulo text-negro text-center">Artículos</h2> <div class="card mx-auto"> <div class="card-header">Más recientes</div> <ul class="list-group list-group-flush"> <a href="https://www.freecodecamp.org/news/tag/news-tag/" target="_blank" rel="noopener noreferrer" ><li class="list-group-item">An item</li></a > <a href="https://www.freecodecamp.org/news/tag/news-tag/" target="_blank" rel="noopener noreferrer" ><li class="list-group-item">Another item</li></a > <a href="https://www.freecodecamp.org/news/tag/news-tag/" target="_blank" rel="noopener noreferrer" ><li class="list-group-item">Another Another item</li></a > <a href="https://www.freecodecamp.org/news/tag/news-tag/" target="_blank" rel="noopener noreferrer" ><li class="list-group-item">Another Another item</li></a > <a href="https://www.freecodecamp.org/news/tag/news-tag/" target="_blank" rel="noopener noreferrer" ><li class="list-group-item">Another Another item</li></a > <a href="https://www.freecodecamp.org/news/tag/news-tag/" target="_blank" rel="noopener noreferrer" ><li class="list-group-item">Another Another item</li></a > </ul> </div> <a href="https://www.freecodecamp.org/news/tag/news-tag/" rel="noopener noreferrer" target="_blank" class="mx-auto" > <button type="button" class="btn btn-info"> VER MÁS ARTICULOS <i class="bi bi-arrow-right-circle-fill"></i></button ></a> </section> <!-- Testimonios --> <section class="testimonio seccion-clara" id="testimonial"> <h2 class="seccion-titulo text-center">Testimonios</h2> <h3 class="seccion-descripcion text-center"> Estos son unos testimonios de mis clientes... </h3> <div id="testimonios-carrusel" class="carousel carousel-dark slide"> <div class="carousel-inner"> <div class="carousel-item active"> <div class="container"> <img src="images/cliente1.svg" class="testimonio-imagen rounded-circle" alt="cliente1" /> <p class="testimonio-texto"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque risus libero, molestie ut metus quis, luctus consequat nisl. Nunc vel bibendum est.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc auctor ex eget dui consectetur tempor. Nullam in ornare eros. Nulla a commodo justo. </p> <div class="testimonio-info"> <p class="cliente">Gino</p> <p class="cargo">Gerente de Proyecto</p> </div> </div> </div> <div class="carousel-item active"> <div class="container"> <img src="images/cliente2.svg" class="testimonio-imagen rounded-circle" alt="cliente1" /> <p class="testimonio-texto"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque risus libero, molestie ut metus quis, luctus consequat nisl. Nunc vel bibendum est.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc auctor ex eget dui consectetur tempor. Nullam in ornare eros. Nulla a commodo justo. </p> <div class="testimonio-info"> <p class="cliente">Nora</p> <p class="cargo">Gerente de Proyecto</p> </div> </div> </div> <div class="carousel-item active"> <div class="container"> <img src="images/cliente3.svg" class="testimonio-imagen rounded-circle" alt="cliente1" /> <p class="testimonio-texto"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque risus libero, molestie ut metus quis, luctus consequat nisl. Nunc vel bibendum est.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc auctor ex eget dui consectetur tempor. Nullam in ornare eros. Nulla a commodo justo. </p> <div class="testimonio-info"> <p class="cliente">Juan</p> <p class="cargo">Gerente de Proyecto</p> </div> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#testimonios-carrusel" data-bs-slide="prev" > <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Anterior</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#testimonios-carrusel" data-bs-slide="next" > <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Siguiente</span> </button> </div> </section> <!-- Contacto --> <section class="contacto seccion-oscura" id="contact"> <div class="container"> <div class="container text-center rectangulo d-flex justify-content-evenly" > <div class="row"> <div class="col-12 col-md-4 seccion-titulo">Hablemos!</div> <div class="col-12 col-md-4 descripcion"> Contactamente para iniciar tu proyecto y hare que tu vision se haga realidad </div> <div class="col-12 col-md-4"> <a href="mailto:chelini@micorreo.com" ><button type="button"> Contacto <i class="bi bi-envelope-check"></i></button ></a> </div> </div> </div> </div> </section> <!-- Footer --> <footer class="seccion-oscura d-flex flex-column align-items-center justify-content-center" > <img class="footer-logo" src="images/icono-blanco.svg" alt="icono" /> <p class="footer-text text-center"> Aprendo y creo todos los días <br />Creemos un proyecto juntos </p> <div class="iconos-redes-sociales d-flex flex-wrap align-items-center justify-content-center" > <a href="https://steamcommunity.com/profiles/76561198036814855/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-xbox"></i ></a> <a href="https://steamcommunity.com/profiles/76561198036814855/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-steam"></i ></a> <a href="https://steamcommunity.com/profiles/76561198036814855/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-nintendo-switch"></i ></a> <a href="https://steamcommunity.com/profiles/76561198036814855/" target="_blank" rel="noopener noreferrer" ><i class="bi bi-playstation"></i ></a> </div> <div class="derechos-de-autor">Creado por Chelini (2023) &#169;</div> </footer> <!-- Script --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous" ></script> </body> </html>
package code_10_quickSort; import static utils.utils.printfArray; import static utils.utils.swap; public class QuickSort_S02 { public static void quickSort(int[] arr){ if(arr == null || arr.length < 2){ return; } quickSort(arr,0,arr.length-1); } public static void quickSort(int[] arr,int l ,int r){ if( l < r){ int[] p = partition(arr,l,r); quickSort(arr,l,p[0]-1); quickSort(arr,p[1]+1,r); } } public static int[] partition(int[] arr,int l ,int r){ int less = l-1; int more = r+1; int num =arr[r]; int cur = l; while (cur < more){ if(arr[cur] < num){ swap(arr,cur++,++less); }else if(arr[cur] > num){ swap(arr,cur,--more); }else { cur++; } } //返回的是等于区间的下标值。 return new int[]{less+1,more-1}; } public static void main(String[] args){ int[] arr = {1,3,4,2,9,5}; System.out.print("The origin is:"); printfArray(arr); quickSort(arr); System.out.print("The sorted is:"); printfArray(arr); } }
<!doctype html> <html> <head> <meta charset="utf8"> <script src="static/pipe/csv-viewer.js"></script> <title>Easily add it to your web page</title> </head> <body> <p> To any anchor element to show <a data-grist-csv-open href="./StudentData.csv" data-name="Students">CSV</a> data on a popup. </p> <p> Same, but multipage: <a data-grist-csv-open href="./StudentData.csv" data-name="Students" data-single-page="false">CSV</a> </p> <p> Same, but without name <a data-grist-csv-open href="./StudentData.csv">CSV</a>. </p> <p> Or any <a data-grist-doc-open="./investment-research.grist" href="#" data-name="Students" data-single-page>Grist document</a> as well. </p> <p> Here is anchor with an image <a data-grist-doc-open="./investment-research.grist" href="#" data-name="Students" data-single-page> <img src="https://picsum.photos/100/50" /> </a> as well. </p> <p> There is a <button data-grist-doc-open="investment-research.grist" data-name="Students" data-single-page>button</button> variant. </p> <p> And one with default style <button class="grist" data-grist-doc-open="investment-research.grist" data-name="Students" data-single-page>View as csv</button> <button class="grist-large" data-grist-csv-open="./StudentData.csv" data-name="Students" data-single-page>Large view data</button> </p> <p> Works in any framework, like <span id="react"></span> or <span id="vue"></span> and others. <!-- React part--> <script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script> <script> const App = () => { return ( React.createElement("a", {'data-grist-doc-open': '', href: "./investment-research.grist"}, "React") ); }; ReactDOM.render(React.createElement(App), document.getElementById("react")); </script> <!-- Vue part--> <script src="https://unpkg.com/vue@3.2.6/dist/vue.global.js"></script> <script> const app = Vue.createApp({ template: ` <a data-grist-doc-open href="./investment-research.grist" name="Students" single-page>Vue</a> `, }); app.mount("#vue"); </script> </p> <p> Allows easily preview CSV documents. <script> // This is just a concept of how it can be done. class CsvDrop extends HTMLElement { constructor() { super(); this.attachShadow({mode: 'open'}); this.shadowRoot.innerHTML = ` <style> :host { font-family: sans-serif; display: block; } #drop-area-surround { border-radius: 24px; padding: 20px; width: 480px; margin: 50px auto; padding: 8px; background-color: #27d843; } #drop-area { border: 2px dashed #fff; border-radius: 16px; padding: 20px; } #drop-area.highlight { border: 2px solid yellow; } p { margin-top: 0; } .my-form { color: white; text-align: center; margin: 0; padding: 0; display: flex; justify-content: space-around; align-items: center; width: 100%; } #gallery { margin-top: 10px; display: none; } #gallery img { width: 150px; margin-bottom: 10px; margin-right: 10px; vertical-align: middle; } .button { display: inline-block; padding: 10px; color: black; background: #eee; cursor: pointer; border-radius: 5px; border: 1px solid #ccc; } .button:hover { background: #ddd; } #fileElem { display: none; } </style> <div id="drop-area-surround"> <div id="drop-area"> <form class="my-form"> <div> Drag & Drop to<br /> Upload File </div> <div> OR </div> <div> <input type="file" id="fileElem" accept=".csv" /> <label class="button" for="fileElem">Browse File</label> </div> </form> </div> </div> `; } connectedCallback() { const root = this.shadowRoot; function setupLoader(element, callback) { let dropArea = root.getElementById(element); ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, preventDefaults, false) document.body.addEventListener(eventName, preventDefaults, false) }); ['dragenter', 'dragover'].forEach(eventName => { dropArea.addEventListener(eventName, () => dropArea.classList.add('highlight'), false) }); ['dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, () => dropArea.classList.remove('highlight'), false) }); dropArea.addEventListener('drop', handleDrop, false) dropArea.querySelector('input[type=file]').addEventListener('change', function() { handleFiles(this.files); this.value = null; }); function preventDefaults(e) { e.preventDefault(); e.stopPropagation(); } function handleDrop(e) { var dt = e.dataTransfer; var files = dt.files; handleFiles(files); } function handleFiles(files) { files = [...files]; files.forEach(previewFile); } function previewFile(file) { let reader = new FileReader(); reader.readAsText(file); reader.onloadend = function() { callback({ txt: reader.result, name: file.name, }); } } } const processAddition = (addition) => { const {txt, name} = addition; const event = new CustomEvent('file-changed', { detail : { data: txt, name, } }); this.dispatchEvent(event); } setupLoader('drop-area', processAddition); } } customElements.define('csv-drop', CsvDrop); </script> <csv-drop id="csv-drop"></csv-drop> <script> const csvDrop = document.getElementById("csv-drop"); csvDrop.addEventListener("file-changed", (e) => { previewInGrist({ initialContent: e.detail.data, singlePage: true }); }); </script> </p> <p> Can also be easily embedded as a plain HTML element. <csv-viewer initial-file="investment-research.grist" name="Investment" style="height: 500px; border: 1px solid black"></csv-viewer> </p> </body> </html>
import React from 'react' // components import Modal from '../components/UI/Modal' // Redux import { useSelector, useDispatch } from 'react-redux' import { resetNewMsgs, setConvoAsSeen } from '../store/notifSlice' import { useNavigate, useLocation, useParams } from 'react-router-dom' import { PaperAirplaneIcon, RocketLaunchIcon } from '@heroicons/react/24/outline' import useChat from '../hooks/useChat' function Chat() { const [modalIsOpen, setModalIsOpen] = React.useState(false) // react-router const navigate = useNavigate() const location = useLocation() const params = useParams() // Scroll to bottom trick. const bottomRef = React.useRef(null) // redux const dispatch = useDispatch() const { isLoggedIn, accessToken, uid: clientUid } = useSelector(slices => slices.auth) const { updatedConvos } = useSelector(slices => slices.notif) const { id, // the chat/match id uid, // the profile id url, // the profile pic url username } = location.state const chatId = params.id const { messageList, getMessageList, sendMessage, isOnline } = useChat() const [messageInput, setMessageInput] = React.useState('') React.useEffect(() => { if (!isLoggedIn) navigate('/', { replace: true }) // check if newMessages has item with same id as chat if (updatedConvos.includes(chatId)) { getMessageList({ accessToken, interlocutor: uid, url: location.pathname }) } }, [updatedConvos, isLoggedIn]) React.useEffect(() => { getMessageList({ accessToken, interlocutor: uid, url: location.pathname }) }, []) React.useEffect(() => { dispatch(resetNewMsgs()) dispatch(setConvoAsSeen(id.toString())) bottomRef.current?.scrollIntoView({behavior: 'smooth'}); }, [messageList]) React.useEffect(() => { dispatch(setConvoAsSeen(id.toString())) }, []) function handleSendMessage() { // If the text area is empty (or just whitespace) clear it and return. if (messageInput.trim() === '') { setMessageInput('') return } sendMessage({ url: location.pathname, to: uid, msg: messageInput, cb: () => setMessageInput(''), accessToken, setModalIsOpen }) } function handleInput(e) { if (e.target.value.length >= 256) return setMessageInput(e.target.value) } function closeModalHandler() { setModalIsOpen(false) navigate('/', { replace: true }) } return ( <div className='flex flex-col space-y-3 mx-2 max-w-4xl'> {modalIsOpen && (<Modal closeModal={closeModalHandler}> <RocketLaunchIcon className='inline w-6 text-green-500 -mt-2'/>That match is gone dawg! </Modal>) } <div className='flex mt-4 p-2 border border-white rounded-lg'> <img src={url} className='w-14 rounded-full mr-4' crossOrigin='anonymous' /> <div className='flex flex-col'> <h1 className='text-white hover:underline hover:underline-offset-2 hover:text-blue-600 text-lg font-bold ml-1 hover:cursor-pointer' onClick={() => navigate(`/profiles/${uid}`, {replace: true})} >{username}</h1> <div className='flex'> <span className={`rounded-full w-3 h-3 block mt-[6px] mr-1 ${isOnline ? 'bg-green-500' : 'bg-slate-500'}`}></span> <p className='text-white'> Online</p> </div> </div> </div> <ul className='flex flex-col space-y-2 bg-gray-100 p-2 rounded-lg overflow-y-scroll overscroll-contain h-96 scroll-auto'> {messageList.map(m => { const classes = m.line.to === clientUid ? 'text-left place-self-start bg-orange-300 rounded-bl-none mr-8' : 'text-right place-self-end bg-pink-400 rounded-br-none ml-8' return (<li className={`text-white font-bold p-2 rounded-xl drop-shadow-md max-w-60 break-all ${classes}`} key={Math.random()} >{m.line.content}</li>) })} {/* Extra list item to force automatic scroll */} <li ref={bottomRef}></li> </ul> <div className="flex flex-col pb-4"> <div className="flex "> <textarea type="text" value={messageInput} onChange={e => handleInput(e)} className='outline-none border-none rounded-l-xl w-[70%] text-gray-700 bg-gray-100 text-lg' /> <button className='text-white rounded-r-xl border border-l-0 border-white p-4 w-[30%] hover:bg-white hover:bg-opacity-20' onClick={handleSendMessage} >Send <PaperAirplaneIcon className='w-6 inline -mt-1'/> </button> </div> <p className='text-white pl-4'>{255 - messageInput.length} characters left.</p> </div> </div> ) } export default Chat
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import Paper from '@material-ui/core/Paper'; import { getFermenters, getFermenterTypes, createFermenter } from '../../actions/fermenters'; import FermenterRow from './FermenterRow'; import TableHeader from '../common/TableHeader'; import HardwareTableTitle from '../common/HardwareTableTitle'; class FermentersConfigTable extends React.Component { static styles = theme => ({ root: { marginBottom: theme.spacing.unit * 5, overflowX: 'auto' }, row: { '&:nth-of-type(odd)': { backgroundColor: theme.palette.background.default } } }) static mapStateToProps = state => ({ fermenterList: state.fermenters.fermenters, fermenterTypes: state.fermenters.types }) static mapDispatchToProps = dispatch => ({ getFermenters: () => dispatch(getFermenters()), getFermenterTypes: () => dispatch(getFermenterTypes()), addFermenter: () => dispatch(createFermenter()) }) static propTypes = { classes: PropTypes.shape({ root: PropTypes.string, table: PropTypes.string }).isRequired, fermenterList: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number, name: PropTypes.string })).isRequired, fermenterTypes: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.string, properties: PropTypes.arrayOf(PropTypes.shape({ configurable: PropTypes.bool, description: PropTypes.string, label: PropTypes.string, name: PropTypes.string, type: PropTypes.string })) })).isRequired, getFermenters: PropTypes.func.isRequired, getFermenterTypes: PropTypes.func.isRequired, addFermenter: PropTypes.func.isRequired } state = { deleteMode: false } componentWillMount() { if (this.props.fermenterList.length < 1) { this.props.getFermenters(); } if (this.props.fermenterTypes.length < 1) { this.props.getFermenterTypes(); } } toggleDelete = () => { this.setState({ deleteMode: !this.state.deleteMode }); } render() { const { addFermenter, classes, fermenterList, fermenterTypes } = this.props; return ( <React.Fragment> <HardwareTableTitle text="Fermenters" addAction={addFermenter} deleteAction={this.toggleDelete} /> <Paper className={classes.root}> <Table> <TableHeader columns={this.state.deleteMode ? ['Delete?', 'Name', 'Logic', 'Heater', 'Cooler', 'Sensor1', 'Sensor2', 'Sensor3'] : ['Name', 'Logic', 'Heater', 'Cooler', 'Sensor1', 'Sensor2', 'Sensor3']} /> <TableBody> {fermenterList.map(fermenter => ( <FermenterRow key={fermenter.id} fermenter={fermenter} types={fermenterTypes} deleteMode={this.state.deleteMode} /> ))} </TableBody> </Table> </Paper> </React.Fragment> ); } } export default connect( FermentersConfigTable.mapStateToProps, FermentersConfigTable.mapDispatchToProps )(withStyles(FermentersConfigTable.styles)(FermentersConfigTable));
package com.voyager.hotels import android.view.LayoutInflater import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.voyager.databinding.CategoryItemBinding class CategoryAdapter(var categories: ArrayList<String> ) : RecyclerView.Adapter<CategoryAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( CategoryItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.category.text = categories[position] } override fun getItemCount(): Int = categories.size inner class ViewHolder(binding: CategoryItemBinding) : RecyclerView.ViewHolder(binding.root) { val category: TextView = binding.category } }
<template> <div class="content"> <div class="header"> <h3 class="title">分类列表</h3> <el-button type="primary" @click="handleNewClassifyClick">新建分类</el-button> </div> <div class="table"> <el-table :data="classifyList" border style="width: 100%"> <el-table-column align="center" label="分类名称" prop="name" width="140px" /> <el-table-column align="center" label="排序" prop="sort" width="140px" /> <el-table-column align="center" label="创建时间" prop="createAt"> <template #default="scope"> {{ formatUTC(scope.row.createAt) }} </template> </el-table-column> <el-table-column align="center" label="操作" width="200px"> <template #default="scope"> <el-button size="small" icon="Edit" type="primary" text @click="handleEditBtnClick(scope.row)"> 编辑 </el-button> <el-button size="small" icon="Delete" type="danger" text @click="handleDeleteBtnClick(scope.row.cfy_id)"> 删除 </el-button> </template> </el-table-column> </el-table> </div> <div class="pagination"> <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="classifyTotalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" /> </div> </div> </template> <script setup lang="ts"> import { storeToRefs } from 'pinia' import { ref } from 'vue'; import useClassifyStore from '@/stores/main/classify' import { formatUTC } from '@/utils/format'; const currentPage = ref(1) const pageSize = ref(10) // 1.发起action,请求usersList的数据 const classifyStore = useClassifyStore() fetchClassifyListData() const emit = defineEmits(['newClick', 'editClick']) // 2.获取usersList数据,进行展示 const { classifyList, classifyTotalCount } = storeToRefs(classifyStore) function handleCurrentChange() { fetchClassifyListData() } function handleSizeChange() { fetchClassifyListData() } function fetchClassifyListData() { const size = pageSize.value const offset = (currentPage.value - 1) * size const pageInfo = { size, offset } const queryInfo = { ...pageInfo } classifyStore.getClassifyList(queryInfo) } function handleDeleteBtnClick(id) { classifyStore.deleteClassifyAction({ id }); } function handleEditBtnClick(itemData) { emit('editClick', itemData) } function handleNewClassifyClick() { emit('newClick') } defineExpose({ fetchClassifyListData }) </script> <style lang="less" scoped> .content { margin-top: 20px; padding: 20px; background-color: #fff; } .header { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 10px; .title { font-size: 22px; } } .table { :deep(.el-table__cell) { padding: 12px 26px; } .el-button { margin-left: 0; padding: 5px 8px; } } .pagination { display: flex; justify-content: flex-end; margin-top: 10px; } </style>
from torch.utils.data import Dataset from PIL import Image import pandas as pd from typing import List import numpy as np import os import rasterio import torch from torchvision import transforms def default_loader(path): return rasterio.open(path).read() class DigitDataset(Dataset): # data loading def __init__(self, file_path,INPUT_FRAMES , OUTPUT_FRAMES, loader=default_loader, transform=None ): with open(file_path, 'r') as fh: self.X = [] for line in fh: line = line.strip('\n').rstrip() self.X.append(line) # print(self.X, self.Y) self.loader = loader self.INPUT_FRAMES = INPUT_FRAMES self.OUTPUT_FRAMES = OUTPUT_FRAMES self.clip_count = INPUT_FRAMES + OUTPUT_FRAMES self.transform = transform # working for indexing def __getitem__(self, index): clip = self.X[index * self.clip_count: (index + 1) * self.clip_count] input = [self.loader(img_path) for img_path in clip[:self.INPUT_FRAMES]] output = [self.loader(img_path) for img_path in clip[self.INPUT_FRAMES:self.clip_count]] input_stack = np.stack(input) output_stack = np.stack(output) input_tensor = torch.from_numpy(input_stack).float().contiguous() output_tensor = torch.from_numpy(output_stack).float().contiguous() return index, output_tensor, input_tensor # return the length of our dataset def __len__(self): return len(self.X) // self.clip_count
import { Box, Table as ChakraTable, TableProps as ChakraTableProps, Text, Th, Thead, Tr, useColorMode } from "@chakra-ui/react"; import { memo, ReactNode } from "react"; interface Props extends ChakraTableProps { theadData: string[]; isEmpty?: boolean; showAdditionalColumn?: boolean; children: ReactNode; } const TableComponent = ({ theadData, isEmpty = false, showAdditionalColumn = true, children, ...rest }: Props) => { const { colorMode } = useColorMode(); const colorScheme = colorMode === 'light' ? 'blackAlpha' : 'whiteAlpha' return ( <Box overflowX="auto"> { isEmpty ? ( <Text fontWeight={"bold"} mt={[4]}> Nenhum registro encontrado </Text> ) : ( <ChakraTable colorScheme={colorScheme} {...rest} > <Thead> <Tr> { theadData.map(head => ( <Th key={head}>{ head }</Th> )) } { showAdditionalColumn && <Th w="8"></Th> } </Tr> </Thead> { children } </ChakraTable> )} </Box> ) } export const Table = memo(TableComponent);
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> // 正则(RegExp):制定的规则,通常是用来处理字符串一些文本内容(查找、效验文本内容是否合法) // 正则组成部分 元字符和修饰符 // 字面量方式 // let reg = /元字符/修饰符 // 元字符 // 特殊元字符(在正则中有特殊意义的字符) // 量词元字符(限定元字符连续出现的次数) // 其他元字符 // 普通元字符 /a/ // 特殊元字符 // \ 转义字符(转换成原义)本来的意思 // \d 0 到 9 中任意一个数[0~9](包含0和9) // \D 除了0 到 9 数字,以外 任何一个字符 // \w 匹配数字、字母(大小写)、下划线 [0-9a-zA-Z_] // \W 匹配除了数字、字母(大小写)、下划线 [0-9a-zA-Z_],以外任意一个字符 // \s 匹配空白符(空格 换行符 制表符) // \S 匹配除空白符(空格 换行符 制表符),以外任意字符 // \b 匹配单词的边界 'hello world' (每个单词两边就是边界) // \B 匹配除了单词的边界 // \n 匹配换行符 // ^ 匹配字符串的开头(以什么什么开头) // $ 匹配的是 字符串的末尾 (以什么什么结尾) // . 匹配除了\n(换行符),以外的任意字符(默认不是小数点的意思,需要转义为小数点 \.) /* \d 0 到 9 中任意一个数[0~9](包含0和9) let reg = /\d/; console.log(reg.test('1'));// true reg.test('0'); // true reg.test('9'); // true reg.test('a'); // false RegExp.prototype.test 匹配 验证字符串是否符合这个正则规则 符合返回true 否则返回false 语法: reg.test('字符内容'); */ /* \D 除了0 到 9 数字,以外 任何一个字符 let reg = /\D/; console.log(reg.test('-1')); // true console.log(reg.test('a')); //true */ // \w 匹配数字、字母(大小写)、下划线 [0-9a-zA-Z_] /* let reg = /\w/; reg.test('1'); // true reg.test('a'); // true reg.test('A'); // true reg.test('_'); // true */ // \W 匹配除了数字、字母(大小写)、下划线 [0-9a-zA-Z_],以外任意一个字符 /* let reg = /\W/; reg.test('1'); // false reg.test('a'); // false reg.test('A'); // false reg.test('_'); // false reg.test('='); // true */ // \s 匹配空白符(空格 换行符 制表符) // let reg = /\s/; // let str = ` // `; // console.log(reg.test(' ')); // true // console.log(reg.test(str)); // true // \S 匹配除空白符(空格 换行符 制表符),以外任意字符 // let reg = /\S/; // console.log(reg.test('a')); //true // console.log(reg.test(' ')); //false // \b 匹配单词的边界 'hello world' (每个单词两边就是边界) // let reg = /\bworld\b/; // console.log(reg.test('world')); // true // console.log(reg.test('helloworld')); // false // 匹配的字母w 必须在左边边界 // let reg = /\bw/; // console.log(reg.test('awc')); // false 在中间没有边界 // console.log(reg.test('wc')); // true 在左边边界 // console.log(reg.test('cw')); // false 没有左边边界 有右边边界 // 匹配的字母w 必须在右边边界 // let reg = /w\b/; // console.log(reg.test('awc')); // false 在中间没有边界 // console.log(reg.test('wc')); // false 没有右边边界 有左边边界 // console.log(reg.test('cw')); // true 在右边边界 // \B 匹配除了单词的边界 // 匹配 不在左边边界的字符a // let reg = /\Bw/; // console.log(reg.test('w')); // false // \n 匹配换行符 // let reg = /\n/; // console.log(reg.test('a')); // false // console.log(reg.test(` // a`)); // true // ^匹配字符串的开头(以什么什么开头) // 只要 匹配的字符内容中包含字符a 就返回true // let reg = /a/; // console.log(reg.test('123223a2')); // true // 字符串的开头必须是以a 作为开头的 // let reg = /^a/; // console.log(reg.test('12323a3')); // false // console.log(reg.test('a12323a3')); // true // let reg2 = /^world/ // console.log(reg2.test('world hello')) // true // console.log(reg2.test('hello world')) // false // $ 匹配的是 字符串的末尾 (以什么什么结尾) // let reg = /利$/; // console.log(reg.test('文利')); //true // console.log(reg.test('布罗利')); //true // console.log(reg.test('悟空')); //false // 只能是这个字符 // let reg = /^hello$/; // console.log(reg.test('hello')); // true 只能匹配 hello 这五个字符 // console.log(reg.test('hello hello')); // false // .匹配除了\n(换行符),以外的任意字符 // 当你回车时,不仅有换行符,还有空格符 // let reg = /./; // console.log(reg.test(` // `)); // false // console.log(reg.test('a')); // true // console.log(reg.test('.')); // true // 只想匹配小数点 需要将.转义 // let reg = /\./; // console.log(reg.test('.')); // true // console.log(reg.test('1 ')); // false </script> </body> </html>
package suwayomi.tachidesk.launcher.ui /* * Copyright (C) Contributors to the Suwayomi project * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import suwayomi.tachidesk.launcher.FocusListenerEvent import suwayomi.tachidesk.launcher.KeyListenerEvent import suwayomi.tachidesk.launcher.LauncherViewModel import suwayomi.tachidesk.launcher.actions import suwayomi.tachidesk.launcher.bind import suwayomi.tachidesk.launcher.focusListener import suwayomi.tachidesk.launcher.jTextArea import suwayomi.tachidesk.launcher.jTextField import suwayomi.tachidesk.launcher.jbutton import suwayomi.tachidesk.launcher.jpanel import suwayomi.tachidesk.launcher.keyListener import java.awt.event.KeyEvent import javax.swing.JFileChooser import javax.swing.UIManager import kotlin.io.path.Path import kotlin.io.path.createDirectories import kotlin.io.path.isWritable fun RootDir(vm: LauncherViewModel, scope: CoroutineScope) = jpanel( MigLayout( LC().alignX("center").alignY("center") ) ) { jTextArea("Root path") { isEditable = false }.bind() val rootDirField = jTextField(vm.rootDir.value.orEmpty()) { // todo toolTipText = "" focusListener() .filterIsInstance<FocusListenerEvent.Lost>() .combine( keyListener() .filterIsInstance<KeyListenerEvent.Released>() .filter { it.event?.keyCode == KeyEvent.VK_ENTER } ) { _, _ -> } .map { text?.trim() } .onEach { if (it.isNullOrBlank() || runCatching { Path(it).createDirectories().isWritable() }.getOrElse { false }) { vm.rootDir.value = it?.ifEmpty { null } } } .flowOn(Dispatchers.Default) .launchIn(scope) columns = 10 }.bind() jbutton(icon = UIManager.getIcon("FileView.directoryIcon")) { // todo toolTipText = "" actions() .onEach { val chooser = JFileChooser().apply { val details = actionMap.get("viewTypeDetails") details?.actionPerformed(null) fileSelectionMode = JFileChooser.DIRECTORIES_ONLY } when (chooser.showOpenDialog(this)) { JFileChooser.APPROVE_OPTION -> { val path = chooser.selectedFile.absolutePath vm.rootDir.value = path rootDirField.text = path } } } .flowOn(Dispatchers.Default) .launchIn(scope) }.bind(CC().grow().spanX().wrap()) }
Arithmetic–geometric mean Arithmetic–geometric mean In mathematics, the arithmetic–geometric mean (AGM) of two positive real numbers and is defined as follows: First compute the arithmetic mean of and and call it . Next compute the geometric mean of and and call it ; this is the square root of the product : Then iterate this operation with taking the place of and taking the place of . In this way, two sequences and are defined: These two sequences converge to the same number, which is the arithmetic–geometric mean of and ; it is denoted by , or sometimes by . This can be used for algorithmic purposes as in the AGM method. Example To find the arithmetic–geometric mean of 24}} and 6}}, first calculate their arithmetic mean and geometric mean, thus: and then iterate as follows: The first five iterations give the following values: 0 24 6 1 5 2 2 .5 .416407864998738178455042… 3 203932499369089227521… 139030990984877207090… 4 45176983217305… 06053858316334… 5 20… 06… As can be seen, the number of digits in agreement (underlined) approximately doubles with each iteration. The arithmetic–geometric mean of 24 and 6 is the common limit of these two sequences, which is approximately 13.4581714817256154207668131569743992430538388544.1 History The first algorithm based on this sequence pair appeared in the works of Lagrange. Its properties were further analyzed by Gauss.2 Properties The geometric mean of two positive numbers is never bigger than the arithmetic mean (see inequality of arithmetic and geometric means); as a consequence, is an increasing sequence, is a decreasing sequence, and . These are strict inequalities if . is thus a number between the geometric and arithmetic mean of and ; in particular it is between and . If , then . There is an integral-form expression for : where is the complete elliptic integral of the first kind: Indeed, since the arithmetic–geometric process converges so quickly, it provides an efficient way to compute elliptic integrals via this formula. In engineering, it is used for instance in elliptic filter design.3 Related concepts The reciprocal of the arithmetic–geometric mean of 1 and the square root of 2 is called Gauss's constant, after Carl Friedrich Gauss. The geometric–harmonic mean can be calculated by an analogous method, using sequences of geometric and harmonic means. The arithmetic–harmonic mean can be similarly defined, but takes the same value as the geometric mean. The arithmetic–geometric mean can be used to compute logarithms and complete elliptic integrals of the first kind. A modified arithmetic–geometric mean can be used to efficiently compute complete elliptic integrals of the second kind.4 Proof of existence From inequality of arithmetic and geometric means we can conclude that: and thus that is, the sequence is nondecreasing. Furthermore, it is easy to see that it is also bounded above by the larger of and (which follows from the fact that both arithmetic and geometric means of two numbers both lie between them). Thus by the monotone convergence theorem the sequence is convergent, so there exists a such that: However, we can also see that: and so: Q.E.D. Proof of the integral-form expression This proof is given by Gauss.5 Let Changing the variable of integration to , where gives Thus, we have The last equality comes from observing that . Finally, we obtain the desired result See also Generalized mean Inequality of arithmetic and geometric means Gauss–Legendre algorithm External links Arithmetic-Geometric Mean Calculator Proof of convergence rate in PlanetMath References Jonathan Borwein, Peter Borwein, Pi and the AGM. A study in analytic number theory and computational complexity. Reprint of the 1987 original. Canadian Mathematical Society Series of Monographs and Advanced Texts, 4. A Wiley-Interscience Publication. John Wiley & Sons, Inc., New York, 1998. xvi+414 pp. ISBN 0-471-31515-X Zoltán Daróczy, Zsolt Páles, Gauss-composition of means and the solution of the Matkowski–Suto problem. Publ. Math. Debrecen 61/1-2 (2002), 157–218. " Category:Means Category:Special functions Category:Elliptic functions Category:Articles containing proofs agm(24, 6) at WolframAlpha first published in L'Enseignement Mathématique, t. 30 (1984), p. 275-330
/* eslint-disable array-callback-return */ import React, { useEffect, useState } from "react"; import axios from "axios"; import Box from "@mui/material/Box"; import Table from "@mui/material/Table"; import TableBody from "@mui/material/TableBody"; import TableCell from "@mui/material/TableCell"; import TableContainer from "@mui/material/TableContainer"; import TableHead from "@mui/material/TableHead"; import TablePagination from "@mui/material/TablePagination"; import TableRow from "@mui/material/TableRow"; import TableSortLabel from "@mui/material/TableSortLabel"; import Paper from "@mui/material/Paper"; import FormControlLabel from "@mui/material/FormControlLabel"; import Switch from "@mui/material/Switch"; import { visuallyHidden } from "@mui/utils"; // import { Button } from "react-bootstrap"; // import { Typography } from "@mui/material"; // import Collapse from "@mui/material/Collapse"; // import Dialog from "@mui/material/Dialog"; // import DialogActions from "@mui/material/DialogActions"; // import DialogContent from "@mui/material/DialogContent"; // import DialogContentText from "@mui/material/DialogContentText"; // import DialogTitle from "@mui/material/DialogTitle"; import { Collapse, IconButton } from "@mui/material"; import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown"; import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp"; import ApplicationTable from "./ApplicationTable"; // import { useParams } from "react-router-dom"; function descendingComparator(a, b, orderBy) { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; } function getComparator(order, orderBy) { return order === "desc" ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); } function stableSort(array, comparator) { const stabilizedThis = array.map((el, index) => [el, index]); stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) return order; return a[1] - b[1]; }); return stabilizedThis.map((el) => el[0]); } const headCells = [ { id: "name", numeric: false, disablePadding: true, label: "Job Name", }, { id: "level", numeric: false, disablePadding: false, label: "Job Level", }, { id: "quota", numeric: false, disablePadding: false, label: "Quota" }, ]; function EnhancedTableHead(props) { const { order, orderBy, onRequestSort } = props; const createSortHandler = (property) => (event) => { onRequestSort(event, property); }; return ( <TableHead> <TableRow> <TableCell /> {headCells.map((headCell) => ( <TableCell key={headCell.id} align="center" sortDirection={orderBy === headCell.id ? order : false} > <TableSortLabel active={orderBy === headCell.id} direction={orderBy === headCell.id ? order : "asc"} onClick={createSortHandler(headCell.id)} > {headCell.label} {orderBy === headCell.id ? ( <Box component="span" sx={visuallyHidden}> {order === "desc" ? "sorted descending" : "sorted ascending"} </Box> ) : null} </TableSortLabel> </TableCell> ))} </TableRow> </TableHead> ); } export default function ShortlistTable() { const [order, setOrder] = React.useState("asc"); const [orderBy, setOrderBy] = React.useState("calories"); const [selected, setSelected] = React.useState([]); const [page, setPage] = React.useState(0); const [dense, setDense] = React.useState(false); const [rowsPerPage, setRowsPerPage] = React.useState(5); const [rows, setRows] = useState([]); //collapsible table const [open, setOpen] = useState([]); const applicantId = JSON.parse( atob(localStorage.getItem("authToken").split(".")[1]) ).detailId; useEffect(() => { axios .get("http://localhost:5000/applications/jobs") .then((res) => { console.log(res.data); setRows(res.data); }) .catch((err) => { console.log(err); }); }, [applicantId]); const handleRequestSort = (event, property) => { const isAsc = orderBy === property && order === "asc"; setOrder(isAsc ? "desc" : "asc"); setOrderBy(property); }; const handleSelectAllClick = (event) => { if (event.target.checked) { const newSelecteds = rows.map((n) => n.name); setSelected(newSelecteds); return; } setSelected([]); }; const handleChangePage = (_event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; const handleChangeDense = (event) => { setDense(event.target.checked); }; const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0; return ( <Box sx={{ width: "100%" }}> <Paper sx={{ width: "100%", mb: 2 }}> <TableContainer> <Table sx={{ minWidth: 750, border: "float" }} aria-labelledby="tableTitle" size={dense ? "small" : "medium"} padding="default" > <EnhancedTableHead numSelected={selected.length} order={order} orderBy={orderBy} onSelectAllClick={handleSelectAllClick} onRequestSort={handleRequestSort} rowCount={rows.length} /> <TableBody> {stableSort(rows, getComparator(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((row, index) => { return ( <> <TableRow hover> <TableCell align="center"> <IconButton aria-label="expand row" size="small" onClick={() => setOpen( open.includes(index) ? open.filter((i) => i !== index) : [...open, index] ) } > {open.includes(index) ? ( <KeyboardArrowUpIcon /> ) : ( <KeyboardArrowDownIcon /> )} </IconButton> </TableCell> <TableCell align="center">{row?.name}</TableCell> <TableCell align="center">{row?.level}</TableCell> <TableCell align="center">{row?.quota}</TableCell> </TableRow> <TableRow> <TableCell style={{ paddingBottom: 0, paddingTop: 0, backgroundColor: "black", color: "white", }} colSpan={6} > <Collapse in={open.includes(index)} timeout="auto" unmountOnExit > <br></br> <h6 align="left">Applicant List</h6> <p>List of applicant who apply for {row?.name}</p> <ApplicationTable applicants={row?.application} quota={row?.quota} job_id={row?._id}/> </Collapse> </TableCell> </TableRow> </> ); })} {emptyRows > 0 && ( <TableRow style={{ height: (dense ? 33 : 53) * emptyRows, }} > <TableCell colSpan={6} /> </TableRow> )} </TableBody> </Table> </TableContainer> <TablePagination rowsPerPageOptions={[5, 10, 25]} component="div" count={rows.length} rowsPerPage={rowsPerPage} page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /> </Paper> <FormControlLabel control={<Switch checked={dense} onChange={handleChangeDense} />} label="Dense padding" /> </Box> ); }
import { configureStore, ThunkAction, Action } from "@reduxjs/toolkit"; import counterReducer from "../features/counter/counterSlice"; import { persistStore, persistReducer } from "redux-persist"; import storage from "redux-persist/lib/storage"; // defaults to localStorage for web const persistConfig = { key: "root", storage, }; export const store = configureStore({ reducer: { counter: persistReducer(persistConfig, counterReducer), }, }); export const persistor = persistStore(store); export type AppDispatch = typeof store.dispatch; export type RootState = ReturnType<typeof store.getState>; export type AppThunk<ReturnType = void> = ThunkAction< ReturnType, RootState, unknown, Action<string> >;
package com.nayan.nayancamv2.scout import android.annotation.SuppressLint import android.app.AlertDialog import android.content.IntentSender import android.content.res.Configuration import android.location.Location import android.os.Bundle import android.os.Handler import android.os.Looper import androidx.activity.result.IntentSenderRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import co.nayan.c3v2.core.models.ActivityState import co.nayan.c3v2.core.models.FinishedState import co.nayan.c3v2.core.models.InitialState import co.nayan.c3v2.core.models.LocationFailureState import co.nayan.c3v2.core.models.LocationSuccessState import co.nayan.c3v2.core.models.ProgressState import co.nayan.c3v2.core.utils.gone import co.nayan.c3v2.core.utils.visible import co.nayan.nayancamv2.R import co.nayan.nayancamv2.databinding.ActivityDriverScoutBinding import com.google.android.gms.common.api.ResolvableApiException import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.ktx.Firebase import com.nayan.nayancamv2.BaseActivity import com.nayan.nayancamv2.adjustConstraints import com.nayan.nayancamv2.getDefaultUserLocation import com.nayan.nayancamv2.helper.CameraPreviewScoutListener import com.nayan.nayancamv2.helper.GlobalParams.scoutDismissStatus import com.nayan.nayancamv2.helper.GlobalParams.userLocation import com.nayan.nayancamv2.viewBinding import kotlinx.coroutines.launch import timber.log.Timber class DriverScoutModeActivity : BaseActivity() { private val locationRequestHandler by lazy { Handler(Looper.getMainLooper()) } private val locationRequestRunnable = Runnable { nayanCamRepository.checkForLocationRequest() } private val binding: ActivityDriverScoutBinding by viewBinding(ActivityDriverScoutBinding::inflate) private lateinit var eventsAdapter: EventsAdapter private lateinit var cameraPreviewScoutListener: CameraPreviewScoutListener @SuppressLint("CommitTransaction") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) cameraPreviewScoutListener = CameraPreviewScoutListener() eventsAdapter = EventsAdapter() nayanCamModuleInteractor.getDriverEvents().also { data -> val orientation = this.resources.configuration.orientation val isLandscapeMode = (orientation == Configuration.ORIENTATION_LANDSCAPE) if (data.isNullOrEmpty()) { binding.rvEvents.gone() if (isLandscapeMode) binding.cameraLayout.adjustConstraints(binding.rootView) } else { data.sortByDescending { events -> events.score?.toInt() ?: run { 0 } } binding.rvEvents.apply { this.layoutManager = layoutManager adapter = eventsAdapter eventsAdapter.addAll(data) eventsAdapter.updateOrientation(isLandscape = isLandscapeMode) visible() } } } val fragment = CameraConnectionFragment.newInstance( cameraPreviewScoutListener = cameraPreviewScoutListener, imageAvailableListener = cameraPreviewScoutListener ) nayanCamComponent.inject(fragment) supportFragmentManager.beginTransaction().replace(R.id.cameraContainer, fragment).commit() nayanCamRepository.getLocationState().observe(this, locationUpdateObserver) if (scoutDismissStatus.value == InitialState) scoutDismissStatus.postValue(ProgressState) scoutDismissStatus.observe(this) { changeScoutState(it) } binding.scoutBtn.setOnClickListener { if (binding.scoutBtn.text == getString(R.string.click)) { // Capture scout image userLocation?.let { storageUtil.createNewScoutModeFile(this, it)?.also { file -> cameraPreviewScoutListener.captureStillImage(file) val scoutPreviewFragment = ScoutModePreviewFragment.newInstance(file) nayanCamComponent.inject(scoutPreviewFragment) supportFragmentManager.beginTransaction() .replace(R.id.cameraContainer, scoutPreviewFragment) .commit() } } } else { // Submit image to backend with tags } } } private val locationUpdateObserver: Observer<ActivityState> = Observer { when (it) { is LocationSuccessState -> { it.location?.let { loc -> Timber.e("Location Received with ${loc.time}") nayanCamModuleInteractor.saveLastLocation(loc.latitude, loc.longitude) locationAvailable(loc) } } is LocationFailureState -> { it.exception?.let { exception -> if (exception is ResolvableApiException) { // Location settings are not satisfied, but this can be fixed // by showing the user a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). resolutionForResult.launch( IntentSenderRequest.Builder(exception.resolution).build() ) } catch (sendEx: IntentSender.SendIntentException) { Firebase.crashlytics.recordException(sendEx) Timber.e(sendEx) } } } ?: run { AlertDialog.Builder(this) .setTitle("Please enable Location!!") .setMessage("Camera mode can not function properly without Location enabled.") .setPositiveButton("Close Camera") { _, _ -> finish() } .setCancelable(false) .show() } } } } private fun locationAvailable(location: Location) = lifecycleScope.launch { userLocation = getDefaultUserLocation(location) } private fun changeScoutState(state: ActivityState) = lifecycleScope.launch { if (state == FinishedState) { scoutDismissStatus.postValue(InitialState) finishAffinity() } } private val resolutionForResult = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { activityResult -> if (activityResult.resultCode == RESULT_OK) { Timber.i("User agreed to make required location settings changes.") nayanCamRepository.startLocationUpdate() } else { Timber.i("User chose not to make required location settings changes.") AlertDialog.Builder(this) .setTitle("Please enable Location!!") .setMessage("Camera mode can not function properly without Location enabled.") .setPositiveButton( "Close Camera" ) { _, _ -> finish() } .setCancelable(false) .show() } } override fun onResume() { super.onResume() locationRequestHandler.post(locationRequestRunnable) } override fun onPause() { super.onPause() nayanCamRepository.stopLocationUpdate() locationRequestHandler.removeCallbacksAndMessages(null) } }
<?php // Initialize the session session_start(); // Check if the user is already logged in, if yes then redirect him to welcome page if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){ header("location: welcome.php"); exit; } // Include config file require_once "config.php"; // Define variables and initialize with empty values $username = $password = ""; $username_err = $password_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Check if username is empty if(empty(trim($_POST["username"]))){ $username_err = " Please enter username."; } else{ $username = trim($_POST["username"]); } // Check if password is empty if(empty(trim($_POST["password"]))){ $password_err = " Please enter your password."; } else{ $password = trim($_POST["password"]); } // Validate credentials if(empty($username_err) && empty($password_err)){ // Prepare a select statement $sql = "SELECT id, username, password FROM users WHERE username = ?"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "s", $param_username); // Set parameters $param_username = $username; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ // Store result mysqli_stmt_store_result($stmt); // Check if username exists, if yes then verify password if(mysqli_stmt_num_rows($stmt) == 1){ // Bind result variables mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password); if(mysqli_stmt_fetch($stmt)){ if(password_verify($password, $hashed_password)){ // Password is correct, so start a new session session_start(); // Store data in session variables $_SESSION["loggedin"] = true; $_SESSION["id"] = $id; $_SESSION["username"] = $username; // Redirect user to welcome page header("location: welcome.php"); } else{ // Display an error message if password is not valid $password_err = " The password you entered was not valid."; } } } else{ // Display an error message if username doesn't exist $username_err = " No account found with that username."; } } else{ echo " Oops! Something went wrong. Please try again later."; } } // Close statement mysqli_stmt_close($stmt); } // Close connection mysqli_close($link); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> <style type="text/css"> body{ margin:0px; padding: 0px; font: 14px sans-serif; background: url(m2.jpg) no-repeat; background-size: cover; height: 900px; } .wrapper{ position: absolute; top: 50%; left:50%; transform: translate(-50%,-50%); width:400px; padding:40px; background: rgba(0,0,0,.8); box-sizing: border-box; box-shadow: 0 15px 25px rgba(0,0,0,.5); border-radius: 10px; } .wrapper h2,p{ margin: 0 0 30px; padding:0; color: #fff; text-align: center; } .wrapper .form-group{ position: relative; } .wrapper .form-group input{ width:71%; border: 2px solid #03a9f4; border-radius: 20px; text-align: center; padding: 10px 0; font-size: 16px; color:#fff; margin-left: 45px; margin-top: 20px; margin-bottom: 10px; outline:none; background: transparent; } .wrapper input[type="text"]:hover, .wrapper input[type="password"]:hover{ border-color: #4caf50; } .wrapper input[type="text"]:focus, .wrapper input[type="password"]:focus{ border-color: #4caf50; margin-left: 18px; width: 90%; } .wrapper input[type="submit"]{ background: transparent; border:none; width: 30%; margin-left: 120px; position: middle; outline: none; background: #03a9f4; padding:7px 20px; cursor:pointer; border-radius: 15px; } .wrapper input[type="submit"]:hover{ background: #4caf50; color: black; border-color: 2px solid #03a9f4; } .wrapper input[type="submit"]:focus{ background-color: black; color: white; border: 2px solid #4caf50; } .wrapper a{ color: red; } .help-block{ color: red; font-size: 18px; margin-left: 50px; } </style> </head> <body> <div class="wrapper"> <h2>Login</h2> <p>Please fill in your credentials to login.</p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>"> <input type="text" name="username" placeholder = "Username" class="form-control" value="<?php echo $username; ?>"> <span class="help-block"><?php echo $username_err; ?></span> </div> <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>"> <input type="password" name="password" placeholder = "Password" class="form-control"> <span class="help-block"><?php echo $password_err; ?></span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Login"> </div> <p>Don't have an account? <a href="register.php">Sign up now</a>.</p> </form> </div> </body> </html>
// App.js import React, { useEffect, useState } from 'react'; import { Route, Routes, useNavigate } from 'react-router-dom'; import Home from './Home'; import Login from './Login'; import Checkout from './Checkout'; import Header from './Header'; import MenProduct from './MenProducts'; import Orders from './Orders'; import Search from './Search'; import WomenProduct from './WomenProducts'; import About from './About'; import Payment from './Payment'; import './App.css'; import { onAuthStateChanged } from "firebase/auth"; import { auth } from './firebase'; import { useStateValue } from './StateProvider'; import { loadStripe } from '@stripe/stripe-js'; import { Elements } from '@stripe/react-stripe-js'; const promise = loadStripe('pk_test_51O2imWKagkfSGuynOKrVFkx3HxTBAQOYnhII39cFwgjcPsp2ItEHaZ1msSlQp6bNOxrTu1FegFkoDghIJ4QFeOXE00peoZI2AI'); function App() { const [filteredProducts, setFilteredProducts] = useState([]); const [, dispatch] = useStateValue(); const navigate = useNavigate(); useEffect(() => { const listen = onAuthStateChanged(auth, (authUser) => { if(authUser){ dispatch({ type: 'SET_USER', user: authUser }); } else{ dispatch({ type: 'SET_USER', user: null }); } }) return () => { listen(); } }, [dispatch]); const handleSearch = (filteredProducts) => { setFilteredProducts(filteredProducts); navigate('/search'); } return ( <Routes> <Route path='/search' element={ <> <Header onSearch={handleSearch} /> <Search filteredProducts={filteredProducts} /> </> } /> <Route path='/' element={ <> <Header onSearch={handleSearch}/> <Home /> </> } /> <Route path='/orders' element={ <> <Header onSearch={handleSearch}/> <Orders /> </> } /> <Route path='/login' element={<Login />} /> <Route path='/checkout' element={ <> <Header onSearch={handleSearch}/> <Checkout /> </> } /> <Route path='/men' element={ <> <Header onSearch={handleSearch}/> <MenProduct /> </> } /> <Route path='/women' element={ <> <Header onSearch={handleSearch}/> <WomenProduct /> </> } /> <Route path='/about' element={ <> <Header onSearch={handleSearch}/> <About /> </> } /> <Route path='/payment' element={ <> <Header onSearch={handleSearch}/> <Elements stripe={promise}> <Payment /> </Elements> </> } /> </Routes> ); } export default App;
import React, { useState, useEffect } from 'react'; import { ContentState, Editor } from 'react-draft-wysiwyg'; import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'; import { EditorState, convertToRaw } from 'draft-js'; import draftToHtml from 'draftjs-to-html'; import '../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css'; import style from './css/EditorText.module.scss' import { useQuery } from '@apollo/client'; import { GET_ALL_USER } from '../../query/UserQuery'; import { User } from '../../model/UserModel'; import { Post } from '../../model/PostModel'; import { GET_ALL_POST_DEBUG } from '../../query/PostQuery'; interface EditorTextProps { handleOnChange: (value: string) => void; placeholder: string resetEditor: boolean initialValue: ContentState | null } export default function EditorText({ handleOnChange, placeholder, resetEditor, initialValue }: EditorTextProps) { const [editorState, setEditorState] = useState(EditorState.createEmpty()) useEffect(() => { if (resetEditor) { setEditorState(EditorState.createEmpty()); } }, [resetEditor]); useEffect(() => { if (initialValue == null || initialValue == undefined) { return; } // setEditorState(EditorState.createWithContent(initialValue)); }, [initialValue]); const handleEditorStateChange = (newEditorState: EditorState) => { setEditorState(newEditorState); handleOnChange(draftToHtml(convertToRaw(newEditorState.getCurrentContent()))); }; const { data: allUserData } = useQuery<{ getAllUser: User[] }>(GET_ALL_USER) const { data: allPostData } = useQuery<{ getAllPostDebug: Post[] }>(GET_ALL_POST_DEBUG) const formattedUsers = allUserData?.getAllUser.map(user => ({ ...user, text: `${user.first_name} ${user.last_name}`, value: `${user.first_name} ${user.last_name}`, url: `/main/profile/${user.id}`, })); const mentionSuggestions = formattedUsers || [] return ( <Editor placeholder={placeholder} toolbarHidden editorState={editorState} onEditorStateChange={handleEditorStateChange} wrapperClassName={style['wrapper']} editorClassName="demo-editor" mention={{ separator: ' ', trigger: '@', suggestions: mentionSuggestions, }} /> ); }
-- restaurant database -- 5 tables -- write 3-5 queries -- 1x WITH -- 1x SUBQUERY -- 1x Aggregate Function .open pizza.db --CREATE & INSERT-- --TABLE 1 MENU-- drop table menu; create table if not exists menu ( menu_id int not null primary key, name text, price real); insert into menu values (1,'pizza',100), (2,'chicken wing',70), (3,'french fries',50), (4,'coca cola',15), (5,'water',10); --TABLE 2 MENU-- drop table staff; create table if not exists staff ( staff_id int not null primary key, name text, position); insert into staff values (1,'pond','chef'), (2,'may','chef'), (3,'aum','casher'), (4,'tar','waiter'); --TABLE 3 CUSTOMER-- drop table customer; create table if not exists customer ( cust_id int not null primary key, name text, gender text); insert into customer values (1,'som','f'), (2,'bill','m'), (3,'big','m'), (4,'ant','f'), (5,'olive','f'); --TABLE 4 ORDERS-- drop table orders; create table if not exists orders ( order_id int not null primary key, staff_id int, --foreign key references staff(staff_id), cust_id int, --foreign key references customer(cust_id), menu_id int, --foreign key references menu(menu_id), date date); insert into orders values (1,3,5,1,'2023-01-07'), (2,3,3,2,'2023-01-07'), (3,3,2,3,'2023-01-08'), (4,3,1,1,'2023-01-10'), (5,3,4,2,'2023-01-10'), (6,3,3,3,'2023-01-10'); --TABLE 5 PAYMENT-- drop table payment; create table if not exists payment ( pay_id int not null primary key, cust_id int, order_id int, amount int, date date); insert into payment values (1,1,1,100,'2023-01-07'), (2,3,2,70,'2023-01-07'), --foreign key references customer(cust_id), (3,2,3,50,'2023-01-08'), --foreign key references oders(order_id), (4,5,4,100,'2023-01-10'), (5,4,5,70,'2023-01-10'), (6,3,6,50,'2023-01-10'); .mode column .header on select * from menu; select * from staff; select * from customer; select * from orders; select * from payment; -- Query 1 menu sell report select menu.name as mune, count(*) as count, sum(payment.amount) as amount from menu join orders on menu.menu_id = orders.menu_id join customer on orders.cust_id = customer.cust_id join payment on customer.cust_id = payment.cust_id join staff on orders.staff_id = staff.staff_id group by menu.name; -- Query 2 who buy in 2023-01-07 with cust as ( select * from customer), d07 as ( select * from orders where date = '2023-01-07') select name from cust join d07 on cust.cust_id = d07.cust_id; --Query 3 Who buy pizza with pizza as ( select * from menu where name = 'pizza'), cust as ( select * from customer), ord as (select * from orders) select cust.name, count(*) from pizza join ord on pizza.menu_id = ord.order_id join cust on ord.cust_id = cust.cust_id; --Query 4 Customer Buy detail with cust as ( select * from customer), pay as ( select * from payment) select cust.name, cust.gender, count(*) as count, sum(pay.amount) as sum, avg(pay.amount) as avg from pay join cust on pay.cust_id = cust.cust_id group by cust.name, cust.gender order by cust.name desc;
import {IBlock} from "../../models/block.model"; const BlockClass = require('../../models/block.model'); describe("Block Class", () => { test("Block class constructor test", () => { let block: IBlock = new BlockClass.Block({data: BlockClass.GENESIS_BLOCK}); expect(block).toBeDefined(); }); test("Block class height 0 test", () => { let block: IBlock = new BlockClass.Block({data: BlockClass.GENESIS_BLOCK}); return block.init(0, null) .then(b => expect(b.getHeight()).toBe(0)); }); test("Block class height 1 test", () => { let block: IBlock = new BlockClass.Block({data: BlockClass.GENESIS_BLOCK}); return block.init(1, null) .then(b => expect(b.getHeight()).toBe(1)); }); test("Block class getBData test", () => { let testData: any = { data: 'Test Block' }; let block: IBlock = new BlockClass.Block(testData); return block.getBData().then(data => { expect(data).toStrictEqual(testData); }); }); test("Block class getBData Genesis Block test", () => { let testData: any = { data: BlockClass.GENESIS_BLOCK }; let block: IBlock = new BlockClass.Block(testData); return expect(block.getBData()).rejects.toEqual(Error(BlockClass.GENESIS_BLOCK)); }); test("Block class validate test", () => { let testData: any = { data: 'Test Block' }; let block: IBlock = new BlockClass.Block(testData); return block.init(0, null) .then(b => { expect(b.validate()).resolves.toEqual(true); }) }); test("Block class validate tampered test", () => { let testData: any = { data: 'Test Block' }; let block = new BlockClass.Block(testData); return block.init(0, null) .then((b: { body: { data: string; }; validate: () => any; }) => { b.body = { data: 'Tampered with' }; expect(b.validate()).resolves.toEqual(false); }); }); });
import torch from torch.utils.data import Dataset from PIL import Image import os import pandas as pd import re class PneumoniaDataSet(Dataset): def __init__(self, data_dir, image_list_file, transform=None): self.data_frame = pd.read_csv(image_list_file) self.data_frame = self.data_frame[self.data_frame['Frontal/Lateral'] == 'Frontal'] self.data_frame = self.data_frame.dropna(subset=['Pneumonia']) self.data_frame['pid'] = self.data_frame['Path'].apply(self.extract_pid) # Filter data to include only specific patient IDs self.data_frame = self.data_frame[(self.data_frame['pid'] >= 1) & (self.data_frame['pid'] <= 198)] self.data_frame['Path'] = self.data_frame['Path'].apply(lambda x: os.path.join(data_dir, x)) self.transform = transform def extract_pid(self, path): try: # Assuming the PID format is something like 'pid00123' pid = re.search(r'pid(\d+)', path) if pid: return int(pid.group(1)) # Extracts and converts the number part else: print("No PID found in path:", path) return None # Return None or some default value or raise an exception except Exception as e: print("Error processing path:", path, "; Error:", str(e)) raise def __getitem__(self, index): image_path = self.data_frame.iloc[index]['Path'] # print("Attempting to open:", image_path) image = Image.open(image_path).convert('RGB') # Focus on pneumonia only (assuming 'Pneumonia' is a column in your CSV) pneumonia_label = self.data_frame.iloc[index]['Pneumonia'] label = 0 if pd.isna(pneumonia_label) else int(pneumonia_label > 0) if self.transform: image = self.transform(image) return image, torch.FloatTensor([label]) # Ensure label is still a tensor def __len__(self): return len(self.data_frame)
--- description: "Bahan Cilok Bandung | Cara Buat Cilok Bandung Yang Sedap" title: "Bahan Cilok Bandung | Cara Buat Cilok Bandung Yang Sedap" slug: 885-bahan-cilok-bandung-cara-buat-cilok-bandung-yang-sedap date: 2020-09-19T07:33:13.541Z image: https://img-global.cpcdn.com/recipes/c625029aa1f4338c/751x532cq70/cilok-bandung-foto-resep-utama.jpg thumbnail: https://img-global.cpcdn.com/recipes/c625029aa1f4338c/751x532cq70/cilok-bandung-foto-resep-utama.jpg cover: https://img-global.cpcdn.com/recipes/c625029aa1f4338c/751x532cq70/cilok-bandung-foto-resep-utama.jpg author: Gary Francis ratingvalue: 3 reviewcount: 11 recipeingredient: - "7-8 sdm penuh tepung terigu serbaguna" - "5 sdm penuh tepung tapioka" - "200 ml Air panas" - "2 batang daun bawang" - " Bumbu halus" - "3 siung bawang putih" - "1/2 sdt lada putih bubuk" - "1 sdt garam" - "1 sdt kaldu jamur" - "1 sdt gula pasiroptional" - " Bumbu kacang" - "Segenggam kacang tanah yang sudah digoreng" - "2 siung bawang putih" - "1 sdm air asam jawa" - "2 lembar daun jeruk" - "1 sdt garam" - "7 biji cabe rawit optional" - "4 sdm gula merah" - "Secukupnya minyak untuk menumis" recipeinstructions: - "Didihkan air. Sementara menunggu air mendidih, siapkan wadah berisi tepung terigu dan haluskan bumbu juga potong daun bawang tipis-tipis." - "Tuang air panas dalam wadah berisi tepung, daun bawang dan bumbu halus tadi sedikit demi sedikit sambil diaduk-aduk sampai air habis kemudian masukan tepung tapioka sedikit demi sedikit sambil diuleni pakai tangan hingga adonan bisa dibentuk." - "Didihkan air dalam panci untuk merebus ciloknya. Kira-kira setengah dari panci ukuran 22-24 cm. Tambahkan sedikit kaldu jamur dan garam." - "Bentuk adonan bulat-bulat dan rebus sampai adonan mengambang. Tandanya cilok sudah matang." - "Tips: Jika adonan susah dibentuk bulat, bisa gunakan tangan ya dengan cara diremas dan dikeluarkan melalui celah jari antara ibu jari dan jempol lalu disendokin ke dalam air rebusan. Seperti membuat bakso." - "Untuk bumbu kacangnya semua dihaluskan jadi satu." - "Tumis dalam minyak panas dengan api kecil sampai keluar aromanya." - "Bumbu kacang siap dilarutkan dengan air sampai kekentalan yang diinginkan dan digunakan sebagai cocolan cilok." - "Selamat mencoba❤" categories: - Resep tags: - cilok - bandung katakunci: cilok bandung nutrition: 184 calories recipecuisine: Indonesian preptime: "PT16M" cooktime: "PT59M" recipeyield: "1" recipecategory: Lunch --- ![Cilok Bandung](https://img-global.cpcdn.com/recipes/c625029aa1f4338c/751x532cq70/cilok-bandung-foto-resep-utama.jpg) Lagi mencari ide resep cilok bandung yang Paling Enak? Cara Buatnya memang tidak terlalu sulit namun tidak gampang juga. andaikan salah mengolah maka hasilnya akan hambar dan justru cenderung tidak enak. Padahal cilok bandung yang enak seharusnya mempunyai aroma dan rasa yang mampu memancing selera kita. Cilok Bandung bumbu kacang sederhana. foto: Instagram/@corza_food. Cara Mudah Membuat Cilok Bandung yang Empuk, Kenyal dan Tahan Lama disertai Bumbu kacang yang Mantap. Cilok memang banyak macam dan variasinya. meski. Banyak hal yang sedikit banyak mempengaruhi kualitas rasa dari cilok bandung, pertama dari jenis bahan, lalu pemilihan bahan segar sampai cara membuat dan menghidangkannya. Tidak usah pusing kalau mau menyiapkan cilok bandung enak di mana pun anda berada, karena asal sudah tahu triknya maka hidangan ini bisa menjadi suguhan spesial. Nah, kali ini kita coba, yuk, buat cilok bandung sendiri di rumah. Tetap berbahan sederhana, hidangan ini dapat memberi manfaat untuk membantu menjaga kesehatan tubuhmu sekeluarga. Anda dapat membuat Cilok Bandung memakai 19 bahan dan 9 langkah pembuatan. Berikut ini cara dalam membuat hidangannya. <!--inarticleads1--> ##### Bahan-bahan dan bumbu yang dibutuhkan untuk pembuatan Cilok Bandung: 1. Siapkan 7-8 sdm penuh tepung terigu serbaguna 1. Ambil 5 sdm penuh tepung tapioka 1. Ambil 200 ml Air panas 1. Gunakan 2 batang daun bawang 1. Ambil Bumbu halus 1. Gunakan 3 siung bawang putih 1. Gunakan 1/2 sdt lada putih bubuk 1. Ambil 1 sdt garam 1. Gunakan 1 sdt kaldu jamur 1. Ambil 1 sdt gula pasir(optional) 1. Gunakan Bumbu kacang 1. Siapkan Segenggam kacang tanah yang sudah digoreng 1. Sediakan 2 siung bawang putih 1. Sediakan 1 sdm air asam jawa 1. Sediakan 2 lembar daun jeruk 1. Ambil 1 sdt garam 1. Sediakan 7 biji cabe rawit (optional) 1. Sediakan 4 sdm gula merah 1. Gunakan Secukupnya minyak untuk menumis Cilok, walaupun dengar-dengar muasalnya dari Jawa Barat atau tepatnya Bandung, tapi saat ini rasanya sudah bisa ditemukan dimana-mana. Mungkin hanya variasinya saja yang berbeda-beda. Warga Bandung, khususnya yang tinggal di sekitar Jalan Dr. Setiabudi pasti nggak asing sama Cilok. <!--inarticleads2--> ##### Cara membuat Cilok Bandung: 1. Didihkan air. Sementara menunggu air mendidih, siapkan wadah berisi tepung terigu dan haluskan bumbu juga potong daun bawang tipis-tipis. 1. Tuang air panas dalam wadah berisi tepung, daun bawang dan bumbu halus tadi sedikit demi sedikit sambil diaduk-aduk sampai air habis kemudian masukan tepung tapioka sedikit demi sedikit sambil diuleni pakai tangan hingga adonan bisa dibentuk. 1. Didihkan air dalam panci untuk merebus ciloknya. Kira-kira setengah dari panci ukuran 22-24 cm. Tambahkan sedikit kaldu jamur dan garam. 1. Bentuk adonan bulat-bulat dan rebus sampai adonan mengambang. Tandanya cilok sudah matang. 1. Tips: Jika adonan susah dibentuk bulat, bisa gunakan tangan ya dengan cara diremas dan dikeluarkan melalui celah jari antara ibu jari dan jempol lalu disendokin ke dalam air rebusan. Seperti membuat bakso. 1. Untuk bumbu kacangnya semua dihaluskan jadi satu. 1. Tumis dalam minyak panas dengan api kecil sampai keluar aromanya. 1. Bumbu kacang siap dilarutkan dengan air sampai kekentalan yang diinginkan dan digunakan sebagai cocolan cilok. 1. Selamat mencoba❤ RESEP CILOK BANDUNG ENAK KENYAL EMPUK. Resep Cara Membuat Cilok - Resep dari cara membuat cilok sama sekali tidak sulit. Makanan ini juga termasuk ke dalam makanan yang paling mudah dan sederhana cara pembuatannya. Bandung memang terkenal akan aneka kuliner lezatnya mulai dari siomay bandung, batagor bandung, cilok bandung dan masih banyak jenis jajanan khas bandung lainnya. Bandung merupakan kota pertama yang memperkenalkan makanan satu ini, tak ayal sekarang ini Bahan-bahan yang digunakan untuk membuat resep cilok Bandung ini sangatlah mudah untuk. Terima kasih telah membaca resep yang tim kami tampilkan di sini. Besar harapan kami, olahan Cilok Bandung yang mudah di atas dapat membantu Anda menyiapkan hidangan yang lezat untuk keluarga/teman maupun menjadi ide untuk berjualan makanan. Semoga bermanfaat dan selamat mencoba!
# tal-tech-challenge Basic console application demonstrating an API layer with basic database functionality. This console application is meant to simulate an appointment system by being able to add an appointment, and block out timeslots as required. All appointments and blockouts are fixed 30 minute durations, and can be assigned any day except outside 9AM - 5PM. There is also an additional constraint that appointments also cannot be created from 4PM to 5PM on each second day of the third week of any month (I have interpreted this requirement as being every third Tuesday of the month), this time will be reserved and unavailable. In the interest of scalability, and clearer data, I decided to split out the definition of an Appointment, and a Blockout. For this application's purpose, an Appointment is a 30 minute timeslot booked out within the day, to prevent another Appointment being added on the same date and timeslot. A Blockout is essentially a recurring Appointment every day, that prevents any new Appointments from being added in its timeslot every day. Another way to look at it is a Blockout can also be an Appointment without a defined Date component, and thus can be coded to treated as continually recurring. This aspect can most certainly be refined further, which would lead to removing the Blockout component entirely, and thus reducing the number of repositories by 1. This would also mean that the AppointmentService will only have require access to an AppointmentRepository, and this keeps it rather clean as we don't have one designated service writing to two different repositories. The application has been designed with the fact of being able to making appointments in 30 minute intervals (e.g. minutes are either 0 or 30). This hasn't been enforced in code (ie. KEEP 15:52 is a legal input), but the display for the available timeslots will be displayed as such (i.e. if an appointment is listed for 09:00 and 09:01, the one with 09:00 will cause the timeslot "09:00 AM - 09:30 AM" to not display when using FIND, but the one with 09:01 will cause that same timeslot to appear in FIND). Database is handled via migration (code-first approach). The console application accepts 4 different commands (all commands are case insensitive): # Setup There isn't much setup that needs to be done, except to get the database up and running. To create the database, an Initial_Create migration has already been created. You will simply need to run: ``` Update-Database -s "TAL.TechTest.DAL" ``` Ensure that in Package Manager Console, the Default project is set to TAL.TechTest.DAL. Once the database has been created with the tables, you can simply execute the console app via Visual Studio. ## 1. ADD Input format: DD/MM hh:mm Example: ADD 24/04 15:00 Adds an appointment to the database. This locks out 30 minutes access to that timeslot in the specified day. ## 2. DELETE Input format: DD/MM hh:mm Example: DELETE 24/04 15:00 Removes the appointment in that time slot from the database. ## 3. FIND Input format: DD/MM Example: FIND 24/04 Find all available timeslots for the given day, taking into factor existing appointments and blockouts. ## 4. KEEP Input format: hh:mm Example: KEEP 15:00 Allows the user to block out the timeslot specified in the input from allowing an appointment to be added to that timeslot at any date. Blocks out 30 minutes from the specified time. ## 5. EXIT No input required Example: EXIT Kills the console application. The user can also choose to input an empty command, and it will work exactly the same as EXIT. ## Areas for Improvement 1. For time input, allow smart conversion of time based on AM or PM. For example, since the app's restriction is that appointments cannot be added outside of 9AM to 5PM, therefore putting in 01:00 should be automatically read as 01:00PM, rather than AM. 2. Adding a weekend check. I did not add this, as this would be dependent on the app's use case. For example, the user may be working on the weekends, and so I did not make the assumption that this app would be used in an office setting where people work only from Monday to Friday, but the 9AM to 5PM requirement made me consider this aspect of the functionality. 3. Deleting a Blockout. As it is now, you can add a Blockout, but you can't Delete one. Given there are a finite amount of timeslots in a day with zero restrictions (16 timeslots maximum), adding 16 blockouts essentially means you can never add any appointments to the app ever. 4. Better defined timeslots. For example, actually enforcing the 30 minute input, or even extending it to allow 15 minute intervals instead. 5. Allow the addition of an assigned user. For example, if this was a medical appointment system, we should be able to add a doctor. 6. Allows the functionality of adding multiple appointments to a single timeslot. This can only work if there was a user added as per above. 7. Email functionality. To send a confirmation email to the user that their appointment was successfully booked in the timeslot. Will also require an email field input. 8. Defining the connection string via an appsettings.json file in the console application level, then have it be passed down to the DbContext via dependency injection. Currently, the connection string is hard defined in the DbContext level. 9. Adding logging. 10. Integration tests. It will be good to ensure that the correct data operations are taking place. 11. Containerize the application. This is not really all that required, but it would be nice to have to show that we can containerize the app for better deployment too. 12. Convert the application into a proper executable. At the current point of time, it cannot be run without either access to Visual Studio, or VS command lines.
import Image from 'next/image'; import growingTechniquesList from '@/i18n/en/growingTechniques.json'; const growingTechniques = () => { return ( <div className="flex flex-col"> <div className="mb-4 md:mb-0 w-full max-w-screen-md mx-auto relative h-[24em]"> <div className="absolute left-0 bottom-0 w-full h-full z-10" style={{ backgroundImage: 'linear-gradient(180deg,transparent,rgba(0,0,0,.7))', }} ></div> <Image src="/cannabis-plant.jpg" alt="Green House cultivation system" layout="fill" className="absolute left-0 top-0 w-full h-full z-0 object-cover" /> <div className="p-4 absolute bottom-0 left-0 z-20"> <a href="#" className="px-4 py-1 bg-black text-gray-200 inline-flex items-center justify-center mb-2" > {growingTechniquesList.topic} </a> <h2 className="text-4xl font-semibold text-gray-100 leading-tight"> {growingTechniquesList.title} </h2> </div> </div> <div className="px-4 lg:px-0 my-12 text-gray-700 max-w-screen-md mx-auto text-lg leading-relaxed"> {growingTechniquesList.content.map((technique) => { return ( <> <h5 className="text-lg font-semibold mb-2">{technique.title}</h5> <p className="font-normal mb-4">{technique.content}</p> </> ); })} </div> </div> ); }; export default growingTechniques;
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, } from "@mui/material"; import "../ConfirmationPopup/styles.css"; import { AiOutlineClose } from "react-icons/ai"; import DeleteIcon from "@mui/icons-material/Delete"; import classes from "./index.module.css"; import { openFileNewWindow } from "../../helper"; function MultipleFileViewPopup({ handleClose, files, titleText, open, downloadFile, removeFileHandler, type = "comman", }) { return ( <Dialog open={open} fullWidth={true} maxWidth="xs" aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description"> <DialogTitle id="alert-dialog-title" className="titletext"> {titleText} <Button onClick={() => handleClose()} className="closebtns"> <AiOutlineClose /> </Button> </DialogTitle> <DialogContent> {files.length > 0 && files.map((file, i) => ( <div key={i} className={classes.flex}> {file.fileData ? ( <p className={classes.fileName} onClick={(e) => { if (file.fileData.includes("base64")) { e.preventDefault(); openFileNewWindow(file?.fileData); } else { downloadFile(file); } }}> {file.fileName} </p> ) : ( <p className={classes.fileName} onClick={(e) => { if (file.filePath.includes("base64")) { e.preventDefault(); openFileNewWindow(file?.filePath); } else { downloadFile(file); } }}> {file.fileName} </p> )} {type !== "milestone" && ( <DeleteIcon sx={{ cursor: "pointer", color: "red", }} onClick={() => removeFileHandler(i)} /> )} </div> ))} </DialogContent> <DialogActions> <Button onClick={() => handleClose()} className="nobtn"> close </Button> </DialogActions> </Dialog> ); } export default MultipleFileViewPopup;
#version 330 core out vec4 FragColor; struct Material { sampler2D diffuse; sampler2D specular; sampler2D emission; int shininess; float diffuseStrength; float specularStrength; float ambient; float emissionRate; }; struct Light { vec3 position; vec3 color; float constant; float linear; float quadratic; }; uniform Material material; uniform Light pointLight; uniform vec3 cameraPos; in vec3 Normal; in vec3 WorldPos; in vec2 TexCoords; void main() { //Light Map vec3 baseColor = vec3(texture(material.diffuse, TexCoords)); vec3 speculColr = vec3(texture(material.specular, TexCoords)); vec3 emissionColor = vec3(texture(material.emission, TexCoords)); //point light float distance = length(pointLight.position - WorldPos); float attenuation = 1.0 / (pointLight.constant + pointLight.linear * distance + pointLight.quadratic * (distance * distance)); vec3 lightColor = pointLight.color * attenuation; //ambient vec3 ambient = lightColor * (baseColor + emissionColor * material.emissionRate) * material.ambient; // diffuse vec3 norm = normalize(Normal); vec3 lightDir = normalize(pointLight.position - WorldPos); float diff = max(dot(norm, lightDir), 0.0); vec3 diffuse = lightColor * diff * (baseColor + emissionColor * material.emissionRate) * material.diffuseStrength; // specular vec3 viewDir = normalize(cameraPos - WorldPos); vec3 reflectDir = reflect(-lightDir, norm); float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess); vec3 specular = lightColor * spec * speculColr * material.specularStrength; vec3 result = ambient + diffuse + specular; FragColor = vec4(result, 1.0); }
import os import subprocess import yaml class RenderEngine: """ The RenderEngine class provides functionality to render K8 templates and add a service to a kustomization file. """ def __init__(self, path, kustomization_path, service_name): """ Initializes a new instance of the RenderEngine class. Args: path (str): The path to the directory containing the templates to render. kustomization_path (str): The path to the kustomization file. service_name (str): The name of the service to add to the kustomization file. """ self.path = path self.service_name = service_name self.kustomization_path = kustomization_path self.remove_template_file = True def __retrieve_files_to_render(self): """ Retrieves a list of files to render. Returns: A list of files to render. """ files_to_render = [] for root, _, files in os.walk(self.path): for file in files: if file.endswith(".tmpl"): files_to_render.append(os.path.join(root, file)) return files_to_render def render(self): """ Renders the templates and adds the service to the kustomization file. """ files_to_render = self.__retrieve_files_to_render() for file in files_to_render: print(f"Rendering {file}") self.__run_command(f"envsubst < {file} > {file[:-5]}") if self.remove_template_file: os.remove(file) self.__add_service_to_kustomization_resources() def __run_command(self, command): """ Runs a shell command. Args: command (str): The command to run. Returns: The output of the command. """ try: output = subprocess.check_output(command, stderr=subprocess.STDOUT, \ universal_newlines=True, shell=True) return output.strip() except subprocess.CalledProcessError as ex: print(f"Error: {ex.output}") return None def __add_service_to_kustomization_resources(self): """ Adds the service to the kustomization file. """ # verify that the kustomization file exists if not os.path.exists(self.kustomization_path): raise ValueError( f"The kustomization file {self.kustomization_path} does not exist." ) with open(self.kustomization_path, "r", encoding="utf-8") as r_stream: yaml_dict = yaml.safe_load(r_stream) # check if the resources key exists if "resources" not in yaml_dict: raise ValueError("No resources found in kustomization yaml file.") # Check if the service already exists in the resources if f"./services/{self.service_name}" not in yaml_dict["resources"]: yaml_dict["resources"].append(f"./services/{self.service_name}") # Write the updated yaml to the kustomization file\ with open(self.kustomization_path, "w", encoding="utf-8") as w_stream: print(f"Adding {self.service_name} to {self.kustomization_path}") yaml.safe_dump(yaml_dict, w_stream, default_flow_style=False, sort_keys=False) def __run_command(self, command): """ Runs a shell command. Args: command (str): The command to run. Returns: The output of the command. """ try: output = subprocess.check_output(command, stderr=subprocess.STDOUT, \ universal_newlines=True, shell=True) return output.strip() except subprocess.CalledProcessError as ex: print(f"Error: {ex.output}") return None
import Foundation var greeting = "Hello, Day 10" let realData = """ noop addx 10 addx -4 addx -1 noop noop addx 5 addx -12 addx 17 noop addx 1 addx 2 noop addx 3 addx 2 noop noop addx 7 addx 3 noop addx 2 noop noop addx 1 addx -38 addx 5 addx 2 addx 3 addx -2 addx 2 addx 5 addx 2 addx -4 addx 26 addx -19 addx 2 addx 5 addx -2 addx 7 addx -2 addx 5 addx 2 addx 4 addx -17 addx -23 addx 1 addx 5 addx 3 noop addx 2 addx 24 addx 4 addx -23 noop addx 5 addx -1 addx 6 noop addx -2 noop noop noop addx 7 addx 1 addx 4 noop noop noop noop addx -37 addx 5 addx 2 addx 1 noop addx 4 addx -2 addx -4 addx 9 addx 7 noop noop addx 2 addx 3 addx -2 noop addx -12 addx 17 noop addx 3 addx 2 addx -3 addx -30 addx 3 noop addx 2 addx 3 addx -2 addx 2 addx 5 addx 2 addx 11 addx -6 noop addx 2 addx -19 addx 20 addx -7 addx 14 addx 8 addx -7 addx 2 addx -26 addx -7 noop noop addx 5 addx -2 addx 5 addx 15 addx -13 addx 5 noop noop addx 1 addx 4 addx 3 addx -2 addx 4 addx 1 noop addx 2 noop addx 3 addx 2 noop noop noop noop noop """ let sampleData = """ addx 15 addx -11 addx 6 addx -3 addx 5 addx -1 addx -8 addx 13 addx 4 noop addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx -35 addx 1 addx 24 addx -19 addx 1 addx 16 addx -11 noop noop addx 21 addx -15 noop noop addx -3 addx 9 addx 1 addx -3 addx 8 addx 1 addx 5 noop noop noop noop noop addx -36 noop addx 1 addx 7 noop noop noop addx 2 addx 6 noop noop noop noop noop addx 1 noop noop addx 7 addx 1 noop addx -13 addx 13 addx 7 noop addx 1 addx -33 noop noop noop addx 2 noop noop noop addx 8 noop addx -1 addx 2 addx 1 noop addx 17 addx -9 addx 1 addx 1 addx -3 addx 11 noop noop addx 1 noop addx 1 noop noop addx -13 addx -19 addx 1 addx 3 addx 26 addx -30 addx 12 addx -1 addx 3 addx 1 noop noop noop addx -9 addx 18 addx 1 addx 2 noop noop addx 9 noop noop noop addx -1 addx 2 addx -37 addx 1 addx 3 noop addx 15 addx -21 addx 22 addx -6 addx 1 noop addx 2 addx 1 noop addx -10 noop noop addx 20 addx 1 addx 2 addx 2 addx -6 addx -11 noop noop noop """ enum Operation { init(rawValue: String) { if rawValue == "noop" { self = .noop } else { let addData = rawValue.split(separator: " ") self = .add(value: Int(addData[1])!) } } case add(value: Int) case noop var executionTime: Int { switch self { case .add: return 1 case .noop: return 0 } } } class CPU { var register: Int = 1 var cycleCounter: Int = 0 { didSet { if cycleCounter%20 == 0 { if skip20 { return skip20 = false } print("bump counter for \(cycleCounter) with \(register) value \(cycleCounter * register)" ) multipleCounter += cycleCounter * register skip20 = true } } } var multipleCounter = 0 var skip20 = false func execute(operations: [Operation]) { operations.forEach { switch $0 { case .add(let value): cycle() cycle() register += value case .noop: cycle() } } } func cycle() { cycleCounter += 1 } } struct Sprite { init(center: Int) { self.center = center } let center: Int var left: Int { center - 1 } var right: Int { center + 1 } func positionIsInSprite(position: Int) -> Bool { position == center || position == left || position == right } } class Computer { private var register: Int = 1 { didSet { currentSprite = Sprite(center: register) } } private var cycleCounter: Int = 0 { didSet { if cycleCounter%numberOfPixelsPerRow == 0 { appendPixel() addNewDisplayRow() } else { appendPixel() } } } private var display: [[String]] = [[]] private var currentSprite: Sprite = Sprite(center: 1) private var currentRow = 0 private let numberOfPixelsPerRow = 40 func execute(operations: [Operation]) { operations.forEach { switch $0 { case .add(let value): cycle() register += value cycle() case .noop: cycle() } } } func showDisplay() { display.forEach { print($0.joined()) } } private func cycle() { cycleCounter += 1 } private func appendPixel() { let offset = numberOfPixelsPerRow * currentRow display[currentRow].append(currentSprite.positionIsInSprite(position: cycleCounter - offset) ? "#" : ".") } private func addNewDisplayRow() { display.append([]) currentRow += 1 } } func parsePart1(data: String) { let operations = data .split(separator: "\n") .map { String($0) } .map { Operation(rawValue: $0) } let cpu = CPU() cpu.execute(operations: operations) print("Part one: \(cpu.multipleCounter)") } //parsePart1(data: realData) func parsePart2(data: String) { let operations = data .split(separator: "\n") .map { String($0) } .map { Operation(rawValue: $0) } let computer = Computer() computer.execute(operations: operations) computer.showDisplay() } parsePart2(data: realData)
#include<iostream> #include<algorithm> #include<vector> using namespace std; int main(){ vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); //we can directly apply algorithms using algo library cout<<"Binary search for 4 is "<<binary_search(v.begin(), v.end(), 4)<<endl; //to return iterator index cout<<"lower bound is "<<lower_bound(v.begin(), v.end(), 4) - v.begin()<<endl; cout<<"upper bound is "<<upper_bound(v.begin(), v.end(), 4) - v.begin()<<endl; cout<<endl; //to find max int a = 3; int b = 4; cout<<"Max of a and b is "<<max(a,b)<<endl; //to swap swap(a,b); cout<<"a is "<<a<<endl; cout<<"b is "<<b<<endl; cout<<endl; //to reverse the string string s = "abcd"; reverse(s.begin(), s.end()); cout<<"Reverse of abcd is "<<s<<endl; cout<<endl; //rotate rotate(v.begin(), v.begin()+1, v.end()); cout<<"After rotate "<<endl; for(int i:v){ cout<<i<<" "; } cout<<endl; cout<<endl; //sort sort(v.begin(), v.end()); cout<<"After sort "<<endl; for(int i:v){ cout<<i<<" "; } return 0; }
const express = require("express"); const path = require("path"); const bcrypt = require('bcrypt'); const { open } = require("sqlite"); const sqlite3 = require("sqlite3"); const app = express(); app.use(express.json()); const dbPath = path.join(__dirname, "userData.db"); let db = null; const initializeDBAndServer = async () => { try { db = await open({ filename: dbPath, driver: sqlite3.Database, }); app.listen(3000, () => { console.log("Server Running at http://localhost:3000/"); }); } catch (e) { console.log(`DB Error: ${e.message}`); process.exit(1); } }; initializeDBAndServer(); app.post("/register/", async (request, response) => { const { username, name, password, gender, location } = request.body; const hashedPassword = await bcrypt.hash(request.body.password, 10); const selectUserQuery = `SELECT * FROM user WHERE username = '${username}'`; const dbUser = await db.get(selectUserQuery); if (dbUser === undefined) { if(password.length<5){ response.status(400); response.send("Password is too short"); } else{ const createUserQuery = ` INSERT INTO user (username, name, password, gender, location) VALUES ( '${username}', '${name}', '${hashedPassword}', '${gender}', '${location}' )`; const dbResponse = await db.run(createUserQuery); const newUserId = dbResponse.lastID; response.send(`User created successfully`); } } else { response.status(400); response.send('User already exists'); } }); app.post("/login", async (request, response) => { const { username, password } = request.body; const selectUserQuery = `SELECT * FROM user WHERE username = '${username}'`; const dbUser = await db.get(selectUserQuery); if (dbUser === undefined) { response.status(400); response.send("Invalid user"); } else { const isPasswordMatched = await bcrypt.compare(password, dbUser.password); if (isPasswordMatched === true) { response.send("Login success!"); } else { response.status(400); response.send("Invalid password"); } } }); app.put("/change-password",async(request,response)=>{ const { username, oldPassword,newPassword } = request.body; const selectUserQuery = `SELECT * FROM user WHERE username = '${username}'`; const dbUser = await db.get(selectUserQuery); const isPasswordMatched = await bcrypt.compare(oldPassword, dbUser.password); if(isPasswordMatched === false){ response.status(400); response.send("Invalid current password"); } else{ if(newPassword.length<5){ response.status(400); response.send("Password is too short"); } else{ const hashedPassword = await bcrypt.hash(request.body.newPassword, 10); const changePasswordQuery=`UPDATE user SET password = '${hashedPassword}' WHERE username = '${username}';` await db.run(changePasswordQuery); response.status(200); response.send("Password updated"); } } }) module.exports = app;
<!DOCTYPE html> <html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:sec="http://www.thymeleaf.org/extras/spring-security" layout:decorate="~{layout}"> <head> <meta charset="UTF-8"> <title>Композиторы онлайн кинотеатра</title> <script th:inline="javascript"> let flag = [[${exception}]]; //переменная-флаг Thymeleaf window.onload = () => { if (flag) new bootstrap.Modal(document.getElementById('deleteErrorModal'), {keyboard: false}).show() }; </script> </head> <body> <div layout:fragment="content"> <div> <hr class="hr"/> <h3>Поиск композитора</h3> <form method="POST" th:action="@{/composers/search}" th:object="${composerSearchForm}"> <div class="mt-0 row g-2"> <div class="col-md"> <div class="form-floating"> <input name="composersFio" type="text" class="form-control" id="composersFio" placeholder="ФИО композитора"> <label for="composersFio">ФИО композитора</label> </div> </div> <div class="row g-2"> <button type="submit" class="btn btn-secondary">Найти композитора</button> </div> </div> </form> </div> <hr class="mt-3 hr"/> <div class="mt-5"> <div class="row"> <div class="col"> <h2>Все композиторы онлайн кинотеатра</h2> </div> <div class="col"> <a sec:authorize="isAuthenticated() && (hasRole('ADMIN') || hasRole('LIBRARIAN'))" href="composers/add" class="btn btn-success" role="button" style="float: right" aria-disabled="true">Добавить композитора</a> </div> </div> <div> <table class="table table-hover mt-3"> <thead> <tr> <th scope="col">ФИО</th> <th scope="col" class="col-md-5">Позиция</th> <th scope="col"></th> </tr> </thead> <tbody> <tr th:each="composer : ${composers}"> <td> <a class="text-link text-blue" th:href="'/composers/' + ${composer.getId()}" th:text="${composer.getComposersFio()}"></a> </td> <td th:text="${composer.getPosition()}"></td> <td> <div sec:authorize="isAuthenticated() && (hasRole('ADMIN') || hasRole('LIBRARIAN'))"> <a class="btn btn-sm btn-outline-success" th:href="'/composers/update/' + ${composer.getId()}">Обновить</a> <a th:if="${!composer.isDeleted()}" class="btn btn-sm btn-outline-danger" th:href="'/composers/delete/' + ${composer.getId()}" onclick="return confirm('Вы действительно хотите удалить композитора?');">Удалить</a> <a th:if="${composer.isDeleted()}" class="btn btn-sm btn-outline-warning" th:href="'/composers/restore/' + ${composer.getId()}">Восстановить</a> </div> </td> </tr> </tbody> </table> </div> <!--Модальное окно для ошибок старт--> <div th:if="${exception != null && exception != ''}" class="modal fade" id="deleteErrorModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ошибка</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" th:text="${exception}"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">OK</button> </div> </div> </div> </div> <!--Модальное окно для ошибок конец--> <div> <nav aria-label="Pagination" th:if="${composers.totalPages gt 0}"> <ul class="pagination justify-content-center font-weight-bold"> <li class="page-item" th:classappend="${composers.number eq 0} ? 'disabled'"> <a class="page-link" th:href="@{/composers?page={id}(id=${composers.number lt 2 ? 1 : composers.number})}" aria-label="Previous" title="Previous Page" data-toggle="tooltip"> <span aria-hidden="true">&laquo;</span> </a> </li> <li class="page-item" th:classappend="${i eq composers.number + 1} ? 'active'" th:each="i : ${#numbers.sequence( 1, composers.totalPages, 1)}"> <a class="page-link" th:href="@{/composers?page={id}(id=${i})}" th:text="${i}" th:title="${'Page '+ i}" data-toggle="tooltip"></a> </li> <li class="page-item" th:classappend="${composers.number eq composers.totalPages - 1} ? 'disabled'"> <a class="page-link" th:href="@{/composers?page={id}(id=${composers.number + 2})}" aria-label="Next" title="Next Page" data-toggle="tooltip"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> </div> </div> </div> </body> </html>
#ifndef VIDEO_H #define VIDEO_H #include "Head.h" #include <iostream> // Forward declaration of DataBase class to avoid circular dependency class DataBase; /// @brief declaration and definition of the Video class inheriting from Head class Video : public Head { friend class DataBase; // Allowing DataBase class to access private members protected: unsigned duration; // Duration of the video in seconds public: // Constructor initializing multimedia name, file path, and duration Video(std::string multimedia, std::string filePath, unsigned int duration) : Head(multimedia, filePath), duration(duration){}; // Method to retrieve the duration of the video unsigned int getDuration() const { return duration; }; // Method to display details of the video void display(std::ostream &s) const override { s << "Multimedia type: VIDEO, " << "Multimedia name: " << this->getMultimediaName() << ", " << "File path: " << this->getFilePathName() << ", " << "Duration: " << this->getDuration() << ", "; }; // Method to play the video std::string play() const override { std::string arg = "mpv " + this->getFilePathName() + " &"; // Command to play video int status = system(arg.data()); // Execute command to play video in background if(status != 0){ return "Failed to play video : " + this->getMultimediaName(); } return "Video played successfully !"; }; // Destructor (currently commented out) // ~Video() { // /*std::cout << "décédé" << std::endl;*/ // Uncomment for debugging // purposes // } }; #endif // VIDEO_H
package main import ( "fmt" "github.com/efulmo/advent-of-code-2023/util" ) type Tile struct { rowIdx int colIdx int } type Step struct { direction uint8 fromTile Tile toTile Tile } const ( directionUp = 1 directionRight = 2 directionDown = 3 directionLeft = 4 ) const ( charStart = "S" charGround = "." charBeyondBorders = "?" charUpDown = "|" charUpRight = "F" charUpLeft = "7" charRightLeft = "-" charRightUp = "J" charRightDown = charUpLeft charDownUp = charUpDown charDownRight = "L" charDownLeft = charRightUp charLeftRight = charRightLeft charLeftUp = charDownRight charLeftDown = charUpRight ) func main() { lines, err := util.ReadInputFile() util.PanicOnError(err) var startTile Tile for lineIdx, line := range lines { for colIdx, r := range line { if string(r) == charStart { startTile = Tile{ rowIdx: lineIdx, colIdx: colIdx, } break } } } var currentTile = startTile pathLength := uint(1) var previousTile Tile for { nextStep := getNextStep(lines, currentTile, previousTile) // start is found again; the loop has closed nextTileChar := getCharAt(lines, nextStep.toTile) if nextTileChar == charStart { break } fmt.Printf("%d. Taking a step in direction %d to tile %d:%d with char %s\n", pathLength, nextStep.direction, nextStep.toTile.rowIdx+1, nextStep.toTile.colIdx+1, nextTileChar) previousTile = currentTile currentTile = nextStep.toTile pathLength++ } fmt.Println("Path length:", pathLength) fmt.Println("Farthest tile:", pathLength/2) } func getNextStep(lines []string, currentTile Tile, previousTile Tile) Step { availableDirs := getAvailableDirectionsFromChar(getCharAt(lines, currentTile)) for _, dir := range availableDirs { var nextTile Tile switch dir { case directionUp: nextTile = Tile{currentTile.rowIdx - 1, currentTile.colIdx} case directionRight: nextTile = Tile{currentTile.rowIdx, currentTile.colIdx + 1} case directionDown: nextTile = Tile{currentTile.rowIdx + 1, currentTile.colIdx} case directionLeft: nextTile = Tile{currentTile.rowIdx, currentTile.colIdx - 1} } // don't go back if previousTile == nextTile { continue } // check if getting to that tile allowed from this direction if !isStepDestinationValid(lines, dir, nextTile) { continue } return Step{ direction: dir, fromTile: previousTile, toTile: nextTile, } } panic(fmt.Errorf("Failed to find next tile from %d:%d(%s)", currentTile.rowIdx, currentTile.rowIdx, getCharAt(lines, currentTile))) } func getAvailableDirectionsFromChar(c string) []uint8 { var dirs []uint8 if c == charStart || c == charDownUp || c == charRightUp || c == charLeftUp { dirs = append(dirs, directionUp) } if c == charStart || c == charLeftRight || c == charUpRight || c == charDownRight { dirs = append(dirs, directionRight) } if c == charStart || c == charUpDown || c == charRightDown || c == charLeftDown { dirs = append(dirs, directionDown) } if c == charStart || c == charRightLeft || c == charUpLeft || c == charDownLeft { dirs = append(dirs, directionLeft) } dirsLen := uint(len(dirs)) if dirsLen < 1 || dirsLen > 4 { panic(fmt.Errorf("Unexpected number of directions for char %s: %v", c, dirs)) } return dirs } func getCharAt(lines []string, tile Tile) string { row, col := tile.rowIdx, tile.colIdx if row < 0 || col < 0 || row >= len(lines) { return charBeyondBorders } line := lines[row] if col >= len(line) { return charBeyondBorders } return string(line[col]) } func isStepDestinationValid(lines []string, direction uint8, to Tile) bool { r := getCharAt(lines, to) if r == charStart { return true } switch direction { case directionUp: return r == charUpDown || r == charUpRight || r == charUpLeft case directionRight: return r == charRightLeft || r == charRightUp || r == charRightDown case directionDown: return r == charDownUp || r == charDownRight || r == charDownLeft case directionLeft: return r == charLeftRight || r == charLeftUp || r == charLeftDown default: panic(fmt.Errorf("Unexpected direction %d", direction)) } }
import * as React from "react"; import { FhirGoalUtil } from "next-shared/src/fhirUtil/utilClasses/FhirGoalUtil"; import { ICardProps } from "../../structure/Card"; import { mapObservationTypeToIcon } from "../../../helpers/mapObservationTypeToIcon"; import MetricCell from "../../atoms/MetricCell"; import { Cell, CellHeader } from "../../structure/Cell"; import { Card, CardBody } from "../../structure/Card"; import { NoDataFallback } from "../../structure/NoDataFallback"; import { fhirUtil } from "next-shared/src/fhirUtil"; export interface IGoalCardProps extends ICardProps { goal: null | fhir3.Goal; } /** * Component showing information about GoalCard metrics */ export const GoalCard: React.FC<IGoalCardProps> = ({ goal }) => { // if there are no goals, just return a 'no records in our system' Card component if (!goal) { return ( <Card className="center"> <CardBody> <NoDataFallback /> </CardBody> </Card> ); } const goalUtil: FhirGoalUtil = fhirUtil(goal); const displayName = goalUtil.getGoalObsDisplayName(); const resourceType = goalUtil.getObsResourceType(); const icon = mapObservationTypeToIcon(resourceType); const cells: Array<React.ReactElement<any>> = []; const leadCell = ( <Cell isLead key={goal.id} className="center" hasGoal={!!goal} decorationIcon={icon} > <CellHeader>{displayName}</CellHeader> </Cell> ); cells.push(leadCell); cells.push(<MetricCell fhirGoal={goal} />); return ( <Card className="center"> <CardBody> {cells.length && cells.map((cell, index) => React.cloneElement(cell, { key: index }))} </CardBody> </Card> ); }; export default GoalCard;
// // AudioFileDetailView.swift // AI_Scribe // // Created by Erkin Otles on 6/30/23. // import AVFoundation import SwiftUI struct AudioFileDetailView: View { @Environment(\.presentationMode) var presentationMode var audioFile: AudioFile var recordingsManager: RecordingsManager var deletedCallback: () -> () @State private var audioPlayer: AVAudioPlayer? @State private var isPlaying = false @State private var currentTime: TimeInterval = 0 @State private var question: String = "" @State private var answer: Substring? @State private var selectedKey: String = "lastLiveTranscription" @State private var selectedString: String = "" init(audioFile: AudioFile, recordingsManager: RecordingsManager, deletedCallback: @escaping () -> ()) { self.audioFile = audioFile self.recordingsManager = recordingsManager self.deletedCallback = deletedCallback } var body: some View { VStack { Text("Date: \(formatDate(audioFile.date))") Picker(selection: $selectedKey, label: Text("Processed Data")) { ForEach(Array(audioFile.processedData.keys), id: \.self) { key in Text(key).tag(key) } } .onChange(of: selectedKey) { newValue in selectedString = audioFile.processedData[newValue] ?? "" } ZStack { RoundedRectangle(cornerRadius: 20) .stroke(.primary, lineWidth: 3) .frame(width: 300, height: 300) ScrollView { Text(selectedString) .textSelection(.enabled) //.padding() } .frame(maxWidth: 270, maxHeight: 270) } Spacer() Text("Current Time: \(formattedTime(currentTime))") Text("Total Time: \(formattedTime(audioFile.length))") Slider(value: $currentTime, in: 0...audioFile.length, onEditingChanged: sliderChanged) .padding() Button(action: { if isPlaying { audioPlayer?.pause() } else { startPlaying() } isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.fill" : "play.fill") .resizable() .frame(width: 40, height: 40) } /* Button(action: { recordingsManager.deleteRecording(audioFile) deletedCallback() presentationMode.wrappedValue.dismiss() // dismiss this view }) { Text("Delete Recording") .foregroundColor(.red) } */ } .onAppear(perform: { preparePlayer() selectedString = audioFile.processedData["lastLiveTranscription"] ?? "No lastLiveTranscript." }) .onDisappear(perform: stopPlayer) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: { recordingsManager.deleteRecording(audioFile) //deletedCallback() presentationMode.wrappedValue.dismiss() // dismiss this view }) { Image(systemName: "trash.fill") .foregroundColor(.red) } } } } func preparePlayer() { let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let absoluteURL = documentsURL.appendingPathComponent(audioFile.relativeURL.path) do { audioPlayer = try AVAudioPlayer(contentsOf: absoluteURL) audioPlayer?.prepareToPlay() } catch { print("Failed to load audio file: \(error)") } } func startPlaying() { audioPlayer?.play() startTimer() } func stopPlayer() { audioPlayer?.stop() stopTimer() } func sliderChanged(editingStarted: Bool) { if editingStarted { audioPlayer?.pause() stopTimer() } else { if let currentTime = audioPlayer?.currentTime { self.currentTime = currentTime } audioPlayer?.play() startTimer() } } private func startTimer() { Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { timer in guard let audioPlayer = audioPlayer else { timer.invalidate() return } if audioPlayer.isPlaying { currentTime = audioPlayer.currentTime } else { timer.invalidate() } } } private func stopTimer() { currentTime = 0 isPlaying = false } }
<div ng-controller="MenuCtrl" flex id="menu"> <md-toolbar layout="row"> <button ng-click="toggleSidenav('left')" class="menuBtn"> <span class="visually-hidden">Menu</span> </button> <section class="md-toolbar-tools" layout="row" layout-align="end end"> <md-button aria-label="Search" md-no-ink ng-disabled="true" > <md-icon md-svg-src="icons/ic_search_24px.svg"</md-icon> </md-button> </section> </md-toolbar> <div layout="column" flex> <md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left"> <md-toolbar> <div class="md-toolbar-tools" style="margin: 1em 0;"> <span class="face"> <!--<img ng-src="{{'https://material.angularjs.org/img/list/60.jpeg'}}" alt="">--> </span> </div> <!--email--> <md-select class="md-toolbar-tools md-toolbar-tools-bottom" ng-model="email" ng-init="email='1'"> <div ng-repeat="email in emails"> <md-option value="{{$index+1}}"> {{email}} </md-option> </div> </md-select> </md-toolbar> <!--Bottom--> <div style=""> <!--buttons--> <div class="bottom-sheet-demo inset" layout="column" layout-align="start start"> <md-button class="text-clear full-width text-indent-left"> <md-icon md-svg-src="icons/ic_phone_24px.svg" class="abs-left-middle" alt="Consultations"></md-icon> <span>Consultations</span> </md-button> <md-button class="text-clear full-width text-indent-left"> <md-icon md-svg-src="icons/file-document-box.svg" class="abs-left-middle" alt="Prescriptions"></md-icon> <span>Prescriptions</span> </md-button> <md-button class="text-clear full-width text-indent-left"> <md-icon md-svg-src="icons/ic_group_24px.svg" class="abs-left-middle" alt="Patients"></md-icon> <span>Patients</span> </md-button> </div> <md-divider></md-divider> <!--buttons--> <div class="bottom-sheet-demo inset" layout="column" layout-align="space-around start"> <md-button class="text-clear full-width"> Settings </md-button> <md-button class="text-clear full-width" ng-click="logOut()"> Logout </md-button> </div> </div> </md-sidenav> <md-content layout="column" flex class="md-padding"> <md-list> <md-item ng-repeat="post in posts track by $index"> <md-item-content> <div class="md-tile-content"> <p> {{post}} </p> </div> </md-item-content> <md-divider ng-if="!$last"></md-divider> </md-item> </md-list> </md-content> <section layout="row" layout-align="end end"> <md-button class="md-primary md-hue-1 md-fab md-fab-bottom-right" aria-label="Plus"> <md-icon md-svg-src="icons/ic_add_24px.svg" </md-icon> </md-button> </section> </div> </div>
import React from "react"; import { View } from "react-native"; import { createAppContainer } from "react-navigation"; import { createStackNavigator } from "react-navigation-stack"; import { colors } from "../../assets/Data/data"; import CatagoriesScreen from "../../screens/CatagoriesScreen"; import CatagoryMealsScreen from "../../screens/CatagoryMealsScreen"; import MealsDetailScreen from "../../screens/MealsDetailScreen"; import { createBottomTabNavigator } from "react-navigation-tabs"; import FavoriteScreen from "../../screens/FavoriteScreen"; import { Ionicons } from "@expo/vector-icons"; const MealsNavigation = createStackNavigator( { Categories: CatagoriesScreen, CategoryMeals: CatagoryMealsScreen, MealDetail: MealsDetailScreen, }, { mode: "card", defaultNavigationOptions: { headerStyle: { backgroundColor: colors.primaryColor, }, headerTintColor: "white", }, } ); const MealsTabNavigator = createBottomTabNavigator( { Meals: { screen: MealsNavigation, navigationOptions: { tabBarIcon: (tabInfo) => { return ( <Ionicons name="ios-restaurant" size={25} color={tabInfo.tintColor} /> ); }, }, }, Favorite: { screen: FavoriteScreen, navigationOptions: { tabBarIcon: (tabInfo) => { return ( <Ionicons name="ios-star" size={25} color={tabInfo.tintColor} /> ); }, }, }, }, { tabBarOptions: { activeTintColor: colors.accentColor, }, } ); export default createAppContainer(MealsTabNavigator);
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateIsplateTable extends Migration { /** * Run the migrations. * * * @return void */ public function up() { Schema::create('isplate', function (Blueprint $table) { $table->id(); // Auto-increment ID column $table->unsignedBigInteger('rkpid')->index(); $table->foreign('rkpid')->references('rkpid')->on('opcines')->onDelete('cascade'); $table->string('naziv')->nullable(); $table->string('adresa')->nullable(); $table->string('mjesto')->nullable(); $table->string('zupanija')->nullable(); $table->string('homepage')->nullable(); // Allowing for potential null values $table->string('oib')->nullable(); $table->string('url')->nullable(); $table->string('grb')->nullable(); $table->string('favico')->nullable(); $table->string('background')->nullable(); $table->string('isplatitelj')->nullable(); $table->string('vrstarashoda')->nullable(); $table->string('opis')->nullable(); $table->string('primatelj')->nullable(); $table->string('iznos')->nullable(); $table->unsignedBigInteger('isplatiteljrkp'); $table->unsignedBigInteger('kategorija')->index(); $table->text('description')->nullable(); // Assuming descriptions can be longer than a string $table->timestamps(); // Automatically add created_at and updated_at columns }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('isplate'); } }
using System; using System.Linq; using System.Threading.Tasks; using AutoFixture; using BaseTests; using BaseTests.EndToEndHelpers; using BookLovers.Base.Infrastructure.Extensions; using BookLovers.Base.Infrastructure.Persistence; using BookLovers.Base.Infrastructure.Services; using BookLovers.Readers.Application.Commands.Reviews; using BookLovers.Readers.Domain.Readers; using BookLovers.Readers.Domain.Readers.Services; using BookLovers.Readers.Domain.Reviews; using BookLovers.Readers.Domain.Reviews.Services; using BookLovers.Readers.Infrastructure.Dtos.Reviews; using BookLovers.Readers.Infrastructure.Persistence; using BookLovers.Readers.Infrastructure.Queries.Readers.Reviews; using BookLovers.Readers.Infrastructure.Root; using BookLovers.Readers.Store.Persistence; using FluentAssertions; using Moq; using Ninject; using NUnit.Framework; namespace BookLovers.Readers.Tests.IntegrationTests.UnLikeReview { public class UnLikeReviewTestsWithEventStoreSnapshot : IntegrationTest<ReadersModule, UnlikeReviewCommand> { private Mock<IHttpContextAccessor> _mock = new Mock<IHttpContextAccessor>(); private Guid _userWhoUnlikesReviewGuid; private Guid _readerGuid; private int _bookId; private int _readerId; [Test] public async Task UnLikeReview_WhenCalled_ShouldRemoveLike() { var validationResult = await Module.SendCommandAsync(Command); validationResult.HasErrors.Should().BeFalse(); var queryResult = await Module.ExecuteQueryAsync<ReaderBookReviewQuery, ReviewDto>( new ReaderBookReviewQuery(_readerId, _bookId)); queryResult.Value.Likes.Count.Should().Be(0); } protected override void InitializeRoot() { _userWhoUnlikesReviewGuid = Fixture.Create<Guid>(); _mock.Setup(s => s.UserGuid).Returns(_userWhoUnlikesReviewGuid); var appManagerMock = new Mock<IAppManager>(); var readersConnectionString = Environment.GetEnvironmentVariable(ReadersContext.ConnectionStringKey); if (readersConnectionString.IsEmpty()) readersConnectionString = E2EConstants.ReadersConnectionString; var readersStoreConnectionString = Environment.GetEnvironmentVariable(ReadersStoreContext.ConnectionStringKey); if (readersStoreConnectionString.IsEmpty()) readersStoreConnectionString = E2EConstants.ReadersStoreConnectionString; appManagerMock.Setup(s => s.GetConfigValue(ReadersContext.ConnectionStringKey)) .Returns(readersConnectionString); appManagerMock.Setup(s => s.GetConfigValue(ReadersStoreContext.ConnectionStringKey)) .Returns(readersStoreConnectionString); ReadersModuleStartup.Initialize(_mock.Object, appManagerMock.Object, new FakeLogger().GetLogger(), PersistenceSettings.Default()); } protected override Task ClearStore() { CompositionRoot.Kernel.Get<ReadersStoreContext>().CleanReadersStore(); return Task.CompletedTask; } protected override Task ClearReadContext() { CompositionRoot.Kernel.Get<ReadersContext>().CleanReadersContext(); return Task.CompletedTask; } protected override async Task PrepareData() { var readerFactory = new ReaderFactory(); _readerGuid = this.Fixture.Create<Guid>(); _readerId = this.Fixture.Create<int>(); var profileGuid = this.Fixture.Create<Guid>(); var notificationWallGuid = this.Fixture.Create<Guid>(); var userName = this.Fixture.Create<string>(); var email = this.Fixture.Create<string>(); var identification = new ReaderIdentification(_readerId, userName, email); var socials = new ReaderSocials(profileGuid, notificationWallGuid, Fixture.Create<Guid>()); var reader = readerFactory.Create(_readerGuid, identification, socials); await UnitOfWork.CommitAsync(reader); var likeAdderEmail = Fixture.Create<string>(); var likeAdderId = Fixture.Create<int>(); var likeAdderIdentification = new ReaderIdentification(likeAdderId, Fixture.Create<string>(), likeAdderEmail); var likeAdderSocials = new ReaderSocials(Fixture.Create<Guid>(), Fixture.Create<Guid>(), Fixture.Create<Guid>()); var likeAdder = readerFactory.Create(_userWhoUnlikesReviewGuid, likeAdderIdentification, likeAdderSocials); await UnitOfWork.CommitAsync(likeAdder); var bookGuid = Fixture.Create<Guid>(); _bookId = Fixture.Create<int>(); var date = Fixture.Create<DateTime>(); var bookAdder = new BookResourceAdder(); bookAdder.AddResource(reader, new AddedBook(bookGuid, _bookId, date)); await UnitOfWork.CommitAsync(reader); var reviewParts = ReviewParts.Initialize() .WithGuid(Fixture.Create<Guid>()) .WitBook(bookGuid) .AddedBy(_readerGuid) .WithContent(Fixture.Create<string>()) .WithDates(Fixture.Create<DateTime>(), Fixture.Create<DateTime>()) .HasSpoilers(); var reviewFactory = new ReviewFactory(); var review = reviewFactory.Create(reviewParts); await UnitOfWork.CommitAsync(review); await Enumerable.Range(0, 30).ForEach(async (i) => { await this.Module.SendCommandAsync(new AddSpoilerTagCommand(review.Guid)); await this.Module.SendCommandAsync(new RemoveSpoilerTagCommand(review.Guid)); }); await Module.SendCommandAsync(new LikeReviewCommand(review.Guid)); Command = new UnlikeReviewCommand(review.Guid); } protected override void SetCompositionRoot() { this.CompositionRoot = new CompositionRoot(); } } }
{% load static %} <form action="" method="POST" enctype="multipart/form-data" class="postForm"> {% csrf_token %} <h3>{{page_title_content}}</h3> <div class="form-group topic"> <label for="topic">Topic:</label> <input type="text" name="topic" id="topic" list='topic-list' value={{post.topic.title}}> <datalist id="topic-list"> <select name="" id="topic"> {% for topic in topics %} <option value="{{topic.title}}">{{topic.title}}</option> {% endfor %} </select> </datalist> </div> <div class="form-group subtitle"> <label for="subtitle">Subtitle:</label> <input type="text" name="subtitle" id="subtitle" list='subtitle_list' value={{post.topic.subtitle}}> <datalist id="subtitle_list"> <select name="" id="subtitle"> {% for topic in topics %} <option value="{{topic.subtitle}}">{{topic.subtitle}}</option> {% endfor %} </select> </datalist> </div> <div class="form-group category"> <label for="category">Category</label> <input type="text" name="category" id="category" list='category_list' value={{post.categories.title}}> <datalist id="category_list"> <select name="" id="category" multiple="multiple"> {% for category in categories %} <option value="{{category.title}}">{{category.title}}</option> {% endfor %} </select> </datalist> </div> <div class="form-group headline"> <label for="id_headline">Headline:</label> {{form.headline}} </div> <div class="form-group overview"> <label for="id_body">Overview:</label> {{form.overview}} </div> <div class="form-group body"> <label for="id_body">Body:</label> {{form.body}} </div> <div class="form-group image"> <label for="id_image"><span></span></label> {{form.image}} <div class="img-box"> <img src="" alt="" id="file-preview"> {{form.image.path}} </div> </div> <input type="submit" value="{{button_text}}"> </form>
import { View, KeyboardAvoidingView,Keyboard,Text,StyleSheet,SafeAreaView,TouchableOpacity,ActivityIndicator,ScrollView,Dimensions,Platform,ImageBackground,Image,TextInput } from 'react-native' import * as React from 'react' import {RFValue,RFPercentage} from "react-native-responsive-fontsize" import {useTheme} from "@react-navigation/native" const heightdevice=Dimensions.get('window').height import { AntDesign,Feather,Entypo,EvilIcons,FontAwesome5,MaterialIcons } from '@expo/vector-icons'; import * as ImagePicker from "expo-image-picker" import { Video, AVPlaybackStatus } from 'expo-av'; import app from "../../firebase" import {createUserWithEmailAndPassword,getAuth,deleteUser,updateProfile,sendEmailVerification,signInWithEmailAndPassword} from "firebase/auth" import {doc,setDoc,getFirestore, addDoc,updateDoc,getDocs,serverTimestamp, collection} from "firebase/firestore" import { ref,getDownloadURL,getStorage, uploadBytes,uploadBytesResumable } from "firebase/storage" import { useSelector,useDispatch } from 'react-redux'; import Toast from 'react-native-root-toast' import {loginuser,logoutuser,updateuser} from "../redux/action" import sendPushNotification from '../configurations/notificationalerts' import DropDownPicker from 'react-native-dropdown-picker'; export default function Addpost({navigation}) { const auth=getAuth(app) const db=getFirestore(app) const storage=getStorage(app) const [loading,setloading]=React.useState(false) const[desc,setdesc]=React.useState("") const[content,setcontent]=React.useState("") const [isvdeo,setisvideo]=React.useState(false) const [isKeyboardVisible, setKeyboardVisible] = React.useState(false); const video = React.useRef(null); const [status, setStatus] = React.useState({}); const {colors}=useTheme() const [open, setOpen] = React.useState(false); const [value, setValue] = React.useState([]); const [items, setItems] = React.useState([ {label: 'Tag', value: ''} ]); const userinfo = useSelector(state => state.Reducers.user); const getuserinfo=async()=>{ setloading(true) setTimeout(() => { getDocs(collection(db, "users")).then((res)=>{ const quests=res.docs.map(doc=>doc.data()) let temptags=[] quests.map((item,i)=>{ let cont={ label:item.username, value:item } temptags.push(cont) }) setItems(temptags) setTimeout(() => { setloading(false) }, 2000); }).catch(()=>{ setloading(false) }) }, 1000); } //images video picker code const showImagePicker = async () => { // Ask the user for the permission to access the media library const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (permissionResult.granted === false) { alert("You've refused to allow this appp to access your photos!"); return; } const result = await ImagePicker.launchImageLibraryAsync( { mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, quality: 1, } ); if (!result.cancelled) { setcontent(result); } } //end images video pickers const uploadpost=async(url)=>{ try{ const docinfo=await addDoc(collection(db,"posts"),{ userid:auth.currentUser.uid, userinfo:userinfo, post:url, vdeo:content?.type==='video'?true:false, desc:desc, tags:value, timestamp:serverTimestamp() }) await setDoc(doc(db,"postlikes",docinfo.id),{ postid:docinfo.id, likes:[], timestamp:serverTimestamp() }) await setDoc(doc(db,"postcomments",docinfo.id),{ postid:docinfo.id, comments:[], timestamp:serverTimestamp() }) await setDoc(doc(db,"postshares",docinfo.id),{ postid:docinfo.id, shares:[], timestamp:serverTimestamp() }) value.map((item,i)=>{ let data=`${userinfo.username} tag you in his post` sendPushNotification(item.token,data) }) } catch{ let toast = Toast.show('Upload Failed', { duration: Toast.durations.LONG, }); setTimeout(function hideToast() { Toast.hide(toast); }, 1000); setloading(false) } } const uploadfunction=async()=>{ setloading(true) if(content===""||content===null||content===""||desc==="") { let toast = Toast.show("Details are missing", { duration: Toast.durations.LONG, }); setTimeout(function hideToast() { Toast.hide(toast); }, 1000); setloading(false) return false } const storageRef = ref(storage, `posts/${auth.currentUser.email+new Date().toLocaleTimeString()}`); const img = await fetch(content.uri); const bytes = await img.blob(); //start const uploadTask = uploadBytesResumable(storageRef, bytes); // Listen for state changes, errors, and completion of the upload. uploadTask.on('state_changed',(snapshot) => { // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log('Upload is ' + progress + '% done'); switch (snapshot.state) { case 'paused': console.log('Upload is paused'); break; case 'running': console.log('Upload is running'); break; } }, (error) => { setloading(false) // A full list of error codes is available at // https://firebase.google.com/docs/storage/web/handle-errors switch (error.code) { case 'storage/unauthorized': console.log("User doesn't have permission to access the object"); break; case 'storage/canceled': console.log("User canceled the upload"); break; case 'storage/unknown': console.log("Unknown error occurred, inspect error.serverResponse"); break; } }, () => { // Upload completed successfully, now we can get the download URL getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => { //perform your task uploadpost(downloadURL) let toast = Toast.show('Uploaded', { duration: Toast.durations.LONG, }); setTimeout(function hideToast() { Toast.hide(toast); }, 1000); setloading(false) }).catch((e)=>{ console.log(e) let toast = Toast.show('Upload Failed', { duration: Toast.durations.LONG, }); setTimeout(function hideToast() { Toast.hide(toast); }, 1000); setloading(false) }) }); //end } //start useeffects React.useEffect(() => { const keyboardDidShowListener = Keyboard.addListener( 'keyboardDidShow', () => { setKeyboardVisible(true); // or some other action } ); const keyboardDidHideListener = Keyboard.addListener( 'keyboardDidHide', () => { setKeyboardVisible(false); // or some other action } ); return () => { keyboardDidHideListener.remove(); keyboardDidShowListener.remove(); }; }, []); const controller=new AbortController() React.useEffect(()=>{ getuserinfo() return ()=>{ controller.abort() } },[]) if(loading) { return( <View style={{flex:1,justifyContent:"center",alignItems:"center"}}> <ActivityIndicator color={colors.primary} size="large"></ActivityIndicator> </View> ) } else { return ( <SafeAreaView style={{flex:1}}> <KeyboardAvoidingView style={{flex:1,marginBottom:isKeyboardVisible?RFPercentage(2):0}} behavior={Platform.OS === "ios" ? "padding" : "height"}> <TouchableOpacity style={{maxWidth:RFPercentage(4),margin:RFPercentage(2)}} onPress={()=>navigation.navigate("addcontent")}> <AntDesign name="back" size={30} color={colors.primary} /> </TouchableOpacity> <Text style={{textAlign:"center",color:colors.grey2 ,fontSize:RFPercentage(3),marginBottom:RFPercentage(2),fontWeight:"400",textTransform:"capitalize" }}> Add Post </Text> <View style={{width:"90%",marginHorizontal:"5%",display:"flex",zIndex:999,justifyContent:"center",alignItems:"center"}}> <DropDownPicker placeholder='Tag users' open={open} value={value} items={items} setOpen={setOpen} setValue={setValue} setItems={setItems} style={{borderColor:colors.primary}} multiple={true} mode="BADGE" badgeDotColors={["#e76f51", "#00b4d8", "#e9c46a", "#e76f51", "#8ac926", "#00b4d8", "#e9c46a"]} /> </View> <ScrollView showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false} horizontal={false}> { content?.type==='video'? <> <Video ref={video} style={{ height:(50/100)*heightdevice, padding:RFPercentage(1), display:content===''||content===undefined||content===null?"none":"flex" }} source={{ uri: content?.uri, }} useNativeControls resizeMode="contain" isLooping onPlaybackStatusUpdate={status => setStatus(() => status)} /> </> :<ImageBackground resizeMode='contain' style={{ height:(50/100)*heightdevice, padding:RFPercentage(1), display:content===''||content===undefined||content===null?"none":"flex" }} source={{ uri: content?.uri}} /> } <View style={{display:"flex",justifyContent:"center",alignItems:"center",marginVertical:RFPercentage(2)}}> <TouchableOpacity onPress={showImagePicker}> <Entypo name="camera" size={40} color={colors.primary} /> </TouchableOpacity> <View style={{ backgroundColor:colors.lightprimary, width:"90%", marginVertical:RFPercentage(2), padding:RFPercentage(2), borderRadius:RFPercentage(2), minHeight:RFPercentage(30), shadowColor: colors.primary, shadowOffset: { width: 0, height: 1 }, shadowOpacity: 0.8, shadowRadius: 2, elevation: 5 }} > <TextInput placeholder='Description' value={desc} onChangeText={(e)=>setdesc(e)} autoFocus={true} placeholderTextColor={colors.primary} style={{fontSize:RFPercentage(2.5),color:colors.primary}} multiline/> </View> </View> </ScrollView> <View style={{display:"flex",justifyContent:"center",alignItems:"center"}}> <TouchableOpacity onPress={uploadfunction} style={{width:"50%",backgroundColor:colors.primary,borderRadius:RFPercentage(1.5) ,display:content===''||content===undefined||content===null?"none":"flex",justifyContent:"center",alignItems:"center",padding:RFPercentage(1.8),flexDirection:"row" }}> <Feather name="upload" size={24} color={colors.white} /> <Text style={{color:colors.white,fontSize:RFPercentage(2.8),marginLeft:RFPercentage(1)}}>Post</Text> </TouchableOpacity> </View> </KeyboardAvoidingView> </SafeAreaView> ) } }
import { Client, EmbedBuilder, ChannelType, NewsChannel } from 'discord.js'; import axios from 'axios'; import fs from 'fs'; import path from 'path'; import logger from '../utils/logger'; const zonesPath = path.join(__dirname, '../data/games/d2r/zones.json'); const historyPath = path.join(__dirname, '../data/games/d2r/history.json'); const zones = require(zonesPath) as Record<string, any>; const channelID = '1235719234525593624'; export interface ZoneData { current: string[]; next: string[]; next_terror_time_utc?: number; } let shouldContinueChecking = true; let isUpdating = false; export async function fetchTerrorZoneData(client: Client) { if (isUpdating) { logger.info("Update already in progress. Skipping fetch."); return; } isUpdating = true; try { const data = await fetchDataFromAPI(); if (!data) { isUpdating = false; return; } const lastData: ZoneData = fs.existsSync(historyPath) ? JSON.parse(fs.readFileSync(historyPath, 'utf8')) : {current: [], next: []}; if (isDataDifferent(data, lastData)) { fs.writeFileSync(historyPath, JSON.stringify(data, null, 2)); await postUpdatesToChannel(client, data); logger.info('New zone data fetched and posted.'); shouldContinueChecking = false; } } catch (error) { logger.error('Error in fetching or posting data:', error); } finally { isUpdating = false; if (shouldContinueChecking) { setTimeout(() => fetchTerrorZoneData(client), 30000); // Continue checking every 30 seconds } else { setTimeout(() => setupContinuousCheck(client), computeMillisecondsToNextHour()); // Schedule next check at the next hour } } } function computeMillisecondsToNextHour() { const now = new Date(); return ((60 - now.getMinutes()) * 60 * 1000) - (now.getSeconds() * 1000) - now.getMilliseconds(); } export function setupContinuousCheck(client: Client) { shouldContinueChecking = true; // Reset the flag fetchTerrorZoneData(client); // Start checking immediately } export async function fetchDataFromAPI(): Promise<ZoneData | null> { let retries = 3; while (retries > 0) { try { const response = await axios.get('https://www.d2emu.com/api/v1/tz', { headers: { 'Accept-Encoding': 'gzip, deflate' } }); if (response.status == 200 && response.data.current && Array.isArray(response.data.current)) { return response.data as ZoneData; } else { logger.error('Invalid or missing data:', response.data); retries--; await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second before retrying } } catch (error) { logger.error('Error fetching terror zone data:', error); retries--; await new Promise(resolve => setTimeout(resolve, 1000)); } } return null; // Return null if all retries fail } function isDataDifferent(newData: ZoneData, oldData: ZoneData): boolean { return JSON.stringify(newData) !== JSON.stringify(oldData); } function buildEmbeds(data: any): EmbedBuilder[] { const embeds = []; const createZoneEmbed = (title: string, zoneIds: string[], color: number): EmbedBuilder => { const embed = new EmbedBuilder() .setTitle(title) .setColor(color); for (const id of zoneIds) { const zone = zones[id]; if (zone) { embed.setImage(zone.image); break; } } if (!embed.data.image) { embed.setDescription('No valid zones found.'); } return embed; }; const currentColor = 0x00FF00; const nextColor = 0xFF0000; if (data.current && Array.isArray(data.current)) { const currentEmbed = createZoneEmbed('CURRENT ZONE:', data.current, currentColor); embeds.push(currentEmbed); } if (data.next && Array.isArray(data.next)) { const nextEmbed = createZoneEmbed('NEXT ZONE:', data.next, nextColor); embeds.push(nextEmbed); } const footerEmbed = new EmbedBuilder() .setColor(0x00AE86) .setDescription('**BOT CREATED BY**: <@111629316164481024> | [**SHOW SUPPORT**](https://ko-fi.com/ohitsjudd) | **DATA BY:** [D2Emu](https://www.d2emu.com/api/v1/tz)'); embeds.push(footerEmbed); return embeds; } export async function postUpdatesToChannel(client: Client, data: ZoneData) { const channel = client.channels.cache.get(channelID) as NewsChannel; if (!channel) { logger.error('The channel does not exist.'); return; } if (channel.type !== ChannelType.GuildNews) { logger.error(`The channel with ID ${channelID} is not a news channel.`); return; } const embeds = buildEmbeds(data); try { const message = await channel.send({ embeds }); logger.info('Message sent to the news channel successfully.'); try { await message.crosspost(); logger.info('Message crossposted successfully.'); } catch (crosspostError) { logger.error(`Failed to crosspost message: ${crosspostError}`, crosspostError); } } catch (sendError) { logger.error(`Failed to send message to news channel: ${sendError}`, sendError); } }
//! This crate provides types and functionality for //! representing and handling web ids. //! #![warn(missing_docs)] #![cfg_attr(doc_cfg, feature(doc_auto_cfg))] #![deny(unused_qualifications)] use std::{borrow::Borrow, fmt::Display, ops::Deref, str::FromStr}; use http_uri::{HttpUri, InvalidHttpUri}; use iri_string::types::UriStr; #[cfg(feature = "profile-req-agent")] pub mod profile_req_agent; #[cfg(feature = "invariants")] pub mod invariant; /// A struct for representing valid webids. /// /// A WebID is an HTTP URI which refers to an Agent (Person, Organization, Group, Device, etc.). /// See: <https://www.w3.org/2005/Incubator/webid/spec/identity/> /// /// This struct is cheaply clonable. #[derive(Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(transparent))] pub struct WebId(HttpUri); impl std::fmt::Debug for WebId { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Display::fmt(&self, f) } } impl Display for WebId { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "WebId({})", self.0.as_str()) } } impl Deref for WebId { type Target = HttpUri; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl Borrow<HttpUri> for WebId { #[inline] fn borrow(&self) -> &HttpUri { &self.0 } } impl From<WebId> for HttpUri { #[inline] fn from(value: WebId) -> Self { value.0 } } impl From<HttpUri> for WebId { #[inline] fn from(value: HttpUri) -> Self { Self(value) } } impl AsRef<UriStr> for WebId { #[inline] fn as_ref(&self) -> &UriStr { self.0.as_ref() } } impl AsRef<str> for WebId { #[inline] fn as_ref(&self) -> &str { self.0.as_str() } } impl TryFrom<&str> for WebId { type Error = InvalidWebId; #[inline] fn try_from(value: &str) -> Result<Self, Self::Error> { Ok(Self(value.try_into()?)) } } impl FromStr for WebId { type Err = InvalidWebId; #[inline] fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self(s.try_into()?)) } } /// An error type for invalid webids. #[derive(Debug, thiserror::Error)] #[error("Invalid webid.")] pub struct InvalidWebId(#[from] InvalidHttpUri); #[cfg(feature = "sophia")] mod term_impl { use sophia_api::term::{IriRef, Term, TermKind}; use crate::WebId; impl Term for WebId { type BorrowTerm<'x> = &'x Self where Self: 'x; #[inline] fn kind(&self) -> TermKind { self.0.kind() } #[inline] fn borrow_term(&self) -> Self::BorrowTerm<'_> { self } #[inline] fn iri(&self) -> Option<IriRef<sophia_api::MownStr>> { self.0.iri() } } }
遇到404排查步骤: 1,查看控制台输出,是不是少了什么jar包 2,如果jar包存在,显示无法输出,就在项目结构中添加lib依赖! 3,重启Tomcat即可解决问题 使用springMVC必须配置三大件: 处理器映射器,处理器适配器,视图解析器 通常,我们只需要手动配置视图解析器,而处理器映射器和处理器适配器只需要开启注解驱动即可, 而省去了大段的xml配置 @Component 组件 @Service service @Controller controller @Respository dao 我们的两个请求可以指向同一个视图,但页面显示的结果是不一样的, 从这里可以看出视图时被复用的,而控制器和视图之间是弱耦合关系 Restful风格 资源:互联网所有事务都可以被抽象为资源 资源操作:使用POST,DELETE,PUT,GET使用不同方法对资源进行操作 传统方式操作资源:使用不同参数实现不同效果方法单一,post和get http://127.0.0.1/item/queryItem.action?id=1 查询 GET http://127.0.0.1/item/saveItem.action 新增POST http://127.0.0.1/item/updateItem.action 更新POST http://127.0.0.1/item/delet.action?id=1 删除GET或POST Restful风格操作资源:可以使用不同请求方式实现不同效果,如下:请求地址一样,但功能可以不同 http://127.0.0.1/item/1 查询 GET http://127.0.0.1/item 新增POST http://127.0.0.1/item 更新PUT http://127.0.0.1/item/1 删除DELETE @RequestMapping("/add/{a}/{b}") public String test1(@PathVariable int a, @PathVariable int b, Model model){ int res=a+b; model.addAttribute("msg","结果为"+res); return "test"; } 在参数上注解@PathVariable 在路径上写/{a} 好处: 使路径变得更加简洁; 获得参数更加方便,框架会自动进行类型转换 跳转和重定向 页面:{视图解析器前缀}+viewName+{视图解析器后缀} 通过设置ServletAPI,不需要视图解析器, 1,通过HttpServletResponse进行输出 2,通过HttpServletResponse进行重定向 3,通过HttpServletResponse实现转发 通过springmvc 无需视图解析器 @Controller public class ResultSpringMVC { @RequestMapping("/rsm/t1") public String test1(){ //转发 return "/index.jsp"; } @RequestMapping("/rsm/t2") public String test2(){ //转发2 return "forward:/index.jsp"; } @RequestMapping("/rsm/t3") public String test3(){ //重定向 return "redirect:/index.jsp"; } } @RestController是@Controller和@ResponseBody的结合体,两个标注合并起来的作用。 @Controller类中的方法可以直接通过返回String跳转到jsp、ftl、html等模版页面。在方法上加@ResponseBody注解,也可以返回实体对象。 @RestController类中的所有方法只能返回String、Object、Json等实体对象,不能跳转到模版页面。 接收请求参数及数据回显 LinkedHashMap ModelMap:继承了LinkedHashMap,所以它拥有LinkedHashMap的全部功能! Model:精简版 (大部分情况下,我们都直接使用Model) 前后端分离时代: 后端部署后端,提供接口,提供数据: json 前端独立部署,负责渲染后端的数据: json是一种轻量级的数据交换格式,目前使用的特别广泛 采用完全独立编程语言的文本格式来储存和表示数据 JavaScript支持的类型都可以通过JSON来表示,例如字符串,数字,对象,数组等 要求和格式: 1.对象表示为键值对,数据由逗号分隔 2.花括号保存对象 3.方括号保存数组 json键值对是用来保存javascript对象的一种方式, 键名写在前面并用双引号“”包裹,使用冒号:分割然后紧接着值: {“name": "lizhiwei"} {"age": "3"} {”sex":"男"} Ajax技术 异步无刷新请求 jQuery是一个库,jQuery.ajax()的部分参数: url:请求地址 type:请求方式,GET,POST data:要发送的数据 success:成功之后执行的回调函数 error:失败后的回调函数 HTML+CSS+js(超级熟练) js:函数:闭包, DOM(id,name,tag,creat,remove), BOM(window事件,document) ES6:import require 拦截器 拦截器只会拦截访问的控制器方法,如果访问的是jsp/html/css/image/js是不会拦截的 写一个类实现HandlerInterceptor接口 在WEB-INF下的所有页面或者资源只能通过controller,或者servlet进行访问
import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader' import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader' import gsap from 'gsap' import * as dat from 'dat.gui' // 目标:孔明灯 // 1. 加载环境纹理 // 2. 孔明灯纹理 // 顶点着色器 import flylightVertexShader from './assets/shader/flylight/vertex.glsl?raw' // 片元着色器 import flylightFragmentShader from './assets/shader/flylight/fragment.glsl?raw' //创建gui对象 const gui = new dat.GUI() // 初始化场景 const scene = new THREE.Scene() // 创建透视相机 const camera = new THREE.PerspectiveCamera(90, window.innerHeight / window.innerHeight, 0.1, 1000) // 设置相机位置 // object3d具有position,属性是1个3维的向量 camera.position.set(0, 0, 2) // 更新摄像头 camera.aspect = window.innerWidth / window.innerHeight // 更新摄像机的投影矩阵 camera.updateProjectionMatrix() scene.add(camera) // 着色器抽取成文件 const shaderMaterial = new THREE.ShaderMaterial({ vertexShader: flylightVertexShader, fragmentShader: flylightFragmentShader, side: THREE.DoubleSide, uniforms: {}, }) // 创建纹理加载器对象 // 1. 加载环境纹理 const rgbLoader = new RGBELoader() rgbLoader.loadAsync('./textures/flylight/2k.hdr').then(texture => { // 圆柱反射映射,设置之后才可以旋转坐标轴跟随运动 texture.mapping = THREE.EquirectangularReflectionMapping scene.background = texture scene.environment = texture }) // 2. 孔明灯纹理 const gltfLoader = new GLTFLoader() gltfLoader.load('./textures/flylight/model/flyLight.glb', gltf => { let lightBox = null scene.add(gltf.scene) console.log(gltf) lightBox = gltf.scene.children[0] lightBox.material = shaderMaterial for (let i = 0; i < 150; i++) { let flyLight = gltf.scene.clone(true) let x = (Math.random() - 0.5) * 300 let z = (Math.random() - 0.5) * 300 let y = Math.random() * 60 + 25 flyLight.position.set(x, y, z) gsap.to(flyLight.rotation, { y: 2 * Math.PI, duration: 10 + Math.random() * 30, repeat: -1, }) gsap.to(flyLight.position, { x: '+=' + Math.random() * 5, y: '+=' + Math.random() * 20, yoyo: true, duration: 5 + Math.random() * 10, repeat: -1, }) scene.add(flyLight) } }) // 初始化渲染器 const renderer = new THREE.WebGLRenderer({ alpha: true }) renderer.outputEncoding = THREE.SRGBColorSpace // 控制输出渲染编码 renderer.toneMapping = THREE.ACESFilmicToneMapping // 设置色调,让亮暗更加的分明 renderer.oneMappingExposure = 0.1 // 色调曝光程度 // 设置渲染尺寸大小 renderer.setSize(window.innerWidth, window.innerHeight) // 监听屏幕大小改变的变化,设置渲染的尺寸 window.addEventListener('resize', () => { // console.log("resize"); // 更新摄像头 camera.aspect = window.innerWidth / window.innerHeight // 更新摄像机的投影矩阵 camera.updateProjectionMatrix() // 更新渲染器 renderer.setSize(window.innerWidth, window.innerHeight) // 设置渲染器的像素比例 renderer.setPixelRatio(window.devicePixelRatio) }) // 将渲染器添加到body document.body.appendChild(renderer.domElement) // 初始化控制器 const controls = new OrbitControls(camera, renderer.domElement) // 设置控制器阻尼 controls.enableDamping = true // 设置自动旋转 controls.autoRotate = true const clock = new THREE.Clock() function animate(t) { const elapsedTime = clock.getElapsedTime() // console.log(elapsedTime); requestAnimationFrame(animate) // 使用渲染器渲染相机看这个场景的内容渲染出来 renderer.render(scene, camera) } animate()
<div class="card"> <div class="card-header text-center"> Sign Up </div> <div class="card-body"> <form novalidate (ngSubmit)="save(signupForm)" #signupForm="ngForm"> <div class="form-group row mb-2"> <label class="col-md-2 col-form-label" for="firstNameId">First Name</label> <div class="col-md-8"> <input class="form-control" type="text" id="firstNameId" placeholder="First Name (Required)" required minlength="3" [(ngModel)]="customer.firstName" name="firstName" #firstNameVar="ngModel" [ngClass]="{'is-invalid': (firstNameVar.touched || firstNameVar.dirty) && !firstNameVar.valid}"> <span class="invalid-feedback"> <span *ngIf="firstNameVar.errors?.['required']"> Please enter your first name. </span> <span *ngIf="firstNameVar.errors?.['minlength']"> The first name must be longer than 3 characters. </span> </span> </div> </div> <div class="form-group row mb-2"> <label class="col-md-2 col-form-label" for="lastNameId">Last Name</label> <div class="col-md-8"> <input class="form-control" type="text" id="lastNameId" placeholder="Last Name (Required)" required maxlength="15" [(ngModel)]="customer.lastName" name="lastName" #lastNameVar="ngModel" [ngClass]="{'is-invalid': (lastNameVar.touched || lastNameVar.dirty) && !lastNameVar.valid}"> <span class="invalid-feedback"> <span *ngIf="lastNameVar.errors?.['required']"> Please enter your last name. </span> </span> </div> </div> <div class="form-group row mb-2"> <label class="col-md-2 col-form-label" for="emailId">Email</label> <div class="col-md-8"> <input class="form-control" type="email" id="emailId" placeholder="Email (Required)" required email [(ngModel)]="customer.email" name="email" #emailVar="ngModel" [ngClass]="{'is-invalid': (emailVar.touched || emailVar.dirty) && !emailVar.valid}"> <span class="invalid-feedback"> <span *ngIf="emailVar.errors?.['required']"> Please enter your email address. </span> <span *ngIf="emailVar.errors?.['email']"> Please enter a valid email address. </span> </span> </div> </div> <div class="form-group row mb-2"> <div class="col-md-8"> <div class="form-check"> <label class="form-check-label" for="sendCatalogId"> <input class="form-check-input" type="checkbox" name="sendCatalog" id="sendCatalogId" [(ngModel)]="customer.sendCatalog"> Send me your catalog </label> </div> </div> </div> <div *ngIf="customer.sendCatalog"> <div class="form-group row mb-2"> <label class="col-md-2 col-form-label pt-0">Address Type</label> <div class="col-md-8"> <div class="form-check form-check-inline"> <label class="form-check-label" for="addressType1Id"> <input class="form-check-input" type="radio" name="addressType" id="addressType1Id" value="home" [(ngModel)]="customer.addressType"> Home </label> </div> <div class="form-check form-check-inline"> <label class="form-check-label" for="addressType1Id"> <input class="form-check-input" type="radio" name="addressType" id="addressType1Id" value="work" [(ngModel)]="customer.addressType"> Work </label> </div> <div class="form-check form-check-inline"> <label class="form-check-label" for="addressType1Id"> <input class="form-check-input" type="radio" name="addressType" id="addressType1Id" value="other" [(ngModel)]="customer.addressType"> Other </label> </div> </div> </div> <div class="form-group row mb-2"> <label class="col-md-2 col-form-label" for="street1Id"> Street Address 1 </label> <div class="col-md-8"> <input class="form-control" type="text" name="street1" id="street1Id" placeholder="Street Address" [(ngModel)]="customer.street1"> </div> </div> <div class="form-group row mb-2"> <label class="col-md-2 col-form-label" for="street2Id"> Street Address 2 </label> <div class="col-md-8"> <input class="form-control" type="text" name="street2" id="street2Id" placeholder="Street Address (Second Line)" [(ngModel)]="customer.street2"> </div> </div> <div class="form-group row mb-2"> <label class="col-md-2 col-form-label" for="cityId"> City, State, Zip Code </label> <div class="col-md-3"> <input class="form-control" type="text" name="city" id="cityId" placeholder="City" [(ngModel)]="customer.city"> </div> <div class="col-md-3"> <select class="form-control" name="state" id="stateId" [(ngModel)]="customer.state"> <option value="" disabled selected hidden> Select a State </option> <option value="AL">Alabama</option> <option value="AK">Alaska</option> <option value="AZ">Arizona</option> <option value="AR">Arkansas</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="WI">Wisconsin</option> <option value="WY">Wyoming</option> </select> </div> <div class="col-md-2"> <input class="form-control" type="number" name="zip" id="zipId" placeholder="Zip Code" [(ngModel)]="customer.zip"> </div> </div> </div> <div form-group row mb-2> <div class="offset-md-2 col-md-4"> <button class="btn btn-primary mr-3" type="submit" style="width: 80px;" [title]="signupForm.valid ? 'Save your entered data' : 'Disabled until the form data is valid'" [disabled]="!signupForm.valid"> Save </button> </div> </div> </form> </div> </div> <!-- <br>Dirty: {{ signupForm.dirty }} <hr> <br>Touched: {{ signupForm.touched }} <hr> <br>Valid: {{ signupForm.valid }} <hr> <br>Value: {{ signupForm.value | json }} -->
/** * Concord CRM - https://www.concordcrm.com * * @version 1.3.5 * * @link Releases - https://www.concordcrm.com/releases * @link Terms Of Service - https://www.concordcrm.com/terms * * @copyright Copyright (c) 2022-2024 KONKORD DIGITAL */ import find from 'lodash/find' import findIndex from 'lodash/findIndex' import sortBy from 'lodash/sortBy' const state = { // The available saved filters for resource filters: {}, // The current available rules for resource availableRules: {}, // Visible filters builders by resource visibleBuilders: {}, // Active filters by resource activeFilters: {}, } const mutations = { /** * Set the saved filters in store */ SET(state, data) { state.filters[data.identifier] = data.filters }, /** * Set the available rules for identigier */ SET_AVAILABLE_RULES(state, data) { state.availableRules[data.identifier] = data.rules }, /** * Update the filter in store */ UPDATE(state, data) { let index = findIndex(state.filters[data.identifier], [ 'id', parseInt(data.filter.id), ]) if (index !== -1) { state.filters[data.identifier][index] = data.filter } }, /** * Add new saved filter in store */ PUSH(state, data) { state.filters[data.identifier].push(data.filter) }, /** * Remove filter from store */ REMOVE(state, data) { let index = findIndex(state.filters[data.identifier], [ 'id', parseInt(data.id), ]) if (index !== -1) { state.filters[data.identifier].splice(index, 1) } }, /** * Set filter as active */ SET_ACTIVE(state, data) { if (!state.activeFilters[data.identifier]) { state.activeFilters[data.identifier] = {} } state.activeFilters[data.identifier][data.view] = data.id }, /** * Clear active filter */ CLEAR_ACTIVE(state, data) { delete state.activeFilters[data.identifier][data.view] }, /** * Unmark the given filter as default */ UNMARK_AS_DEFAULT(state, data) { let index = findIndex(state.filters[data.identifier], [ 'id', parseInt(data.id), ]) if (index !== -1) { let defaultViewIndex = findIndex( state.filters[data.identifier][index].defaults, { view: data.view, user_id: data.userId } ) if (defaultViewIndex !== -1) { state.filters[data.identifier][index].defaults.splice( defaultViewIndex, 1 ) } } }, /** * Set filters builder visible indicator for resource */ SET_BUILDER_VISIBLE(state, data) { if (!state.visibleBuilders[data.identifier]) { state.visibleBuilders[data.identifier] = {} } state.visibleBuilders[data.identifier][data.view] = data.visible }, } const getters = { /** * Get all resource saved filters */ getAll: state => identifier => { return sortBy( state.filters[identifier], ['is_system_default', 'name'], 'desc', 'asc' ) }, /** * Get resource saved filter by id */ getById: state => (identifier, id) => { return find(state.filters[identifier], ['id', parseInt(id)]) }, /** * Get resource default filter */ getDefault: state => (identifier, view, userId) => { return find(state.filters[identifier], filter => { return find(filter.defaults, { view: view, user_id: userId }) }) }, /** * Get resource active filter */ getActive: state => (identifier, view) => { if ( !state.activeFilters[identifier] || !state.activeFilters[identifier][view] ) { return null } return find(state.filters[identifier], [ 'id', parseInt(state.activeFilters[identifier][view]), ]) }, /** * Check whether the filters builder is visible for the given identifier and view */ filtersBuilderVisible: state => (identifier, view) => { if ( !state.visibleBuilders[identifier] || !state.visibleBuilders[identifier][view] ) { return false } return state.visibleBuilders[identifier][view] || false }, } const actions = { /** * Set the available saved filters and the available rules */ setFiltersAndRules({ commit }, data) { commit('SET', { identifier: data.identifier, filters: data.filters, }) commit('SET_AVAILABLE_RULES', { identifier: data.identifier, rules: data.rules, }) }, /** * Clear active filter */ clearActive({ commit, getters }, data) { let filter = getters.getActive(data.identifier, data.view) if (filter) { commit('CLEAR_ACTIVE', { identifier: data.identifier, view: data.view, }) commit( 'queryBuilder/RESET_BUILDER_RULES', { identifier: data.identifier, view: data.view, }, { root: true } ) return true } return false }, /** * Delete saved filter */ async destroy({ commit, getters }, payload) { await Innoclapps.request().delete(`filters/${payload.id}`) let active = getters.getActive(payload.identifier, payload.view) if (active && parseInt(payload.id) === parseInt(active.id)) { commit('CLEAR_ACTIVE', { identifier: payload.identifier, view: payload.view, }) } commit('REMOVE', { identifier: payload.identifier, id: payload.id, }) }, } export default { namespaced: true, state, getters, mutations, actions, }
'use strict'; //10. (Nâng cao) Tìm kiếm bài viết theo từ khóa const newsContainer = document.getElementById('news-container'); const navPageNum = document.getElementById('nav-page-num'); const prevBtn = document.getElementById('btn-prev'); const nextBtn = document.getElementById('btn-next'); const pageNum = document.getElementById('page-num'); const searchBtn = document.getElementById('btn-submit'); const inputSearch = document.getElementById('input-query'); //hàm báo lỗi const renderError = function (message) { newsContainer.insertAdjacentText("beforeend", message); }; //hàm tạo element bản tin const renderNews = function (newsData) { newsContainer.innerHTML = ""; newsData.articles.forEach((news) => { const html = `<div class="card flex-row flex-wrap"> <div class="card mb-3" style="max-width:100%;"> <div class="row no-gutters"> <div class="col-md-4"> <img src=${news.urlToImage} class="card-img" alt="Photo"> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">${news.title}</h5> <p class="card-text">${news.description}</p> <a href=${news.url} target="_blank" class="btn btn-primary">View</a> </div> </div> </div> </div> </div>` newsContainer.insertAdjacentHTML("beforeend", html); }); }; let totalResults let pageLimit = ""; //tong so trang hien thi let keyword = ""; let page = ""; //lấy data setting từ classUser const pageSize = currentUser.pageSize || 5; const apiKey = "1332ec5fb9864069b2a45c81a9c7d53e"; //"fc35919017154287a67c76b1a5825373"; //"6eab18f380ef46a5a7cc50044af5f96b" //"1332ec5fb9864069b2a45c81a9c7d53e" //"8b1b3c1bbda94011abf107e3ef0d3ca7" //"75e2657cbdf64e45b77e27e8a6a86a11" //"469a274465ae4c8e8a3e64eac72ed8c7" //"ee8796817b5e4bc09c278b467a924206" //"d32a9d321d144f5bb98fa91618af9797" //"19718e50b69a4717ae10de68286cfb0d" //"b45f738b9170486698bd716ab3a8d56e" //tạo hàm lấy data từ API const searchNews = async function (keyword, pageSize, page, apiKey) { try { const resSearchNews = await fetch(`https://newsapi.org/v2/everything?q=${keyword}&pageSize=${pageSize}&page=${page}&apiKey=${apiKey}`); if (!resSearchNews.ok) throw new Error('Problem getting news data!'); const dataSearchNews = await resSearchNews.json(); console.log(dataSearchNews); renderNews(dataSearchNews); totalResults = dataSearchNews.totalResults; if (totalResults == 0) { navPageNum.classList.add("hidden"); throw new Error('Could not be found in any documents!') } //tính số page hiển thị -%-phép tính lấy dư if (totalResults % pageSize) { pageLimit = Math.floor(totalResults / pageSize) + 1; } else { pageLimit = totalResults / pageSize; } //xử lý nút Next khi pageLimit=1 if (pageLimit === 1) { nextBtn.classList.add("hidden"); } //xử lý nút Next khi pageLimit>1 if (pageLimit > 1) { nextBtn.classList.remove("hidden"); } //xử lý nút Next khi page=pageLimit if (page === pageLimit) { nextBtn.classList.add('hidden'); } console.log(`page limit:${pageLimit}`); } catch (err) { console.error(`${err}`); renderError(`Something went wrong: ${err.message}`); } }; //1.1 không hiển thị các nút chọn trang khi chưa search navPageNum.classList.add("hidden"); if (currentUser.username) { //Xử lý sự kiện search searchBtn.addEventListener('click', function () { page = 1; newsContainer.innerHTML = ""; if (inputSearch.value === "") { alert("Please input keyword!"); } else { keyword = inputSearch.value; navPageNum.classList.remove("hidden"); // hiển thị trang searchNews(keyword, pageSize, page, apiKey); //hiển thị các nút khi serach prevBtn.classList.add("hidden") pageNum.innerText = page; }; }); //2. Sự kiện nút prev;next //2.1.Sự kiện Next nextBtn.addEventListener('click', function () { prevBtn.classList.remove('hidden'); if (page < pageLimit) { page++; pageNum.innerText = page; } //hiển thị news tương ứng searchNews(keyword, pageSize, page, apiKey); //hết page hiển thị:Ẩn Next if (page === pageLimit) { nextBtn.classList.add('hidden'); } }) //2.2.Sự kiện Prev prevBtn.addEventListener('click', function () { nextBtn.classList.remove('hidden'); if (page > 1) { page--; pageNum.innerText = page; } //hiển thị news tương ứng searchNews(keyword, pageSize, page, apiKey); //Trang1:Ẩn Prev if (page === 1) { prevBtn.classList.add('hidden'); } }); };
import { useAtom } from "jotai" import { useState } from "react" import { ReactEditor, useSlateStatic } from "slate-react" import { isHeadActive, toggleHead } from "../../../Nodes/Block/Head/headHelper" import type { IHeadGrade } from "../../../Nodes/Block/Head/types" import { activeButtonAtom } from "../../state" import ToolBarItem from "../ToolBarItem/ToolBarItem" import { useIconColor } from "../ToolBarItem/useIconColor" import HeadButtonBar from "./HeadButtonBar" import HeadIcon from "./HeadIcon" const HeadButton: React.FC<{ headGrade: IHeadGrade | "no-grade" }> = ({ headGrade }) => { const [isMouseEnter, setIsMouseEnter] = useState(false) const { fillColor, backgroundColor } = useIconColor(false, isMouseEnter) const [activeButton, setActiveButton] = useAtom(activeButtonAtom) let styleMessage: string let shortcutMessage: string switch (headGrade) { case "1": styleMessage = "一级标题" shortcutMessage = "Markdown: # 空格" break case "2": styleMessage = "二级标题" shortcutMessage = "Markdown: ## 空格" break case "3": styleMessage = "三级标题" shortcutMessage = "Markdown: ### 空格" break case "4": styleMessage = "四级标题" shortcutMessage = "Markdown: #### 空格" break case "5": styleMessage = "五级标题" shortcutMessage = "Markdown: ##### 空格" break case "6": styleMessage = "六级标题" shortcutMessage = "Markdown: ###### 空格" break default: styleMessage = "一级标题" shortcutMessage = "Markdown: # 空格" break } if (headGrade === "no-grade") { // 大部分逻辑来自 ToolBarItem return ( <div className={"py-2 px-1"}> <div onMouseEnter={() => { setIsMouseEnter(true) setActiveButton("head-bar") }} onMouseLeave={() => { setIsMouseEnter(false) }} className={"flex items-center justify-center h-8 w-8 rounded-md cursor-pointer"} style={{ backgroundColor: backgroundColor, position: "relative", // 为了给箭头留出空间, 覆盖类中的样式 justifyContent: "start", width: "32px", }} > <div className={"h-6 w-6"} style={{ // 设计上这应该是离 icon svg 最近的一个 color, // 否则 svg 中的 currentColor 会导致颜色与预期不符 color: fillColor, }} > <HeadButtonBar></HeadButtonBar> <HeadIcon headGrade={headGrade}></HeadIcon> </div> <svg className={"absolute left-5 top-[10px] w-3 h-3 transition-transform"} style={{ transform: activeButton === "head-bar" ? "rotate(180deg)" : undefined, }} viewBox="0 0 12 12" > <path d="M6 6.69l2.65-2.65a.5.5 0 11.7.7L6 8.1 2.65 4.75a.5.5 0 11.7-.71L6 6.69z" fillRule="nonzero" fill="#ffffff" ></path> </svg> </div> </div> ) } else { const editor = useSlateStatic() const isActive = isHeadActive(editor, headGrade) const onClick = () => { toggleHead(editor, headGrade) ReactEditor.focus(editor) } const onMouseEnter = () => { if (headGrade === "1" || headGrade === "2" || headGrade === "3") { setActiveButton(headGrade === "1" ? "head-1" : headGrade === "2" ? "head-2" : "head-3") } } return ( <ToolBarItem styleMessage={styleMessage} shortcutMessage={shortcutMessage} isStyleActive={isActive} onClick={onClick} onMouseEnter={onMouseEnter} > <HeadIcon headGrade={headGrade}></HeadIcon> </ToolBarItem> ) } } export default HeadButton
/* * Copyright (c) 2016 - 2019 Jolla Ltd. * * License: Proprietary */ import QtQuick 2.2 import Sailfish.Silica 1.0 import QtMultimedia 5.5 import QtDocGallery 5.0 import org.nemomobile.systemsettings 1.0 import ".." CsdTestPage { id: page property bool shouldShowControls: true readonly property bool controlsVisible: shouldShowControls && !video.loading property bool firstVideoLoaded property int totalPlayTime property int minimumPlayingTime: runInTests ? page.parameters["RunInTestTime"] * 60*1000 : 15000 allowedOrientations: firstVideoLoaded ? ((video.contentRect.height > video.contentRect.width) ? Orientation.Portrait : Orientation.Landscape) : Orientation.Portrait orientation: allowedOrientations property bool originalAmbientLightSensor property int originalBrightness Component.onDestruction: { // Restore original values. displaySettings.ambientLightSensorEnabled = originalAmbientLightSensor displaySettings.brightness = originalBrightness } onStatusChanged: { if (status == PageStatus.Active) { video.tryNext() } } VideoPlayer { id: video readonly property bool loading: (video.status === MediaPlayer.Loading) && firstVideoLoaded property bool atLastUrl: videoIndex === videosModel.count - 1 property int videoIndex: -1 property int lastPosition function tryNext() { if (videosModel.status != DocumentGalleryModel.Finished && videosModel.status != DocumentGalleryModel.Error) { tryNextTimer.start() return } if (videosModel.count == 0 || atLastUrl) { console.log("CSD VideoPlayback failure, video count: ", videosModel.count, "or at last url:", atLastUrl) setTestResult(false) testCompleted(true) } else { videoIndex += 1 source = videosModel.get(videoIndex).url } } anchors.fill: parent fillMode: VideoOutput.PreserveAspectFit opacity: !video.loading ? 1.0 : 0.0 Behavior on opacity { FadeAnimator {} } loops: MediaPlayer.Infinite onErrorChanged: { if (atLastUrl && error !== MediaPlayer.NoError) { console.log("CSD VideoPlayback failure, error code: ", error) setTestResult(false) testCompleted(true) } } onAvailabilityChanged: { if (availability !== MediaPlayer.Available) { console.log("CSD VideoPlayback failure no available: ", availability) setTestResult(false) testCompleted(true) } } onPositionChanged: { if (position > 0) { totalPlayTime += (position - lastPosition) } lastPosition = position if (totalPlayTime >= minimumPlayingTime) { setTestResult(true) testCompleted(true) } } onStatusChanged: { switch (status) { case MediaPlayer.Loaded: firstVideoLoaded = true play() break case MediaPlayer.EndOfMedia: // loop until we've played for the minimumPlayingTime if (runInTests) { console.log("CSD Video playback ended, video duration: ", video.duration) setTestResult(true) } break case MediaPlayer.InvalidMedia: tryNextTimer.start() break default: } } } CsdPageHeader { id: header //% "Video playback" title: qsTrId("csd-he-video_playback") opacity: !video.loading ? 1.0 : 0.0 Behavior on opacity { FadeAnimator {} } } MouseArea { anchors.fill: parent onClicked: shouldShowControls = !shouldShowControls } DimmerBackground { id: videoStatusBackground enabled: controlsVisible anchors { top: header.bottom topMargin: Theme.paddingMedium } x: Theme.horizontalPageMargin width: parent.width - 2 * x contentHeight: videoStatus.height Column { id: videoStatus width: videoStatusBackground.width Label { width: parent.width //% "Status: %1" text: qsTrId("csd-la-video_status").arg(statusToString(video.status)) function statusToString(status) { switch (status) { case MediaPlayer.NoMedia: //% "No media has been set" return qsTrId("csd-la-video_status_no_media") case MediaPlayer.Loading: //% "Loading media" return qsTrId("csd-la-video_status_loading_media") case MediaPlayer.Loaded: //% "Media loaded" return qsTrId("csd-la-video_media_loaded") case MediaPlayer.Buffering: //% "Buffering media" return qsTrId("csd-la-video_buffering_media") case MediaPlayer.Stalled: //% "Buffering stalled" return qsTrId("csd-la-video_media_stalled") case MediaPlayer.Buffered: //% "Media buffered" return qsTrId("csd-la-video_media_buffered") case MediaPlayer.EndOfMedia: //% "Reached end of media" return qsTrId("csd-la-video_end_of_media") case MediaPlayer.InvalidMedia: //% "Invalid media" return qsTrId("csd-la-video_invalid_media") case MediaPlayer.UnknownStatus: //% "Unknown" return qsTrId("csd-la-video_status_unknown") } } } ProgressBar { width: parent.width maximumValue: video.duration value: video.position } } } DocumentGalleryModel { id: videosModel rootType: DocumentGallery.Video properties: ["url"] } DimmerBackground { id: videoInfoBackground enabled: controlsVisible x: Theme.horizontalPageMargin width: parent.width - 2 * x contentHeight: videoInfo.height anchors { bottom: passFailButtons.visible ? passFailContainer.top : parent.bottom bottomMargin: passFailButtons.visible ? Theme.itemSizeSmall : Theme.paddingLarge } contentWidth: width Column { id: videoInfo spacing: Theme.paddingMedium width: videoInfoBackground.width Label { id: urlLabel width: parent.width wrapMode: Text.Wrap font.pixelSize: Theme.fontSizeSmall text: { if (videosModel.status != DocumentGalleryModel.Finished) { if (videosModel.status == DocumentGalleryModel.Error) { //% "Error while searching for video media!" return qsTrId("csd-la-video_search_error") } else { //% "Searching for video media..." return qsTrId("csd-la-video_searching_for_media") } } videosModel.count == 0 && videosModel.status == DocumentGalleryModel.Finished //% "Error: cannot find any video media!" ? qsTrId("csd-la-video_cannot_find_media") : video.source } } Label { width: parent.width //: Countdown to when the test will automatically be passed //% "Auto-passing in %n seconds" text: qsTrId("csd-la-test_auto_pass_countdown", Math.round((minimumPlayingTime - totalPlayTime) / 1000)) wrapMode: Text.Wrap font.pixelSize: Theme.fontSizeSmall visible: !runInTests } Button { anchors.horizontalCenter: parent.horizontalCenter visible: !runInTests && video.videoIndex < videosModel.count-1 text: video.status == MediaPlayer.NoMedia //% "Start" ? qsTrId("csd-la-start") //% "Next video" : qsTrId("csd-la-next_video") onClicked: video.tryNext() } } } DimmerBackground { id: passFailContainer anchors { bottom: parent.bottom bottomMargin: Theme.paddingLarge } visible: !runInTests enabled: controlsVisible x: Theme.horizontalPageMargin width: parent.width - 2 * x contentWidth: width contentHeight: passFailButtons.height ButtonLayout { id: passFailButtons rowSpacing: Theme.paddingLarge anchors.horizontalCenter: parent.horizontalCenter PassButton { id: passButton onClicked: { setTestResult(true) testCompleted(true) } } FailButton { id: failButton onClicked: { setTestResult(false) testCompleted(true) } } } } Timer { id: tryNextTimer interval: 1000 onTriggered: video.tryNext() } DisplaySettings { id: displaySettings onPopulatedChanged: { // Save existing backlight settings originalAmbientLightSensor = displaySettings.ambientLightSensorEnabled originalBrightness = displaySettings.brightness // Max out the brightness before test displaySettings.brightness = displaySettings.maximumBrightness // Also disable the ambient light sensor. displaySettings.ambientLightSensorEnabled = false } } }
/* * * Copyright 2023 Doğu Kocatepe * This file is part of Theory Lisp. * Theory Lisp 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. * Theory Lisp 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 Theory Lisp. If not, see <https://www.gnu.org/licenses/>. */ #include "automaton.h" #include <assert.h> #include <stdbool.h> #include <string.h> #include "../parser/parser.h" #include "../scanner/scanner.h" #include "../types/error.h" #include "../types/void.h" #include "../types/object.h" #include "../utils/list.h" #include "../utils/string.h" #include "../automaton/automaton.h" #include "common.h" #include "expression.h" #include "expression_base.h" #include "lambda.h" #include "polish.h" typedef enum { HEAD_OP_MOVE_LEFT_EXPR, HEAD_OP_MOVE_RIGHT_EXPR, HEAD_OP_WRITE_EXPR, HEAD_NOP_EXPR } head_operation_type_expr; typedef struct { head_operation_type_expr op; exprptr write_value; } head_operation_expr; typedef struct { exprptr condition; listptr head_operations; exprptr output; char *next_state_name; } transition_expr; typedef struct { exprptr base_machine; char *name; exprptr output; listptr transitions; } state_expr; typedef struct { listptr captures; size_t number_of_tapes; listptr states; automaton_t *compiled; } automaton_expr; static const char automaton_expr_name[] = "automaton_expr"; static const expr_vtable automaton_expr_vtable = { .destroy = destroy_automaton_expr, .interpret = interpret_automaton, .to_string = automaton_expr_tostring, .call = call_automaton, .call_internal = call_automaton_internal, .get_arity = automaton_expr_get_arity, .get_pn_arity = automaton_expr_get_pn_arity}; bool is_automaton_expr(exprptr e) { return strcmp(e->expr_name, automaton_expr_name) == 0; } exprptr new_automaton_expr(size_t number_of_tapes, tokenptr tkn) { automaton_expr *ae = malloc(sizeof *ae); ae->states = new_list(); ae->captures = new_list(); ae->compiled = NULL; ae->number_of_tapes = number_of_tapes; return expr_base_new(ae, &automaton_expr_vtable, automaton_expr_name, tkn); } static void delete_head_operation_list(listptr lst) { for (size_t i = 0; i < list_size(lst); ++i) { head_operation_expr *head_op = list_get(lst, i); if (head_op->write_value) { delete_expr(head_op->write_value); } free(head_op); } delete_list(lst); } static void delete_transition(transition_expr *tr) { delete_head_operation_list(tr->head_operations); free(tr->next_state_name); delete_expr(tr->condition); if (tr->output) { delete_expr(tr->output); } free(tr); } static void delete_state(state_expr *st) { for (size_t j = 0; j < list_size(st->transitions); ++j) { transition_expr *tr = list_get(st->transitions, j); delete_transition(tr); } if (st->base_machine) { delete_expr(st->base_machine); } if (st->output) { delete_expr(st->output); } free(st->name); delete_list(st->transitions); free(st); } void destroy_automaton_expr(exprptr self) { automaton_expr *ae = self->data; for (size_t i = 0; i < list_size(ae->states); ++i) { state_expr *st = list_get(ae->states, i); delete_state(st); } for (size_t i = 0; i < list_size(ae->captures); ++i) { char *capture = list_get(ae->captures, i); free(capture); } if (ae->compiled) { delete_automaton(ae->compiled); } delete_list(ae->states); delete_list(ae->captures); free(ae); } char *transition_tostring(transition_expr *tr) { char *cond_str = expr_tostring(tr->condition); char *next_name_str = tr->next_state_name; char *output_str = NULL; if (tr->output) { output_str = expr_tostring(tr->output); } else { output_str = strdup(""); } char *beginning = format("(%s", cond_str); free(cond_str); for (size_t i = 0; i < list_size(tr->head_operations); ++i) { head_operation_expr *head_op = list_get(tr->head_operations, i); char *str = NULL; switch (head_op->op) { case HEAD_OP_MOVE_RIGHT_EXPR: str = strdup("->"); break; case HEAD_OP_MOVE_LEFT_EXPR: str = strdup("<-"); break; case HEAD_OP_WRITE_EXPR: str = expr_tostring(head_op->write_value); break; case HEAD_NOP_EXPR: str = strdup("."); break; } beginning = unique_append_sep(beginning, " ", str); } char *result = format("%s %s) %s", beginning, next_name_str, output_str); free(beginning); free(output_str); return result; } char *state_tostring(state_expr *st) { char *output_str = NULL; if (st->output) { output_str = expr_tostring(st->output); } else { output_str = strdup(""); } char *base_machine_str = NULL; if (st->base_machine) { base_machine_str = expr_tostring(st->base_machine); } else { base_machine_str = strdup(""); } char *result = NULL; if (st->base_machine == NULL) { result = format("(%s %s", st->name, output_str); } else { result = format("(%s:%s %s", st->name, base_machine_str, output_str); } free(output_str); free(base_machine_str); for (size_t i = 0; i < list_size(st->transitions); ++i) { transition_expr *tr = list_get(st->transitions, i); char *tr_str = transition_tostring(tr); char *new_result = format("%s\n%s", result, tr_str); free(result); free(tr_str); result = new_result; } char *new_result = format("%s)", result); free(result); return new_result; } char *automaton_expr_tostring(exprptr self) { automaton_expr *ae = self->data; char *captures = capture_list_tostring(ae->captures); char *result = format("(automaton\\%ld %s", ae->number_of_tapes, captures); free(captures); for (size_t i = 0; i < list_size(ae->states); ++i) { state_expr *st = list_get(ae->states, i); char *st_str = state_tostring(st); char *new_result = format("%s\n%s", result, st_str); free(result); free(st_str); result = new_result; } char *new_result = format("%s)", result); free(result); return new_result; } static void automaton_expr_add_state(exprptr self, state_expr *st) { automaton_expr *ae = self->data; list_add(ae->states, st); } static void automaton_expr_add_capture(exprptr self, char *capture) { automaton_expr *ae = self->data; list_add(ae->captures, strdup(capture)); } static listptr head_operations_parse(size_t arity, tokenstreamptr tkns, stack_frame_ptr sf) { listptr head_operations = new_list(); for (size_t i = 0; i < arity; ++i) { head_operation_expr *head_op = malloc(sizeof *head_op); head_op->write_value = NULL; tokenptr head_operation_tkn = current_tkn(tkns); switch (head_operation_tkn->type) { case TOKEN_MOVE_LEFT: (void)next_tkn(tkns); head_op->op = HEAD_OP_MOVE_LEFT_EXPR; break; case TOKEN_MOVE_RIGHT: (void)next_tkn(tkns); head_op->op = HEAD_OP_MOVE_RIGHT_EXPR; break; case TOKEN_NOP: (void)next_tkn(tkns); head_op->op = HEAD_NOP_EXPR; break; default: head_op->op = HEAD_OP_WRITE_EXPR; if (!(head_op->write_value = expr_parse(tkns, sf))) { delete_head_operation_list(head_operations); free(head_op); return NULL; } break; } list_add(head_operations, head_op); } return head_operations; } transition_expr *automaton_expr_parse_transition_parse(size_t arity, tokenstreamptr tkns, stack_frame_ptr sf) { exprptr condition = expr_parse(tkns, sf); if (condition == NULL) { return NULL; } listptr head_operations = head_operations_parse(arity, tkns, sf); if (head_operations == NULL) { delete_expr(condition); return NULL; } tokenptr next_state_name_tkn = next_tkn(tkns); if (next_state_name_tkn->type != TOKEN_IDENTIFIER) { delete_expr(condition); delete_head_operation_list(head_operations); return parser_error(next_state_name_tkn, "Expected next state name"); } tokenptr right_p = next_tkn(tkns); if (right_p->type != TOKEN_RIGHT_PARENTHESIS) { delete_expr(condition); delete_head_operation_list(head_operations); return parser_error(right_p, "Expected right parenthesis"); } exprptr transition_output = NULL; token_t *tkn = current_tkn(tkns); if (tkn->type == TOKEN_LEFT_CURLY_BRACKET) { (void)next_tkn(tkns); transition_output = pn_expr_parse(tkns, sf); } transition_expr *tr = malloc(sizeof *tr); tr->condition = condition; tr->next_state_name = strdup(next_state_name_tkn->value.character_sequence); tr->output = transition_output; tr->head_operations = head_operations; return tr; } state_expr *automaton_expr_state_parse(size_t arity, tokenstreamptr tkns, stack_frame_ptr sf) { tokenptr left_p = next_tkn(tkns); if (left_p->type != TOKEN_LEFT_PARENTHESIS) { return parser_error(left_p, "Expected left parenthesis"); } tokenptr tkn_state_name = next_tkn(tkns); if (tkn_state_name->type != TOKEN_IDENTIFIER) { return parser_error(tkn_state_name, "Expected state name identifier"); } tokenptr tkn_colon = current_tkn(tkns); exprptr base_machine = NULL; if (tkn_colon->type == TOKEN_COLON) { (void)next_tkn(tkns); base_machine = expr_parse(tkns, sf); } tokenptr tkn = current_tkn(tkns); exprptr state_output = NULL; if (tkn->type == TOKEN_LEFT_CURLY_BRACKET) { (void)next_tkn(tkns); state_output = pn_expr_parse(tkns, sf); } state_expr *st = malloc(sizeof *st); st->transitions = new_list(); st->name = strdup(tkn_state_name->value.character_sequence); st->output = state_output; st->base_machine = base_machine; while ((tkn = next_tkn(tkns))->type != TOKEN_RIGHT_PARENTHESIS) { if (tkn->type != TOKEN_LEFT_PARENTHESIS) { delete_state(st); return parser_error(tkn, "Expected left parenthesis"); } transition_expr *tr = automaton_expr_parse_transition_parse(arity, tkns, sf); if (tr == NULL) { delete_state(st); return NULL; } list_add(st->transitions, tr); } return st; } exprptr automaton_expr_parse(tokenstreamptr tkns, stack_frame_ptr sf) { tokenptr automaton_token = next_tkn(tkns); assert(automaton_token->type == TOKEN_AUTOMATON); tokenptr backslash = next_tkn(tkns); if (backslash->type != TOKEN_BACKSLASH) { return parser_error(backslash, "Expected backslash followed by an arity number"); } tokenptr arity_token = next_tkn(tkns); if (arity_token->type != TOKEN_INTEGER) { return parser_error(arity_token, "Expected an integer denoting number of tapes"); } tokenptr optional_left_curly_bracket = current_tkn(tkns); listptr captures = NULL; if (optional_left_curly_bracket->type == TOKEN_LEFT_SQUARE_BRACKET) { captures = get_capture_list(tkns); if (captures == NULL) { return NULL; } } size_t arity = arity_token->value.integer; exprptr e = new_automaton_expr(arity, automaton_token); if (captures) { for (size_t i = 0; i < list_size(captures); ++i) { automaton_expr_add_capture(e, list_get(captures, i)); } delete_list(captures); } while (current_tkn(tkns)->type != TOKEN_RIGHT_PARENTHESIS) { state_expr *st = automaton_expr_state_parse(arity, tkns, sf); if (!st) { delete_expr(e); return NULL; } automaton_expr_add_state(e, st); } return e; } static size_t find_state_index(listptr states, char *name) { for (size_t k = 0; k < list_size(states); ++k) { state_expr *search_st = list_get(states, k); if (strcmp(search_st->name, name) == 0) { return k; break; } } return (size_t)(-1); } /** * Helper function of compile_automaton. * Returns the first error in the compiled automaton */ static objectptr find_compilation_errors(automaton_t *aut) { for (size_t i = 0; i < aut->number_of_states; ++i) { state_t *st = &aut->states[i]; for (size_t j = 0; j < st->number_of_transitions; ++j) { transition_t *tr = &st->transitions[j]; if (tr->action == ACT_CONTINUE && tr->next_state_index == (size_t)(-1)) { return make_error("Next state does not exist."); } } } return make_void(); } static void compile_head_operations(size_t ntapes, transition_expr *expr_tr, transition_t *aut_tr, stack_frame_ptr sf) { aut_tr->head_operations = malloc(ntapes * sizeof(head_op_t)); for (size_t k = 0; k < ntapes; ++k) { head_operation_expr *expr_op = list_get(expr_tr->head_operations, k); head_op_t *head_op = &aut_tr->head_operations[k]; switch (expr_op->op) { case HEAD_OP_MOVE_LEFT_EXPR: head_op->op = HEAD_OP_MOVE_LEFT; head_op->write_value = NULL; break; case HEAD_OP_MOVE_RIGHT_EXPR: head_op->op = HEAD_OP_MOVE_RIGHT; head_op->write_value = NULL; break; case HEAD_OP_WRITE_EXPR: head_op->op = HEAD_OP_WRITE; head_op->write_value = clone_expr(expr_op->write_value); break; case HEAD_NOP_EXPR: head_op->op = HEAD_NOP; head_op->write_value = NULL; break; } } } static void compile_transitions(size_t ntapes, listptr states, state_expr *expr_st, size_t self_index, state_t *aut_st, stack_frame_ptr sf) { if (aut_st->number_of_transitions == 0) { aut_st->transitions = NULL; } else { aut_st->transitions = malloc(aut_st->number_of_transitions * sizeof(*aut_st->transitions)); for (size_t j = 0; j < aut_st->number_of_transitions; ++j) { transition_expr *expr_tr = list_get(expr_st->transitions, j); transition_t *aut_tr = &aut_st->transitions[j]; aut_tr->condition = clone_expr(expr_tr->condition); aut_tr->output = expr_tr->output ? clone_expr(expr_tr->output) : NULL; if (strcmp(expr_tr->next_state_name, "self") == 0) { aut_tr->next_state_index = self_index; aut_tr->action = ACT_CONTINUE; } else if (strcmp(expr_tr->next_state_name, "next") == 0) { aut_tr->next_state_index = self_index + 1; aut_tr->action = ACT_CONTINUE; } else if (strcmp(expr_tr->next_state_name, "halt") == 0) { aut_tr->next_state_index = (size_t)(-1); aut_tr->action = ACT_HALT; } else if (strcmp(expr_tr->next_state_name, "accept") == 0) { aut_tr->next_state_index = (size_t)(-1); aut_tr->action = ACT_ACCEPT; } else if (strcmp(expr_tr->next_state_name, "reject") == 0) { aut_tr->next_state_index = (size_t)(-1); aut_tr->action = ACT_REJECT; } else { aut_tr->next_state_index = find_state_index(states, expr_tr->next_state_name); aut_tr->action = ACT_CONTINUE; } compile_head_operations(ntapes, expr_tr, aut_tr, sf); } } } static objectptr compile_automaton(automaton_expr *ae, stack_frame_ptr sf) { automaton_t *aut = malloc(sizeof *aut); aut->number_of_states = list_size(ae->states); aut->states = malloc(aut->number_of_states * sizeof(*aut->states)); aut->number_of_tapes = ae->number_of_tapes; for (size_t i = 0; i < aut->number_of_states; ++i) { state_expr *expr_st = list_get(ae->states, i); state_t *aut_st = &aut->states[i]; aut_st->base_machine = expr_st->base_machine ? clone_expr(expr_st->base_machine) : NULL; aut_st->output = expr_st->output ? clone_expr(expr_st->output) : NULL; aut_st->number_of_transitions = list_size(expr_st->transitions); compile_transitions(ae->number_of_tapes, ae->states, expr_st, i, aut_st, sf); } objectptr result = find_compilation_errors(aut); if (is_error(result)) { delete_automaton(aut); return result; } ae->compiled = aut; return result; } /* * Interprets the automaton expression. */ objectptr interpret_automaton(exprptr self, stack_frame_ptr sf) { automaton_expr *ae = self->data; if (!ae->compiled) { objectptr error = compile_automaton(ae, sf); if (is_error(error)) { return error; } delete_object(error); } return make_procedure(self, ae->captures, sf); } /* * Calls the automaton with tape arguments */ objectptr call_automaton(exprptr self, size_t nargs, objectptr *args, stack_frame_ptr sf) { automaton_expr *ae = self->data; automaton_t *aut = ae->compiled; return automaton_run(aut, nargs, args, sf); } objectptr call_automaton_internal(exprptr self, void *args, stack_frame_ptr sf) { automaton_expr *ae = self->data; automaton_t *aut = ae->compiled; return automaton_run_internal(aut, args, sf); } size_t automaton_expr_get_arity(exprptr self) { automaton_expr *ae = self->data; return ae->number_of_tapes; } size_t automaton_expr_get_pn_arity(exprptr self) { automaton_expr *ae = self->data; return ae->number_of_tapes; }
// -*- c -*- #include <stdio.h> #include <stdlib.h> /* Pointer on function which take 1 pointer, an index and return int */ typedef int (*pifii)(int *, int); typedef int (*pifsi)(short *, int); typedef int (*pifci)(char *, int); /* C compilette prototype */ h2_insn_t * gen_Array_St(h2_insn_t * ptr, int wordSize) { #[ int 32 1 Array_St (int[] #(wordSize) 1 a, int 32 1 index) { a[index] = 42; return 1; } ]# return (h2_insn_t *)ptr; } #define CHECK(ARRAY, INDICE, RESULT, LIMIT, VALUE) \ for (int i = 0; i < LIMIT; i++) \ { \ if (INDICE == i) \ { \ if (ARRAY[INDICE] != VALUE) \ { \ RESULT ++; \ } \ } \ else \ { \ if (ARRAY[i] != i) \ { \ RESULT ++; \ } \ } \ } #define PRINTARRAY(MSG, ARRAY, LIMIT)\ printf (MSG); \ for (int i = 0; i < LIMIT; i++) \ { \ printf("%4d ", ARRAY[i]); \ } \ printf ("\n"); int main(int argc, char * argv[]) { h2_insn_t * ptr; int in0, res, resultOK, loopLimit; pifii fPtr32; pifsi fPtr16; pifci fPtr8; int a32[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; short a16[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; char a8[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; if (argc < 2) { printf("Give 1 values\n"); exit(-1); } in0 = atoi (argv[1]); // Get the users values in1 printf ("Size of (bytes) 10 : INTs %d, SHORTs %d, CHARs %d\n", sizeof (a32), sizeof (a16), sizeof (a8)); resultOK = 0; loopLimit = sizeof(a32) / sizeof (int); ptr = h2_malloc (1024); // Allocate memory for 1024 instructions fPtr32 = (pifii) gen_Array_St(ptr, 32); // Generate instructions res = fPtr32(a32, in0); // Call generated code CHECK (a32, in0, resultOK, loopLimit, 42); PRINTARRAY("32 bits : ", a32, loopLimit); ptr = h2_malloc (1024); // Allocate memory for 1024 instructions fPtr16 = (pifsi) gen_Array_St(ptr, 16); // Generate instructions res = fPtr16(a16, in0); // Call generated code PRINTARRAY("16 bits : ", a16, loopLimit); CHECK (a16, in0, resultOK, loopLimit, 42); ptr = h2_malloc (1024); // Allocate memory for 1024 instructions fPtr8 = (pifci) gen_Array_St(ptr, 8); // Generate instructions res = fPtr8(a8, in0); // Call generated code CHECK (a8, in0, resultOK, loopLimit, 42); PRINTARRAY("8 bits : ", a8, loopLimit); if (resultOK == 0) return 0; else return -1; }
import React, {ChangeEvent, useState} from "react"; import ProfileDataForm from "./ProfileDataForm"; import style from "./ProfileInfo.module.css"; import defaultAvatar from "../../../assets/images/avatar.png" import {ContactsType, ProfileType} from "../../../types/types"; import ProfileStatusWithHooks from "./ProfileStatusWithHooks"; import Preloader from "../../../utils/Preloader/Preloader"; export type ProfileInfoPropsType = { profile: ProfileType status: string updateStatus: (status: string) => void isOwner: boolean savePhoto: (photoFile: File) => void saveProfile: (formData: ProfileType, setStatus: any, setSubmitting: any, goToViewMode: any) => void } const ProfileInfo: React.FC<ProfileInfoPropsType> = (props) => { let [editMode, setEditMode] = useState(false) let {profile, saveProfile} = props if (!profile) { return <Preloader/> } let alt_descriptionBlock = `photo_${profile.userId}` const onMainPhotoSelected = (event: ChangeEvent<HTMLInputElement>) => { if (event.target.files?.length) { props.savePhoto(event.target.files[0]) } } const handleSubmit = (formData: ProfileType, setStatus: any, setSubmitting: any, goToViewMode: any) => { saveProfile(formData, setStatus, setSubmitting, goToViewMode) } return ( <div> <div className={style.descriptionBlock}> <img src={profile.photos.large !== null ? profile.photos.large : defaultAvatar} className={style.userPhoto} alt={alt_descriptionBlock} /> <div> {profile.fullName} - userId - {profile.userId} </div> <div> {props.isOwner && <input type={'file'} onChange={onMainPhotoSelected} />} </div> <div className={style.profileBlock}> {editMode ? <ProfileDataForm profile={profile} handleSubmit={handleSubmit} goToViewMode={ () => setEditMode(false)}/> : <ProfileData profile={profile} isOwner={props.isOwner} goToEditMode={ () => setEditMode(true)}/>} <ProfileStatusWithHooks status={props.status} updateStatus={props.updateStatus} isOwner={props.isOwner}/> </div> </div> </div> ) } type ProfileDataPropsType = { profile: ProfileType isOwner: boolean goToEditMode: () => void } const ProfileData: React.FC<ProfileDataPropsType> = ({profile, isOwner, goToEditMode}) => { return ( <div> <div> {isOwner && <button onClick={goToEditMode}>Edit</button> } </div> <div> <b> Full name</b>: {profile.fullName} </div> <div> <b> Looking for a job</b>: {profile.lookingForAJob ? 'yes' : 'no'} </div> {profile.lookingForAJob && <div> <b> My professional skills</b>: {profile.lookingForAJobDescription} </div>} <div> <b> About me</b>: {profile.aboutMe} </div> <div> <b> Contacts</b>: {Object.keys(profile.contacts).map(key => { return <Contacts key={key} contactTitle={key} contactValue={profile.contacts[key as keyof ContactsType]}/> })} </div> </div>) } type ContactsPropsType = { contactTitle: string contactValue: string } const Contacts: React.FC<ContactsPropsType> = ({contactTitle, contactValue}) => { return ( <div className={style.contact}> <b> {contactTitle}</b>: {contactValue} </div>) } export default ProfileInfo
# React Compound Pattern 연습 > React Compound Pattern을 구현하고 적용해보기 위한 프로젝트입니다. [React Compound Pattern 연습](https://master--zesty-nasturtium-afef2b.netlify.app/) ## 목차 - [들어가며](#들어가며) - [프로젝트 소개](#1-프로젝트-소개) - [요구사항](#2-요구사항) - [구조 및 설계](#구조-및-설계) - [프로젝트 구조](#1-프로젝트-구조) - [데이터](#2-데이터) ## 들어가며 ### 1. 프로젝트 소개 이 프로젝트는 원티드에서 진행한 12월 프리온보딩 프론트엔드 챌린지를 통해 배운 리액트 디자인 패턴 중에 Compound Component Pattern을 직접 구현하고 적용해보기 위해 요구사항을 직접 정의하고 개발한 프로젝트입니다. ### 2. 요구사항 프로젝트의 요구사항은 다음과 같습니다. - 음료에 대한 정보를 카드형태로 보여줍니다. - 카드에 들어가는 정보는 이미지, 음료명, 가격, 설명이 포함됩니다. - 하위에는 Add To Cart 버튼을 통해 장바구니에 추가하며, 품절일 경우 Sold Out 버튼을 보여줍니다. ![image](https://github.com/jeehwan-lee/react_compound_pattern/assets/26796099/f918c3ea-62eb-492e-a8e8-d454ce7afebe) - 장바구니 기능은 구현하지 않고 Alert창을 통해 "장바구니에 추가되었습니다" 또는 "품절되었습니다" 라는 문구만 띄워줍니다. - 만약, 음료가 Hot과 Cold 두 가지 종류가 있다면 위 버튼이 아닌 Hot or Cold? 라는 문구를 갖는 버튼을 보여주며, 카드에 가격을 표시하지 않고 드롭다운 형태로 Hot과 Cold의 가격을 표시합니다. - Hot or Cold? 버튼을 클릭하면 드롭다운 형태로 Hot의 가격과 Cold의 가격을 보여줍니다. - Hot 또는 Cold가 품절일 경우 가격 대신 Sold Out 문구를 보여주며, 해당 드롭다운 내용을 클릭할 수 있습니다. ![image](https://github.com/jeehwan-lee/react_compound_pattern/assets/26796099/6a42c779-c143-49be-90ff-8f74c28366c8) - 해당 내용을 클릭하면 Alert창을 통해 "장바구니에 추가되었습니다" 또는 "품절되었습니다" 문구를 띄워줍니다. ## 구조 및 설계 ### 1. 프로젝트 구조 ```bash ├── node_modules ├── public └── src ├── api ├── components ├── card └── container ├── db ├── hook ├── index.js └── App.js ``` ### 2. 데이터 - 데이터는 아래와 같습니다. - subContent는 Hot 과 Cold 종류를 갖는 음료만 갖고 있습니다. - subContent를 갖는 경우, 해당 음료의 price와 soldOut은 null이며, subContent에서 데이터를 갖습니다. ```bash [ { "id": 1, "name": "Espresso", "content": "볶은 커피를 곱게 분쇄하여 고압의 물을 사용하여 짧은 시간 동안 추출한 음료입니다.", "price": "3000", "img": "/img/espresso.png", "soldOut": "N" }, { "id": 2, "name": "Americano", "content": "에스프레소 샷 두 개를 추출해 뜨거운 물을 재빠르게 부어 만든 음료입니다.", "price": null, "img": "/img/americano.png", "soldOut": null, "subContent": [ { "id": 1, "name": "HOT", "price": "3500", "soldOut": "N" }, { "id": 2, "name": "COLD", "price": "4000", "soldOut": "N" } ] }, ... ] ```
export default class HashMap { constructor(hashArray = new Array(16)) { this.hashArray = hashArray; this.loadFactor = 0.75; } // take key (string), produce hash code hash(key) { let hashCode = 0; const primeNumber = 31; for (let i = 0; i < key.length; i++) { hashCode = (primeNumber * hashCode + key.charCodeAt(i)) % this.hashArray.length; } return hashCode; } // set or update value assigned to key set(key, value) { const index = this.hash(key); if (!this.hashArray[index]) { // empty location this.hashArray[index] = [[key, value]]; } else { // collision for (let i = 0; i < this.hashArray[index].length; i++) { if (this.hashArray[index][i][0] === key) { this.hashArray[index][i][1] = value; return; } } // push new pair into bucket this.hashArray[index].push([key, value]); } } // return value that is assigned to key get(key) { const index = this.hash(key); for (let i = 0; i < this.hashArray[index].length; i++) { if (this.hashArray[index][i][0] === key) { return this.hashArray[index][i][1]; } } return null; } // return true or false if key is in hash map has(key) { const keys = this.keys(); for (let i = 0; i < keys.length; i++) { if (keys[i] === key) { return true; } } return false; } // remove value at key, or return false if not found remove(key) { const index = this.hash(key); if (this.hashArray[index]) { for (let i = 0; i < this.hashArray[index].length; i++) { if (this.hashArray[index][i][0] === key) { this.hashArray[index].splice(i, i + 1); return; } } } return false; } // return number of stored keys length() { return this.hashArray.length; } // removes all entries clear() { this.hashArray = new Array(16); } // return array containing all keys keys() { let keyArray = []; let entries = this.entries(); for (let i = 0; i < entries.length; i++) { keyArray.push(entries[i][0]); } return keyArray; } // return array containing all values values() { let valueArray = []; let entries = this.entries(); for (let i = 0; i < entries.length; i++) { valueArray.push(entries[i][1]); } return valueArray; } // return array containing all key/value pairs // [[firstKey, firstValue], [secondKey, secondValue]] entries() { let pairArray = []; for (let i = 0; i < this.hashArray.length; i++) { if (this.hashArray[i]) { for (let j = 0; j < this.hashArray[i].length; j++) { pairArray.push([this.hashArray[i][j][0], this.hashArray[i][j][1]]); } } } return pairArray; } // double size of array when size surpasses loadFactor growBuckets() { const newArray = new Array(this.hashArray.length * 2); const entries = this.entries(); for (let i = 0; i < entries.length; i++) { const key = entries[i][0]; const value = entries[i][1]; const index = this.hash(key); if (!newArray[index]) { // empty location newArray[index] = [[key, value]]; } else { // push new pair into bucket newArray[index].push([key, value]); } } this.hashArray = newArray; } // call growBuckets if hashmap load exceeds loadFactor checkLoad() { let counter = 0; for (let i = 0; i < this.hashArray.length; i++) { if (this.hashArray[i]) { counter++; } } if (counter / this.hashArray.length > this.loadfactor) { console.log('buckets grown'); this.growBuckets(); } } }
import React from "react"; import { FC } from "react"; import { Issue } from "jexp-common"; import { useJiraRecentIssues } from "jexp-api"; import { JiraIssue } from "jexp-api/types"; import styled from "styled-components"; import { DashboardToolbar } from "./DashboardToolbar"; import { useHistory } from "react-router-dom"; import { PulsatingLogo } from "jexp-common"; import { UseFetch } from "use-http"; enum DashboardStatus { Error, InitialLoading, RefreshingContent, Ready, } const getDashboardStatus = ({ error, data, loading }: UseFetch<any>) => { const hasResults = Object.keys(data || {}).length > 0 && data.total > 0; if (error) { return DashboardStatus.Error; } else if (!hasResults && loading) { return DashboardStatus.InitialLoading; } else if (loading) { return DashboardStatus.RefreshingContent; } else { return DashboardStatus.Ready; } }; export const Dashboard: FC = function () { const history = useHistory(); const recentIssuesStatus = useJiraRecentIssues({ persist: true }, []); const dashboardStatus = getDashboardStatus(recentIssuesStatus); const { error: recentIssuesError, data: recentIssuesData, } = recentIssuesStatus; const handleSearchClick = () => { history.push("/search"); }; const handleSettingsClick = () => { history.push("/settings"); }; return ( <> <DashboardToolbar loading={dashboardStatus === DashboardStatus.RefreshingContent} onSearchClick={handleSearchClick} onSettingsClick={handleSettingsClick} /> {dashboardStatus === DashboardStatus.InitialLoading && ( <LoadingWrapper> <PulsatingLogo /> </LoadingWrapper> )} {dashboardStatus === DashboardStatus.Error && ( <ErrorWrapper></ErrorWrapper> )} {(dashboardStatus === DashboardStatus.Ready || dashboardStatus === DashboardStatus.RefreshingContent) && ( <IssuesList> {recentIssuesError && `Error ${recentIssuesError.message}`} {recentIssuesData?.issues?.map((issue: JiraIssue) => ( <Issue data={issue} key={issue.key} /> ))} </IssuesList> )} </> ); }; const IssuesList = styled.div` display: flex; flex-direction: column; overflow: auto; `; const LoadingWrapper = styled.div` display: flex; flex: 1; justify-content: center; align-items: center; `; const ErrorWrapper = styled.div` display: flex; flex: 1; justify-content: center; align-items: center; `;
package com.vishwayan.spring.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.vishwayan.spring.dao.DriverMasterDAO; import com.vishwayan.spring.dao.GenericDAO; import com.vishwayan.spring.model.DriverMaster; @Service("driverMasterService") public class DriverMasterServiceImpl implements DriverMasterService { @Autowired private DriverMasterDAO driverMastersDAO; @Autowired private GenericDAO<DriverMaster> genericDAO; @Override @Transactional public void addDriverMaster(DriverMaster driverMaster) { this.driverMastersDAO.saveDriverMaster(driverMaster); } @Override @Transactional public void updateDriverMaster(DriverMaster driverMaster) { this.driverMastersDAO.updateDriverMaster(driverMaster); } @Override @Transactional public List<DriverMaster> getDriverMasterList() { return this.driverMastersDAO.getDriverMasterList(); } @Override @Transactional public DriverMaster getDriverMasterById(String driverId) { return this.driverMastersDAO.getDriverMaster(driverId); } @Override @Transactional public void removeDriverMaster(String driverId) { this.driverMastersDAO.removeDriverMaster(driverId); } }
import 'package:flutter/material.dart'; import 'package:blurry_modal_progress_hud/blurry_modal_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; class LandingPage extends StatefulWidget { static const routeName = '/landingPage'; const LandingPage({Key? key}) : super(key: key); @override _LandingPageState createState() => _LandingPageState(); } class _LandingPageState extends State<LandingPage> { TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); late bool isLoading = false; @override Widget build(BuildContext context) { return BlurryModalProgressHUD( inAsyncCall: isLoading, blurEffectIntensity: 4, progressIndicator: SpinKitFadingCircle( color: Colors.purple, size: 90.0, ), dismissible: false, opacity: 0.4, color: Colors.black87, child: Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.transparent, automaticallyImplyLeading: false, elevation: 0, centerTitle: true, title: Text( 'SIGN IN', style: TextStyle( fontSize: MediaQuery.of(context).size.width * 0.060, color: Colors.black, fontWeight: FontWeight.bold, ), ), ), body: SingleChildScrollView( child: Column( children: [ SizedBox( height: 40, ), Text( 'Email', ), TextField( controller: emailController, keyboardType: TextInputType.emailAddress, ), Text( 'Password', ), TextField( controller: passwordController, ), Container( height: MediaQuery.of(context).size.height * 0.074, width: MediaQuery.of(context).size.width * 0.68, margin: MediaQuery.of(context).size.width == 320.0 ? EdgeInsets.symmetric( vertical: MediaQuery.of(context).size.height * 0.09) : EdgeInsets.symmetric( vertical: MediaQuery.of(context).size.height * 0.1), child: TextButton( style: TextButton.styleFrom( backgroundColor: Colors.purple, elevation: 4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), )), onPressed: () async { setState(() { isLoading = true; }); await Future.delayed(Duration(seconds: 6), () { setState(() { isLoading = !isLoading; }); }); }, child: Text( 'Login', style: TextStyle( color: Colors.white, fontFamily: 'LibreBaskerville', fontSize: MediaQuery.of(context).size.width * 0.056, ), )), ), ], ), ), ), ); } }
# DIVERSION 2k23 - Ledged <!-- PROJECT LOGO --> <br /> <div align="center"> <a href="https://github.com/IRSHIT033/Ledged/"> <img src="https://user-images.githubusercontent.com/63441472/221374116-f811bcfd-d878-480c-ae07-80909064296d.png" alt="Logo" width="120" height="120"> </a> # Ledged ## Immutable and Decentralized ledgers <b><a align="center" href="https://www.youtube.com/watch?v=AWZpPUwqZ2s">Watch Demo Video</a></b> <br/> <b><a a align="center" href="or-jurm-nahi-b.us">Live</a><b> <p align="center"> Use this readme for getting stared with this project <br /> <a href="https://github.com/arnab2001/Ledged"><strong>docs »</strong></a> <br /> <br /> <a href="#"> Blog </a> · <a href="https://github.com/arnab2001/ledged/issues">Report Issues</a> · <a href="https://github.com/arnab2001/ledged/issues">Request Feature</a> </p> </div> <!-- TABLE OF CONTENTS --> <details> <summary>Table of Contents</summary> <ol> <li> <a href="#about-the-project">About The Project</a> <ul> <li><a href="#built-with">Built With</a></li> </ul> </li> <li> <a href="#getting-started">Getting Started</a> <ul> <li><a href="#prerequisites">Prerequisites</a></li> <li><a href="#installation">Installation</a></li> </ul> </li> <li><a href="#usage">Usage</a></li> <li><a href="#roadmap">Roadmap</a></li> <li><a href="#contributing">Contributing</a></li> <li><a href="#license">License</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#acknowledgments">Acknowledgments</a></li> </ol> </details> <!-- ABOUT THE PROJECT --> ## 🤩🤩About The Project🤩🤩 https://user-images.githubusercontent.com/63441472/221376076-b5807660-1f6f-4e8f-8f20-27afd96658d1.mp4 ### 💭Inspiration : - Currently, Data in centralized systems is at the risk of being easily **tampered/modified** as there is a single entity(central authority) which is controlling them. For example , FIR copies being tampered/deleted or bank information altered by misusers or post morterm reports manipulated , etc. - To solve this problem , we came up with a solution using **blockchain**. - <H4>Usecase :In law enforcement</H4> &nbsp;&nbsp; In the field of law enforcement , it is seen that crucial informations like FIR reports , Post-mortem reports are often **illegally tampered** , by influence or power , to favour a certain side. We can prevent this by using blockchain technology , which is immutable and non-destructable. - <H4>Another Usecase :In banking</H4> &nbsp;&nbsp; Most of banking and their servers are centeralized. This , however unwillingly , gives them supreme authority over our data, including access to our account balance , cheque details , money transfers , etc. Servers are prone to hacking or other data breach issues , also , the centeralized company might not be very trustworthy with our data. This issue is also valid for businesses of all scale. &nbsp;&nbsp;&nbsp;&nbsp; **Blockchain (One of the ways to implement decentralization)** steps into the picture to solve our problems. ### 💡What problem does the project solve? - The project aims to solve the problem of **information manipulation** in public and private sectors. - The **DAPP** helps us to create **customizable** ledgers (records) that are stored in **decentralised blockchain** networks. - Ledged also allows us to upload files using **FileCoin** IPFS - It also enables the user to systematically preview the past ledgers - This makes it immune to tampering or manipulation. * **Transparency** of data is maintained. ### 🙌Overview - In The landing Page, the user will be able to see features of our DAPP and also get started with our ledger - After clicking the **get started** button , the login happens using **Metamask** wallet - The user is redirected to their **profile page** , where they can view their **past ledgers** or **create new ledgers** - At New Ledger page , user can create their **custom fields and data** , and also upload **files** - They are also allowed to preview the file in the **preview section** before finally clicking **Deploy** - The previously created ledgers can be viewed under Previous Ledgers page. ### 💀 Challenges we ran into: - Since blockchain is fairly new technology , we were finding it difficult to get solutions of out bugs due to smaller community. - In the solidity file , i was using a struct of my own , but due to lack of resources , we faced problems initially. - A very recent and major update of **Ether JS** made it very confusing , and we had to go through a lot of documentations ### 🔮 What's Next For Our Project: - Restructuring the view-ledger section for better readibility and better organization - Optimization and minor bug fixes <p align="right">(<a href="#read<img width="191" alt="an_logo_light_temp" src="https://user-images.githubusercontent.com/63441472/190889937-afb28215-5bb5-4115-83d2-f7afb73ef8f8.png"> <me-top">back to top</a>)</p> ### 💻 Built With - <img src = "https://user-images.githubusercontent.com/25181517/183897015-94a058a6-b86e-4e42-a37f-bf92061753e5.png" style="margin-top: 40px" height=30px width=30px > **React** - for building the frontend UI <br> - <img src = "https://user-images.githubusercontent.com/63441472/190888196-9164551f-eb48-4da6-ab91-db17adad7c73.svg" height=30px width=30px>**Vite** - as Module bundler instead of webpack <br> - <img src = "https://user-images.githubusercontent.com/63441472/221376795-45668137-c096-470e-b288-ea98f1728e94.png" height=40px width=40px > **Etherium**- as main blockchain <br> - <img src = "https://user-images.githubusercontent.com/63441472/221376691-706e8087-7ba9-45be-9d60-583b0fdf518d.png" height=40px width=40px> **Solidity**- for writing smart contract <br> - <img src = "https://user-images.githubusercontent.com/63441472/221376973-6ecb124f-12b4-429f-86ac-96afe68d258c.png" height=40px width=40px > **5ire** - RPC to host our dapp and as our main blockchain service<br> - <img src = "https://user-images.githubusercontent.com/63441472/221377772-d474f54c-6049-467c-b830-7c8a220bce5d.png" height=40px width=40px> **Filecoin**- as IPFS<br> - <img src = "https://user-images.githubusercontent.com/63441472/190890501-54045447-d458-4413-a1fa-91a4216bfb44.svg" height=40px width=80px> - Build on Top of **Polygon** chain <br> - GoDaddy for our domain registry <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- GETTING STARTED --> ## Getting Started For setting up your project locally, follow these simple steps. ### Prerequisites You must have NPM(Node Package Manager) installed in your system , If you dont we got you covered [Install NPM](https://phoenixnap.com/kb/install-node-js-npm-on-windows) ### Installation _How to setup this project_ 1. Clone the repo ```sh git clone https://github.com/arnab2001/Ledged.git ``` 3. Install all the NPM packages ```sh npm install ``` 4. configure `.env` and add ```env DB_CONNECT = 'mongodb+srv://<username>:<password>@cluster0.dehf4yw.mongodb.net/?retryWrites=true&w=majority' ``` 5. Create a wallet.json file and add your public and private key ```json { "privateKey": "<private_key>", "publicKey": "<public_key>" } ``` 6. Then import wallet using the private key, use the following command ```sh Metamask ``` 7. run ```sh npm start dev ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- USAGE EXAMPLES ## Usage <div align="center"> <img src="https://media2.giphy.com/media/UYpelo7WbjZQg0dDQY/200.gif" width="500" height="200" /> </div> <p align="right">(<a href="#readme-top">back to top</a>)</p> --> <!-- ROADMAP --> ## Roadmap &nbsp; - [x] landing page - [x] Avatar component - [x] Ledger page - [x] PastLedger page - [x] Adding smart contract - [x] Intigrate 5ire - [x] Intigrate filecoin - [x] Add backend for Autosave - [ ] deploy in digital ocean See the [open issues](https://github.com/arnab2001/Ledged/issues) for a full list of proposed features (and known issues). <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- CONTRIBUTING --> ## Contributing If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "improvement". Don't forget to star this project!! 1. Fork the Project 2. Create your Feature Branch (`git checkout -b feature/Feature1`) 3. Commit your Changes (`git commit -m 'Add Feature 1'`) 4. Push to the Branch (`git push origin feature/Feature1`) 5. Open a Pull Request <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- LICENSE --> ## License Distributed under the MIT License <p align="right">(<a href="#readme-top">back to top</a>)</p> <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- ACKNOWLEDGMENTS --> ## Contributors <br> <div> <h1 align="center"> <b>Made with ❤️ by team Bugbyte <h1> <a href="https://github.com/arnab2001/Ledged/contributors"> <img src="https://contrib.rocks/image?repo=arnab2001/ledged&&max=817" /> </a> </div> <!-- MARKDOWN LINKS & IMAGES --> <!-- https://www.markdownguide.org/basic-syntax/#reference-style-links --> [contributors-shield]: https://img.shields.io/github/contributors/othneildrew/Best-README-Template.svg?style=for-the-badge [contributors-url]: https://github.com/othneildrew/Best-README-Template/graphs/contributors [forks-shield]: https://img.shields.io/github/forks/othneildrew/Best-README-Template.svg?style=for-the-badge [forks-url]: https://github.com/othneildrew/Best-README-Template/network/members [stars-shield]: https://img.shields.io/github/stars/othneildrew/Best-README-Template.svg?style=for-the-badge [stars-url]: https://github.com/othneildrew/Best-README-Template/stargazers [issues-shield]: https://img.shields.io/github/issues/othneildrew/Best-README-Template.svg?style=for-the-badge [issues-url]: https://github.com/othneildrew/Best-README-Template/issues [license-shield]: https://img.shields.io/github/license/othneildrew/Best-README-Template.svg?style=for-the-badge [license-url]: https://github.com/othneildrew/Best-README-Template/blob/master/LICENSE.txt [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555 [linkedin-url]: https://linkedin.com/in/othneildrew [product-screenshot]: images/screenshot.png [Next.js]: https://img.shields.io/badge/next.js-000000?style=for-the-badge&logo=nextdotjs&logoColor=white [Next-url]: https://nextjs.org/ [React.js]: https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB [React-url]: https://reactjs.org/ [Node.js]: https://img.shields.io/badge/Node.js-35495E?style=for-the-badge&logo=nodedotjs&logoColor=4FC08D [Vue-url]: https://vuejs.org/ [Express]: https://img.shields.io/badge/Express-35495E?style=for-the-badge&logo=express&logoColor=white [Angular-url]: https://angular.io/ [Svelte.dev]: https://img.shields.io/badge/Svelte-4A4A55?style=for-the-badge&logo=svelte&logoColor=FF3E00 [Svelte-url]: https://svelte.dev/ [Laravel.com]: https://img.shields.io/badge/Laravel-FF2D20?style=for-the-badge&logo=laravel&logoColor=white [Laravel-url]: https://laravel.com [Bootstrap.com]: https://img.shields.io/badge/Bootstrap-563D7C?style=for-the-badge&logo=bootstrap&logoColor=white [Bootstrap-url]: https://getbootstrap.com [JQuery.com]: https://img.shields.io/badge/jQuery-0769AD?style=for-the-badge&logo=jquery&logoColor=white [JQuery-url]: https://jquery.com
'use client' import { skills } from "@/skills"; import styles from "./Skills.module.css"; import ArrowBackIcon from '@mui/icons-material/ArrowBackIos'; import ArrowForwardIcon from '@mui/icons-material/ArrowForwardIos'; import { TtButton } from "@/app/TtButton/TtButton"; import { useContext, useEffect, useRef, useState } from "react"; import { SkillEntry } from "./SkillEntry"; import { TooltipContext } from "@/app/Providers"; export const SkillCarousel=()=>{ const context=useContext(TooltipContext) const ssStorage=context.state.sessionStorage const [currentSkill,setCurrentSkill]=useState(parseInt(ssStorage?.getItem("skill")||0)) const skill=skillList[currentSkill] const [upDown,setUpDown]=useState(null) const [delayTransition,setDelayTranstition]=useState(true) const [swipeDir,setSwipeDir]=useState(null) const container=useRef(null) const skillContent=useRef(null) const touchStartX=useRef(null) const cycleSkill=(upDown)=>{ const ind=getInd(upDown) setCurrentSkill(ind) setDelayTranstition(true) ssStorage.setItem("skill",ind) setUpDown(upDown>0) } const getInd=(upDown)=>{ if(upDown+currentSkill>=skillList.length) return 0; if(upDown+currentSkill<0) return skillList.length-1; return upDown+currentSkill; } const setTouchStart = ({touches}) => touchStartX.current=touches[0].clientX const followTouch = ({touches}) => { const delta=touches[0].clientX-touchStartX.current skillContent.current.style.transform=`translateX(${delta}px)` skillContent.current.style.transition="none" if(Math.abs(delta)<swipeThreshold){ useSwipeDir.current(null) return; } if(delta<0) useSwipeDir.current(1) else useSwipeDir.current(-1) } const useSwipeDir=useRef(setSwipeDir) const swipe = ({changedTouches}) => { const delta=touchStartX.current-changedTouches[0].clientX skillContent.current.style.transform="none" touchStartX.current=null useSwipeDir.current(null) if(Math.abs(delta)<swipeThreshold){ skillContent.current.style.transition=".25s transform" return; } if(delta<0) useCycle.current(1) else useCycle.current(-1) } const useCycle=useRef(cycleSkill) useEffect(()=>{ container.current.addEventListener("touchstart",setTouchStart) container.current.addEventListener("touchmove",followTouch) container.current.addEventListener("touchend",swipe) },[]) useEffect(()=>{ useCycle.current=cycleSkill useSwipeDir.current=setSwipeDir }) useEffect(()=>{ /** * no transition if css prop changed on render; need to delay setting * elem style filter:(rotateHue n deg) for hue transition; * cannot hardcode as keyframes in css module because deg is dynamic */ setTimeout(()=>{setDelayTranstition(false)},250) },[currentSkill]) return( <div ref={container} className={styles.container}> <h1 key={`${skill}_header`} className={`${styles.skillHeader} ${styles[upDown?"slideRight":"slideLeft"]}`} > {skill} </h1> <TtButton className={`${styles.cycleButton}${swipeDir<0?" "+styles.swiping:""}`} onClick={()=>cycleSkill(-1)} icon=<ArrowBackIcon/> tooltip="Previous" /> <div className={styles.SkillsContainer}> <div ref={skillContent} className={styles.skillContent}> { skills[skill].map((entry,ind) => <SkillEntry key={`${entry.name}_entry`} {...{ entry, ind, upDown, delayTransition }} /> )} </div> </div> <TtButton className={`${styles.cycleButton}${swipeDir>0?" "+styles.swiping:""}`} onClick={()=>cycleSkill(1)} icon=<ArrowForwardIcon/> tooltip="Next" /> </div> ) } const skillList=Object.keys(skills) const swipeThreshold=100
import { createReducer, on } from "@ngrx/store"; import { CatBreed, CatBreedImage } from "../../models/breed.model"; import { breedsLoaded, catsImagesLoaded } from "./cats-api.actions"; export interface CatPageState { breeds: CatBreed[]; catsImages: CatBreedImage[]; } export const initialState: CatPageState = { breeds: [], catsImages: [], }; export const catsApiReducer = createReducer( initialState, on(breedsLoaded, (state, action) => { return { ...state, breeds: action.breeds, } }), on(catsImagesLoaded, (state, action) => { return { ...state, catsImages: action.images, } }), );
/*⦁ Devuelve el número total de alumnas que hay.*/ SELECT COUNT(a.id_alumno) FROM `alumno_se_matricula_asignatura` a INNER JOIN persona p ON p.id = a.id_alumno WHERE p.sexo LIKE 'M'; /* ⦁ Calcula cuántos alumnos nacieron en 1999.*/ SELECT COUNT(a.id_alumno) FROM `alumno_se_matricula_asignatura` a INNER JOIN persona p ON p.id = a.id_alumno WHERE YEAR(p.fecha_nacimiento) = '1999'; /* ⦁ Calcula cuántos profesores hay en cada departamento. El resultado sólo debe mostrar dos columnas, una con el nombre del departamento y otra con el número de profesores que hay en ese departamento. El resultado sólo debe incluir los departamentos que tienen profesores asociados y deberá estar ordenado de mayor a menor por el número de profesores.*/ SELECT d.nombre, COUNT(p.id_profesor) FROM departamento d RIGHT JOIN profesor p ON p.id_departamento = d.id GROUP BY d.id ORDER BY COUNT(p.id_profesor) DESC; /* ⦁ Devuelve un listado con todos los departamentos y el número de profesores que hay en cada uno de ellos. Tenga en cuenta que pueden existir departamentos que no tienen profesores asociados. Estos departamentos también tienen que aparecer en el listado. */ SELECT d.nombre, COUNT(p.id_profesor) FROM departamento d LEFT JOIN profesor p ON p.id_departamento = d.id GROUP BY d.id; /* ⦁ Devuelve un listado con el nombre de todos los grados existentes en la base de datos y el número de asignaturas que tiene cada uno. Tenga en cuenta que pueden existir grados que no tienen asignaturas asociadas. Estos grados también tienen que aparecer en el listado. El resultado deberá estar ordenado de mayor a menor por el número de asignaturas.*/ SELECT g.nombre, COUNT(a.id) FROM grado g LEFT JOIN asignatura a ON a.id_grado = g.id GROUP BY g.id ORDER BY COUNT(a.id) DESC; /* ⦁ Devuelve un listado con el nombre de todos los grados existentes en la base de datos y el número de asignaturas que tiene cada uno, de los grados que tengan más de 40 asignaturas asociadas.*/ SELECT g.nombre, COUNT(a.id) FROM grado g LEFT JOIN asignatura a ON a.id_grado = g.id GROUP BY g.id HAVING COUNT(a.id) > 40; /* ⦁ Devuelve un listado que muestre el nombre de los grados y la suma del número total de créditos que hay para cada tipo de asignatura. El resultado debe tener tres columnas: nombre del grado, tipo de asignatura y la suma de los créditos de todas las asignaturas que hay de ese tipo.*/ SELECT g.nombre, a.tipo, SUM(a.creditos) FROM grado g LEFT JOIN asignatura a ON a.id_grado = g.id GROUP BY a.tipo; /* ⦁ Devuelve un listado que muestre cuántos alumnos se han matriculado de alguna asignatura en cada uno de los cursos escolares. El resultado deberá mostrar dos columnas, una columna con el año de inicio del curso escolar y otra con el número de alumnos matriculados. */ SELECT c.anyo_inicio, COUNT(a.id_alumno) FROM curso_escolar c LEFT JOIN alumno_se_matricula_asignatura a ON a.id_curso_escolar = c.id GROUP BY c.anyo_inicio; /* ⦁ Devuelve un listado con el número de asignaturas que imparte cada profesor. El listado debe tener en cuenta aquellos profesores que no imparten ninguna asignatura. El resultado mostrará cinco columnas: id, nombre, primer apellido, segundo apellido y número de asignaturas. El resultado estará ordenado de mayor a menor por el número de asignaturas. */ SELECT p.id_profesor, COUNT(a.id) FROM profesor p LEFT JOIN asignatura a ON p.id_profesor = a.id_profesor GROUP BY p.id_profesor ORDER BY (a.id) DESC;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cameron's Portfolio</title> <link rel="stylesheet" href="./assets/css/style.css" /> </head> <body> <!-- Header starts--> <header> <h1> <a href="/">Cameron Sickler</a> <!-- need to style header h1 a--> </h1> <!-- nav begins here--> <nav> <!--need to style nav | nav ul li | nav ul li a as seperate css styles?--> <ul> <li> <a href="#about-me">About Me</a> </li> <li> <a href="#work">Work</a> </li> <li> <a href="#contact-me">Contact Me</a> </li> <li> <a href="#resume">Resume</a> </li> </ul> </nav> </header> <!--Header Ends--> <!-- Hero section begins here--> <section class="hero"> <div class="hero-quote"> <h3>Welcome to my portfolio page!</h3> </div> </section> <!-- hero section ends--> <!-- About Me container start--> <section id="about-me"> <div class="section-titles"> <h3>About Me</h3> <!-- need class for all of our h3 link item text here --> <!-- about me bio text begins here--> </div> <!-- might need class for container styles here--> <div class="bio"> <img class="portfolio-pic" src="./assets/images/profile-picture.jpg" alt="Cameron smiling" /> <p class="portfolio-text">My name is Cameron Sickler. I am a web devoloper in the making. My education history includes a Bachelor's Degree in Organizational Communication and a minor in Information Systems. Upon achieving a full stack web developer certification, I will be fully prepared to apply all my aquired skills towards a successful and meaningful career!</p> </div> </section> <!-- About Me container end--> <!-- Work container start--> <section id="work"> <!--need class for all section styles here--> <div class="section-titles"> <!-- need class for all of our link item containers here--> <h3>Work</h3> <!-- need class for all of our h3 link item text here --> </div> <!--RunBuddy work project start--> <div class="projects"> <!-- need class here for work item description container--> <div class="project1-container"> <a href="https://CameronSickler.github.io/run-buddy/"> <img class="project1-pic" src="./assets/images/run-buddy.jpg" alt="run buddy" /> <span class="project1-text"> <!--Need class here to style h4 & h5text here--> <h4>Run Buddy</h4> <h5>Made with HTML & CSS</h5> </span> </a> </div> <!--RunBuddy work project end--> <!-- Other work projects start--> <div class="other-projects-container"> <a class="other-project" href="https://CameronSickler.github.io/robotco/" alt="Robotco"> <img class="other-project-pic" src="./assets/images/robotco.jpg" alt="robotco" /> <span class="other-project-text"> <h4>Robotco</h4> <h5>Made with HTML & CSS</h5> </span> </a> <a class="other-project" href="https://github.com/patrickarcher414/meal-maker" alt="Meal Maker"> <img class="other-project-pic" src="./assets/images/meal-maker.jpg" alt="meal maker" /> <span class="other-project-text"> <h4>Meal Maker</h4> <h5>Made with HTML, Materialize, Javascript, and web APIs</h5> </span> </a> <a class="other-project" href="https://codingnkobolds.herokuapp.com/" alt="Coding N Kobolds"> <img class="other-project-pic" src="./assets/images/dog-field.jpg" alt="dog in a field" /> <span class="other-project-text"> <h4>Coding N Kobolds</h4> <h5>Made with Javascript, HTML, CSS, Sequelize, and various NPM packages</h5> </span> </a> <a class="other-project" href="https://gather-the-magic.herokuapp.com/" alt="Gather The Magic"> <img class="other-project-pic" src="./assets/images/frozen-lake.jpg" alt="frozen lake" /> <span class="other-project-text"> <h4>Gather The Magic</h4> <h5>Made with MongoDB, React, GraqphQL, Node.js, and Express.js </h5> </span> </a> </div> </div> <!--Other work projects ends--> </section> <!-- Work section end--> <!-- Contact Me section start--> <section id="contact-me"> <!--need class for all section styles here--> <div class="section-titles"> <!-- need class for all of our link item containers here--> <h3>Contact Me</h3> <!-- need class for all of our h3 link item text here --> </div> <footer> <!-- contains links and needs class styles similar to nav--> <ul> <li> <a href="linkedin.com/in/cameron-sickler-a17764106">LinkedIn</a> </li> <li> <p class=>Phone Number *Private*</p> </li> <li> <a href="https://github.com/CameronSickler/">GitHub</a> </li> </ul> </footer> </section> <!--Contact Me section end--> </body> </html>
import { Ciudad } from '../ciudad/ciudad'; import { CulturaCulinaria } from '../culturaculinaria/culturaculinaria'; import { Region } from '../region/region'; import { Ubicacion } from '../ubicacion/ubicacion'; import { Pais } from './pais'; export class PaisDetail extends Pais { ciudades: Array<Ciudad> = []; regiones: Array<Region> = []; culturasCulinarias: Array<CulturaCulinaria> = []; /** * Constructor de PaisDetail * @param id * @param nombre * @param ubicacion * @param ciudades * @param regiones * @param culturasCulinarias */ constructor( public id: number, public nombre: string, public ubicacion: Ubicacion, ciudades: Ciudad[], regiones: Region[], culturasCulinarias: CulturaCulinaria[] ) { super(id, nombre, ubicacion); this.ciudades = ciudades; this.regiones = regiones; this.culturasCulinarias = culturasCulinarias; } }
<?php declare(strict_types=1); namespace App\Tests\Feature\Http\Controller; use App\Domain\Document\Company\Company; use App\Domain\Document\Invitation; use App\Domain\Document\Role\Role; use App\Infrastructure\Repository\InvitationRepository; use App\Tests\Feature\BaseTestCase; class InvitationControllerTest extends BaseTestCase { /** * @group smoke */ public function testItShowsInvitationList(): void { self::$client->request('GET', '/onboarding/invitation'); self::assertResponseIsSuccessful(); self::assertSelectorExists('onboarding-invitation-list'); } /** * @group smoke */ public function testItListsInvitation(): void { self::$client->request('GET', '/onboarding/invitation/list'); $this->assertGridResponse(); } public function testItAllowsToDeleteAInvitation(): void { /** @var Invitation $testInvitation */ $testInvitation = self::$fixtures['invitation_test']; self::$client->request('DELETE', sprintf('/onboarding/invitation/%s/delete', $testInvitation->getId())); self::assertResponseIsSuccessful(); $testInvitation = $this->getDocumentManager()->find(Invitation::class, $testInvitation->getId()); self::assertInstanceOf(Invitation::class, $testInvitation); self::assertTrue($testInvitation->isDeleted()); } public function testItCreatesInvitation(): void { /** @var Role $role */ $role = self::$fixtures['test_role_1']; /** @var Company $company */ $company = self::$fixtures['test_company_1']; self::$client->request('GET', '/onboarding/invitation/create'); self::assertResponseIsSuccessful(); self::assertSelectorTextContains('html', 'Create invitation'); self::$client->submitForm('Submit', [ 'invitation' => [ 'email' => 'test@test.com', 'invitationCode' => 'test', 'company' => $company->getId(), 'roles' => [$role->getId()], ], ]); $invitation = self::getContainer()->get(InvitationRepository::class)->findOneBy(['email' => 'test@test.com']); self::assertInstanceOf(Invitation::class, $invitation); } }
<template> <TodoTabs/> <div class="relative"> <Transition name="all-animation"> <TransitionGroup name="todos" tag="ul" class="section-container relative" v-if="todoStore.tab === 'all'"> <TodoItem v-for="todo in todoStore.todos" :key="todo.id" :id="todo.id" :title="todo.title" :is-complete="todo.isComplete"/> </TransitionGroup> </Transition> <Transition name="completed-animation"> <TransitionGroup name="todos" tag="ul" class="section-container relative" v-if="todoStore.tab === 'completed'"> <TodoItem v-for="todo in todoStore.completedTodos" :key="todo.id" :id="todo.id" :title="todo.title" :is-complete="todo.isComplete"/> </TransitionGroup> </Transition> <Transition name="incomplete-animation"> <TransitionGroup name="todos" tag="ul" class="section-container relative" v-if="todoStore.tab === 'incomplete'"> <TodoItem v-for="todo in todoStore.incompleteTodos" :key="todo.id" :id="todo.id" :title="todo.title" :is-complete="todo.isComplete"/> </TransitionGroup> </Transition> </div> <Transition name="no-todos-animation"> <NoTodo/> </Transition> </template> <script setup> // import { watchEffect } from 'vue' import { useTodoStore } from "../stores/todoStore" import TodoItem from "./TodoItem.vue" import TodoTabs from "./TodoTabs.vue"; import NoTodo from "./NoTodo.vue"; const todoStore = useTodoStore() // ovde napisati logiku da se switchuje na all tabu kada nema todosa u complete i pending // watchEffect(() => { // if (todoStore.completedTodos.length === 0 || todoStore.incompleteTodos.length === 0) { // todoStore.tab = 'all'; // } // }) </script> <style> /* adding todos */ .todos-enter-from { opacity: 0; transform: scale(0.7); } .todos-enter-to { opacity: 1; transform: scale(1); } .todos-enter-active, .todos-leave-active, .todos-move { transition: all 0.2s; } .todos-leave-active { position: absolute; left:16px; right: 16px;} .todos-leave-from { opacity: 1; transform: scale(1); } .todos-leave-to { opacity: 0; transform: scale(0.7); } /* switching tabs animation */ .all-animation-enter-from, .completed-animation-enter-from, .incomplete-animation-enter-from, .no-todos-animation-enter-from { opacity: 0; transform: scale(0.7); } .all-animation-enter-to, .completed-animation-enter-to, .incomplete-animation-enter-to, .no-todos-animation-enter-to { opacity: 1; transform: scale(1); } .all-animation-leave-from, .completed-animation-leave-from, .incomplete-animation-leave-from, .no-todos-animation-leave-from { opacity: 1; transform: scale(1); } .all-animation-leave-to, .completed-animation-leave-to, .incomplete-animation-leave-to, .no-todos-animation-leave-to { opacity: 0; transform: scale(0.7); } .all-animation-enter-active, .all-animation-leave-active, .completed-animation-enter-active, .completed-animation-leave-active, .incomplete-animation-enter-active, .incomplete-animation-leave-active, .no-todos-animation-enter-active, .no-todos-animation-leave-active { transition: all 0.3s; } .all-animation-leave-active, .completed-animation-leave-active, .incomplete-animation-leave-active, .no-todos-animation-leave-active { position: absolute; left:16px; right: 16px; top: 0; } </style>
/** * * takeUntil(arr, callbackF) takes in an array and a callback function and returns a new array with content, up until it satifies the callback function condition * * @param {Array} arr - the array we will use to apply our callback function on * @param {Object} callbackF - the callback function we will invoke on the array * @returns {Array} - a new array */ //takeUntil const takeUntil = function(arr, callbackF) { const result = []; // Apply callback function to each item in the array // Once callback function returns true, stop looping // Otherwise add item to result array for (let item of arr) { if (callbackF(item)) { return result; } result.push(item); } return result; }; module.exports = takeUntil;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP and For Loops</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> </head> <body> <div class = "container"> <div class = "row"> <?php function getUsers(){ $url = "https://jsonplaceholder.typicode.com/users"; $data = file_get_contents($url); return json_decode($data, true); } $users = getUsers(); for($i = 0; $i<count($users); $i++){ echo '<div class="container text-center"> <div class="row justify-content-center"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">' .$users[$i]['name']. '</div></h5> <h6 class="card-subtitle mb-2 text-body-secondary">'.$users[$i]['username']. '</h6> <p class="card-text">' .$users[$i]['address']['street'].'</p> <p class="card-text">' .$users[$i]['address']['suite'].'</p> <p class="card-text">' .$users[$i]['address']['city'].'</p> <p class="card-text">' .$users[$i]['address']['zipcode'].'</p> <a href="#" class="card-link">'.$users[$i]['email'].'</a> <a href="#" class="card-link"> <button class="btn btn-primary" type="submit">'.$users[$i]['website'].'</button></a> </div> </div> </div> </div>'; } //echo '<pre>'; //echo print_r($users); //echo '</pre>' ?> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </body> </html>
import { useState, useEffect, useRef, RefObject } from "react"; import { Container, CssBaseline, Box } from "@material-ui/core"; import { useSocketConnection } from "./hooks"; import { MessageInput, MessagesList } from "./components"; import "./_index.scss"; import { IMessage } from "./models"; const Chat = () => { const [messages, setMessages] = useState<IMessage[]>([]); const listScrollRef = useRef(null); const onMessageReceived = (message: IMessage) => { setMessages((prevState) => [...prevState, message]); }; const { socket } = useSocketConnection({ onMessageReceived }); useEffect(() => { if (listScrollRef.current) { (listScrollRef as RefObject<HTMLElement>).current?.scrollIntoView({ behavior: "smooth", block: "start" }); } }, [messages]); return ( <Container component="main" maxWidth="md" className="chat-layout"> <CssBaseline /> <Box className="chat-layout__body"> <MessagesList messages={messages} listScrollRef={listScrollRef} /> <MessageInput socket={socket} /> </Box> </Container> ); }; export default Chat;
{% extends 'layouts/navbar.html' %} {% load static %} {% block content %} <!-- Estilos CSS --> <link rel="stylesheet" href="{% static 'vendors/feather/feather.css' %}" /> <link rel="stylesheet" href="{% static 'vendors/ti-icons/css/themify-icons.css' %}" /> <link rel="stylesheet" href="{% static 'vendors/css/vendor.bundle.base.css' %}" /> <link rel="stylesheet" href="{% static 'vendors/datatables.net-bs4/dataTables.bootstrap4.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'js/select.dataTables.min.css' %}" /> <link rel="stylesheet" href="{% static 'css/vertical-layout-light/style.css' %}" /> <link rel="stylesheet" href="{% static 'vendors/mdi/css/materialdesignicons.min.css' %}" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="https://cdn.datatables.net/v/dt/dt-1.10.25/datatables.min.js"></script> <script src="{% static 'js/reservas.js' %}"></script> <style> .fecha-cita-button { cursor: pointer; background-color: #007bff; color: #fff; border: 1px solid #007bff; border-radius: 4px; padding: 8px 12px; text-align: center; transition: background-color 0.3s; } .fecha-cita-button:hover { background-color: #0056b3; } </style> <!-- Contenido principal --> <div class="row"> <div class="col-lg-12 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <h4 class="card-title">Mis Reservas</h4> <div class="table-responsive"> <table id="reservaTable" class="table table-hover row-border" style="width:100%"> <thead> <tr> <th>Usuario</th> <th>Fecha Reserva</th> <th>Descripción</th> <th>Estado</th> </tr> </thead> <tbody> {% for reserva in reservas %} <tr> <td>{{ reserva.usuario.nombre }}</td> <td> <label class="badge badge-info hover-cursor editarfechacita" data-reserva-id="{{ reserva.id }}">{{ reserva.fecha_cita }}</label> </td> <td>{{ reserva.descripcion }}</td> <td> <label class="badge badge-outline-primary hover-cursor change-estado" data-reserva-id="{{ reserva.id }}" {% if reserva.estado == 'Completada' or reserva.estado == 'Cancelada' %}style="pointer-events: none; color: grey;"{% endif %} > {{ reserva.estado }} </label> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> <script> $(document).ready(function () { if ($.fn.DataTable.isDataTable('#reservaTable')) { $('#reservaTable').DataTable().destroy(); } var dataTableConfig = { "lengthChange": false, "pageLength": 5, "searching": true, "language": { "search": "Buscar:", "zeroRecords": "No se encontraron resultados", "info": "Mostrando _START_ a _END_ de _TOTAL_ registros", "infoEmpty": "Mostrando 0 a 0 de 0 registros", "infoFiltered": "(filtrados de _MAX_ registros en total)", "paginate": { "first": "Primero", "last": "Último", "next": "Siguiente", "previous": "Anterior" } }, "dom": '<"top"lf>rt<"bottom"ip>', }; $('#reservaTable').DataTable(dataTableConfig); $('#reservaTable').on('click', 'td .change-estado', function () { var reserva_id = $(this).data('reserva-id'); var estado_actual = $(this).text().trim(); // Verificar si el estado es "Completada" o "Cancelada" if (estado_actual === 'Completada' || estado_actual === 'Cancelada') { return; // Salir de la función si no se permite la edición } console.log("ID de la reserva:", reserva_id); // Imprime el ID de la reserva en la consola Swal.fire({ title: '¿Estás seguro de cambiar estado?', html: '<h3>Esta opcion no es reversible</h3>'+' <input type="hidden" name="" id="estadoSelect" value="Cancelada">', icon: 'info', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Cambiar', preConfirm: () => { var nuevoEstado = $('#estadoSelect').val(); return fetch("{% url 'reservas:cambiar_estado_reserva' %}", { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'estado': nuevoEstado, 'reserva_id': reserva_id // Añadir el ID de la reserva al cuerpo de la petición }), }) .then(response => { if (!response.ok) { throw new Error('Hubo un problema al cambiar el estado.'); } return response.json(); }) .catch(error => { Swal.showValidationMessage(`Request failed: ${error}`); }); }, }).then((result) => { if (result.isConfirmed) { Swal.fire('¡Estado cambiado!', 'El estado de la reserva se ha cambiado correctamente.', 'success').then(() => { location.reload(); }); } }); }); }); </script> <script> $(document).ready(function () { $('#reservaTable').on('click', 'td .editarfechacita', function () { var reserva_id = $(this).data('reserva-id'); var fecha_cita = $(this).text().trim(); // Crear el campo de fecha y hora con Flatpickr var flatpickrInput = $('<input>').attr({ type: 'text', id: 'swal-input1', class: 'swal2-input', }); // Mostrar la alerta de SweetAlert para editar la fecha y hora Swal.fire({ title: 'Editar Fecha y Hora de Cita', html: flatpickrInput[0], showCancelButton: true, confirmButtonText: 'Guardar', cancelButtonText: 'Cancelar', allowOutsideClick: false, preConfirm: () => { return flatpickrInput.val(); }, didOpen: () => { // Inicializar Flatpickr en el campo de entrada flatpickr(flatpickrInput[0], { enableTime: true, dateFormat: 'Y-m-d H:i', // Formato de fecha y hora }); } }).then((result) => { if (result.isConfirmed) { // Obtener la nueva fecha y hora ingresada por el usuario var nueva_fecha = flatpickrInput.val(); // Realizar la petición para actualizar la fecha y hora de la reserva fetch("{% url 'reservas:cambiar_fecha_reserva' %}", { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'fecha_cita': nueva_fecha, 'reserva_id': reserva_id }), }) .then(response => { if (!response.ok) { throw new Error('Hubo un problema al cambiar la fecha de la reserva.'); } return response.json(); }) .then(data => { if (data.success) { // Mostrar una alerta de éxito Swal.fire('¡Fecha y Hora cambiadas!', 'La fecha y hora de la reserva se han cambiado correctamente.', 'success').then(() => { // Recargar la página o realizar alguna otra acción location.reload(); }); } else { // Mostrar una alerta de error si no se pudo cambiar la fecha y hora Swal.fire('Error', 'Hubo un problema al cambiar la fecha y hora de la reserva. Por favor, inténtelo de nuevo más tarde.', 'error'); } }) .catch(error => { // Mostrar una alerta de error si hubo un problema con la petición Swal.fire('Error', 'Hubo un problema al procesar su solicitud. Por favor, inténtelo de nuevo más tarde.', 'error'); console.error('Error:', error); }); } }); }); }); </script> {% if not request.session.usuario_id %} <script> window.location.href = "{% url 'usuarios:requestLogin' %}"; </script> {% elif "Listar Mis Reservas" not in request.session.permisos %} <script> window.location.href = "{% url 'usuarios:requestLogin' %}"; </script> {% endif %} {% endblock %}
import { FaAmazon, FaApple, FaCheckCircle, FaChevronRight, FaGoogle, FaSlack, FaSpotify, } from "react-icons/fa"; import { FaPhoneFlip, FaUserDoctor } from "react-icons/fa6"; import { IoCalendarNumberSharp } from "react-icons/io5"; import { MdEmail } from "react-icons/md"; import { SiNotion } from "react-icons/si"; import { useState } from "react"; import { format } from "date-fns"; import {speciality} from "@/manifest.json"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { Calendar } from "@/components/ui/calendar"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; function Hero() { const [date, setDate] = useState<Date>(); return ( <> <div className="min-h-lvh bg-heroGradient pt-40 px-24"> {/* Start Hero */} <section className="w-full flex flex-row gap-5"> <div className="w-1/2 flex flex-col gap-10 relative z-20"> {/* Start Title of the hero */} <h1 className="text-5xl font-semibold leading-snug capitalize"> Your <span className="gradient-text">trusted partner</span> <br />{" "} in digital healthcare. </h1> {/* End Title of the hero */} {/* Start para */} <p className="text-xl font-normal leading-normal"> <span className="text-blues-500">Empowering Your Health </span>at Every Step. Experience personalized medical care from the comfort of your home. Connect with{" "} <span className="text-blues-500">certified doctors</span>, or manage prescriptions, and schedule appointments with ease. Ready to take control of your health?{" "} <a className="text-blues-500 cursor-pointer" href="/"> Get Started </a>{" "} or{" "} <a className="text-blues-500 cursor-pointer" href="/"> Book an Appointment today. </a> </p> {/* End para */} {/* Start Button fo Booking appe */} <Button variant={"outline"} size={"lg"} className="w-1/2 bg-gradient-to-r from-[#98ddff] to-[#0095DE] text-white text-xl p-8 gap-5 hover:text-white" > Book an appointment <FaChevronRight /> </Button> <div className="space-y-5"> <h1 className="text-xl text-[#4c4c4d] font-semibold"> Trusted by thousands of doctors and millions of patients : </h1> <div className="inline-flex gap-5 items-center justify-between "> <FaAmazon size={35} className="text-[#4c4c4d]" /> <FaApple size={35} className="text-[#4c4c4d]" /> <FaGoogle size={35} className="text-[#4c4c4d]" /> <SiNotion size={35} className="text-[#4c4c4d]" /> <FaSpotify size={35} className="text-[#4c4c4d]" /> <FaSlack size={35} className="text-[#4c4c4d]" /> </div> </div> {/* End Button fo Booking oppe */} </div> <div className="w-1/2 flex items-center justify-center relative"> <img src="/doc1.png" alt="doc1" /> <img src="/testo.svg" alt="testo 1" className="absolute -bottom-20 translate-x-24 z-20" /> <img src="/positivePoint.svg" alt="positive point" className="absolute bottom-28 -translate-x-52 z-20" /> <img src="/rates.svg" alt="rates" className="absolute bottom-28 translate-x-52 z-20" /> </div> </section> {/* End Hero */} </div> {/* Start Line */} <img src="bgAsserts/Line.svg" alt="line" className="absolute top-80 w-full z-10" /> {/* End Line */} {/* Start Point */} <img src="/bgAsserts/points.svg" alt="points" className="absolute top-[1000px] right-5 w-[200px] z-10" /> {/* End Point */} {/* Send book ampoienent */} <div className="relative w-[calc(100vw-10%)] bg-white border-2 border-blues-500/20 space-y-10 px-10 py-12 z-30 mx-auto rounded-xl shadow-sm"> <h1 className="text-3xl text-blues-700 font-semibold "> Easily book an appointment in 4 simple steps </h1> <div className="w-full inline-flex gap-5 items-center justify-between"> {/* Start Input */} <div className="text-xl w-full space-y-4"> <h1 className="text-neutral-400 inline-flex items-center justify-center gap-2"> <MdEmail size={25} className="text-blues-500" /> Email Address </h1> <Input placeholder="Enter your email address" className="w-full py-8 px-4 text-xl ring-offset-blue-500 rounded-lg focus-visible:ring-1 focus-visible:ring-blues-500" type="email" /> </div> {/* End Input */} {/* Start Input */} <div className="text-xl w-full space-y-4"> <h1 className="text-neutral-400 inline-flex items-center justify-center gap-2"> <FaPhoneFlip size={25} className="text-blues-500 rotate-90" /> Phone Number </h1> <Input placeholder="Enter your phone number" className="w-full py-8 px-4 text-xl ring-offset-blue-500 focus-visible:ring-1 focus-visible:ring-blues-500" type="tel" pattern="[0-9+-]*" /> </div> {/* End Input */} {/* Start Input */} <div className="text-xl w-full space-y-4"> <h1 className="text-neutral-400 inline-flex items-center justify-center gap-2"> <IoCalendarNumberSharp size={25} className="text-blues-500 " /> Date of Appointment </h1> <Popover> <PopoverTrigger className="w-full"> <Input placeholder="Select the date of the appointment" className="w-full py-8 px-4 text-xl ring-offset-blue-500 focus-visible:ring-1 focus-visible:ring-blues-500" value={date ? format(date?.toString(), "PPP") : ""} /> </PopoverTrigger> <PopoverContent className="w-auto p-0"> <Calendar mode="single" selected={date} onSelect={setDate} initialFocus /> </PopoverContent> </Popover> </div> {/* End Input */} {/* Start Input */} <div className="text-xl w-full space-y-4"> <h1 className="text-neutral-400 inline-flex items-center justify-center gap-2"> <FaUserDoctor size={25} className="text-blues-500 " /> Specialty </h1> <Select> <SelectTrigger className="w-full py-8 px-4 text-xl ring-offset-blue-500 focus-visible:ring-1 focus-visible:ring-blues-500"> <SelectValue placeholder="Internal Medicine" defaultValue={"Internal Medicine"} /> </SelectTrigger> <SelectContent> {speciality.map((item, index) => ( <SelectItem className="text-xl" key={index} value={item}> {item} </SelectItem> ))} </SelectContent> </Select> </div> {/* End Input */} {/* Start Validate */} <div className="text-xl w-1/2 mt-12"> <Button variant={"outline"} size={"lg"} className="w-full bg-[#0095DE] text-white text-xl p-8 gap-5 hover:text-white rounded-xl hover:bg-blues-500/90" > Book now <FaCheckCircle /> </Button> </div> {/* End Validate */} </div> </div> {/* Send book ampoienent */} </> ); } export default Hero;
import std/[strutils, strformat, times, options, sequtils] var source* : string type Parser = proc(): Option[string] ParseObj = object isSuccessful : bool parsed : string ParseError* = object kind* : string expected* : string actual* : string message* : string line* : int pos* : int startPos* : int endPos* : int curLineNum* : int curLineText* : string prevLineNum* : int prevLineText* : string lastLineNum* : int lastLineText* : string CompilerMetadata* = object parseDuration* : Duration linesCompiled* : int NodeKind = enum # the different node types nkInt, # a leaf with an integer value nkFloat, # a leaf with a float value nkString, # a leaf with a string value nkAdd, # an addition nkSub, # a subtraction nkIf # an if statement Node = ref object case kind: NodeKind # the `kind` field is the discriminator of nkInt: intVal: int of nkFloat: floatVal: float of nkString: strVal: string of nkAdd, nkSub: leftOp, rightOp: Node of nkIf: condition, thenPart, elsePart: Node # var n = Node(kind: nkFloat, floatVal: 1.0) NodeObj = object kind*: string args*: seq[string] children*: seq[NodeObj] # We don't need the parsers to return anything other than a true. only in case of failure do we need to return a full error object proc parse* (code: string) : void = # start timer let parseStartTime = getTime() var remaining = code var line = 1 var pos = 0 var errors : seq[ParseError] proc curse(errmsg : string) : Parser = return ( proc(): Option[string] = var err = ParseError( kind: "SyntaxError", expected: "", actual: "", message: errmsg, line: line, pos: pos, startPos: pos, endPos: pos ) errors.add err none(string) ) proc eos() : Parser = return ( proc(): Option[string] = if pos == remaining.len - 1: echo "FOUND EOF" return some("EOF") else: echo "Did not find EOF" return none(string) ) proc c(c: char) : Parser = return ( proc(): Option[string] = if pos < remaining.len and remaining[pos] == c: if remaining[pos] == '\n': inc line inc pos return some($c) else: return none(string) # if remaining[pos] == c: # echo "Matched ", $c, " with ", remaining[pos] , " at pos ", pos # if pos < remaining.len: # echo "incrementing pos" # inc pos # else: # return none(string) # return some($c) # else: # return none(string) ) # NOT - Anything but the given parser - always true. proc anythingButC(c: char) : Parser = return ( proc(): Option[string] = var res: string while true: if remaining[pos] == c: return some(res) else: res.add remaining[pos] inc pos ) proc `|` (lp: Parser, rp: Parser) : Parser = return ( proc(): Option[string] = let lpOut = lp() if lpOut.isSome(): return lpOut else: let rpOut = rp() if rpOut.isSome(): return rpOut else: return none(string) ) proc `&` (lp: Parser, rp: Parser) : Parser = return ( proc(): Option[string] = let lpOut = lp() if lpOut.isNone(): return none(string) else: let rpOut = rp() if rpOut.isNone(): return none(string) else: return some(lpOut.get() & rpOut.get()) ) # P1 - P2 # matches P1 if P2 does not match proc `-` (lp: Parser, rp: Parser) : Parser = return ( proc(): Option[string] = let rpOut = rp() if rpOut.isSome: # echo "Right side was successful. This is wrong." return none(string) else: let lpOut = lp() if lpOut.isSome(): # echo "left side was successful" return lpOut else: # echo "both sides were unsuccessful" return none(string) ) # Zero or more repetitions of the given parser - always return success proc `*` (p: Parser) : Parser = return ( proc(): Option[string] = var res: string while true: let pOut = p() if pOut.isSome(): # echo "* received ", pOut.get() res.add pOut.get() # echo "* has res: ", res else: break return some(res) ) # One or more repetitions of the given parser - if zero instances of succes, it returns failure. Esle returns success proc `+` (p: Parser) : Parser = return ( proc(): Option[string] = var res: string var atLeastOne = false while true: let pOut = p() if pOut.isSome: atLeastOne = true res.add pOut.get() else: break if atLeastOne: return some(res) else: return none(string) ) # Zero or One - always true. proc `?` (p: Parser) : Parser = return ( proc(): Option[string] = let pOut = p() if pOut.isSome(): return pOut else: return none(string) ) # Not-predicate: !P # The pattern !P returns a pattern that matches only if the input does not match P. In contrast to most other patterns, this pattern does not consume any input. proc `!` (p: Parser) : Parser = return ( proc(): Option[string] = let pOut = p() if pOut.isNone(): return some("") else: return none(string) ) let space = c(' ') | c('\t') | c('\r') let ws = space | c('\n') let lowerChar = c('a') | c('b') | c('c') | c('d') | c('e') | c('f') | c('g') | c('h') | c('i') | c('j') | c('k') | c('l') | c('m') | c('n') | c('o') | c('p') | c('q') | c('r') | c('s') | c('t') | c('u') | c('v') | c('w') | c('x') | c('y') | c('z') let upperChar = c('A') | c('B') | c('C') | c('D') | c('E') | c('F') | c('G') | c('H') | c('I') | c('J') | c('K') | c('L') | c('M') | c('N') | c('O') | c('P') | c('Q') | c('R') | c('S') | c('T') | c('U') | c('V') | c('W') | c('X') | c('Y') | c('Z') let alphabet = lowerChar | upperChar let digit = c('0') | c('1') | c('2') | c('3') | c('4') | c('5') | c('6') | c('7') | c('8') | c('9') let nonZeroDigit = c('1') | c('2') | c('3') | c('4') | c('5') | c('6') | c('7') | c('8') | c('9') let alphanum = alphabet | digit let trueKwd = c('t') & c('r') & c('u') & c('e') let falseKwd = c('f') & c('a') & c('l') & c('s') & c('e') let boolDef = trueKwd | falseKwd let intDef = ?c('-') & nonZeroDigit & * (digit | c('_')) let decDef = ?c('-') & digit & * (digit | c('_')) & c('.') & * (digit | c('_')) let literals = intDef | boolDef let equalTok = c('=') & *ws let colonTok = c(':') & *ws let orTok = c('|') & *ws let varKwd = c('v') & c('a') & c('r') & +ws let constKwd = c('c') & c('o') & c('n') & c('s') & c('t') & +ws let intTypeKwd = c('I') & c('n') & c('t') let boolTypeKwd = c('B') & c('o') & c('o') & c('l') let decTypeKwd = c('D') & c('e') & c('c') let voidTypeKwd = c('D') & c('e') & c('c') let keywords = varKwd | constKwd | boolDef | intTypeKwd | boolTypeKwd | decTypeKwd let identifierRule = alphabet & *(alphanum | c('_')) let identifier = (identifierRule - keywords) & *ws let primitiveType = boolTypeKwd | decTypeKwd | intTypeKwd let sumType = primitiveType & * (orTok & primitiveType) let typedIdentifier = identifier & colonTok & sumType let expression = literals | identifier let varDeclareAndAssign = varKwd & typedIdentifier & equalTok & expression let statement = varDeclareAndAssign #| varDeclaration | assignment let program = * statement # var x = 1 # const y = 2 # var a, b, c = 1, 2, 3 # var a : Int, b: Bool, c = 1, true, 3 # var # a, b, c : Int = 1, 2, 3 # var # a : Int, # b : String # var d: Int = 1 # const e: Int = 1 # let mutable x : Int = 1 # let mutable str : String = mutable "Hello" # c, f - it is taking all keyward starting letters remaining = "vxe" pos = 0 let resProg = identifier() if resProg.isSome(): echo "Success" echo resProg.get() else: echo "Failure" echo "Ending string = ", remaining[pos .. ^1] echo "----------------" remaining = "xconst" pos = 0 let resIdent = identifier() if resIdent.isSome(): echo "Success" echo resIdent.get() else: echo "Failure" echo "Ending string = ", remaining[pos .. ^1] echo "----------------" remaining = "const x = {something}" pos = 0 echo "Starting string = ", remaining let declr = varKwd | constKwd | curse("Expected variable or constant declaration") let blockStmts = c('{') & anythingButC('}') & c('}') let chk = declr & + c(' ') & c('x') & c(' ') & c('=') & c(' ') & blockStmts let res = chk() if res.isSome(): echo "Success" echo res.get() else: echo "Failure" echo "Ending string = ", remaining[pos .. ^1] echo "Time taken = ", getTime() - parseStartTime echo "Errors = ", errors echo "----------------"
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void * */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('username'); $table->string('email')->unique(); $table->jsonb('address'); $table->string('phone'); $table->string('website'); $table->jsonb('company'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
// import 'package:flutter/material.dart'; // import 'package:cloud_firestore/cloud_firestore.dart'; // import 'package:firebase_auth/firebase_auth.dart'; // void signUserOut() { // FirebaseAuth.instance.signOut(); // } // class ParentProfilePage extends StatelessWidget { // const ParentProfilePage({Key? key}) : super(key: key); // @override // Widget build(BuildContext context) { // final String? userEmail = FirebaseAuth.instance.currentUser?.email; // return Scaffold( // appBar: AppBar( // title: const Text("Parent's Profile"), // actions: [ // IconButton( // onPressed: () { // Navigator.push( // context, // MaterialPageRoute(builder: (context) => EditProfilePage()), // ); // }, // icon: Icon(Icons.edit), // ), // IconButton( // onPressed: signUserOut, // icon: Icon(Icons.logout), // ), // ], // ), // body: FutureBuilder<QuerySnapshot>( // future: FirebaseFirestore.instance // .collection('parent') // .where('email', isEqualTo: userEmail) // .limit(1) // .get(), // builder: (context, snapshot) { // if (snapshot.connectionState == ConnectionState.waiting) { // return Center( // child: CircularProgressIndicator(), // ); // } // if (snapshot.hasError) { // return Center( // child: Text('Error: ${snapshot.error}'), // ); // } // final parentDocs = snapshot.data?.docs; // if (parentDocs == null || parentDocs.isEmpty) { // return Center( // child: Text('No parent data found.'), // ); // } // final parentData = parentDocs.first.data() as Map<String, dynamic>; // final firstName = parentData['firstName'] as String?; // final lastName = parentData['lastName'] as String?; // final email = parentData['email'] as String?; // final address = parentData['address'] as String?; // final contact = parentData['contact'] as String?; // return Padding( // padding: const EdgeInsets.all(16.0), // child: Center( // child: Column( // mainAxisAlignment: MainAxisAlignment.start, // children: [ // SizedBox( // height: 50, // ), // Image.asset( // 'lib/images/logo.png', // height: 150, // ), // SizedBox(height: 15), // Text( // 'First Name: $firstName', // style: TextStyle( // fontSize: 18, // fontWeight: FontWeight.w900, // ), // ), // SizedBox(height: 5), // Text( // 'Last Name: $lastName', // style: TextStyle(fontSize: 18), // ), // SizedBox(height: 5), // Text( // 'Email: $email', // style: TextStyle(fontSize: 18), // ), // SizedBox(height: 5), // Text( // 'Contact: $contact', // style: TextStyle(fontSize: 18), // ), // SizedBox(height: 5), // Text( // 'Address: $address', // style: TextStyle(fontSize: 18), // ), // ], // ), // ), // ); // }, // ), // ); // } // }
import os import torch import torchvision.transforms as transforms from nltk.translate.bleu_score import corpus_bleu from datasets.dataset import ImageTextDataset import json vocab_path = '../data/deepfashion/vocab.json' with open(vocab_path, 'r') as f: vocab = json.load(f) rev_vocab = {v:k for k,v in vocab.items()} def get_optimizer(model, config): return torch.optim.Adam([{"params": filter(lambda p: p.requires_grad, model.encoder.parameters()), "lr": config.encoder_learning_rate}, {"params": filter(lambda p: p.requires_grad, model.decoder.parameters()), "lr": config.decoder_learning_rate}]) def adjust_learning_rate(optimizer, epoch, config): """ 每隔lr_update个轮次,学习速率减小至当前十分之一, 实际上,我们并未使用该函数,这里是为了展示在训练过程中调整学习速率的方法。 """ optimizer.param_groups[0]['lr'] = config.encoder_learning_rate * (0.1 ** (epoch // config.lr_update)) optimizer.param_groups[1]['lr'] = config.decoder_learning_rate * (0.1 ** (epoch // config.lr_update)) def filter_useless_words(sent, filterd_words): # 去除句子中不参与BLEU值计算的符号 return [w for w in sent if w not in filterd_words] def evaluate(data_loader, model, config, logger=None, global_step=None): model.eval() # 存储候选文本 cands = [] # 存储参考文本 refs = [] # 需要过滤的词 filterd_words = set({model.vocab['<start>'], model.vocab['<end>'], model.vocab['<pad>']}) cpi = config.captions_per_image device = next(model.parameters()).device for i, (imgs, caps, caplens) in enumerate(data_loader): if i > 1: break with torch.no_grad(): # 通过束搜索,生成候选文本 texts = model.generate_by_beamsearch(imgs.to(device), config.beam_k, config.max_len+2) # 候选文本 cands.extend([filter_useless_words(text, filterd_words) for text in texts]) # 参考文本 refs.extend([filter_useless_words(cap, filterd_words) for cap in caps.tolist()]) # 实际上,每个候选文本对应cpi条参考文本 multiple_refs = [] for idx in range(len(refs)): multiple_refs.append(refs[(idx//cpi)*cpi : (idx//cpi)*cpi+cpi]) # 计算BLEU-4值,corpus_bleu函数默认weights权重为(0.25,0.25,0.25,0.25) # 即计算1-gram到4-gram的BLEU几何平均值 if not logger: bleu4 = corpus_bleu(multiple_refs, cands, weights=(0.25,0.25,0.25,0.25)) model.train() return bleu4 else: # import numpy as np # print(multiple_refs, cands) # print(multiple_refs[0], cands[0]) # tt = [rev_vocab[idx] for idx in cands[0]] # print(' '.join(tt)) # ttt = [rev_vocab[idx] for idx in multiple_refs[0][0]] # print(' '.join(ttt)) # print(multiple_refs, cands) # print(np.array(multiple_refs).shape, np.array(cands).shape) multiple_refs = [[' '.join([rev_vocab[idx] for idx in ref]) for ref in multiple_refs[i]] for i in range(len(multiple_refs))] # print(multiple_refs) # print(cands) cands = [' '.join([rev_vocab[idx] for idx in cand]) for cand in cands] # print(cands) rouge_l, cider, meteor, bleu = logger.log(multiple_refs, cands, global_step) model.train() return rouge_l, cider, meteor, bleu def mktrainval(data_dir, vocab_path, batch_size, workers=4, captions_per_image=1, max_len=100): train_tx = transforms.Compose([ transforms.Resize(256), transforms.RandomCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) val_tx = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) train_set = ImageTextDataset(os.path.join(data_dir, 'train_data.json'), vocab_path, 'train', transform=train_tx, captions_per_image=captions_per_image, max_len=max_len) valid_set = ImageTextDataset(os.path.join(data_dir, 'test_data.json'), vocab_path, 'val', transform=val_tx, captions_per_image=captions_per_image, max_len=max_len) test_set = ImageTextDataset(os.path.join(data_dir, 'test_data.json'), vocab_path, 'test', transform=val_tx, captions_per_image=captions_per_image, max_len=max_len) # print(len(train_set), len(valid_set), len(test_set)) train_loader = torch.utils.data.DataLoader( train_set, batch_size=batch_size, shuffle=True, num_workers=workers, pin_memory=True) valid_loader = torch.utils.data.DataLoader( valid_set, batch_size=batch_size, shuffle=False, num_workers=workers, pin_memory=True, drop_last=False) test_loader = torch.utils.data.DataLoader( test_set, batch_size=batch_size, shuffle=False, num_workers=workers, pin_memory=True, drop_last=False) # print(len(train_set), len(valid_set), len(test_set)) return train_loader, valid_loader, test_loader if __name__ == '__main__': mktrainval('../data/deepfashion', '../data/deepfashion/vocab.json', 32, workers=0)
# Fitness Site Landing Page Welcome to the Fitness Site Landing Page project! This landing page is designed for fitness enthusiasts and is built with React, Tailwind CSS, Vite, TypeScript, Framer Motion, react-anchor-link-smooth-scroll, and react-hook-form. ![alt text](<landing page.jpg>) ## Features - **Modern UI:** Clean and responsive user interface designed with React components and Tailwind CSS. - **Animation:** Engaging animations and transitions powered by Framer Motion. - **Smooth Scrolling:** Smooth scroll functionality for seamless navigation with react-anchor-link-smooth-scroll. - **Form Handling:** Form validation and submission handled with ease using react-hook-form. - **TypeScript Support:** Strongly-typed JavaScript with TypeScript for improved code quality and developer experience. ## Technologies Used - **React**: JavaScript library for building user interfaces. - **Tailwind CSS**: Utility-first CSS framework for fast and responsive UI development. - **Vite**: Next-generation frontend build tool that offers lightning-fast development server and optimized production builds. - **TypeScript**: Superset of JavaScript with static typing for enhanced code quality and maintainability. - **Framer Motion**: Animation library for creating smooth and interactive UI animations. - **react-anchor-link-smooth-scroll**: Library for smooth scrolling to anchor links within the page. - **react-hook-form**: Performant form library with easy form validation and submission. ## Installation 1. Clone the repository: ```bash git clone https://github.com/Anubhav-dev-web/Evo_Fitness.git ``` 2. Navigate to the project directory: ```bash cd fitness-landing-page ``` 3. Install dependencies: ```bash npm install ``` 4. Start the development server: ```bash npm run dev ``` This will open the project in your default browser at `http://localhost:5173/`. ## Usage - Explore the landing page to discover fitness-related content and features. - Navigate smoothly through different sections using the smooth scrolling functionality. - Experience engaging animations and transitions throughout the site. - Fill out and submit forms with ease using the react-hook-form library. ## Contributing Contributions are welcome! Feel free to fork the repository and submit pull requests for any improvements, features, or bug fixes. 1. Fork the repository. 2. Create your feature branch: ```bash git checkout -b feature/new-feature ``` 3. Commit your changes: ```bash git commit -am 'Add new feature' ``` 4. Push to the branch: ```bash git push origin feature/new-feature ``` 5. Submit a pull request.
const options = ["rock" ,"paper" ,"scissors"]; function getcomputerchoice(){ const choice = options[Math.floor(Math.random() * options.length)]; return choice; } function checkWinner(playerSelection, computerSelection){ if(playerSelection == computerSelection){ return "Tie"; } else if( (playerSelection == "rock" && computerSelection == "scissors") || (playerSelection == "scissors" && computerSelection == "paper") || (playerSelection == "paper" && computerSelection == "rock") ){ return "Player"; } else{ return "Computer"; } } function playRound(playerSelection, computerSelection){ const result = checkWinner(playerSelection,computerSelection); if(result == "Tie"){ return "It's a Tie"; } else if(result == "Player"){ return "You Win!"; } else{ return "You Lose!"; } } function getplayerchoice(){ let validatedInput = false; while(validatedInput == false){ const choice = prompt("Rock Paper Scissors"); if (choice == null){ continue; } const choiceInLower = choice.toLowerCase(); if(options.includes(choiceInLower)){ validatedInput = true; return choiceInLower; } } } function game(){ let scorePlayer = 0; let scoreComputer = 0; console.log("Welcome!"); for(let i=0 ;i<5;i++){ const playerSelection = getplayerchoice(); const computerSelection = getcomputerchoice(); console.log(playRound(playerSelection,computerSelection)); console.log("--------------"); if(checkWinner(playerSelection,computerSelection) =="Player" ){ scorePlayer++; } else if(checkWinner(playerSelection,computerSelection)=="Computer"){ scoreComputer++; } console.log("Game Over"); if(scorePlayer > scoreComputer){ console.log("Player was the winner"); } else if(scorePlayer < scoreComputer) { console.log("Computer was the winner"); } else{ console.log("We have a Tie"); } } } game();
// import getUserById from "@/lib/users/getUserById" import { getUserById } from "@/lib/prisma/users"; import getUserPosts from "@/lib/users/getUserPosts"; import { User } from "@prisma/client"; import type { Metadata } from "next"; import { notFound } from "next/navigation"; import { Suspense } from "react"; import UserTable from "./components/UserTable"; import Link from "next/link"; type Params = { params: { user_id: string; }; }; export async function generateMetadata({ params: { user_id }, }: Params): Promise<Metadata> { // @ts-ignore const user: User = await getUserById(user_id); return { title: user.name, description: `This is the page of ${user.name}`, }; } export default async function UserPage({ params: { user_id } }: Params) { // @ts-ignore const user: User = await getUserById(user_id); if (!user) { notFound(); } return ( <main> <Link href="/users/add"> <button className="btn">Add User</button> </Link> {/* @ts-ignore */} <UserTable user={user} /> <br />s{" "} </main> ); }
import { createSlice } from "@reduxjs/toolkit"; import { createTicket, getAllUserTickets, getAllTickets, sendMessage, getTicketById, updateTicket, deleteTicket, } from "../actions/ticketActions"; const initialState = { ticket: {}, tickets: [], loading: false, success: false, error: null, }; const ticketSlice = createSlice({ name: "ticket", initialState, extraReducers: (builder) => { builder .addCase(createTicket.pending, (state) => { state.loading = true; }) .addCase(createTicket.fulfilled, (state, action) => { state.loading = false; state.ticket = action.payload; state.success = true; state.error = ""; }) .addCase(createTicket.rejected, (state, action) => { state.loading = false; state.ticket = null; state.error = action.error.message; }) .addCase(sendMessage.pending, (state) => { state.loading = true; }) .addCase(sendMessage.fulfilled, (state, action) => { state.loading = false; state.ticket = action.payload; state.success = true; state.error = ""; }) .addCase(sendMessage.rejected, (state, action) => { state.loading = false; state.ticket = null; state.error = action.error.message; }) .addCase(getAllUserTickets.pending, (state) => { state.loading = true; }) .addCase(getAllUserTickets.fulfilled, (state, action) => { state.loading = false; state.tickets = action.payload; state.success = true; state.error = ""; }) .addCase(getAllUserTickets.rejected, (state, action) => { state.loading = false; state.tickets = []; state.error = action.error.message; }) .addCase(getAllTickets.pending, (state) => { state.loading = true; }) .addCase(getAllTickets.fulfilled, (state, action) => { state.loading = false; state.tickets = action.payload; state.success = true; state.error = ""; }) .addCase(getAllTickets.rejected, (state, action) => { state.loading = false; state.tickets = []; state.error = action.error.message; }) .addCase(getTicketById.pending, (state) => { state.loading = true; }) .addCase(getTicketById.fulfilled, (state, action) => { state.loading = false; state.ticket = action.payload.ticket; state.error = ""; }) .addCase(getTicketById.rejected, (state, action) => { state.loading = false; state.ticket = null; state.error = action.error.message; }) .addCase(updateTicket.pending, (state) => { state.loading = true; }) .addCase(updateTicket.fulfilled, (state, action) => { state.loading = false; state.ticket = action.payload; state.error = ""; }) .addCase(deleteTicket.pending, (state) => { state.loading = true; }) .addCase(deleteTicket.fulfilled, (state, action) => { state.loading = false; state.ticket = action.payload; state.success = true; state.error = ""; }) .addCase(deleteTicket.rejected, (state, action) => { state.loading = false; state.ticket = null; state.error = action.error.message; }); }, }); export default ticketSlice.reducer;
# -*- coding: utf-8 -*- from zvtm import zvt_config from zvtm.informer import EmailInformer import logging from apscheduler.schedulers.background import BackgroundScheduler from zvtm.contract.api import get_db_engine, get_schema_columns from zvtm import init_log from zvtm.domain.fundamental.valuation1 import StockValuation1 import requests import pandas as pd from zvtm.utils.time_utils import now_pd_timestamp, to_time_str, to_pd_timestamp from zvtm.utils.pd_utils import pd_is_not_null from zvtm.contract.api import df_to_db # from zvtm.contract.api import get_data from schedule.utils.query_data import get_data as get_data_sch import datetime logger = logging.getLogger(__name__) sched = BackgroundScheduler() def code_id_map_em() -> dict: """ 东方财富-股票和市场代码 http://quote.eastmoney.com/center/gridlist.html#hs_a_board :return: 股票和市场代码 :rtype: dict """ url = "http://80.push2.eastmoney.com/api/qt/clist/get" params = { "pn": "1", "pz": "50000", "po": "1", "np": "1", "ut": "bd1d9ddb04089700cf9c27f6f7426281", "fltt": "2", "invt": "2", "fid": "f3", "fs": "m:1 t:2,m:1 t:23", "fields": "f12", "_": "1623833739532", } r = requests.get(url, params=params) data_json = r.json() if not data_json["data"]["diff"]: return dict() temp_df = pd.DataFrame(data_json["data"]["diff"]) temp_df["market_id"] = 1 temp_df.columns = ["sh_code", "sh_id"] code_id_dict = dict(zip(temp_df["sh_code"], temp_df["sh_id"])) params = { "pn": "1", "pz": "50000", "po": "1", "np": "1", "ut": "bd1d9ddb04089700cf9c27f6f7426281", "fltt": "2", "invt": "2", "fid": "f3", "fs": "m:0 t:6,m:0 t:80", "fields": "f12", "_": "1623833739532", } r = requests.get(url, params=params) data_json = r.json() if not data_json["data"]["diff"]: return dict() temp_df_sz = pd.DataFrame(data_json["data"]["diff"]) temp_df_sz["sz_id"] = 0 code_id_dict.update(dict(zip(temp_df_sz["f12"], temp_df_sz["sz_id"]))) params = { "pn": "1", "pz": "50000", "po": "1", "np": "1", "ut": "bd1d9ddb04089700cf9c27f6f7426281", "fltt": "2", "invt": "2", "fid": "f3", "fs": "m:0 t:81 s:2048", "fields": "f12", "_": "1623833739532", } r = requests.get(url, params=params) data_json = r.json() if not data_json["data"]["diff"]: return dict() temp_df_sz = pd.DataFrame(data_json["data"]["diff"]) temp_df_sz["bj_id"] = 0 code_id_dict.update(dict(zip(temp_df_sz["f12"], temp_df_sz["bj_id"]))) return code_id_dict def stock_zh_a_hist( symbol: str = "000001", period: str = "daily", start_date: str = "20230210", end_date: str = "20500101", adjust: str = "", ) -> pd.DataFrame: """ 东方财富网-行情首页-沪深京 A 股-每日行情 https://quote.eastmoney.com/concept/sh603777.html?from=classic :param symbol: 股票代码 :type symbol: str :param period: choice of {'daily', 'weekly', 'monthly'} :type period: str :param start_date: 开始日期 :type start_date: str :param end_date: 结束日期 :type end_date: str :param adjust: choice of {"qfq": "前复权", "hfq": "后复权", "": "不复权"} :type adjust: str :return: 每日行情 :rtype: pandas.DataFrame """ code_id_dict = code_id_map_em() adjust_dict = {"qfq": "1", "hfq": "2", "": "0"} period_dict = {"daily": "101", "weekly": "102", "monthly": "103"} url = "http://push2his.eastmoney.com/api/qt/stock/kline/get" params = { "fields1": "f1,f2,f3,f4,f5,f6,f9,f10,", "fields2": "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f116", "ut": "7eea3edcaed734bea9cbfc24409ed989", "klt": period_dict[period], "fqt": adjust_dict[adjust], "secid": f"{code_id_dict[symbol]}.{symbol}", "beg": start_date, "end": end_date, "_": "1623766962675", } r = requests.get(url, params=params) data_json = r.json() if not (data_json["data"] and data_json["data"]["klines"]): return pd.DataFrame() temp_df = pd.DataFrame( [item.split(",") for item in data_json["data"]["klines"]] ) temp_df.columns = [ "日期", "开盘", "收盘", "最高", "最低", "成交量", "成交额", "振幅", "涨跌幅", "涨跌额", "换手率", ] temp_df.index = pd.to_datetime(temp_df["日期"]) temp_df.reset_index(inplace=True, drop=True) temp_df["开盘"] = pd.to_numeric(temp_df["开盘"]) temp_df["收盘"] = pd.to_numeric(temp_df["收盘"]) temp_df["最高"] = pd.to_numeric(temp_df["最高"]) temp_df["最低"] = pd.to_numeric(temp_df["最低"]) temp_df["成交量"] = pd.to_numeric(temp_df["成交量"]) temp_df["成交额"] = pd.to_numeric(temp_df["成交额"]) temp_df["振幅"] = pd.to_numeric(temp_df["振幅"]) temp_df["涨跌幅"] = pd.to_numeric(temp_df["涨跌幅"]) temp_df["涨跌额"] = pd.to_numeric(temp_df["涨跌额"]) temp_df["换手率"] = pd.to_numeric(temp_df["换手率"]) temp_df["code"] = data_json["data"]["code"] temp_df["entity"] = data_json["data"]["market"] temp_df["name"] = data_json["data"]["name"] temp_df["entity"] = temp_df["entity"].apply(lambda x: 'sz' if x == 0 else 'sh') temp_df["name"] = data_json["data"]["name"] return temp_df df = stock_zh_a_hist() print(df)
import { Injectable, UnauthorizedException } from '@nestjs/common' import { PassportStrategy } from '@nestjs/passport' import { InjectRepository } from '@nestjs/typeorm' import { ExtractJwt, Strategy } from 'passport-jwt' import { Repository } from 'typeorm' import { UserEntity } from './../../entities/user.entity' import { AuthPayload } from './interface/user.interface' @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( @InjectRepository(UserEntity) private userRepository: Repository<UserEntity>, ) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: process.env.SECRET, }) } async validate(payload: AuthPayload) { const { id, username } = payload const user = this.userRepository.find({ where: { username } }) if (!user) { throw new UnauthorizedException('Not logged in.') } return user } }
package day23datetimevarargs; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class DateTime02 { public static void main(String[] args) { //Anlik zamani nasil aliriz? LocalTime myCurrentTime = LocalTime.now(); System.out.println(myCurrentTime);//10:21:25.160861500 //Anlik zamanda bilesenler nasil alinir? int hour = myCurrentTime.getHour(); System.out.println(hour);//10 int minute = myCurrentTime.getMinute(); System.out.println(minute);//22 int second = myCurrentTime.getSecond(); System.out.println(second);//29 int nano = myCurrentTime.getNano(); System.out.println(nano);//887337800 LocalTime next = myCurrentTime.plusMinutes(13).plusHours(3).minusMinutes(13).minusHours(3); System.out.println(next);//10:45:15.646673200 //Zaman formati nasil degistirilir? /* DateTime class ta kullanılan tarih saat formları HH : mm ==> 24 lu saat sistemi hh : mm ==> 12 li saat sistemiAM, PM gosterilmez hh : mm a ==> 12 li saat sistemiAM, PM gosterilir HH : mm : ss ==> 24 lu saat sistemi HH : MM ==> yanlıs format MM aylar icin kullanılır "mm" minute demektir. "MM" month demektir dd-MM-yyyy ==> gun ay yıl MMM ==> Aug MMMM ==> August yy ==> 2022 ==> 22 */ DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("HH : mm"); String formattedMyCurrentTime = dtf1.format(myCurrentTime); System.out.println(formattedMyCurrentTime);//11 : 01 //Date formati nasıl degistirilir? LocalDate myDate = LocalDate.of(2023, 8, 13); System.out.println(myDate);//2023-08-13 //Tarihi AY/GUN/YIL sekline ceviriniz DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MM/dd/yyyy"); String formattedMyDate = dtf2.format(myDate); System.out.println(formattedMyDate);//08/13/2023 //Tarih GUN/Ay ismnin ilk uc harfi / yıl sekline ceviriniz 25/Aug/22 DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("dd/MMM/yy"); String formattedMyDate2 = dtf3.format(myDate); System.out.println(formattedMyDate2);//13/Ağu/23 //Tarih GUN/Ay ismi / yıl sekline ceviriniz 25/Aug/2023 DateTimeFormatter dtf4 = DateTimeFormatter.ofPattern("dd/MMMM/yyyy"); String formattedMyDate3 = dtf4.format(myDate); System.out.println(formattedMyDate3);//13/Ağustos/2023 //Baska bir zaman dilimindeki tarih ve zamani nasil alabiliriz? LocalDate dateInTokyo = LocalDate.now(ZoneId.of("Asia/Tokyo")); System.out.println(dateInTokyo);//2023-12-01 //Amsterdam'da ayin kaçi? LocalDate dateInfAmsterdam = LocalDate.now(ZoneId.of("Europe/Amsterdam")); System.out.println(dateInfAmsterdam);//2023-12-01 //Tokyo da saat kaç? LocalTime timeInTokyo = LocalTime.now(ZoneId.of("Asia/Tokyo")); System.out.println(timeInTokyo);//19:51:03.786800500 //Amsterdam da saat kaç? LocalTime timeInAmsterdam = LocalTime.now(ZoneId.of("Europe/Amsterdam")); System.out.println(timeInAmsterdam);//11:52:29.567256700 } }
// // MockURLSessionRepository.swift // CookSecretTests // // Created by Alvaro Grimal Cabello on 18/12/23. // import Foundation @testable import CookSecret class MockURLSessionRepository: HttpRepository { enum ResponseType { case failure case success } var response: ResponseType = .success init(response: ResponseType = .success) { self.response = response } // MARK: - HttpRepository func searchIngredient(by text: String) async throws -> [String] { switch response { case .failure: throw NSError() case .success: return ["Ingredient1", "Ingredient2", "Ingredient3"] } } func getExploreCategories() async throws -> [CookSecret.ExploreCategoryDomainModel] { switch response { case .failure: throw NSError() case .success: return [ .init(id: "TEST1", value: "CATEGORY1"), .init(id: "TEST2", value: "CATEGORY2"), .init(id: "TEST3", value: "CATEGORY3") ] } } func getExploreMeals(by filter: CookSecret.ExploreMealsRequestDomainModel) async throws -> [CookSecret.ExploreMealSummaryDomainModel] { switch response { case .failure: throw NSError() case .success: return [ .init(id: "TEST1", name: "NAME1", thumbnail: nil), .init(id: "TEST2", name: "NAME2", thumbnail: nil), .init(id: "TEST3", name: "NAME3", thumbnail: nil) ] } } func getExploreMeal(by id: String) async throws -> CookSecret.RecipeDomainModel? { switch response { case .failure: throw NSError() case .success: return .init(title: "title", description: "description", people: 1, preparation: "preparation", dateUpdated: .now, time: 1, isCustom: true, ingredients: [.init(name: "INGREDIENT1", quantity: "QUANTITY1")], extraInfo: [], resources: []) } } }
import "client-only"; import { Sampler, start } from "tone"; import type { Frequency, Time } from "tone/build/esm/core/type/Units"; const samples = { A0: "A0.[mp3|ogg]", C1: "C1.[mp3|ogg]", "D#1": "Ds1.[mp3|ogg]", "F#1": "Fs1.[mp3|ogg]", A1: "A1.[mp3|ogg]", C2: "C2.[mp3|ogg]", "D#2": "Ds2.[mp3|ogg]", "F#2": "Fs2.[mp3|ogg]", A2: "A2.[mp3|ogg]", C3: "C3.[mp3|ogg]", "D#3": "Ds3.[mp3|ogg]", "F#3": "Fs3.[mp3|ogg]", A3: "A3.[mp3|ogg]", C4: "C4.[mp3|ogg]", "D#4": "Ds4.[mp3|ogg]", "F#4": "Fs4.[mp3|ogg]", A4: "A4.[mp3|ogg]", C5: "C5.[mp3|ogg]", "D#5": "Ds5.[mp3|ogg]", "F#5": "Fs5.[mp3|ogg]", A5: "A5.[mp3|ogg]", C6: "C6.[mp3|ogg]", "D#6": "Ds6.[mp3|ogg]", "F#6": "Fs6.[mp3|ogg]", A6: "A6.[mp3|ogg]", C7: "C7.[mp3|ogg]", "D#7": "Ds7.[mp3|ogg]", "F#7": "Fs7.[mp3|ogg]", A7: "A7.[mp3|ogg]", C8: "C8.[mp3|ogg]", }; class ToneUtil { private static loadingTask?: Promise<Sampler>; private sampler?: Sampler; async init() { if (!ToneUtil.loadingTask) { ToneUtil.loadingTask = this.load(); ToneUtil.loadingTask.finally(() => { ToneUtil.loadingTask = undefined; }); } this.sampler = await ToneUtil.loadingTask; } async triggerAttack( notes: Frequency | Frequency[], time?: Time, velocity?: number ) { const sampler = await this.getSampler(); sampler.triggerAttack(notes, time, velocity); } async triggerAttackRelease( notes: Frequency | Frequency[], duration: Time | Time[], time?: Time, velocity?: number ) { const sampler = await this.getSampler(); sampler.triggerAttackRelease(notes, duration, time, velocity); } async releaseAll(time?: Time) { const sampler = await this.getSampler(); sampler.releaseAll(time); } private async getSampler() { if (!this.sampler) { await this.init(); } await start(); return this.sampler!; } private async load() { return new Promise<Sampler>((resolve, reject) => { const sampler = new Sampler(samples, { release: 1, baseUrl: "/audio/salamander/", onload() { resolve(sampler.toDestination()); }, onerror(err) { reject(err); }, }); }); } } export const toneUtil = new ToneUtil();
# noti ## About A simple cross-platform notifier library. It uses the operating system's native notification system. For Windows, this is toast notifications, for Linux it uses `notify-send` Platform support: - [x] Linux - [x] Windows 8 and Windows 10 - [ ] MacOS 10.11 and higher (I'm still working on getting macos support) ![A screenshot of noti on the GNOME desktop](https://raw.githubusercontent.com/daniel071/noti/master/Screenshots/notiExample.png) ## Installation ### Using precompiled binaries: **(Recommended method)** 1. Download the precompiled binary from the releases page 2. In the terminal, if you're on linux/unix, type `./noti` and if you're on windows, type `.\noti.exe` ### Compiling it yourself: **(Experts only)** NOTE: This requires you to have Go installed 1. Clone this repository with `git clone https://github.com/daniel071/noti.git` 2. Run this with `go run noti.go` **OR** compile this with `go build noti.go` which will then create an executable. ## Usage: Using noti is very simple, all you have to do is: `.\noti.exe title message` - If you are on Windows `./noti title message` - If you are on Linux or macOS Note: Replace "title" and "message" with your own text.
import React from "react"; import { Routes, Route, BrowserRouter } from "react-router-dom"; import LoginPage from "./pages/loginPage/LoginPage"; import HomePage from "./pages/homePage/HomePage"; import StockUpdate from "./components/StockUpdate"; import CreateEntry from "./pages/create Entry/CreateEntry"; import NotificationList from "./pages/notification list/NotificationList"; import UpdatePage from "./pages/update page/UpdatePage"; import ApprovePage from "./pages/approve page/ApprovePage"; import NotificationApprove from "./pages/notification approve/NotificationApprove"; import StockList from "./pages/Stock page/StockList"; import NotFoundPage from "./pages/not found/NotFoundPage"; import AzureADAuth from "./auth/AzureADAuth"; const App = () => { const accessData = JSON.parse(localStorage.getItem("access_data")); const zv_web_AccType = accessData && accessData.zv_web_AccType; const pmNotifCr = zv_web_AccType?.PmNotifCr === "true"; const pmNotifRep = zv_web_AccType?.PmNotifRep === "true"; const pmNotifSuper = zv_web_AccType?.PmNotifSuper === "true"; const stockTransf = zv_web_AccType?.StockTransf === "true"; return ( <Routes> <Route path='/' element={<LoginPage />} /> <Route path='/home' element={<HomePage />} /> {pmNotifCr && <Route path='/entry' element={<CreateEntry />} />} {pmNotifRep && <Route path='/list' element={<NotificationList />} />} {pmNotifRep && ( <Route path='/update/:NotificationNumber' element={<UpdatePage />} /> )} {pmNotifSuper && ( <Route path='/approve' element={<NotificationApprove />} /> )} {pmNotifSuper && ( <Route path='/approve/:NotificationNumber' element={<ApprovePage />} /> )} {stockTransf && <Route path='/stockList' element={<StockList />} />} {stockTransf && ( <Route path='/stockUpdate/:MaterialNumber' element={<StockUpdate />} /> )} <Route path='*' element={<NotFoundPage />} /> </Routes> ); }; export default App;
import showdown from 'showdown' import fs from 'fs' const converter = new showdown.Converter({ ghCompatibleHeaderId: true, simpleLineBreaks: true, ghMentions: true, tables: true }) converter.setFlavor('github') export function markdownToHTML(path: string) { const readmeFile = fs.readFileSync(path).toString().replace(/\\\n/g, '\n') return ` <html> <head> <title> </title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type='text/css'> ${fs.readFileSync(`${__dirname}/../static/highlight.js/stackoverflow-light.min.css`).toString()} </style> <script> ${fs.readFileSync(`${__dirname}/../static/highlight.js/highlight.min.js`).toString()} </script> </head> <body> <div id='content'> ${converter.makeHtml(readmeFile).replaceAll('&lt;br /&gt;', '<br>')} </div> <style type='text/css'> ${fs.readFileSync(`${__dirname}/../static/style.css`).toString()} </style> <script> hljs.highlightAll() </script> </body> </html> ` }
import { defineStore } from "pinia"; import { api } from "src/boot/axios"; import { ref } from "vue"; import { useUserStore } from "./user-store.js"; import { useQuasar } from "quasar"; export const useLinkStore = defineStore("link", () => { const userStore = useUserStore(); const links = ref([]); const $q = useQuasar(); const createLink = async (original_link) => { try { $q.loading.show({ message: "Estamos creando el link...", }); const res = await api({ url: "/links", method: "POST", headers: { Authorization: `Bearer ${userStore.token}`, }, data: { original_link, }, }); links.value.push(res.data.newLink); // console.log(res.data); } catch (error) { // if (error.response) { // console.log(error.response); // throw error.response.data; // } else if (error.request) { // console.log(error.request); // } else { // console.log(error.message); // } throw error.response?.data || error; } finally { $q.loading.hide(); } }; const getLinks = async () => { try { $q.loading.show({ message: "Cargando informacion...", }); // console.log("Llamando a los links 🐱‍🏍"); const res = await api({ url: "/links", method: "GET", headers: { Authorization: `Bearer ${userStore.token}`, }, }); // console.log(res.data); // links.value = [...res.data.links] links.value = res.data.links.map((item) => { return { original_link: item.original_link, nano_link: item.nano_link, _id: item._id, uid: item.uid, }; }); } catch (error) { throw error.response?.data || error; } finally { $q.loading.hide(); } }; const removeLink = async (id) => { try { $q.loading.show({ message: "Estamos borrando el link...", }); await api({ url: `/links/${id}`, method: "DELETE", headers: { Authorization: `Bearer ${userStore.token}`, }, }); links.value = links.value.filter((item) => item._id !== id); } catch (error) { throw error.response?.data || error; } finally { $q.loading.hide(); } }; const modifyLink = async (newlink) => { try { $q.loading.show({ message: "Estamos actualizando el link", }); // console.log(newlink); await api({ url: `/links/${newlink._id}`, method: "PATCH", headers: { Authorization: `Bearer ${userStore.token}`, }, data: { original_link: newlink.original_link, }, }); links.value = links.value.map((item) => item._id === newlink._id ? newlink : item ); } catch (error) { throw error.response?.data || error; } finally { $q.loading.hide(); } }; const resetLinkStore = () => { links.value = []; }; getLinks(); return { links, createLink, getLinks, removeLink, modifyLink, resetLinkStore, }; });
import React, { useState } from 'react'; import { Button, Form } from 'react-bootstrap'; import { useDispatch, useSelector } from 'react-redux'; import { Link, useNavigate } from 'react-router-dom'; import { DotLoader } from 'react-spinners'; import image from '../assets/img/bumi.png'; import useInput from '../hooks/UseInput'; import { register } from '../utils/api'; function RegisterInput() { const [username, onUsernameChange] = useInput(''); const [email, onEmailChange] = useInput(''); const [password, onPasswordChange] = useInput(''); const dispatch = useDispatch(); const { isFetching } = useSelector((state) => state.user); const [error, setError] = useState(null); const navigate = useNavigate(); const onSubmitHandler = (event) => { event.preventDefault(); register( dispatch, { username, email, password }, ).then((response) => { if (response.error) { setError(response.error); } else { navigate('/login'); } }); }; return ( <div className="register-input d-flex"> <div className="register-left"> <div className="row justify-content-center align-items-center"> <div className="col-12 col-md-10 col-lg-8"> <h1>Buat akun baru</h1> <p>Silakan, Masukkan data Anda dengan benar</p> <Form onSubmit={onSubmitHandler}> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Label>Username</Form.Label> <Form.Control type="text" placeholder="Masukan nama anda" onChange={onUsernameChange} required /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Label>Email</Form.Label> <Form.Control type="email" placeholder="Masukan email anda" onChange={onEmailChange} required /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicPassword"> <Form.Label>Password</Form.Label> <Form.Control type="password" placeholder="Min. 8 karakter" onChange={onPasswordChange} required /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicCheckbox"> <Form.Check type="checkbox" label="saya setuju dengan Syarat dan ketentuan" required /> </Form.Group> <div className="mt-5 d-flex justify-content-center align-items-center"> <Button className="btn3 fw-bold" type="submit" disabled={isFetching}> {isFetching ? ( <div className="d-flex justify-content-center"> <DotLoader color="#fff" size={20} speedMultiplier={3} /> </div> ) : ( 'Daftar' )} </Button> </div> </Form> <p className="mt-3 text-center">Sudah memiliki akun?<Link to="/login"> Masuk</Link></p> {error ? <span className="text-center d-inline-flex justify-content-center w-100 text-white rounded bg-danger">Email atau password tidak valid, silahkan coba lagi...</span> : null} </div> </div> </div> <div className="register-right"> <div className="row justify-content-center align-items-center"> <div className="col-12 col-md-10 col-lg-8"> <div className="image-register"> <img src={image} alt="bumi" /> </div> <h1>Sistem Penjualan Sampah Elektronik Berbasis Website</h1> <p>Meningkatkan kontribusi masyarakat dalam menanggulangi masalah sampah sehingga dapat membantu melindungi lingkungan sekitar kita.</p> </div> </div> </div> </div> ); } export default RegisterInput;
import { useState } from 'react'; import Typography from '@mui/material/Typography'; import Button from '@mui/material/Button'; import { faker } from '@faker-js/faker'; import VirtualizedTable from './components/VirtualizedTable'; import AddIcon from '@mui/icons-material/PostAddRounded'; export type Product = { id: number; name: string; description: string; price: string; }; const randomProducts: Product[] = [...Array(200000).keys()].map((key) => { return { id: key, name: `${faker.commerce.productName()}`, description: `${faker.commerce.productDescription()}`, price: faker.commerce.price(), }; }); function App() { const [productsList, setProductsList] = useState<Product[]>(randomProducts); const SETTINGS = { itemHeight: 75, visibleItems: 9, tolerance: 3, minIndex: 0, maxIndex: productsList.length - 1, startIndex: 0, }; const handleAddNewProduct = () => { const newProduct: Product = { id: productsList.length, name: `${faker.commerce.productName()}`, description: `${faker.commerce.productDescription()}`, price: faker.commerce.price(), }; setProductsList([...productsList, newProduct]); }; const getData = (offset: number, limit: number) => { var data: Product[] = []; const start = Math.max(SETTINGS.minIndex, offset); const end = Math.min(offset + limit - 1, SETTINGS.maxIndex); if (start <= end) { data = productsList.slice(start, end + 1); } return data; }; return ( <div style={{ padding: 24 }} id='appContainer'> <div style={{ display: 'flex', textAlign: 'center' }}> <Typography variant='h5' sx={{ marginBottom: 3, fontWeight: 500, flexGrow: 1 }} data-testid={'pageTitle'} > Available Products {`(${productsList.length.toLocaleString()})`} </Typography> <Button variant='contained' disableElevation sx={{ textTransform: 'capitalize', height: 'fit-content', borderRadius: 1, backgroundColor: '#4186cb', fontWeight: 400, }} onClick={handleAddNewProduct} startIcon={<AddIcon />} data-testid='newProductBtn' > New Product </Button> </div> <VirtualizedTable get={getData} settings={SETTINGS} /> </div> ); } export default App;
lll.views.EditProjectCommentView = Backbone.View.extend({ events: { "click .save": "save" }, initialize: function() { var self = this; _.bindAll(self, "destroy", "render", "save"); Backbone.Validation.bind(self); }, onDestroy: function() { var self = this; Backbone.Validation.unbind(self); }, render: function() { var self = this; templateLoader.loadRemoteTemplate("<%= asset_path 'v2/EditProjectComment.html' %>", function(data) { if (!self.template) { self.template = _.template(data); } $(self.el).html(self.template({ comment: self.model })); }); return self; }, save: function() { var self = this; self.$(".clearfix.error").removeClass("error"); self.$("span.error").empty(); self.model.set({ body: self.$('#body').val(), }); if (self.model.isValid()) { if (self.model.isNew()) { if (self.options.create) { self.options.create(self.model); } } else { if (self.options.update) { self.options.update(self.model); } } lll.views.track("comment", self.model.isNew() ? "add" : "edit"); self.model.save(self.model.attributes, { error: function(model, response) { if (response.readyState == 0 || response.status == 0) { // ajax call cancelled } else { lll.views.error("error saving comment: " + response.responseText); if (self.options.error) { self.options.error(model, response); } } } }); } else { self.$(".invalid").each(function() { $(this).closest(".clearfix").addClass("error"); $(this).closest(".clearfix").find("span.error").text($(this).attr("data-error")); }); } return false; } });
import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from "@angular/common/http"; import {Observable} from "rxjs"; import {GetPayload} from '../models/getpayload'; import {PostPayload} from '../models/postpayload'; import {PostResponse} from '../models/postresponse'; import {Router} from "@angular/router"; import {of} from "rxjs"; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', }) }; const routeMapping: {[key: string]: any} = { splash: { next: 'view1', prev: null, formData: {} }, view1: { next: 'view2', prev: null, formData: {} }, view2: { next: 'view3', prev: 'view1', formData: {} }, view3: { next: 'view4', prev: 'view2', formData: {} }, view4: { next: 'view5', prev: 'view3', formData: {} } }; @Injectable({ providedIn: 'root' }) export class BeControllersService { getUrl: string = 'http://localhost:3000/v1/getRouteData'; postUrl: string = 'http://localhost:3000/v1/postRouteData'; constructor(private http: HttpClient, private router: Router) { } getRouteData(): Observable<GetPayload> { if (this.isLocal()) { const getPayload = this.getLocalGetPayload(); const obs: Observable<GetPayload> = of(getPayload); return obs; } return this.http.get<GetPayload>(this.getUrl); } postRouteData(postPayload: PostPayload) { if (this.isLocal()) { const nextRouteObj = this.getLocalNextRoute(postPayload); const obs: Observable<Object> = of(nextRouteObj); return obs; } return this.http.post<PostPayload>(this.postUrl, postPayload, httpOptions); } private isLocal(): boolean { return document.cookie.includes('mock=true'); } private getLocalNextRoute(postPayload: PostPayload) : object { const {formData, currRoute, forward} = postPayload; const routeMappingInner = routeMapping[currRoute] || {}; const nextRoute = forward == true ? routeMappingInner.next : routeMappingInner.prev; routeMappingInner.formData = formData; return {nextRoute: nextRoute}; } private getLocalGetPayload() : GetPayload{ const currRoute = this.router.url.replace('/',''); const routeMappingInner = routeMapping[currRoute] || {}; return { formData: routeMappingInner.formData, showNext: !!(routeMappingInner.next || '').length, showPrev: !!(routeMappingInner.prev || '').length } } }
#The SpeechRecognition Library is uded for performing speech recognition, with support for several engines and APIs, online and offline. #It library needs the PyAudio package to be installed in order for it to interact with the microphone input. import speech_recognition as sr #urllib3 is a powerful, sanity-friendly HTTP client for Python. #It provides Thread safety. Client-side SSL/TLS verification. Helpers for retrying requests and dealing with HTTP redirects. Proxy support for HTTP and SOCKS. import urllib3 #disables the endless 'insecurerequest' warning which arises while trying to connect to the internet. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) while (True == True): #The primary purpose of a Recognizer instance is to recognize speech. #Here Each instance comes with a variety of settings and functionality for recognizing speech from an audio source. #This class helps obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: # listen for 1 second and create the ambient noise energy level r.adjust_for_ambient_noise(source, duration=1) print("Say something!") #listens for the user's input #here source is the microphone as already assigned to the variable source. phrase_time_limit determines the time period microphone will take user input #which here is set to 5 seconds. audio = r.listen(source,phrase_time_limit=5) # recognize speech using Sphinx/Google #Google API Client Library for Python is required if and only if you want to use the Google Cloud Speech API (recognizer_instance.recognize_google_cloud). try: #response = r.recognize_sphinx(audio) response = r.recognize_google(audio) #creates a output.txt names file if it doesn't exist and appends the speech data to the file. f=open('output.txt','a') f.write(response + ".") f.close() #here we ask the user if he/she wants to continue the recognition part or end the program. while True: answer = input('Do you want to continue?:') if answer.lower().startswith("n"): print("Exiting The Program!") exit()#exits the program else: print("Listening Again...") break #continues asking for more input from the user. #error occurs when google could not understand what was said except sr.UnknownValueError: print("Sphinx could not understand audio") #Sphinx cannot understand the user input because of the ambience in the background. except sr.RequestError as e: print("Sphinx error; {0}".format(e)) #this error occurs when some of the libraries required for running sphinx are missing from python.
# Blimp Swarm Create a base case blimp environment to build upon for other experimetns in CoppeliaSim Tested on Windows WSL2 running Ubuntu 22.04 with CoppeliaSim v4.6.0-rev18, Python 3.8, and ROS2 Humble ## Installation 1. ### Install [Coppeliasim](https://www.coppeliarobotics.com/) * sudo apt-get update && apt-get upgrade * sudo apt-get install libgl1 * sudo apt-get install python3 pip * sudo apt-get install '^libxcb.*-dev' libx11-xcb-dev libglu1-mesa-dev libxrender-dev libxi-dev libxkbcommon-dev libxkbcommon-x11-dev * python3 -m pip install pyzmq cbor2 * wget https://downloads.coppeliarobotics.com/V4_6_0_rev16/CoppeliaSim_Edu_V4_6_0_rev18_Ubuntu22_04.tar.xz * tar -xvf CoppeliaSim_Edu_V4_6_0_rev16_Ubuntu22_04.tar.xz * ./copelliaSim.sh Update your ```.bashrc``` with the following (the alias is not required, it just makes it easier to run Coppeliasim) Replace ```<path to coppelia folder>``` with the path. In our case, it was ```/home/<username>/Downloads/CoppeliaSim_Edu_V4_6_0_rev18_Ubuntu22_04```. Unfortunately it looks like using ```~``` does not work for later build commands, so you need to put the full directory. ```bash export COPPELIASIM_ROOT_DIR="<path to coppelia folder>" alias coppeliaSim="$COPPELIASIM_ROOT_DIR/coppeliaSim.sh" ``` **Update Copellia Sim Configuration settings:** * Locate the usrset.txt settings file. For me it was in ```<coppelia folder path>/system/usrset.txt``` * Change the following parameters * doNotShowCrashRecoveryMessage = 'true' (To remove the annoying error messages on setup). * additionalLuaPath = "~/sim/blimpFlow/lua" (To find model lua files) 2. ### Install [ROS2](https://docs.ros.org/) Tested with [ROS2 Humble](https://docs.ros.org/en/humble/Installation.html) on Ubuntu 22.04 Make sure the following line is in the .bashrc file, or is run every terminal (with `<distro>` replaced by ROS distribution, e.g. `foxy`) ```bash source /opt/ros/<distro>/setup.bash ``` Remember to source the bashrc file after: ```bash source ~/.bashrc ``` 3. ### Set up the [ZMQ package](https://www.coppeliarobotics.com/helpFiles/en/zmqRemoteApiOverview.htm) into Coppeliasim ```bash pip3 install pyzmq cbor ``` Then add the following to your ```.bashrc```. Note: since this references COPPELIASIM_ROOT_DIR, it must be on a line after the definition made in step 1 ```bash export PYTHONPATH="$PYTHONPATH:$COPPELIASIM_ROOT_DIR/programming/zmqRemoteApi/clients/python" ``` Again, remember to source the bashrc file after: ```bash source ~/.bashrc ``` 4. ### Clone this directory ```bash git clone https://github.com/pranavraj575/blimple_as_that ``` 4. ### Install the ROS2 Coppelia package "according to the [tutorial](https://www.coppeliarobotics.com/helpFiles/en/ros2Tutorial.htm)" However, the tutorial sucks, so following the directions below will work * Install dependencies ```bash sudo apt update sudo apt-get install xsltproc pip3 install xmlschema ``` * make a ROS2 workspace (the name can probably be different) ```bash cd ~ mkdir -p ros2_ws/src ``` * clone the [sim_ros2_interface](https://github.com/CoppeliaRobotics/simExtROS2) directory and install dependencies. * The best way to do this is with the folder we made ```bash cp -r /<path to blimple_as_that>/setup_files/sim_ros2_interface ros2_ws/src ``` * However, you can try setting up according to the [tutorial](https://www.coppeliarobotics.com/helpFiles/en/ros2Tutorial.htm) like this ```bash cd ros2_ws/src git clone https://github.com/CoppeliaRobotics/simExtROS2 cd sim_ros2_interface git checkout coppeliasim-<your-version-of-coppeliasim> ``` * Build the ROS2 package (note: should be run from the workspace directory) * Note: this command is buggy, if it fails try looking at the compile instructions in the [github tutorial](https://github.com/CoppeliaRobotics/simROS2) ```bash cd ~/ros2_ws colcon build --symlink-install ``` * The following alternate build command works better in cases where there are a lot of compiled interfaces for some reason ```bash cd ~/ros2_ws sudo apt install clang export CXX=clang++ colcon build --symlink-install ``` * Note: if using a conda environment, you might get an error like [this](https://github.com/colcon/colcon-ros/issues/118) running the following might help: ```bash conda install -c conda-forge catkin_pkg empy lark ``` 5. ### Install Python Packages for this Project Clone this directory, copy all the ```.lua``` files into the correct place (replace ```<path to coppelia>``` with the path to the Coppeliasim folder). This should be run from wherever you want the repo to be. ```bash pip3 install -e . ``` ## Examples * ### Coppelia installation test The obvious test to see if Coppeliasim is actually installed: ```bash coppeliaSim ``` This will open the coppelia simulator. Use the ```-h``` argument to test headless mode. Note: if you did not alias in installation step 1, you need to type in the path to the ```coppeliaSim.sh``` file * ### ZMQ test Tests if the python coppelia interface works First open any coppelia scene with the ```coppelia``` command. Though not necessary, it might be useful to [spawn some objects](https://www.coppeliarobotics.com/helpFiles/index.html) to see the physics work. Then run the following file from the ```blimple_as_that``` directory ```bash python3 tests/testZeroMQRemoteAPI.py ``` This will just play the scene, wait a bit, then pause. * ### ROS blimp control test (Pranav) Tests if coppelia ROS package is set up properly using Pranav's blimp ```bash python3 src/blimp_agent.py ``` This test will spawn a blimp, then move the blimp up, then after three seconds stop the scene. * ### ROS Keyboard blimp control test (Tristan) Runs a wall climbing simulation using Tristan's Blimp Model ```bash python3 runExperiment.py -a 10 -st n -mt 20 -et 300 ``` * ### ROS blimp control test (Cameron) Runs a wall climbing simulation using Cameron's Blimp Model ```bash python3 runExperiment.py -a 10 -st n -mt 20 -et 300 ```
import { Position } from "vscode" import { CanHaveParent } from "./CanHaveParent" import { WithPosition } from "./WithPosition" import { JsonArray } from "./Array" import { JsonBoolean } from "./Boolean" import { JsonString } from "./String" import { JsonNull } from "./Null" import { JsonNumber } from "./Number" declare type JsonObjectValue = JsonObject | JsonArray | JsonString | JsonNumber | JsonBoolean | JsonNull export class JsonObject extends WithPosition implements CanHaveParent { public readonly type = 'object' public parent?: JsonObject | JsonArray private children: { key: string[], pos: ({ start: Position, end: Position })[], value: JsonObjectValue[] } constructor() { super() this.children = { key: [], pos: [], value: [] } } public static from({ start, end }: { start?: Position, end?: Position }): JsonObject { return Object.assign(new JsonObject(), { start, end }) } public static isJsonObject(obj: unknown): boolean { return obj instanceof JsonObject } public get(key: string | JsonString): JsonObjectValue | undefined { let index: number if (typeof key === 'string') { index = this.children.key.indexOf(key) } else { index = this.children.key.indexOf(key.value) } return this.children.value.at(index) } public set(key: string | JsonString, value: JsonObjectValue): void { const rawKey = (typeof key === 'string' ? key : key.value) const index = this.children.key.indexOf(rawKey) if (index !== -1) { this.children.pos[index] = value.pos this.children.value[index] = value return } this.children.key.push(rawKey) this.children.pos.push(value.pos) this.children.value.push(value) } public has(key: string | JsonString): boolean { return this.children.key.includes((typeof key === 'string' ? key : key.value)) } public toString(): string { let s: any = {} this.children.key.forEach(k => { const value = this.get(k) if (value instanceof JsonObject || value instanceof JsonArray) { s[k] = value.toString() } else { s[k] = value!.toString() } }) return JSON.stringify(s) } public toJSON() { let obj: any = {} this.children.key.forEach(k => { const value = this.get(k) if (value instanceof JsonObject || value instanceof JsonArray) { obj[k] = value.toJSON() } else { obj[k] = value!.toJSON() } }) return obj } }
import React from "react"; import { Box, Button, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, useColorModeValue, } from "@chakra-ui/react"; import StopWatch from "@components/widgets/time-smart/stop-watch"; function TimerModal(props: { open: boolean; onClose: () => void; text: string }) { return ( <Modal data-testid={"modal"} size={"2xl"} isOpen={props.open} onClose={props.onClose}> <ModalOverlay /> <ModalContent> <ModalHeader data-testid={"modal-header"}>{props.text}</ModalHeader> <ModalCloseButton /> <ModalBody> <StopWatch /> <Box role={"start-time"}>Start time: {new Date().toLocaleTimeString("en-UK")}</Box> </ModalBody> <ModalFooter> <Button role={"done-button"} bg={useColorModeValue("pink", "teal")} mr={3} onClick={props.onClose}> Done </Button> </ModalFooter> </ModalContent> </Modal> ); } export default TimerModal;
import { Inject, Injectable } from '@nestjs/common'; import { States, UpdateStates } from 'src/domain/data/dto/states-records.dto'; import { StatesRepository } from 'src/domain/data/interfaces/states-records-repository.interface'; import { GenericResponse } from 'src/domain/dto/generic'; @Injectable() export class StatesService { constructor(@Inject('StatesRepository') private StatesRepository: StatesRepository){} public async getAll(page,offset): Promise<GenericResponse<States[]>> { const res = await this.StatesRepository.getAll(page,offset); const response: GenericResponse<States[]> = { success: true, message: 'States fetched Successfully', data: res, }; return response; } /** * * * @param {States} data * @return {*} {Promise<GenericResponse<States>>} * @memberof StatesService */ public async create(data: States): Promise<GenericResponse<States>> { const res = await this.StatesRepository.create(data) const response: GenericResponse<States> = { success: true, message: 'States added Successfully', data: res, }; return response; } public async update(data: UpdateStates): Promise<GenericResponse<States>> { const res = await this.StatesRepository.update(data); const response: GenericResponse<States> = { success: true, message: 'States updated Successfully', data: res, }; return response; } public async delete(_id: string): Promise<GenericResponse<any>> { const res = await this.StatesRepository.delete(_id); const response: GenericResponse<any> = { success: true, message: res.deletedCount > 0 ? 'States deleted Successfully' : 'StatesId not found', data: res, }; return response; } public async getOne(_id: string): Promise<GenericResponse<States>>{ const res = await this.StatesRepository.getOne(_id); const response: GenericResponse<any> = { success: true, message: res ? 'States fetched Successfully' : 'States not found', data: res, }; return response; } }
#ifndef MONTY_H #define MONTY_H #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #include <sys/types.h> /** * struct stack_s - doubly linked list representation of a stack (or queue) * @n: integer * @prev: points to the previous element of the stack (or queue) * @next: points to the next element of the stack (or queue) * * Description: doubly linked list node structure * for stack, queues, LIFO, FIFO */ typedef struct stack_s { int n; struct stack_s *prev; struct stack_s *next; } stack_t; /** * struct instruction_s - opcode and its function * @opcode: the opcode * @f: function to handle the opcode * * Description: opcode and its function * for stack, queues, LIFO, FIFO */ typedef struct instruction_s { char *opcode; void (*f)(stack_t **stack, unsigned int line_number); } instruction_t; /** * struct global_var_s - global variable * @argument: argument for the opcode * @top: top of the stack * @exit_status: the exit status of the current function * * Description: global variable for the application */ typedef struct global_var_s { char *argument; stack_t *top; int exit_status; } global_var_t; extern global_var_t global_var; void push(stack_t **stack, unsigned int line_number); void pall(stack_t **stack, unsigned int line_number); void pint(stack_t **stack, unsigned int line_number); void pop(stack_t **stack, unsigned int line_number); void swap(stack_t **stack, unsigned int line_number); void (*getfunc(char *opcode))(stack_t **stack, unsigned int line_number); void free_stack(stack_t **stack); int is_valid_arg(char *arg); #endif /* MONTY_H */
/*************************************************************************** * Copyright (C) 2006 by Pino Toscano <pino@kde.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #ifndef _ANNOTATIONWIDGETS_H_ #define _ANNOTATIONWIDGETS_H_ #include <qwidget.h> #include "annotations.h" #include "qdanodes.h" #include <klineedit.h> class QCheckBox; class QComboBox; class QDoubleSpinBox; class QGridLayout; class QScrollArea; class QLabel; class QWidget; class KColorButton; class QSpinBox; class KFontRequester; class QLineEdit; class AnnotationWidget; class PixmapPreviewSelector : public QWidget { Q_OBJECT public: explicit PixmapPreviewSelector( QWidget * parent = Q_NULLPTR ); virtual ~PixmapPreviewSelector(); void setIcon( const QString& icon ); QString icon() const; void addItem( const QString& item, const QString& id ); void setPreviewSize( int size ); int previewSize() const; void setEditable( bool editable ); signals: void iconChanged( const QString& ); private slots: void iconComboChanged( const QString& icon ); private: QString m_icon; QLabel * m_iconLabel; QComboBox * m_comboItems; int m_previewSize; }; /** * A factory to create AnnotationWidget's. */ class AnnotationWidgetFactory { public: static AnnotationWidget * widgetFor( Okular::Annotation * ann ); }; class AnnotationWidget : public QObject { Q_OBJECT public: AnnotationWidget( Okular::Annotation * ann ); virtual ~AnnotationWidget(); virtual Okular::Annotation::SubType annotationType() const; QWidget * appearanceWidget(); QWidget * extraWidget(); virtual void applyChanges(); signals: void dataChanged(); protected: QWidget * createAppearanceWidget(); virtual QWidget * createStyleWidget(); virtual QWidget * createExtraWidget(); Okular::Annotation * m_ann; QWidget * m_appearanceWidget; QWidget * m_extraWidget; KColorButton *m_colorBn; QSpinBox *m_opacity; }; class TextAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit TextAnnotationWidget( Okular::Annotation * ann ); void applyChanges() Q_DECL_OVERRIDE; protected: QWidget * createStyleWidget() Q_DECL_OVERRIDE; private: Okular::TextAnnotation * m_textAnn; PixmapPreviewSelector * m_pixmapSelector; KFontRequester * m_fontReq; QComboBox * m_textAlign; QDoubleSpinBox * m_spinWidth; }; class StampAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit StampAnnotationWidget( Okular::Annotation * ann ); void applyChanges() Q_DECL_OVERRIDE; protected: QWidget * createStyleWidget() Q_DECL_OVERRIDE; private: Okular::StampAnnotation * m_stampAnn; PixmapPreviewSelector * m_pixmapSelector; }; class LineAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit LineAnnotationWidget( Okular::Annotation * ann ); void applyChanges() Q_DECL_OVERRIDE; protected: virtual QWidget * createStyleWidget(); private: Okular::LineAnnotation * m_lineAnn; int m_lineType; QDoubleSpinBox * m_spinLL; QDoubleSpinBox * m_spinLLE; QCheckBox * m_useColor; KColorButton * m_innerColor; QDoubleSpinBox * m_spinSize; }; class HighlightAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit HighlightAnnotationWidget( Okular::Annotation * ann ); void applyChanges() Q_DECL_OVERRIDE; protected: QWidget * createStyleWidget() Q_DECL_OVERRIDE; private: Okular::HighlightAnnotation * m_hlAnn; QComboBox * m_typeCombo; }; class GeomAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit GeomAnnotationWidget( Okular::Annotation * ann ); void applyChanges() Q_DECL_OVERRIDE; protected: QWidget * createStyleWidget() Q_DECL_OVERRIDE; private: Okular::GeomAnnotation * m_geomAnn; QComboBox * m_typeCombo; QCheckBox * m_useColor; KColorButton * m_innerColor; QDoubleSpinBox * m_spinSize; }; class FileAttachmentAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit FileAttachmentAnnotationWidget( Okular::Annotation * ann ); void applyChanges() Q_DECL_OVERRIDE; protected: QWidget * createStyleWidget() Q_DECL_OVERRIDE; QWidget * createExtraWidget() Q_DECL_OVERRIDE; private: Okular::FileAttachmentAnnotation * m_attachAnn; PixmapPreviewSelector * m_pixmapSelector; }; class CaretAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit CaretAnnotationWidget( Okular::Annotation * ann ); void applyChanges() Q_DECL_OVERRIDE; protected: QWidget * createStyleWidget() Q_DECL_OVERRIDE; private: Okular::CaretAnnotation * m_caretAnn; PixmapPreviewSelector * m_pixmapSelector; }; class InkAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit InkAnnotationWidget( Okular::Annotation * ann ); void applyChanges() Q_DECL_OVERRIDE; protected: QWidget * createStyleWidget() Q_DECL_OVERRIDE; private: Okular::InkAnnotation * m_inkAnn; QDoubleSpinBox * m_spinSize; }; class TextTagAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit TextTagAnnotationWidget( Okular::Annotation * ann ); virtual ~TextTagAnnotationWidget(); void applyChanges() Q_DECL_OVERRIDE; private slots: void nodeChanged(); protected: QWidget * createStyleWidget() Q_DECL_OVERRIDE; QWidget * createExtraWidget() Q_DECL_OVERRIDE; private: Okular::TextTagAnnotation * m_tTagAnn; QComboBox * m_nodeBox; Okular::QDANode * m_QDANode; int m_attrCount; QScrollArea * m_attrArea; KLineEdit ** m_attrName, **m_attrValue; void loadAttributes( QWidget *widget ); }; class BoxTagAnnotationWidget : public AnnotationWidget { Q_OBJECT public: explicit BoxTagAnnotationWidget( Okular::Annotation * ann ); virtual ~BoxTagAnnotationWidget(); void applyChanges() Q_DECL_OVERRIDE; private slots: void nodeChanged(); protected: QWidget * createStyleWidget() Q_DECL_OVERRIDE; QWidget * createExtraWidget() Q_DECL_OVERRIDE; private: Okular::BoxTagAnnotation * m_tTagAnn; QComboBox * m_nodeBox; Okular::QDANode * m_QDANode; int m_attrCount; QScrollArea * m_attrArea; KLineEdit ** m_attrName, **m_attrValue; void loadAttributes( QWidget *widget ); }; #endif
package kz.h2h.H2H; import kz.h2h.H2H.components.post.model.Post; import kz.h2h.H2H.components.post.repository.PostRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @DataJpaTest public class H2HApplicationTests{ @Autowired private TestEntityManager testEntityManager; @Autowired private PostRepository postRepository; @Test public void whenFindByName_thenReturnPosts(){ // given Post post = new Post(); post.setText("Wakanda Test!"); testEntityManager.persist(post); testEntityManager.flush(); // when List<Post> postsFound = postRepository.findPostByTextLike("Wakanda Test!"); // then assertNotNull(postsFound); assertEquals(1, postsFound.size()); assertTrue(postsFound.get(0).getText().equals("Wakanda Test!")); } }