text
stringlengths
184
4.48M
// -*- C++ -*- // ObjectGenerator.h // Copyright (C) 2004 Rejean Ducharme // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The name of the authors may not be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN // NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // This file is part of the PLearn library. For more information on the PLearn // library, go to the PLearn Web site at www.plearn.org /* ******************************************************* * $Id$ ******************************************************* */ #include <plearn/base/Object.h> #include <plearn/math/TVec.h> #ifndef ObjectGenerator_INC #define ObjectGenerator_INC namespace PLearn { using namespace std; class ObjectGenerator: public Object { private: typedef Object inherited; protected: //! Did we begin to generate new Objects??? bool generation_began; public: //! The template Object from which we will generate other Objects PP<Object> template_object; // ****************** // * Object methods * // ****************** private: void build_(); protected: static void declareOptions(OptionList& ol); public: //! Default constructor ObjectGenerator(); //! This will generate the next object in the list of all options //! MUST be define by a subclass virtual PP<Object> generateNextObject() = 0; //! This will generate a list of all possible Objects. //! By default, just loop over generateNextObject() virtual TVec< PP<Object> > generateAllObjects(); //! simply calls inherited::build() then build_() virtual void build(); virtual void forget(); //! Declares name and deepCopy methods PLEARN_DECLARE_ABSTRACT_OBJECT(ObjectGenerator); }; // Declares a few other classes and functions related to this class DECLARE_OBJECT_PTR(ObjectGenerator); } // end of namespace PLearn #endif // ObjectGenerator_INC /* Local Variables: mode:c++ c-basic-offset:4 c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)) indent-tabs-mode:nil fill-column:79 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=79 :
import { useState } from "react" import { Flex, Spacer,Button,Box,ButtonGroup,Heading } from '@chakra-ui/react' import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton} from '@chakra-ui/react' import { useDisclosure,FormControl,FormLabel,Input } from '@chakra-ui/react' import { useToast } from '@chakra-ui/react' function Login() { const { isOpen, onOpen, onClose } = useDisclosure() const toast = useToast(); const [email, setEmail] = useState("") const [password, setPassword] = useState("") const handleSubmit = async () => { if (email == "" || password == "") { toast({ title: 'Fill all the Details', status: 'error', duration: 3000, isClosable: true, }) } else{ const payload = { email, password, } await fetch("https://todo-dlkk.onrender.com/user/login", { method: "POST", headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload) }) .then((res) => res.json()) .then((res) => { console.log(res) if (res.token) { localStorage.setItem("psc_app_token", res.token) localStorage.setItem("username", res.name) window.location.reload(false); } onClose(); }) .catch((err) => console.log(err)) const username = localStorage.getItem("username") console.log('**********',username); if(!username){ toast({ title: 'Invalid credentials', status: 'error', duration: 3000, isClosable: true, }) }} } return <> <Button colorScheme='teal' onClick={onOpen}>Log in</Button> <Modal isOpen={isOpen} onClose={onClose} > <ModalOverlay /> <Login/> <ModalContent> <ModalHeader>Login</ModalHeader> <ModalCloseButton /> <ModalBody pb={6}> <FormControl> <FormLabel>Email</FormLabel> <Input type="text" placeholder="email" onChange={(e) => setEmail(e.target.value)} /> </FormControl> <FormControl mt={4}> <FormLabel>Password</FormLabel> <Input type="text" placeholder="pwd" onChange={(e) => setPassword(e.target.value)} /> </FormControl> </ModalBody> <ModalFooter> <Button colorScheme='blue' mr={3} onClick={() => {handleSubmit();}}> Login </Button> <Button onClick={onClose}>Cancel</Button> </ModalFooter> </ModalContent> </Modal> </> } export { Login }
import React, { useState } from 'react'; interface FormProps { addTask: (task: string) => void; } const Form: React.FC<FormProps> = ({ addTask }) => { const [task, setTask] = useState(''); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (task.trim()) { addTask(task); setTask(''); } }; return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Enter a task" value={task} onChange={(e) => setTask(e.target.value)} /> <button type="submit">Add Task</button> </form> ); }; export default Form;
import { Reply } from "@prisma/client"; import { createContext, useContext, useEffect, useRef, useState } from "react"; import { TextAvatarType, TextCaptcha, TextClose, TextContent, TextDateTime, TextEmail, TextHomepage, TextIAmARobot, TextNewReply, TextNickname, TextNoReply, TextReplies, TextReply, } from "./Text"; import Card from "./ui/Card"; import CardTitle from "./ui/CardTitle"; import md5 from "md5"; import { useFetcher } from "remix"; import { Markdown } from "./Markdown"; import { UserInfoContext } from "~/utils/context/userinfo"; import Space from "./ui/Space"; export type PostReplyData = Pick< Reply, | "nickname" | "email" | "github" | "qq" | "homepage" | "createdAt" | "content" | "id" | "replyTo" >; const colors = [ "pink", "red", "purple", "deep-purple", "indigo", "blue", "light-blue", "cyan", "teal", "green", "light-green", "lime", "yellow", "amber", "orange", "deep-orange", ]; const randomHashColor = (name: string) => { const hash = name.split("").reduce((a, b) => { return (a + b.charCodeAt(0)) % colors.length; }, 0); return colors[hash]; }; const RepliesContext = createContext<{ replies: PostReplyData[] }>({ replies: [], }); type AvatarType = "qq" | "github" | "email"; function ReplyForm({ replyTo, onClose, }: { replyTo?: number; onClose?: () => void; }) { const fetcher = useFetcher(); const isSubmitting = fetcher.state === "submitting"; const contentRef = useRef<HTMLTextAreaElement>(null); const { userInfo, setUserInfo } = useContext(UserInfoContext); const [avatarType, setAvatarType] = useState<AvatarType>(userInfo.avatarType); useEffect(() => { if (!isSubmitting) { if (contentRef.current) { contentRef.current.value = ""; } } }, [isSubmitting]); return ( <fetcher.Form method="post" className="rara-reply-make-reply"> <label htmlFor="nickname"> <TextNickname /> </label> <div> <input type="text" name="nickname" id="nickname" placeholder="Anonymous" defaultValue={userInfo.nickname} onChange={(e) => setUserInfo({ nickname: e.currentTarget.value })} /> </div> <label htmlFor="homepage"> <TextHomepage /> </label> <div> <input type="text" name="homepage" id="homepage" placeholder="https://" defaultValue={userInfo.homepage} onChange={(e) => setUserInfo({ homepage: e.currentTarget.value })} /> </div> <label htmlFor="avatar"> <TextAvatarType /> </label> <div> <select onChange={(e) => { const avatarType = e.currentTarget.value as AvatarType; setAvatarType(avatarType); setUserInfo({ avatarType }); }} defaultValue={avatarType} > <option value="email">Gravatar (Email)</option> <option value="github">GitHub</option> <option value="qq">QQ</option> </select> </div> {avatarType === "email" && ( <> <label htmlFor="email"> <TextEmail /> </label> <div> <input type="email" name="email" id="email" placeholder="Do you know Gravatar?" defaultValue={userInfo.email} onChange={(e) => setUserInfo({ email: e.currentTarget.value })} /> </div> </> )} {avatarType === "github" && ( <> <label htmlFor="github">GitHub</label> <div> <input type="text" name="github" id="github" placeholder="Your GitHub ID" defaultValue={userInfo.github} onChange={(e) => setUserInfo({ github: e.currentTarget.value })} /> </div> </> )} {avatarType === "qq" && ( <> <label htmlFor="qq">QQ</label> <div> <input type="text" name="qq" id="qq" placeholder="1145141919810" defaultValue={userInfo.qq} onChange={(e) => setUserInfo({ qq: e.currentTarget.value })} /> </div> </> )} <label htmlFor="content"> <TextContent /> </label> <div> <textarea name="content" id="content" rows={4} ref={contentRef} placeholder="You can use **Markdown** here." required /> </div> <label htmlFor="captcha"> <TextCaptcha /> </label> <div> <datalist id="answers"> <option value="0.3"></option> <option value="0.30000000000000004"></option> <option value="0.10.2"></option> </datalist> <input id="captcha" name="captcha" type="text" list="answers" placeholder="0.1 + 0.2 =" required /> </div> <span></span> <Space direction="horizontal" gap={10}> <input type="hidden" name="replyTo" value={replyTo ?? ""} /> <button type="submit" disabled={isSubmitting}> <TextReply /> </button> {onClose && ( <button type="button" onClick={onClose}> <TextClose /> </button> )} </Space> </fetcher.Form> ); } function ReplyList({ id }: { id: number }) { const { replies } = useContext(RepliesContext); const reply = replies.find((reply) => reply.id === id)!; const comments = replies.filter((reply) => reply.replyTo === id); const color = randomHashColor(reply.nickname); const avatar = (reply.qq && `https://q1.qlogo.cn/g?b=qq&nk=${reply.qq}&s=160`) || (reply.github && `https://avatars.githubusercontent.com/${reply.github}`) || (reply.email && `https://gravatar.loli.net/avatar/${md5(reply.email)}?s=160&d=mm`); const [open, setOpen] = useState(false); return ( <div className="rara-reply" id={`reply-${reply.id}`}> <div className={`rara-reply-avatar bgcolor-${color}`}> {avatar ? ( <img src={avatar} alt="avatar" /> ) : ( <span>{reply.nickname[0]}</span> )} </div> <div className="rara-reply-main"> <div className="rara-reply-meta"> {reply.homepage ? ( <a href={reply.homepage} target="_blank" className={`rara-reply-meta-nickname color-${color} underline`} rel="noreferrer noopener" > {reply.nickname} </a> ) : ( <span className={`rara-reply-meta-nickname color-${color}`}> {reply.nickname} </span> )} </div> <div className="rara-reply-content"> <Markdown sanitize={true}>{reply.content}</Markdown> </div> <div className="rara-reply-actions"> <TextDateTime time={new Date(reply.createdAt)} /> <span className="rara-reply-action-reply" onClick={() => setOpen(!open)} > <TextReply /> </span> </div> {open && ( <ReplyForm replyTo={reply.id} onClose={() => setOpen(false)} /> )} <div className="rara-reply-comments"> {comments.map((comment) => ( <ReplyList key={comment.id} id={comment.id} /> ))} </div> </div> </div> ); } export default function PostReply({ replies }: { replies: PostReplyData[] }) { const majorReplies = replies.filter((reply) => reply.replyTo === null); return ( <Card header={<CardTitle title={<TextReplies prefix="💬 " />} />}> <RepliesContext.Provider value={{ replies }}> {majorReplies.length > 0 ? ( majorReplies.map((reply) => ( <ReplyList key={reply.id} id={reply.id} /> )) ) : ( <span style={{ color: "var(--fg-color-2)" }}> <TextNoReply /> </span> )} <h3> <TextNewReply /> </h3> <ReplyForm /> </RepliesContext.Provider> </Card> ); }
import 'package:flutter/material.dart'; import '../../constants.dart'; import '../../model/course.dart'; class CourseSectionCard extends StatelessWidget { const CourseSectionCard({super.key, required this.course}); final Course course; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: Container( height: 120.0, decoration: BoxDecoration( gradient: course.background, borderRadius: BorderRadius.circular(41.0), boxShadow: [ BoxShadow( color: course.background.colors[0].withOpacity(0.3), offset: Offset(0, 20), blurRadius: 30.0, ), BoxShadow( color: course.background.colors[0].withOpacity(0.3), offset: Offset(0, 20), blurRadius: 30.0, ), ]), child: ClipRRect( borderRadius: BorderRadius.circular(41.0), child: Padding( padding: EdgeInsets.only(left: 32.0), child: Stack( children: [ Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Image.asset( 'asset/illustrations/${course.illustration}', fit: BoxFit.cover, ), ], ), Row( children: [ Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( course.courseSubtitle, style: kCardSubtitleStyle, ), SizedBox( height: 6.0, ), Text( course.courseTitle, style: kCardTitleStyle, ), ], ), ), Spacer(), ], ) ], ), ), ), ), ); } }
/* * Qompose - A simple programmer's text editor. * Copyright (C) 2013 Axel Rasmussen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef INCLUDE_QOMPOSECOMMON_GUI_MENUS_ENCODING_MENU_H #define INCLUDE_QOMPOSECOMMON_GUI_MENUS_ENCODING_MENU_H #include <set> #include <string> #include <QObject> #include <QString> #include "QomposeCommon/gui/menus/MenuDescriptors.h" class QActionGroup; class QMenu; namespace qompose { /*! * \brief This menu allows the user to select a character encoding. */ class EncodingMenu : public QObject { Q_OBJECT public: /*! * \brief This structure encapsulates an encoding item's state. */ struct EncodingMenuItem { std::string name; QAction *action; }; /*! * \brief This comparator allows sorting EncodingMenuItems. */ struct EncodingMenuItemComparator { /*! * This operator can be used to sort a list of menu items in * case-sensitive alphabetical order. * * \return True if a comes before b, or false otherwise. */ bool operator()(const EncodingMenuItem &a, const EncodingMenuItem &b); }; /*! * \param label The menu label for this new encoding menu. * \param p This encoding menu's parent object. */ EncodingMenu(const QString &label, QObject *p = nullptr); EncodingMenu(const EncodingMenu &) = delete; /*! * Free resources allocated for this encoding menu. */ virtual ~EncodingMenu(); EncodingMenu &operator=(const EncodingMenu &) = delete; /*! * \return This encoding menu's QMenu instance. */ QMenu *getMenu() const; public Q_SLOTS: /*! * This function sets this encoding menu's currently selected * encoding. Note that no signal will be emitted for this change. * * \param e The new encoding to select. */ void setEncoding(const QByteArray &e); private: QMenu *menu; QActionGroup *group; std::set<EncodingMenuItem, EncodingMenuItemComparator> encodings; private Q_SLOTS: /*! * This slot handles the currently selecting encoding changing by * finding the currently selected encoding, and then emitting the * appropriate signals. */ void doEncodingChanged(); Q_SIGNALS: void encodingChanged(const QByteArray &); }; namespace menu_desc { /*! * \brief This structure defines a descriptor for constructing encoding menus. */ struct EncodingMenuDescriptor { QString label; gui_utils::ConnectionList signalConnections; gui_utils::ConnectionList slotConnections; /*! * \param l The menu label for the new EncodingMenu. * \param sigc The connection for the menu's encodingChanged signal. * \param slotc The connection for the menu's setEncoding slot. */ EncodingMenuDescriptor(const std::string &l, const gui_utils::Connection &sigc = gui_utils::Connection(nullptr, nullptr), const gui_utils::Connection &slotc = gui_utils::Connection(nullptr, nullptr)); EncodingMenuDescriptor(const EncodingMenuDescriptor &) = default; ~EncodingMenuDescriptor() = default; EncodingMenuDescriptor & operator=(const EncodingMenuDescriptor &) = default; }; /*! * We specialize this function in order to create an encoding menu from a * descriptor, and to add it to the given menu. * * \param parent The parent for the new encoding menu. * \param menu The menu to add the new encoding menu to. * \param descriptor The descriptor to create the new encoding menu from. */ template <> void constructDescriptor(QObject *parent, QMenu *menu, const EncodingMenuDescriptor &descriptor); } } #endif
package link /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode struct { Val int Next *ListNode } func hasCycle(head *ListNode) bool { if head == nil { return false } var ( fast = head slow = head ) for fast.Next != nil { slow = slow.Next if fast.Next.Next != nil { fast = fast.Next.Next } else { return false } if slow == fast { return true } } return false }
import { useState } from "react"; import axios from "axios"; import { EnumAlerts, EnumAppointmentConfirmModal, IAppointment, IRoot, } from "../../../redux/interfaces"; import { alertMessageActions, appointmentModalActions, } from "../../../redux/store"; import { useDispatch, useSelector } from "react-redux"; interface Props { selectedAppointmentRows?: IAppointment[]; status: number; } function useUpdateBulkAppointments() { const dispatch = useDispatch(); const confirmModalType = useSelector( (state: IRoot) => state.appointmentModal.confirmModalType ); const [data, setData] = useState<any>(null); const [loading, setLoading] = useState<boolean>(false); const [error, setError] = useState<string | null>(null); const updateBulkAppointments = async ({ selectedAppointmentRows, status }: Props) => { setLoading(true); const url = "https://bhc-server.vercel.app/appointment-bulk"; axios .put(url, { selectedAppointmentRows: selectedAppointmentRows, status: status }) .then((res) => { if (res.data.status === "Success") { setTimeout(() => { setLoading(false); setData(res.data); dispatch(appointmentModalActions.toggleConfirmationModal()); dispatch(alertMessageActions.setShowAlert(true)); setTimeout(() => { dispatch(alertMessageActions.setShowAlert(false)); }, 4000); dispatch( alertMessageActions.setAlertDetails({ alertType: EnumAlerts.SUCCESS, alertMessage: confirmModalType === EnumAppointmentConfirmModal.ACCEPT ? "Request success, schedules accepted in bulk!" : "Request success, schedules rejected in bulk!", }) ); dispatch(appointmentModalActions.refetchAppointmentToggler()); }, 1000); } }) .catch((err) => { setTimeout(() => { setLoading(false); setError(err); dispatch(appointmentModalActions.toggleConfirmationModal()); dispatch(alertMessageActions.setShowAlert(true)); setTimeout(() => { dispatch(alertMessageActions.setShowAlert(false)); }, 4000); dispatch( alertMessageActions.setAlertDetails({ alertType: EnumAlerts.ERROR, alertMessage: `Request error, ${err.message}`, }) ); console.log(err); }, 1000); }); }; return { data, loading, error, updateBulkAppointments }; } export default useUpdateBulkAppointments;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Web Layout</title> <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="bg-white"> </section class="p-8"> <div class="max-w-6xl mx-auto grid grid-cols-2 gap-2 lg:grid-cols-3"> <div class="p-2 md:w-full col-span-1"> <img src="images/Outside1.png" class="w-full h-auto rounded-lg shadow-md object-cover"> </div> <div class="p-2 md:w-full col-span-1"> <img src="images/Outside2.png" class="w-full h-auto rounded-lg shadow-md object-cover"> </div> <div class="p-2 col-span-2 flex justify-center lg:col-span-1"> <img src="images/Outside3.png" class="w-1/2 lg:w-full h-auto rounded-lg shadow-md object-cover"> </div> </div> </section> <!-- Plusy Section --> <section class="text-center p-8"> <h2 class="text-2xl font-bold mb-6 text-green-600">Plusy</h2> <div class="max-w-6xl mx-auto grid grid-cols-2 md:grid-cols-4 gap-8 font-semibold"> <div class="flex flex-col items-center"> <img src="images/Logo1.png" class="w-12 h-12 mb-2"> <p>1 ha soukromého lesaparku</p> </div> <div class="flex flex-col items-center"> <img src="images/Logo2.png" class="w-12 h-12 mb-2"> <p>Wellness s bazénem a saunou</p> </div> <div class="flex flex-col items-center"> <img src="images/Logo3.png" class="w-12 h-12 mb-2"> <p>Venkovní posilovna a tělocvična v interiéru</p> </div> <div class="flex flex-col items-center"> <img src="images/Logo4.png" class="w-12 h-12 mb-2"> <p>Umývárna kol a psů</p> </div> <div class="flex flex-col items-center"> <img src="images/Logo5.png" class="w-12 h-12 mb-2"> <p>Možnost pro rodinného lékaře</p> </div> <div class="flex flex-col items-center"> <img src="images/Logo6.png" class="w-12 h-12 mb-2"> <p>Shuttle - privátní doprava</p> </div> <div class="flex flex-col items-center"> <img src="images/Logo7.png" class="w-12 h-12 mb-2"> <p>Dětský klub</p> </div> <div class="flex flex-col items-center"> <img src="images/Logo8.png" class="w-12 h-12 mb-2"> <p>Přímé napojení na cyklostezky</p> </div> </div> </section> <section class="p-8"> <div class="max-w-6xl mx-auto space-y-8 mb-10"> <div class= "flex flex-col md:flex-row items-start md:space-x-4 bg-gradient-to-r from-purple-100 to-purple-300 rounded-lg"> <img src="images/HouseDown1.png" class="w-full md:w-1/2 h-auto rounded-lg mb-4 md:mb-0 flex-1"> <div class="w-full md:w-full flex-1"> <p class="lg:p-4 lg:py-12 lg:text-lg text-sm p-3">Vestibulum fermentum tortor id mi. Phasellus rhoncus. Fusce tellus odio, dapibus id fermentum quis, suscipit id erat. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Aliquam in lorem sit amet leo accumsan lacinia.</p> <p class="lg:p-4 lg:py-12 lg:text-lg text-sm p-3">Aliquam erat volutpat. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat. Fusce dui leo, imperdiet in, aliquam sit amet leo, feugiat eu, orci.</p> </div> </div> <div class="rounded-lg flex flex-col-reverse md:flex-row md:items-start md:space-x-4"> <div class="w-full md:w-1/2 flex-1"> <p class="py-4 lg:py-8 text-sm lg:text-lg px-4">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis viverra diam non justo. Donec quis nibh at felis congue commodo. Nulla turpis magna, cursus sit amet, suscipit a, interdum id, felis. Praesent vitae arcu tempor neque lacinia pretium. Integer tempor. Nunc dapibus tortor vel mi dapibus sollicitudin.</p> <p class="py-4 lg:py-8 text-sm lg:text-lg px-4">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nescuint, repellendus, excepturi possimus voluptatem magnam ipsa impedit architecto cumque veritatis quae modi nobis enim voluptates id amet, tempora animi adipisci debitis?</p> </div> <div class="relative w-full md:w-1/2 flex-1"> <div class="absolute inset-0 bg-gradient-to-r md:from-purple-100 to-purple-300 rounded-lg transform -translate-x-8 translate-y-8"></div> <img src="images/HouseDown2.png" class="relative w-full h-auto rounded-lg"> </div> </div> </div> </section> </body> </html>
package should_return_request_with_correct_query_params import ( "testing" "github.com/EugeneGpil/httpTester/app/modules/GetRequest" "github.com/EugeneGpil/tester" httpTester "github.com/EugeneGpil/httpTester" ) var key1 = "test_key_1" var expectedValue1 = "test_value_1" var key2 = "test_key_2" var expectedValue2 = "test_value_2" func Test_should_return_request_with_correct_query_params(t *testing.T) { tester.SetTester(t) queryParams := map[string]string{ key1: expectedValue1, key2: expectedValue2, } request := GetRequest.GetRequest(httpTester.GetRequestDto{ Method: "test", Url: "test", Query: queryParams, }) resultQuery := request.URL.Query() resultValue1 := resultQuery.Get(key1) resultValue2 := resultQuery.Get(key2) tester.AssertSame(expectedValue1, resultValue1) tester.AssertSame(expectedValue2, resultValue2) tester.AssertLen(resultQuery, 2) }
package mirosha.gui; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.util.ArrayList; /** * Класс для работы с GUI кнопками * @author Mirosha * @version 1.0 */ public class PanelButton { /** Поле хранение кнопок из класса {@link #Button}*/ private ArrayList<Button> buttons; /** * Конструктор - создание нового объекта кнопки * и хранение в массиве для дальнейшего рендера */ public PanelButton() { buttons = new ArrayList<Button>(); } /** * Процедура добавление кнопки * @param button - кнопка */ public void addButton(Button button) { buttons.add(button); } /** * Процедура удаление кнопки * @param button - кнопка */ public void removeButton(Button button) { buttons.remove(button); } /** * Процедура обновление панели */ public void updatePanel() { for(Button button : buttons) { button.update(); } } /** * Процедура рендер панели * @param graphics - создание фигуры панели для рендера */ public void renderPanel(Graphics2D graphics) { for(Button button : buttons) { button.renderButton(graphics); } } /** * Процедура состояние кнопки при движении/наведении мыши * @param event - состояние кнопки */ public void mouseMoved(MouseEvent event) { for(Button button : buttons) { button.mouseMoved(event); } } /** * Процедура состояние кнопки при захвате мышью * @param event - состояние кнопки */ public void mouseDragged(MouseEvent event) { for(Button button : buttons) { button.mouseDragged(event); } } /** * Процедура состояние кнопки при нажатии мыши * @param event - состояние кнопки */ public void mousePressed(MouseEvent event) { for(Button button : buttons) { button.mousePressed(event); } } /** * Процедура состояние кнопки при отпускании мыши * @param event - состояние кнопки */ public void mouseReleased(MouseEvent event) { for(Button button : buttons) { button.mouseReleased(event); } } }
import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs'; import {Country} from 'src/classes/country'; import {map} from 'rxjs/internal/operators'; import {plainToClass} from 'class-transformer'; @Injectable({ providedIn: 'root' }) export class RestcountriesService { private readonly m_COUNTRIES_ALL: string = 'https://restcountries.eu/rest/v2/all'; private readonly m_COUNTRY: string = 'https://restcountries.eu/rest/v2/alpha/'; constructor(private i_httpClient: HttpClient) { } public getCountriesAll(): Observable<Country[]> { return this.i_httpClient.get<Country[]>(this.m_COUNTRIES_ALL).pipe( map((_countries: object[]) => { return _countries.map((_country: object) => plainToClass<Country, object>(Country, _country)); }) ); } public getCountry(_alpha3Code: string): Observable<Country> { return this.i_httpClient.get<Country>(this.m_COUNTRY + _alpha3Code).pipe( map((_country: object) => plainToClass<Country, object>(Country, _country)) ); } }
--- title: Diseño de Páginas Web para Concesionarios en Mollet del Vallés date: '2023-10-04' tags: ['Diseño web', 'Concesionarios', 'Mollet del Vallés'] draft: false banner : diseño_paginas_web_concesionarios fondoBanner : diseño_pagina_web_molletdelvallés summary: Bienvenido al artículo que te mostrará cómo el diseño de páginas web puede potenciar las ventas de tu concesionario en Mollet del Vallés. En Élite Webs, entendemos la importancia de destacar en el mundo digital, especialmente en una ciudad en constante crecimiento como Mollet del Vallés, conocida por su floreciente sector automotriz y su pasión por los coches. --- import Cta from "../../../components/Cta.astro"; import CtaBot from "../../../components/CtaBot.astro"; import GifSeo from "../../../components/GifSeo.astro"; import Gmaps from "../../../components/Gmaps.astro"; import Video from "../../../components/Video.astro"; ## Diseño de Páginas Web para Concesionarios en Mollet del Vallés ### Introducción Bienvenido al artículo que te mostrará cómo el diseño de páginas web puede potenciar las ventas de tu concesionario en Mollet del Vallés. En Élite Webs, entendemos la importancia de destacar en el mundo digital, especialmente en una ciudad en constante crecimiento como Mollet del Vallés, conocida por su floreciente sector automotriz y su pasión por los coches. ### Motivos por los que necesitan una página web en su profesión y ciudad - **Mayor visibilidad:** En un mercado tan competitivo como el de los concesionarios de automóviles en Mollet del Vallés, tener una página web ofrece una ventaja significativa al permitir que los clientes potenciales encuentren fácilmente su negocio en línea. - **Captación de leads:** Una página web optimizada y atractiva puede ser una poderosa herramienta para captar información de clientes potenciales interesados en adquirir un vehículo. Esto les brinda la oportunidad de establecer una relación con ellos y convertirlos en ventas. - **Exposición de inventario:** Una página web profesional y bien diseñada permite mostrar de manera efectiva los vehículos disponibles en su concesionario. Los visitantes podrán explorar su inventario de forma visual, filtrar por características específicas y encontrar el vehículo perfecto para sus necesidades. - **Información actualizada:** Al tener una página web, podrás proporcionar a tus clientes información actualizada sobre promociones, descuentos, servicios adicionales, eventos especiales y cualquier novedad relacionada con tu concesionario. Esto ayuda a mantener a tus clientes informados y atraer nuevos interesados. ### Beneficios del diseño web para su profesión y ciudad - **Mayor alcance local:** Mollet del Vallés, con su creciente comunidad de aficionados a los automóviles, presenta una excelente oportunidad para incrementar su presencia en línea y llegar a un mayor número de clientes potenciales locales. Una página web bien optimizada puede generar tráfico de calidad y aumentar las visitas a su concesionario. - **Experiencia de usuario mejorada:** El diseño de una página web profesional y atractiva garantiza que los visitantes tengan una experiencia fluida y agradable al interactuar con su sitio. Esta experiencia positiva puede generar confianza y aumentar las posibilidades de que los visitantes se conviertan en clientes satisfechos. - **Credibilidad y confianza:** Una página web bien diseñada para su concesionario en Mollet del Vallés muestra profesionalismo y seriedad, lo que se traduce en mayor credibilidad y confianza por parte de los clientes potenciales. Asociarse con su concesionario será visto como una elección segura y confiable. - **Competitividad:** Tener una página web de calidad coloca a su concesionario en una posición de ventaja frente a la competencia que aún no ha incursionado en el mundo digital. Al ofrecer a los clientes una forma conveniente y atractiva de explorar su oferta de vehículos, estarán un paso adelante en el mercado. No esperes más y déjanos ayudarte a potenciar las ventas de tu concesionario en Mollet del Vallés a través del diseño y desarrollo de una página web profesional. Contáctanos en Élite Webs y descubre cómo podemos mejorar tu presencia en línea y convertir visitas en ventas. <GifSeo /> <Cta /> ## Elementos clave del diseño web exitoso para concesionarios en Mollet del Vallés - Diseño atractivo y moderno que refleje la imagen de tu concesionario. - Navegación intuitiva y fácil de usar para los visitantes. - Páginas rápidas en carga para una experiencia fluida. - Adaptabilidad a dispositivos móviles, para llegar a más usuarios. - Integración de herramientas de reserva de cita y solicitud de información. - Integración de catálogo de vehículos con fotos y detalles relevantes. - Optimización del SEO para mejorar el posicionamiento en buscadores. - Utilización de técnicas de copywriting para resaltar los beneficios de los vehículos. En Élite Webs, nos especializamos en el diseño y desarrollo de páginas web para concesionarios en Mollet del Vallés que toman en cuenta todos estos elementos clave. Nuestro equipo de expertos en diseño web y desarrollo técnico se asegurará de que tu página web cumpla con las últimas tendencias y estándares del sector. ## Cómo nuestro servicio de diseño web puede ayudar a tu concesionario Al elegir nuestro servicio de diseño web, te beneficiarás de: - Una página web a medida que se ajuste a las necesidades de tu concesionario y a la experiencia que deseas ofrecer a tus visitantes. - Un diseño atractivo y funcional que capte la atención de los usuarios y los motive a explorar tus productos y servicios. - Una interfaz intuitiva que permita a los usuarios encontrar fácilmente la información que buscan y realizar acciones, como reservar una cita o solicitar más detalles. - Una página web optimizada para dispositivos móviles, lo cual es fundamental considerando que el uso de smartphones para buscar información de compra de vehículos está en constante crecimiento. - Estrategias de SEO aplicadas en el diseño y el contenido de tu página web, para mejorar la visibilidad en los motores de búsqueda y atraer más tráfico cualificado. - Contenidos persuasivos y beneficios destacados, redactados por nuestro equipo de copywriters especializados en el sector automotriz. Con nuestra experiencia y conocimientos en diseño web para concesionarios en Mollet del Vallés, te ayudaremos a convertir las visitas a tu página web en ventas reales de vehículos. ## Conclusión: La importancia de tener una página web de calidad y contratarnos En un mundo cada vez más digitalizado, tener una página web de calidad se ha convertido en una necesidad para los concesionarios en Mollet del Vallés. No solo te proporciona una presencia en línea profesional, sino que también te permite llegar a un público más amplio y generar oportunidades de negocio. Sin embargo, no cualquier página web es suficiente. Para destacar entre la competencia y captar la atención de los usuarios, es crucial contar con un diseño web atractivo, funcional y optimizado para el SEO. En Élite Webs nos especializamos en el diseño de páginas web para concesionarios que no solo cumplen con estos requisitos, sino que también están diseñadas para convertir visitas en ventas. Confía en nosotros para crear una página web única y efectiva para tu concesionario en Mollet del Vallés. Contáctanos hoy mismo y descubre cómo podemos hacer crecer tu negocio en línea. <Video /> <CtaBot job='Concesionarios' city='Mollet del Vallés'/> <Gmaps query='Mollet del Vallés+españa+maps' />
package com.array2d; import java.util.Scanner; class Matrix { private int[][] data; public Matrix(int rows, int columns) { data = new int[rows][columns]; } public void setElement(int row, int col, int value) { data[row][col] = value; } public boolean isSparseMatrix() { int zeroCount = 0; int totalElements = data.length * data[0].length; for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { if (data[i][j] == 0) { zeroCount++; } } } // Define a threshold for sparsity (e.g., 50%) double sparsityThreshold = 0.5; return ((double) zeroCount / totalElements) > sparsityThreshold; } } public class SparseMatrixChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the matrix dimensions System.out.print("Enter the number of rows: "); int rows = scanner.nextInt(); System.out.print("Enter the number of columns: "); int columns = scanner.nextInt(); Matrix matrix = new Matrix(rows, columns); // Input matrix elements System.out.println("Enter matrix elements:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { int value = scanner.nextInt(); matrix.setElement(i, j, value); } } // Check if the matrix is sparse if (matrix.isSparseMatrix()) { System.out.println("Sparse"); } else { System.out.println("Not sparse"); } scanner.close(); } }
\documentclass[11pt]{beamer} \input{../../template/slideTemplate.txt} \renewcommand{\DEBUG}{0} \renewcommand{\PRESENTATION}{1} \subtitle{Qual o resultado?} \usecolortheme[named=slideBlue]{structure} \begin{document} \begin{frame} \titlepage \end{frame} \begin{frame} \tableofcontents \end{frame} \section{Alterações} \begin{frame}{Modificando variáveis} \begin{itemize} \presentationPause\item Variáveis que não variam não são variáveis \presentationPause\item As alterações nas variáveis dependem de seu tipo \presentationPause\item Existem três grupos de operadores: unários, binários e ternários: \begin{itemize} \presentationPause\item[Unário] utiliza apenas um valor \presentationPause\item[Binário] utiliza dois valores \presentationPause\item[Ternário] utiliza três valores \end{itemize} \presentationPause\item Todo operador retorna o valor de sua operação \end{itemize} \end{frame} \section{Unário} \begin{frame}{Incrementos e decrementos unitários} \begin{itemize} \presentationPause\item Variáveis podem ter seu valor acrescido ou descrescido \presentationPause\item Estes operadores unitários o fazem com o valor de 1 \presentationPause\item Podem ser prefixos ou sufixos \presentationPause\item Alteram o valor registrado \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-6}]{../../code/operators/increment.sintax.cpp} \end{frame}\begin{frame}{Incrementos e decrementos unitários} \lstinputlisting{../../code/operators/increment.example.cpp} \end{frame} \begin{frame}{Sinalizadores} \begin{itemize} \presentationPause\item Equivalem aos sinais matemáticos \presentationPause\item Fazem o mesmo que multiplicar um número por $+1$ ou $-1$ \presentationPause\item Não alteram o valor registrado \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-4}]{../../code/operators/sign.sintax.cpp} \end{frame}\begin{frame}{Sinalizadores} \lstinputlisting{../../code/operators/sign.example.cpp} \end{frame} \begin{frame}{Negador booleano} \begin{itemize} \presentationPause\item Retorna o estado inverso de um \basicCode{bool} \presentationPause\item Só pode ser usado no tipo \basicCode{bool} \presentationPause(Mas funciona em outros tipos) \presentationPause\item Não confundir com fatorial! \presentationPause\item Não alteram o valor registrado \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-2}]{../../code/operators/neg.sintax.cpp} \end{frame}\begin{frame}{Negador booleano} \lstinputlisting{../../code/operators/neg.example.cpp} \end{frame} \begin{frame}{Complemento binário} \begin{itemize} \presentationPause\item Este operador inverte todos os bits de uma variável \presentationPause\item Em tipos \basicCode{signed} o sinal é invertido \presentationPause\item Não pode ser utilizado em números flutantes \presentationPause\item Não alteram o valor registrado \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-2}]{../../code/operators/complement.sintax.cpp} \end{frame}\begin{frame}{Complemento binário} \lstinputlisting{../../code/operators/complement.example.cpp} \end{frame} \section{Binário} \begin{frame}{Atribuidor simples} \begin{itemize} \presentationPause\item O operador mais utilizado é o atribuidor simples \presentationPause\item Ele atribui o valor a direita à variável a direita \presentationPause\item Cuidado para não inverter \presentationPause\item Não atribuir tipos a variáveis de outros tipos \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-2}]{../../code/operators/assignment.sintax.cpp} \end{frame}\begin{frame}{Atribuidor simples} \lstinputlisting{../../code/operators/assignment.example.cpp} \end{frame} \begin{frame}{Aritméticos} \begin{itemize} \presentationPause\item As quatro operações básicas da matemática \presentationPause\item Os símbolos padrão \presentationPause\item Não alteram o valor registrado \presentationPause\item Cuidado para não dividir por 0 \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-6}] {../../code/operators/arithmetic.sintax.cpp} \presentationPause\begin{equation}\nonumber \begin{array}{cc} \text{\basicCode{E}} & \multicolumn{1}{|c}{\text{\basicCode{F}}} \\ \cline{2-2} \text{\basicCode{G}} & \text{\basicCode{H}} \end{array} \Rightarrow \begin{array}{cc} 13 & \multicolumn{1}{|c}{5} \\ \cline{2-2} 3 & 2 \end{array} \end{equation} \end{frame}\begin{frame}{Aritméticos} \lstinputlisting{../../code/operators/arithmetic.example.cpp} \end{frame} \begin{frame}{Deslocadores} \begin{itemize} \presentationPause\item Os deslocadores são operações bit-a-bit \presentationPause\item São operadores que multiplicam o valor registrado por potências de 2 \presentationPause\item Não alteram o valor registrado \presentationPause\item É mais rápido do que uma multiplicação comum \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-3}]{../../code/operators/shift.sintax.cpp} \begin{equation}\nonumber V\!\cdot\!2^{+S} \ \ \ \ \ \ \ \ \ \ V\!\cdot\!2^{-S} \end{equation} \end{frame}\begin{frame}{Deslocadores} \lstinputlisting{../../code/operators/shift.example.cpp} \end{frame} \begin{frame}{Lógicos bit-a-bit} \begin{itemize} \presentationPause\item Operadores lógicos normais \presentationPause\item Trabalham separadamente a cada bit \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-4}]{../../code/operators/bitwise.sintax.cpp} \presentationPause\begin{table}[!h] \centering \caption{Tabela verdade para operadores lógicos} \label{table.truth} \begin{tabular}{c|c||c|c|c|c|c} A & B & $_\text{\emph{NOT}}$ A & $_\text{\emph{NOT}}$ B & A $_\text{\emph{OR} }$B & A $_\text{\emph{AND}}$ B & A $_\text{\emph{XOR}}$ B \\\hline 0 & 0 & 1 & 1 & 0 & 0 & 0 \\ 0 & 1 & 1 & 0 & 1 & 0 & 1 \\ 1 & 0 & 0 & 1 & 1 & 0 & 1 \\ 1 & 1 & 0 & 0 & 1 & 1 & 0 \\ \end{tabular} \end{table} \end{frame}\begin{frame}{Lógicos bit-a-bit} \lstinputlisting{../../code/operators/bitwise.example.cpp} \presentationPause\begin{equation}\nonumber \begin{array}{cc} & 10101011\\ _\text{\emph{OR}}\! & 01100100\\\cline{2-2} & 11101111 \end{array}\ \begin{array}{cc} & 10101011\\ _\text{\emph{AND}}\! & 01100100\\\cline{2-2} & 00100000 \end{array}\ \begin{array}{cc} & 10101011\\ _\text{\emph{XOR}}\! & 01100100\\\cline{2-2} & 11001111 \end{array} \end{equation} \end{frame} \begin{frame}{Atribuidor composto} \begin{itemize} \presentationPause\item Uma simplificação de operações que atribuem valores \presentationPause\item Operações mais simples são sempre escritas desta maneira \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-4}]{../../code/operators/compound.sintax.cpp} \end{frame}\begin{frame}{Atribuidor composto} \begin{table}[!h] % \footnotesize \centering \caption{Relação de operadores de atribuição composta e seus equivalentes} \label{table.compound} \begin{tabular}{rclcrcccl} \multicolumn{3}{c}{Composto} & & \multicolumn{5}{c}{Equivalente}\\\hline \basicCode{A} & \basicCode{+=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{+} & \basicCode{B;} \\ \basicCode{A} & \basicCode{-=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{-} & \basicCode{B;} \\ \basicCode{A} & \basicCode{*=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{*} & \basicCode{B;} \\ \basicCode{A} & \basicCode{/=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{/} & \basicCode{B;} \\ \basicCode{A} & \basicCode{\%=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{\%} & \basicCode{B;} \\ \basicCode{A} & \basicCode{>>=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{>>} & \basicCode{B;} \\ \basicCode{A} & \basicCode{<<=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{<<} & \basicCode{B;} \\ \basicCode{A} & \basicCode{\|=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{\|} & \basicCode{B;} \\ \basicCode{A} & \basicCode{\&=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{\&} & \basicCode{B;} \\ \basicCode{A} & \basicCode{^=} & \basicCode{B;} & $\Leftrightarrow$ & \basicCode{A} & \basicCode{=} & \basicCode{A} & \basicCode{^} & \basicCode{B;} \end{tabular} \end{table} \end{frame}\begin{frame}{Atribuidor composto} \lstinputlisting{../../code/operators/compound.example.cpp} \end{frame} \begin{frame}{Comparadores} \begin{itemize} \presentationPause\item Verificar se valores são iguais ou diferentes \presentationPause\item Descobrir se um valor é maior que outro \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-7}]{../../code/operators/comparison.sintax.cpp} \end{frame}\begin{frame}{Comparadores} \lstinputlisting{../../code/operators/comparison.example.cpp} \end{frame} \begin{frame}{Lógicos Booleanos} \begin{itemize} \presentationPause\item Servem para fazer junção de tipos \basicCode{bool} \presentationPause\item Montar expressões de dependências lógicas mais compostas \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-3}]{../../code/operators/logic.sintax.cpp} \end{frame}\begin{frame}{Lógicos Booleanos} \lstinputlisting{../../code/operators/logic.example.cpp} \end{frame} \section{Ternário} \begin{frame}{Operador ternário} \begin{itemize} \presentationPause\item Não tem nome próprio \presentationPause\frownie \presentationPause\item Faz escolhas a partir de decisões \presentationPause\item Não altera o fluxo do código \presentationPause\item É simpático \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-2}]{../../code/operators/ternary.sintax.cpp} \end{frame}\begin{frame}{Operador ternário} \lstinputlisting{../../code/operators/ternary.example.cpp} \end{frame} \section{Precedência} \begin{frame}{Precedência} \begin{itemize} \presentationPause\item Os operadores tem preferência de ordem \presentationPause\item \basicCode{1 + 1 + 1 + 1 * 0 = } ? \end{itemize} \presentationPause\lstinputlisting[numbers=none,linerange={2-2}]{../../code/operators/precedence.example.1.cpp} \presentationPause\lstinputlisting[numbers=none,linerange={2-2}]{../../code/operators/precedence.example.2.cpp} \end{frame}\begin{frame}{Precedência} \begin{itemize} \presentationPause\item Ambiguidades \presentationPause\item Mudando a precedência \presentationPause\item Operador de preferência \presentationPause\item Igual a matemática \end{itemize} \end{frame}\begin{frame}{Precedência} \begin{table}[!h] \footnotesize\centering \caption{Ordem de precedência de operadores} \label{table.precedence} \begin{tabular}{cc} Operador & Descrição \\\hline \basicCode{()} & preferencal\\\hline\presentationPause \basicCode{++}, \basicCode{--} & posfixo \\\hline\presentationPause \basicCode{++}, \basicCode{--} & prefixo \\\hline\presentationPause \basicCode{\~}, \basicCode{!} & lógico \\\hline\presentationPause \basicCode{+}, \basicCode{-} & sinalizadore \\\hline\presentationPause \basicCode{*}, \basicCode{/}, \basicCode{\%} & aritimético \\ \basicCode{+}, \basicCode{-} & aritimético \\\hline\presentationPause \basicCode{<<}, \basicCode{>>} & deslocador \\\hline\presentationPause \basicCode{<}, \basicCode{<=}, \basicCode{>=}, \basicCode{>} & comparador \\ \basicCode{==}, \basicCode{!=} & comparador \\\hline\presentationPause \basicCode{\&} & lógico \\ \basicCode{\^} & lógico \\ \basicCode{|} & lógico \\ \basicCode{\&\&} & lógico \\ \basicCode{\|\|} & lógico \\\hline\presentationPause \basicCode{?:} & ternário \\ \hline\presentationPause \basicCode{=} & atribuidor \\ \basicCode{+=}, \basicCode{-=}, \basicCode{*=}, \basicCode{/=}, \basicCode{\%=}, \basicCode{\&=}, \basicCode{\^=}, \basicCode{\|=}, \basicCode{<<=}, \basicCode{>>=} & atribuidor \end{tabular} \end{table} \end{frame}\begin{frame}{Precedência} \lstinputlisting{../../code/operators/precedence.example.cpp} \end{frame} \section{Hora de brincar} \begin{frame} \begin{center}\Huge Vamos testar! \end{center} \end{frame} \end{document}
import Link from "next/link"; import Head from 'next/head'; import { useRouter } from "next/router"; import { useState } from "react"; import { toast,Toast, ToastContainer } from "react-toastify"; import 'react-toastify/dist/ReactToastify.css' import axios from "axios"; export default function Register() { const [firstName, setFirstName] = useState(''); const [lastName, setLastName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const router = useRouter(); function register(event){ event.preventDefault(); axios.post(`http://127.0.0.1:4100/api/v1/auth/register`,{ firstName: firstName, lastName: lastName, email, password }).then((response) => { console.log(response); toast.success(`Registration Complete`, { position: 'top-right', autoClose: 1000, pauseOnHover: false }) router.push('/login') }).catch(error => { toast.error(`error occured!`, { position: 'top-right', autoClose: 1000, pauseOnHover: false, }) }) } return ( <div className="bg-gray-100 flex items-center justify-center h-screen"> <div className="bg-white w-full max-w-md p-8 rounded-md shadow-md"> <h1 className="text-2xl text-gray-400 font-semibold mb-6">Create Account</h1> <ToastContainer/> <form onSubmit={register} className="bg-white px-1 py-1 rounded-xl text-black w-full"> {/* <div className="mb-4"> <label className="block text-gray-600 text-sm mb-2">Student ID</label> <input type="text" id="studentId" name="studentId" className="w-full px-3 py-2 placeholder-gray-400 border rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white" placeholder="" required onChange={e => setStudentId(e.target.value)} /> </div> */} <div className="mb-4"> <label className="block text-gray-600 text-sm mb-2">First Name</label> <input type="text" className="w-full px-3 py-2 placeholder-gray-400 border rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white" name="firstName" // placeholder="First Name" required onChange={e => setFirstName(e.target.value)} /> </div> <div className="mb-4"> <label className="block text-gray-600 text-sm mb-2">Last Name</label> <input type="text" className="w-full px-3 py-2 placeholder-gray-400 border rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white" name="lastName" // placeholder="Last Name" required onChange={e => setLastName(e.target.value)} /> </div> <div className="mb-4"> <label className="block text-gray-600 text-sm mb-2">Email</label> <input type="email" id="email" name="email" className="w-full px-3 py-2 placeholder-gray-400 border rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white" placeholder="" required onChange={e => setEmail(e.target.value)} /> </div> <div className="mb-4"> <label className="block text-gray-600 text-sm mb-2">Password</label> <input type="password" id="password" name="password" className="w-full px-3 py-2 placeholder-gray-400 border rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white" placeholder="" required onChange={e => setPassword(e.target.value)} /> </div> <button type="submit" className="w-full text-center font-semibold py-2 rounded bg-gray-500 text-white focus:outline-none my-2">Create Account</button> </form> <div className="text-slate-600 mt-6"> Already have an account? <Link href="/login" className="p-2 font-bold font-sans border-b-2 border-double border-transparent hover:border-current cursor-pointer select-none"> Login </Link> </div> </div> </div> ) }
/* Copyright (c) 2006-2009, Tom Thielicke IT Solutions 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /**************************************************************** ** ** Definition of the StartSql class ** File name: startsql.h ** ****************************************************************/ #ifndef STARTSQL_H #define STARTSQL_H #include <QListWidget> //#include <QList> //#include <QString> #include <QComboBox> #include <QLineEdit> #include <QTextEdit> #include <QProgressBar> #include <QRadioButton> //! The StartSql class fills a list widget and resets user data . /*! The StartSql class provides 3 functions. The first, fillLessonList(), is to fill a list widget with a lesson list. The other two functions, deleteUserLessonList and deleteUserChars, are to reset user data tables. @author Tom Thielicke, s712715 @version 0.0.2 @date 27.06.2006 */ class StartSql { public: //! Constructor is empty. StartSql(); //! Converts an unicode char into layout values of a key. /*! This function fills a list widget with items of the table "lesson_list". If field "user_lesson_lesson" is bigger than 1 icon "lesson_done_multiple.png" is shown, otherwise icon "lesson_done_none.png" is shown. @param listLesson QListWidget which is filled @return bool Operation successful true/false @see opSystem */ int fillLessonList(QListWidget *listLesson, QList<QString> *arrayTraining, QString languageLesson); int fillOpenList(QListWidget *listOpen, QList<QString> *arrayOpen, QString themeId, QString languageLesson); int fillOwnList(QListWidget *listOwn, QList<QString> *arrayOwn); int fillThemes(QComboBox *comboTheme, QList<QString> *arrayThemes, QString languageLesson, QString textAll); void fillLanguage(QComboBox *combo, QString table, QString field); //! Deletes the complete content of table "user_lesson_list". bool deleteUserLessonList(); //! Deletes the complete content of table "user_lesson_list". bool deleteUserChars(); //! Deletes the complete content of table "user_lesson_list". bool deleteOwnLesson(QString lessonnumber); //! Updates the complete content of table "user_lesson_list". bool updateOwnLesson(QString lessonnumber, QString lessonname, QString description, QStringList content, int unit); bool getOwnLesson(QString lessonnumber, QLineEdit *lineLessonName, QLineEdit *lineLessonDescription, QTextEdit *lineLessonContent, QRadioButton *radioUnitSentence, QRadioButton *radioUnitWord); bool ownLessonExist(QString lessonname); bool analyzeOwnLessons(); bool analyzeLessons(QString lessonType); private: QString trim(QString s); }; #endif // STARTSQL_H
<?php /** * @author Amasty Team * @copyright Copyright (c) 2016 Amasty (https://www.amasty.com) * @package Amasty_Cart */ namespace Amasty\Cart\Controller\Cart; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Checkout\Model\Cart as CustomerCart; use Magento\Quote\Model\Quote\Address\Total; use Magento\Checkout\Helper\Data as HelperData; use Magento\Framework\View\Result\PageFactory; use Magento\Framework\Url\Helper\Data as UrlHelper; class Add extends \Magento\Checkout\Controller\Cart\Add { /** * @var \Magento\Framework\Registry */ protected $_registry; /** * @var \Amasty\Cart\Helper\Data */ protected $_helper; /** * @var \Magento\Catalog\Helper\Product */ protected $_productHelper; /** * @var \Magento\Framework\View\LayoutFactory */ protected $layoutFactory; /** * @var HelperData */ protected $helperData; /** * @var \Magento\Framework\App\ViewInterface */ protected $_view; /** * @var \Magento\Framework\View\Result\PageFactory */ protected $resultPageFactory; /** * Core registry * * @var \Magento\Framework\Registry */ protected $_coreRegistry; /** * @var UrlHelper */ protected $urlHelper; /** * @var \Magento\Catalog\Model\Session */ protected $catalogSession; /** * @var \Magento\Catalog\Model\CategoryFactory */ protected $categoryFactory; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Checkout\Model\Session $checkoutSession, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator, CustomerCart $cart, ProductRepositoryInterface $productRepository, \Magento\Framework\Registry $registry, \Amasty\Cart\Helper\Data $helper, \Magento\Catalog\Helper\Product $productHelper, \Magento\Framework\View\LayoutInterface $layout, PageFactory $resultPageFactory, \Magento\Framework\Registry $coreRegistry, \Magento\Catalog\Model\Session $catalogSession, \Magento\Catalog\Model\CategoryFactory $categoryFactory, HelperData $helperData, UrlHelper $urlHelper ) { parent::__construct( $context, $scopeConfig, $checkoutSession, $storeManager, $formKeyValidator, $cart, $productRepository ); $this->_registry = $registry; $this->_helper = $helper; $this->_productHelper = $productHelper; $this->layout = $layout; $this->helperData = $helperData; $this->resultPageFactory = $resultPageFactory; $this->_view = $context->getView(); $this->_coreRegistry = $coreRegistry; $this->urlHelper = $urlHelper; $this->catalogSession = $catalogSession; $this->categoryFactory = $categoryFactory; } public function execute() { if (!$this->_formKeyValidator->validate($this->getRequest())) { $message = __('We can\'t add this item to your shopping cart right now. Please reload the page.'); return $this->addToCartResponse($message, 0); } $params = $this->getRequest()->getParams(); $product = $this->_initProduct(); /** * Check product availability */ if (!$product) { $message = __('We can\'t add this item to your shopping cart right now.'); return $this->addToCartResponse($message, 0); } try { $needShowOptions = $product->getTypeInstance()->hasRequiredOptions($product) || ($this->_helper->getModuleConfig('general/display_options') && $product->getHasCustomOptions()); if(in_array($product->getTypeId(), ['configurable', 'grouped', 'bundle']) && !(array_key_exists('super_attribute', $params) || array_key_exists('super_group', $params) || array_key_exists('bundle_option', $params) ) || ($needShowOptions && !array_key_exists('options', $params) && !in_array($product->getTypeId(), ['configurable', 'grouped', 'bundle']) ) ) { return $this->showOptionsResponse($product); } if (isset($params['qty'])) { $filter = new \Zend_Filter_LocalizedToNormalized( ['locale' => $this->_objectManager->get('Magento\Framework\Locale\ResolverInterface')->getLocale()] ); $params['qty'] = $filter->filter($params['qty']); } $related = $this->getRequest()->getParam('related_product'); $this->cart->addProduct($product, $params); if (!empty($related)) { $this->cart->addProductsByIds(explode(',', $related)); } $this->cart->save(); $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] ); if (!$this->_checkoutSession->getNoCartRedirect(true)) { if (!$this->cart->getQuote()->getHasError()) { $message = '<p>' . __( 'You added %1 to your shopping cart.', '<a href="' . $product->getProductUrl() .'" title=" . ' . $product->getName() . '">' . $product->getName() . '</a>' ) . '</p>'; $message = $this->getProductAddedMessage($product, $message); return $this->addToCartResponse($message, 1); } else{ $message = ''; $errors = $this->cart->getQuote()->getErrors(); foreach ($errors as $error){ $message .= $error->getText(); } return $this->addToCartResponse($message, 0); } } } catch (\Magento\Framework\Exception\LocalizedException $e) { return $this->addToCartResponse( $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($e->getMessage()) , 0 ); } catch (\Exception $e) { $message = __('We can\'t add this item to your shopping cart right now.'); $message .= $e->getMessage(); return $this->addToCartResponse($message, 0); } } //creating options popup protected function showOptionsResponse(\Magento\Catalog\Model\Product $product) { $this->_productHelper->initProduct($product->getEntityId(), $this); $page = $this->resultPageFactory->create(false, ['isIsolated' => true]); $page->addHandle('catalog_product_view'); $type = $product->getTypeId(); $page->addHandle('catalog_product_view_type_' . $type); $block = $page->getLayout()->getBlock('product.info'); if (!$block) { $block = $page->getLayout()->createBlock( 'Magento\Catalog\Block\Product\View', 'product.info', [ 'data' => [] ] ); } $block->setProduct($product); $html = $block->toHtml(); /* replace uenc for correct redirect*/ $currentUenc = $this->urlHelper->getEncodedUrl(); $refererUrl = $product->getProductUrl(); $newUenc = $this->urlHelper->getEncodedUrl($refererUrl); $html = str_replace($currentUenc, $newUenc, $html); $result = array( 'title' => __('Set options'), 'message' => $html, 'b1_name' => __('Add to cart'), 'b2_name' => __('Cancel'), 'b1_action' => 'self.submitFormInPopup();', 'b2_action' => 'self.confirmHide();', 'align' => 'self.confirmHide();' , 'is_add_to_cart' => '0' ); $result = $this->replaceJs($result); return $this->getResponse()->representJson( $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result) ); } protected function getProductAddedMessage(\Magento\Catalog\Model\Product $product, $message) { if ($this->_helper->displayProduct()) { $block = $this->layout->getBlock('amasty.cart.product'); if (!$block) { $block = $this->layout->createBlock( 'Amasty\Cart\Block\Product', 'amasty.cart.product', [ 'data' => [] ] ); } $block->setProduct($product); $message = $block->toHtml(); } //display count cart item if ($this->_helper->displayCount()) { $summary = $this->cart->getSummaryQty(); $cartUrl = $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getCartUrl(); if ($summary == 1) { $message .= "<p id='amcart-count'>" . __('There is') . ' <a href="' . $cartUrl . '" id="am-a-count">1' . __(' item') . '</a>'. __(' in your cart.') . "</p>"; } else{ $message .= "<p id='amcart-count'>". __('There are') . ' <a href="'. $cartUrl .'" id="am-a-count">'. $summary. __(' items') . '</a> '. __(' in your cart.') . "</p>"; } } //display summ price if ($this->_helper->displaySumm()) { $message .= '<p>' . __('Cart Subtotal:') . ' <span class="am_price">'. $this->getSubtotalHtml() . '</span></p>'; } //display related products if ($this->_helper->getModuleConfig('selling/related')) { //$this->_coreRegistry->register('product', $product); $this->_productHelper->initProduct($product->getEntityId(), $this); $relBlock = $this->layout->createBlock( 'Amasty\Cart\Block\Product\Related', 'amasty.cart.product_related', [ 'data' => [] ] ); $relBlock->setProduct($product)->setTemplate("Amasty_Cart::product/list/items.phtml"); $message .= $relBlock->toHtml(); /* replace uenc for correct redirect*/ $currentUenc = $this->urlHelper->getEncodedUrl(); $refererUrl = $this->_request->getServer('HTTP_REFERER'); $newUenc = $this->urlHelper->getEncodedUrl($refererUrl); $message = str_replace($currentUenc, $newUenc, $message); } return $message; } //creating finale popup protected function addToCartResponse($message, $status) { $cartUrl = $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getCartUrl(); $checkouttUrl = $this->_helper->getUrl('checkout'); $result = array( 'title' => __('Information'), 'message' => $message, 'b1_name' => __('View cart'), 'b2_name' => __('Continue Shopping'), 'b3_name' => __('Go To Checkout'), 'b1_action' => 'document.location = "' . $cartUrl . '";', 'b2_action' => 'self.confirmHide();', 'b3_action' => 'document.location = "' . $checkouttUrl . '";', 'is_add_to_cart' => $status, 'checkout' => '' ); if ($this->_helper->getModuleConfig('display/disp_checkout_button')) { $goto = __('Go to Checkout'); $result['checkout'] = '<a class="checkout action primary" title="' . $goto . '" data-role="proceed-to-checkout" type="button" href="' . $this->_helper->getUrl('checkout') . '" > <span>' . $goto . '</span> </a>'; } $isProductView = $this->getRequest()->getParam('product_page'); if ($isProductView == 'true' && $this->_helper->getProductButton()) { $categoryId = $this->catalogSession->getLastVisitedCategoryId(); if ($categoryId) { $category = $this->categoryFactory->create()->load($categoryId); if ($category) { $result['b2_action'] = 'document.location = "'. $category->getUrl() .'";'; } } } //add timer $time = $this->_helper->getTime(); if (0 < $time) { $result['b2_name'] .= '(' . $time . ')'; } $result = $this->replaceJs($result); return $this->getResponse()->representJson( $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result) ); } //replace js in one place private function replaceJs($result) { $arrScript = array(); $result['script'] = ''; preg_match_all("@<script type=\"text/javascript\">(.*?)</script>@s", $result['message'], $arrScript); $result['message'] = preg_replace("@<script type=\"text/javascript\">(.*?)</script>@s", '', $result['message']); foreach($arrScript[1] as $script) { $result['script'] .= $script; } $result['script'] = preg_replace("@var @s", '', $result['script']); return $result; } protected function getSubtotalHtml() { $totals = $this->cart->getQuote()->getTotals(); $subtotal = isset($totals['subtotal']) && $totals['subtotal'] instanceof Total ? $totals['subtotal']->getValue() : 0; return $this->helperData->formatPrice($subtotal); } }
Exercise 3.0 - Introduction to AS3 Objective ********* Demonstrate building a virtual server (exactly like the Section 1 Ansible F5 Exercises) with F5 AS3 - Learn about AS3 (`Application Services 3 Extension <https://clouddocs.f5.com/products/extensions/f5-appsvcs-extension/3/userguide/about-as3.html>`__) declarative model. It is not the intention of this exercise to learn AS3 thoroughly, but just give some introduction to the concept and show how it easily integrates with Ansible Playbooks. - Learn about the `set_fact module <https://docs.ansible.com/ansible/latest/modules/set_fact_module.html>`__ - Learn about the `uri module <https://docs.ansible.com/ansible/latest/modules/uri_module.html>`__ Guide ***** .. note:: Make sure the BIG-IP configuration is clean, run exercise `2.1-delete-configuration <../2.1-delete-configuration/README.md>`__ before proceeding Step 1: ------- Examine the ``as3.yml`` in the VSCode editor. Expand in the Explorer (f5-bd-ansible-labs --> 101-F5-Basics --> 3.0-as3-intro): .. figure:: ../images/bigip-as3-intro.png :alt: Examine the Code Step 2: ------- Before executing the Playbook, its important to understand how AS3 works. AS3 requires a JSON template to be handed as an API call to F5 BIG-IP. There are two parts: - examine the ``https.j2`` located in the j2 folder .. code:: yaml { "class": "AS3", "action": "deploy", "persist": true, "declaration": { "class": "ADC", "schemaVersion": "3.0.0", "id": "usecase1", "label": "Ansible Workshops", "remark": "HTTPS with pool", "{{ as3_tenant_name }}": { "class": "Tenant", "AS3-UseCase-1": { "class": "Application", "service_Main": { "class": "Service_HTTPS", "virtualAddresses": [ "{{ private_ip }}" ], "profileMultiplex": { "bigip": "/Common/oneconnect" }, "pool": "app_pool", "serverTLS": { "bigip": "/Common/clientssl" }, "persistenceMethods": [] }, "app_pool": { "class": "Pool", "minimumMembersActive": 0, "minimumMonitors": "all", "monitors": [ "http" ], "members": [{ "servicePort": 443, "serverAddresses": [ {% set comma = joiner(",") %} {% for mem in pool_members %} {{comma()}} "{{ hostvars[mem]['private_ip'] }}" {% endfor %} ] }] } } } } } ``https.j2`` is a JSON representation of the Web Application. The important parts to note are: - The template can use variables just like tasks do in previous exercises. In this case the virtual IP address is the private_ip from our inventory. - There is a virtual server named ``service_Main``. - ``"WorkshopExample"`` - this is the name of our Tenant. The AS3 will create a tenant for this particular WebApp. A WebApp in this case is a virtual server that load balances between our two web servers. - ``"class": "Tenant"`` - this indicates that ``WorkshopExample`` is a Tenant. - ``{{ as3_app_body }}`` - this is a variable that will point to the second jinja2 template which is the actual WebApp. - ``"class": "Service_HTTPS"`` - defines the class of application service delivered, in this case its a HTTP Virtual Server. - ``"virtualAddresses":`` - is an array object that contains the variable private_ip which is used for the Virtual Server being created. - ``"pool": "app_pool"`` - utlizes a pool created further down the template to import the web servers. - There is a Pool named ``app_pool`` The jinja2 template can use a loop to grab all the pool members (which points to our web servers group that will be elaborated on below). - ``"class": "pool"`` - Sets up the pool utilized in the ``serviceMain`` section - ``"monitors":`` - Can utilize a built-in or created monitor (typically created in the AS3 template) to setup proper monitoring for the pool memebers. - ``"members"`` - An arraylist of members and their service ports to attach to the created pool to deliver the application. **In Summary** the ``https.j2`` is a single JSON payload that represents a Web Application. We will build a Playbook that will send this JSON payload to a F5 BIG-IP. Step 3: ------- Change directories to the exercise 3.0 folder to examine and execute the code in the Terminal .. code:: cd ~/f5-bd-ansible-labs/101-F5-Basics/3.0-as3-intro/ Step 4: ------- Run the playbook - Go back to the Terminal on VS Code server on the control host and execute the following: .. code:: ansible-navigator run as3.yml --mode stdout **Playbook Output** .. code:: yaml [rhel-user@ede7a345-c0f1-47f9-a73b-74fded8ec113 3.0-as3-intro]$ ansible-navigator run as3.yml --mode stdout PLAY [AS3 Tenant] ************************************************************** TASK [PUSH AS3 Template] ******************************************************* changed: [f5] PLAY RECAP ********************************************************************* f5 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 .. note:: If there is an error running the AS3 template there is a error handling block that will re-install AS3 automatically then retry the code. Solution ******** The finished Ansible Playbook is provided here. Click here: `as3.yml <https://github.com/network-automation/linklight/blob/master/exercises/ansible_f5/3.0-as3-intro/as3.yml>`__. Verifying the Solution ---------------------- - Login to the F5 with your web browser to see what was configured. Grab the IP information for the F5 load balancer from the lab_inventory/hosts file, and type it in like so: * **AWS Provisioner** - https://X.X.X.X:8443/ * **F5 UDF** - https://X.X.X.X:443/ - Login information for the BIG-IP: * username: admin * password: **found in the inventory hosts file** - Now your application (Virtual Server/Pool/Nodes) will be fully created and now will be located in the partition ``WorkshopExample`` |f5-as3.png| .. note:: The Application will be in a Errored State this is expected behavior and will be remediated in Section 3.1 You have finished this exercise. .. |f5-as3.png| image:: ../images/f5-as3.gif
/* global inject */ 'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('gmitcat')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { // MainCtrl.todos = []; scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope // place here mocked dependencies }); })); it('should have no items to start', function () { expect(MainCtrl.todos.length).toBe(0); }); it('should add items to the list', function () { MainCtrl.todo = 'Test 1'; MainCtrl.addTodo(); expect(MainCtrl.todos.length).toBe(1); }); it('should add then remove item from the list', function () { MainCtrl.todo = 'Test 1'; MainCtrl.addTodo(); MainCtrl.removeTodo(0); expect(MainCtrl.todos.length).toBe(0); }); });
"use client"; import { DataVerifyEmailProps } from "@/@types"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import schema from "@/schemas/verify-email"; import { zodResolver } from "@hookform/resolvers/zod"; import { useRouter } from "next/navigation"; import { useForm, SubmitHandler } from "react-hook-form"; import { Input } from "./ui/input"; import { useMutation } from "@tanstack/react-query"; import ButtonSumit from "./buttonSubmit"; import { toast } from "react-toastify"; import { confirmEmail } from "@/server"; export default function VerifyEmail() { const { data, isPending, isError, isSuccess, mutate } = useMutation({ mutationFn: (validateCode: string | number) => confirmEmail(validateCode), }); const form = useForm<DataVerifyEmailProps>({ mode: "onChange", resolver: zodResolver(schema), defaultValues: { validateCode: "", }, }); const { reset, formState: { isDirty, isValid }, } = form; const { push } = useRouter(); const onSubmit: SubmitHandler<DataVerifyEmailProps> = async ( { validateCode }, event ) => { event?.preventDefault(); mutate(+validateCode); if (isSuccess) { push("/"); reset(); console.log("Conta criada.", data); toast.success("Conta criada com sucesso."); return; } if (isError) { toast.error("código de verificação errado."); toast.info("Enviamos o código de verificação no seu email"); toast.info("O código de verificação expira após cinco minutos."); console.log("validateCode ", validateCode); } }; return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 flex w-[50%] justify-center items-center" > <div className="flex flex-col gap-2 p-4 rounded-2xl bg-blue-300 w-[85%] h-[37%]"> <h1 className="text-center font-bold text-2xl"> Verificação da cota </h1> <FormField control={form.control} name="validateCode" render={({ field }) => ( <FormItem> <FormLabel>Código de verificação: </FormLabel> <FormControl> <Input type="number" placeholder="Digite o codigo de verificação" {...field} className="rounded-full p-2" maxLength={6} /> </FormControl> <FormMessage className="text-red-500" /> </FormItem> )} /> <ButtonSumit isDirty={isDirty} target="Verificar" targetLoading="Verificando..." className="self-center p-4" isValid={isValid} isPending={isPending} /> </div> </form> </Form> ); }
import { LoginUser, NewUser, User } from "../types/user"; const mockUsers: User[] = [ { id: 1, email: "rokas@gmail.com", password: "rokas", first_name: "Rokas", last_name: "Andreikenas", createdAt: "2023-03-02T20:30:06.000000Z", updatedAt: "2023-03-02T20:30:06.000000Z", }, { id: 2, email: "romas@gmail.com", password: "romas", first_name: "Romas", last_name: "Romelis", createdAt: "2023-03-02T20:30:06.000000Z", updatedAt: "2023-03-02T20:30:06.000000Z", }, { id: 3, email: "tomas@gmail.com", password: "tomas", first_name: "Tomas", last_name: "Tomelis", createdAt: "2023-03-02T20:30:06.000000Z", updatedAt: "2023-03-02T20:30:06.000000Z", }, ]; export const fetchUsers = async (): Promise<User[]> => { return new Promise((resolve) => { setTimeout(() => { resolve(mockUsers); }, 1000); }); }; export const createUser = async (newUser: NewUser): Promise<User> => { return new Promise((resolve) => { setTimeout(() => { resolve({ ...newUser, id: Date.now(), createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }); }, 1000); }); }; export const deleteUser = async (id: number): Promise<User> => { const deletedUser = mockUsers.filter((user) => user.id === id)[0]; return new Promise((resolve) => { setTimeout(() => { resolve(deletedUser); }, 1000); }); }; export const loginUser = async (loggingUser: LoginUser): Promise<User> => { const users = await fetchUsers(); return new Promise((resolve, reject) => { const { email, password } = loggingUser; const userChecker = (u: User) => u.email === email && u.password === password; const existingUser = users.find(userChecker); existingUser ? resolve(existingUser) : reject("Invalid credentials"); }); };
package it.leonardo.leonardoapiboot.controller; import io.sentry.Sentry; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import it.leonardo.leonardoapiboot.entity.Livello; import it.leonardo.leonardoapiboot.service.LivelloService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/livelli") @CrossOrigin(origins = {"https://leonardostart.tk", "https://localhost", "https://buybooks.it"}, allowCredentials = "true") public class LivelloController { private final Log log = LogFactory.getLog(LivelloController.class); @Autowired private LivelloService service; @GetMapping @Operation(description = "Restituisce una lista di tutti i livelli raggiungibili.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Richiesta andata a buon fine. La lista è popolata e restituita"), @ApiResponse(responseCode = "204", description = "Richiesta andata a buon fine, ma la lista è vuota"), @ApiResponse(responseCode = "500", description = "Errore generico del server") }) public ResponseEntity<List<Livello>> getAll() { log.info("Invoked LivelloController.getAll()"); try { List<Livello> lst = service.getAll(); if (lst.isEmpty()) return ResponseEntity.noContent().build(); return ResponseEntity.ok(lst); } catch (Exception e) { Sentry.captureException(e); return ResponseEntity.internalServerError().build(); } } @GetMapping("{id}") @Operation(description = "Restituisce l'oggetto relativo al livello il quale id è fornito") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Richiesta andata a buon fine, l'oggetto è restituito"), @ApiResponse(responseCode = "404", description = "Non è stato possibile trovare l'oggetto associato all'id fornito"), @ApiResponse(responseCode = "500", description = "Errore generico del server") }) public ResponseEntity<Livello> getById(@PathVariable("id") Integer id) { log.info("Invoked LivelloController.getById(" + id + ")"); try { Optional<Livello> lvl = service.getById(id); if (!lvl.isPresent()) return ResponseEntity.notFound().build(); return ResponseEntity.ok(lvl.get()); } catch (Exception e) { Sentry.captureException(e); return ResponseEntity.internalServerError().build(); } } }
/* Copyright (c) 2018 Kent Yang This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. limitations under the License. */ package com.makesrc.examples.io; import java.io.Serializable; import java.util.Objects; /** * Simple bean / data transfer Object for storing and passing data types within the particular * domain around. * * @author Kent Yang */ public class Person implements Serializable { static final long serialVersionUID = 1L; private String firstName; private String lastName; private String email; private String phone; public Person(String line) { line = line.trim(); String[] array = line.split("[, ]+"); assert(array.length > 4); this.firstName = array[0]; this.lastName = array[1]; this.email = array[2]; this.phone = array[3]; } public Person(String firstName, String lastName, String email, String phone) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.phone = phone; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmail() { return email; } public String getPhone() { return phone; } @Override public int hashCode() { return Objects.hash(firstName, lastName, email, phone); } @Override public String toString() { final StringBuilder sb; sb = new StringBuilder("Person{"); sb.append("firstName='").append(getFirstName()).append('\''); sb.append(", lastName='").append(getLastName()).append('\''); sb.append(", email='").append(getEmail()).append('\''); sb.append(", phone='").append(getPhone()).append('\''); sb.append('}'); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName) && Objects.equals(email, person.email) && Objects.equals(phone, person.phone); } }
part of blocs; abstract class EmployerState extends Equatable { const EmployerState(); @override List<Object> get props => []; } class EmployerInitialState extends EmployerState { @override String toString() => "InitializePageState"; } //Employer ContactUs class EmployerContactUsLoading extends EmployerState {} class EmployerContactUsSuccess extends EmployerState { final DataResponseModel data; const EmployerContactUsSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerContactUsFail extends EmployerState { final String message; const EmployerContactUsFail({required this.message}); } //Employer Login class EmployerLoginLoading extends EmployerState {} class EmployerLoginSuccess extends EmployerState { final DataResponseModel data; const EmployerLoginSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerLoginFail extends EmployerState { final String message; const EmployerLoginFail({required this.message}); } //Employer Register class EmployerRegisterLoading extends EmployerState {} class EmployerRegisterSuccess extends EmployerState { final DataResponseModel data; const EmployerRegisterSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerRegisterFail extends EmployerState { final String message; const EmployerRegisterFail({required this.message}); } //Employer Social Login class EmployerSocialLoginLoading extends EmployerState {} class EmployerSocialLoginSuccess extends EmployerState { final DataResponseModel data; const EmployerSocialLoginSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerSocialLoginFail extends EmployerState { final String message; const EmployerSocialLoginFail({required this.message}); } //Employer Social Register class EmployerSocialRegisterLoading extends EmployerState {} class EmployerSocialRegisterSuccess extends EmployerState { final DataResponseModel data; const EmployerSocialRegisterSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerSocialRegisterFail extends EmployerState { final String message; const EmployerSocialRegisterFail({required this.message}); } //Employer Logout class EmployerLogoutLoading extends EmployerState {} class EmployerLogoutSuccess extends EmployerState { final DataResponseModel data; const EmployerLogoutSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerLogoutFail extends EmployerState { final String message; const EmployerLogoutFail({required this.message}); } //Employer Configs class EmployerConfigsLoading extends EmployerState {} class EmployerConfigsSuccess extends EmployerState { final DataResponseModel data; const EmployerConfigsSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerConfigsFail extends EmployerState { final String message; const EmployerConfigsFail({required this.message}); } //Employer Countries class EmployerCountriesLoading extends EmployerState {} class EmployerCountriesSuccess extends EmployerState { final DataResponseModel data; const EmployerCountriesSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCountriesFail extends EmployerState { final String message; const EmployerCountriesFail({required this.message}); } //Employer Genders class EmployerGendersLoading extends EmployerState {} class EmployerGendersSuccess extends EmployerState { final DataResponseModel data; const EmployerGendersSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerGendersFail extends EmployerState { final String message; const EmployerGendersFail({required this.message}); } //Employer Language Types class EmployerLanguageTypesLoading extends EmployerState {} class EmployerLanguageTypesSuccess extends EmployerState { final DataResponseModel data; const EmployerLanguageTypesSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerLanguageTypesFail extends EmployerState { final String message; const EmployerLanguageTypesFail({required this.message}); } //Employer Religions class EmployerReligionsLoading extends EmployerState {} class EmployerReligionsSuccess extends EmployerState { final DataResponseModel data; const EmployerReligionsSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerReligionsFail extends EmployerState { final String message; const EmployerReligionsFail({required this.message}); } //Employer Family Status Type class EmployerFamilyStatusTypeLoading extends EmployerState {} class EmployerFamilyStatusTypeSuccess extends EmployerState { final DataResponseModel data; const EmployerFamilyStatusTypeSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerFamilyStatusTypeFail extends EmployerState { final String message; const EmployerFamilyStatusTypeFail({required this.message}); } //Employer Academic Qualification Type class EmployerAcademicQualificationTypeLoading extends EmployerState {} class EmployerAcademicQualificationSuccess extends EmployerState { final DataResponseModel data; const EmployerAcademicQualificationSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerAcademicQualificationTypeFail extends EmployerState { final String message; const EmployerAcademicQualificationTypeFail({required this.message}); } //Employer Availability Status class EmployerAvailabilityStatusLoading extends EmployerState {} class EmployerAvailabilityStatusSuccess extends EmployerState { final DataResponseModel data; const EmployerAvailabilityStatusSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerAvailabilityStatusFail extends EmployerState { final String message; const EmployerAvailabilityStatusFail({required this.message}); } //Employer Update Availability Status class EmployerUpdateAvailabilityStatusLoading extends EmployerState {} class EmployerUpdateAvailabilityStatusSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateAvailabilityStatusSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateAvailabilityStatusFail extends EmployerState { final String message; const EmployerUpdateAvailabilityStatusFail({required this.message}); } //Employer Employments class EmployerEmploymentsLoading extends EmployerState {} class EmployerEmploymentsSuccess extends EmployerState { final DataResponseModel data; const EmployerEmploymentsSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerEmploymentsFail extends EmployerState { final String message; const EmployerEmploymentsFail({required this.message}); } //Employer Create Employment class EmployerCreateEmploymentLoading extends EmployerState {} class EmployerCreateEmploymentSuccess extends EmployerState { final DataResponseModel data; const EmployerCreateEmploymentSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCreateEmploymentFail extends EmployerState { final String message; const EmployerCreateEmploymentFail({required this.message}); } //Employer Update Employments class EmployerUpdateEmploymentLoading extends EmployerState {} class EmployerUpdateEmploymentSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateEmploymentSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateEmploymentFail extends EmployerState { final String message; const EmployerUpdateEmploymentFail({required this.message}); } //Employer Delete Employments class EmployerDeleteEmploymentLoading extends EmployerState {} class EmployerDeleteEmploymentSuccess extends EmployerState { final DataResponseModel data; const EmployerDeleteEmploymentSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerDeleteEmploymentFail extends EmployerState { final String message; const EmployerDeleteEmploymentFail({required this.message}); } //Employer Create Avatar(Image/Video Upload) class EmployerCreateAvatarLoading extends EmployerState {} class EmployerCreateAvatarSuccess extends EmployerState { final DataResponseModel data; const EmployerCreateAvatarSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCreateAvatarFail extends EmployerState { final String message; const EmployerCreateAvatarFail({required this.message}); } //Employer Delete Avatar class EmployerDeleteAvatarLoading extends EmployerState {} class EmployerDeleteAvatarSuccess extends EmployerState { final DataResponseModel data; const EmployerDeleteAvatarSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerDeleteAvatarFail extends EmployerState { final String message; const EmployerDeleteAvatarFail({required this.message}); } //Employer Create About Step(Step 1) class EmployerCreateAboutStepLoading extends EmployerState {} class EmployerCreateAboutStepSuccess extends EmployerState { final DataResponseModel data; const EmployerCreateAboutStepSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCreateAboutStepFail extends EmployerState { final String message; const EmployerCreateAboutStepFail({required this.message}); } //Employer Profile class EmployerProfileLoading extends EmployerState {} class EmployerProfileSuccess extends EmployerState { final DataResponseModel data; const EmployerProfileSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerProfileFail extends EmployerState { final String message; const EmployerProfileFail({required this.message}); } //Employer Update Family Information class EmployerUpdateFamilyInformationLoading extends EmployerState {} class EmployerUpdateFamilyInformationSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateFamilyInformationSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateFamilyInformationFail extends EmployerState { final String message; const EmployerUpdateFamilyInformationFail({required this.message}); } //Employer Update Language class EmployerUpdateLanguageLoading extends EmployerState {} class EmployerUpdateLanguageSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateLanguageSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateLanguageFail extends EmployerState { final String message; const EmployerUpdateLanguageFail({required this.message}); } //App Language & Locale class EmployerUpdateAppLanguageSuccess extends EmployerState { final String language; const EmployerUpdateAppLanguageSuccess({required this.language}); } class EmployerUpdateAppLocaleSuccess extends EmployerState { final String appLocale; const EmployerUpdateAppLocaleSuccess({required this.appLocale}); } //Employer StarList class EmployerStarListLoading extends EmployerState {} class EmployerStarListSuccess extends EmployerState { final DataResponseModel data; const EmployerStarListSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerStarListFail extends EmployerState { final String message; const EmployerStarListFail({required this.message}); } //Employer StarList ADD class EmployerStarListAddLoading extends EmployerState {} class EmployerStarListAddSuccess extends EmployerState { final DataResponseModel data; const EmployerStarListAddSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerStarListAddFail extends EmployerState { final String message; const EmployerStarListAddFail({required this.message}); } //Employer StarList Remove class EmployerStarListRemoveLoading extends EmployerState {} class EmployerStarListRemoveSuccess extends EmployerState { final DataResponseModel data; const EmployerStarListRemoveSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerStarListRemoveFail extends EmployerState { final String message; const EmployerStarListRemoveFail({required this.message}); } //Employer Forgot Password class EmployerForgotPasswordLoading extends EmployerState {} class EmployerForgotPasswordSuccess extends EmployerState { final DataResponseModel data; const EmployerForgotPasswordSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerForgotPasswordFail extends EmployerState { final String message; const EmployerForgotPasswordFail({required this.message}); } //Employer Reset Password class EmployerResetPasswordLoading extends EmployerState {} class EmployerResetPasswordSuccess extends EmployerState { final DataResponseModel data; const EmployerResetPasswordSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerResetPasswordFail extends EmployerState { final String message; const EmployerResetPasswordFail({required this.message}); } //Employer Spotlights class EmployerCreateSpotlightsLoading extends EmployerState {} class EmployerCreateSpotlightsSuccess extends EmployerState { final DataResponseModel data; const EmployerCreateSpotlightsSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCreateSpotlightsFail extends EmployerState { final String message; const EmployerCreateSpotlightsFail({required this.message}); } //Employer Working Preferences class EmployerUpdateWorkingPreferencesLoading extends EmployerState {} class EmployerUpdateWorkingPreferencesSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateWorkingPreferencesSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateWorkingPreferencesFail extends EmployerState { final String message; const EmployerUpdateWorkingPreferencesFail({required this.message}); } //Employer Update FCM class EmployerUpdateFCMLoading extends EmployerState {} class EmployerUpdateFCMSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateFCMSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateFCMFail extends EmployerState { final String message; const EmployerUpdateFCMFail({required this.message}); } //Employer Save Search List class EmployerSaveSearchListLoading extends EmployerState {} class EmployerSaveSearchListSuccess extends EmployerState { final DataResponseModel data; const EmployerSaveSearchListSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerSaveSearchListFail extends EmployerState { final String message; const EmployerSaveSearchListFail({required this.message}); } //Employer Update Save Search class EmployerUpdateSaveSearchLoading extends EmployerState {} class EmployerUpdateSaveSearchSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateSaveSearchSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateSaveSearchFail extends EmployerState { final String message; const EmployerUpdateSaveSearchFail({required this.message}); } //Employer Delete Save Search class EmployerDeleteSaveSearchLoading extends EmployerState {} class EmployerDeleteSaveSearchSuccess extends EmployerState { final DataResponseModel data; const EmployerDeleteSaveSearchSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerDeleteSaveSearchFail extends EmployerState { final String message; const EmployerDeleteSaveSearchFail({required this.message}); } //Employer Create Offer class EmployerCreatOfferLoading extends EmployerState {} class EmployerCreateOfferSuccess extends EmployerState { final DataResponseModel data; const EmployerCreateOfferSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCreateOfferFail extends EmployerState { final String message; const EmployerCreateOfferFail({required this.message}); } //Employer Delete Offer class EmployerDeleteOfferLoading extends EmployerState {} class EmployerDeleteOfferSuccess extends EmployerState { final DataResponseModel data; const EmployerDeleteOfferSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerDeleteOfferFail extends EmployerState { final String message; const EmployerDeleteOfferFail({required this.message}); } //Employer Create Verification class EmployerCreateVerificationLoading extends EmployerState {} class EmployerCreateVerificationSuccess extends EmployerState { final DataResponseModel data; const EmployerCreateVerificationSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCreateVerificationFail extends EmployerState { final String message; const EmployerCreateVerificationFail({required this.message}); } //Employer Delete Account class EmployerDeleteAccountLoading extends EmployerState {} class EmployerDeleteAccountSuccess extends EmployerState { final DataResponseModel data; const EmployerDeleteAccountSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerDeleteAccountFail extends EmployerState { final String message; const EmployerDeleteAccountFail({required this.message}); } //Employer Delete Profile class EmployerDeleteProfileLoading extends EmployerState {} class EmployerDeleteProfileSuccess extends EmployerState { final DataResponseModel data; const EmployerDeleteProfileSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerDeleteProfileFail extends EmployerState { final String message; const EmployerDeleteProfileFail({required this.message}); } //Employer Reviews class EmployerReviewsLoading extends EmployerState {} class EmployerReviewsSuccess extends EmployerState { final DataResponseModel data; const EmployerReviewsSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerReviewsFail extends EmployerState { final String message; const EmployerReviewsFail({required this.message}); } //Employer Create Review class EmployerCreateReviewLoading extends EmployerState {} class EmployerCreateReviewSuccess extends EmployerState { final DataResponseModel data; const EmployerCreateReviewSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCreateReviewFail extends EmployerState { final String message; const EmployerCreateReviewFail({required this.message}); } //Employer Delete Review class EmployerDeleteReviewLoading extends EmployerState {} class EmployerDeleteReviewSuccess extends EmployerState { final DataResponseModel data; const EmployerDeleteReviewSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerDeleteReviewFail extends EmployerState { final String message; const EmployerDeleteReviewFail({required this.message}); } //Employer Coin History class EmployerCoinHistoryListLoading extends EmployerState {} class EmployerCoinHistoryListSuccess extends EmployerState { final DataResponseModel data; const EmployerCoinHistoryListSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCoinHistoryListFail extends EmployerState { final String message; const EmployerCoinHistoryListFail({required this.message}); } //Employer Coin Balance class EmployerCoinBalanceLoading extends EmployerState {} class EmployerCoinBalanceSuccess extends EmployerState { final DataResponseModel data; const EmployerCoinBalanceSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCoinBalanceFail extends EmployerState { final String message; const EmployerCoinBalanceFail({required this.message}); } //Employer Refer Friend List class EmployerReferFriendListLoading extends EmployerState {} class EmployerReferFriendListSuccess extends EmployerState { final DataResponseModel data; const EmployerReferFriendListSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerReferFriendListFail extends EmployerState { final String message; const EmployerReferFriendListFail({required this.message}); } //Employer Update Account class EmployerUpdateAccountLoading extends EmployerState {} class EmployerUpdateAccountSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateAccountSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateAccountFail extends EmployerState { final String message; const EmployerUpdateAccountFail({required this.message}); } //Employer Create Employment Sort class EmployerEmploymentSortLoading extends EmployerState {} class EmployerEmploymentSortSuccess extends EmployerState { final DataResponseModel data; const EmployerEmploymentSortSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerEmploymentSortFail extends EmployerState { final String message; const EmployerEmploymentSortFail({required this.message}); } //Employer Notify Save Search class EmployerNotifySaveSearchLoading extends EmployerState {} class EmployerNotifySaveSearchSuccess extends EmployerState { final DataResponseModel data; const EmployerNotifySaveSearchSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerNotifySaveSearchFail extends EmployerState { final String message; const EmployerNotifySaveSearchFail({required this.message}); } //Employer Update Shareable Link class EmployerUpdateShareableLinkLoading extends EmployerState {} class EmployerUpdateShareableLinkSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateShareableLinkSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateShareableLinkFail extends EmployerState { final String message; const EmployerUpdateShareableLinkFail({required this.message}); } //Employer Check Verified class EmployerCheckVerifiedLoading extends EmployerState {} class EmployerCheckVerifiedSuccess extends EmployerState { final DataResponseModel data; const EmployerCheckVerifiedSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerCheckVerifiedFail extends EmployerState { final String message; const EmployerCheckVerifiedFail({required this.message}); } //Employer Hiring class EmployerHiringLoading extends EmployerState {} class EmployerHiringSuccess extends EmployerState { final DataResponseModel data; const EmployerHiringSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerHiringFail extends EmployerState { final String message; const EmployerHiringFail({required this.message}); } //Employer Profile Complaint class EmployerProfileComplaintLoading extends EmployerState {} class EmployerProfileComplaintSuccess extends EmployerState { final DataResponseModel data; const EmployerProfileComplaintSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerProfileComplaintFail extends EmployerState { final String message; const EmployerProfileComplaintFail({required this.message}); } //Employer Update Configs class EmployerUpdateConfigsLoading extends EmployerState {} class EmployerUpdateConfigsSuccess extends EmployerState { final DataResponseModel data; const EmployerUpdateConfigsSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerUpdateConfigsFail extends EmployerState { final String message; const EmployerUpdateConfigsFail({required this.message}); } //Employer Exchange Rate class EmployerExchangeRateLoading extends EmployerState {} class EmployerExchangeRateSuccess extends EmployerState { final DataResponseModel data; const EmployerExchangeRateSuccess({required this.data}); @override List<Object> get props => [data]; } class EmployerExchangeRateFail extends EmployerState { final String message; const EmployerExchangeRateFail({required this.message}); } //Salary Range Exchange class EmployerPHCSalaryRangeExchangeLoading extends EmployerState {} class EmployerPHCSalaryRangeExchangeSuccess extends EmployerState { final ConvertedSalaryRangeModel convertedSalaryRange; const EmployerPHCSalaryRangeExchangeSuccess({required this.convertedSalaryRange}); @override List<Object> get props => [convertedSalaryRange]; } class EmployerPHCSalaryRangeExchangeFail extends EmployerState { final String message; const EmployerPHCSalaryRangeExchangeFail({required this.message}); }
import { env } from '../src/common/env'; describe('env()', () => { const ENV = process.env; beforeEach(() => { jest.resetModules(); process.env = { ...ENV }; }); afterAll(() => { process.env = ENV; }); it('should return the correct value for an existing environment variable', () => { process.env.TEST_VALUE = 'hello world'; expect(env('TEST_VALUE')).toBe('hello world'); }); it('should throw an error when the specified environment variable does not exist', () => { expect(() => env('hello world')).toThrow('Missing environment variable: hello world'); }); });
import React from "react"; import { BrowserRouter as Router, Route, Routes } from "react-router-dom"; import { Col, Row } from "reactstrap"; import Header from "./components/Header"; import SideNavigation from "./components/SideNavigation"; import Home from "./components/Home"; import UserForm from "./components/User/UserForm"; import ViewUsers from "./components/User/ViewUsers"; import ViewHistory from "./components/ListView/ViewHistory"; import ViewUserInformation from "./components/User/ViewUserInformation"; import ViewAudit from "./components/ListView/ViewAudit"; import ViewProfiles from "./components/Profile/ViewProfiles"; import ProfileForm from "./components/Profile/ProfileForm"; import LoginPage from "./components/Login/LoginPage"; import Logout from "./components/Login/Logout"; import AccountForm from "./components/Account/AccountForm"; import { UserContextProvider } from "./components/User/UserContext"; import { ProfileContextProvider } from "./components/Profile/ProfileContext"; import ViewProfileInformation from "./components/Profile/ViewProfileInformation"; import ApproveUsers from "./components/User/ApproveUsers"; import ApproveProfiles from "./components/Profile/ApproveProfiles"; import ViewApprove from "./components/ListView/ViewApprove"; import { useNavigate } from "react-router-dom"; import { AccountContextProvider } from "./components/Account/AccountContext"; import PrivateRoute from "./components/PrivateRoute"; import { Outlet } from "react-router-dom"; import ViewAccounts from "./components/Account/ViewAccounts"; import { isLoggedInCheck } from "./components/auth/AuthUtils.js"; import ViewAccountInformation from "./components/Account/ViewAccountInformation"; import ApproveAccounts from "./components/Account/ApproveAccounts"; import ChangePassword from "./components/Login/ChangePassword"; import RedirectReq from "./components/RedirectReq"; import ViewCustomers from "./components/Customer/ViewCustomers"; import { CustomerContextProvider } from "./components/Customer/CustomerContext"; import CustomerForm from "./components/Customer/CustomerForm"; import ApproveCustomers from "./components/Customer/ApproveCustomers"; import ViewCustomerInformation from "./components/Customer/ViewCustomerInformation"; import { BalanceContextProvider } from "./components/Balance/BalanceContext"; import ApprovePayments from "./components/Payment/ApprovePayments"; import ViewPayments from "./components/Payment/ViewPayments"; function App() { const styles = { contentDiv: { display: "flex", }, contentMargin: { marginLeft: "10px", width: "100%", }, }; return ( <div> <UserContextProvider> <ProfileContextProvider> <AccountContextProvider> <CustomerContextProvider> <BalanceContextProvider> <Row> <Col> <Header /> </Col> </Row> <div style={styles.contentDiv}> <Router> {isLoggedInCheck() && <SideNavigation />} <Routes> <Route path="/" element={<LoginPage />} /> <Route path="/welcome-user" element={<Home />} /> <Route path="/login" element={<LoginPage />} /> <Route path="/logout" element={<Logout />} /> <Route path="/create-user" element={<UserForm />} /> <Route path="/create-profile" element={<ProfileForm />} /> <Route path="/create-account" element={<AccountForm />} /> <Route path="/create-customer" element={<CustomerForm />} /> <Route path="/edit-user/:username" element={<UserForm />} /> <Route path="/edit-account/:accountnumber" element={<AccountForm />} /> <Route path="/edit-profile/:profileName" element={<ProfileForm />} /> <Route path="/edit-customer/:name" element={<CustomerForm />} /> <Route path="/view-users" element={<ViewUsers />} /> <Route path="/view-accounts" element={<ViewAccounts />} /> <Route path="/view-profiles" element={<ViewProfiles />} /> <Route path="/view-customers" element={<ViewCustomers />} /> <Route path="/view-history" element={<ViewHistory />} /> <Route path="/view-history/:parameter" element={<ViewHistory />} /> <Route path="/view-user/:username" element={<ViewUserInformation />} /> <Route path="/view-profile/:name" element={<ViewProfileInformation />} /> <Route path="/view-account/:accountNumber" element={<ViewAccountInformation />} /> <Route path="/view-customer/:name" element={<ViewCustomerInformation />} /> <Route path="/approve-user/:username" element={<ApproveUsers />} /> <Route path="/approve-profile/:name" element={<ApproveProfiles />} /> <Route path="/approve-account/:accountNumber" element={<ApproveAccounts />} /> <Route path="/approve-customer/:email" element={<ApproveCustomers />} /> <Route path="/view-approve" element={<ViewApprove />} /> <Route path="/view-audit" element={<ViewAudit />} /> <Route path="/change-password" element={<ChangePassword />} /> <Route path="/approve-payments" element={<ApprovePayments/>} /> <Route path="/view-payments" element={<ViewPayments/>} /> <Route path="/redirect/:redirect" element={<RedirectReq />} /> </Routes> </Router> </div> </BalanceContextProvider> </CustomerContextProvider> </AccountContextProvider> </ProfileContextProvider> </UserContextProvider> </div> ); } export default App;
// Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MASTERNODEMAN_H #define MASTERNODEMAN_H #include <masternode.h> #include <sync.h> using namespace std; class CMasternodeMan; class CConnman; extern CMasternodeMan mnodeman; class CMasternodeMan { public: typedef std::pair<arith_uint256, CMasternode*> score_pair_t; typedef std::vector<score_pair_t> score_pair_vec_t; typedef std::pair<int, CMasternode> rank_pair_t; typedef std::vector<rank_pair_t> rank_pair_vec_t; private: static const std::string SERIALIZATION_VERSION_STRING; static const int DSEG_UPDATE_SECONDS = 3 * 60 * 60; static const int LAST_PAID_SCAN_BLOCKS = 100; static const int MIN_POSE_PROTO_VERSION = 70203; static const int MAX_POSE_CONNECTIONS = 10; static const int MAX_POSE_RANK = 10; static const int MAX_POSE_BLOCKS = 10; static const int MNB_RECOVERY_QUORUM_TOTAL = 10; static const int MNB_RECOVERY_QUORUM_REQUIRED = 6; static const int MNB_RECOVERY_MAX_ASK_ENTRIES = 10; static const int MNB_RECOVERY_WAIT_SECONDS = 60; static const int MNB_RECOVERY_RETRY_SECONDS = 3 * 60 * 60; // critical section to protect the inner data structures mutable CCriticalSection cs; // Keep track of current block height int nCachedBlockHeight; // map to hold all MNs std::map<COutPoint, CMasternode> mapMasternodes; // who's asked for the Masternode list and the last time std::map<CNetAddr, int64_t> mAskedUsForMasternodeList; // who we asked for the Masternode list and the last time std::map<CNetAddr, int64_t> mWeAskedForMasternodeList; // which Masternodes we've asked for std::map<COutPoint, std::map<CNetAddr, int64_t> > mWeAskedForMasternodeListEntry; // who we asked for the masternode verification std::map<CNetAddr, CMasternodeVerification> mWeAskedForVerification; // these maps are used for masternode recovery from MASTERNODE_NEW_START_REQUIRED state std::map<uint256, std::pair< int64_t, std::set<CNetAddr> > > mMnbRecoveryRequests; std::map<uint256, std::vector<CMasternodeBroadcast> > mMnbRecoveryGoodReplies; std::list< std::pair<CService, uint256> > listScheduledMnbRequestConnections; /// Set when masternodes are added, cleared when CGovernanceManager is notified bool fMasternodesAdded; /// Set when masternodes are removed, cleared when CGovernanceManager is notified bool fMasternodesRemoved; std::vector<uint256> vecDirtyGovernanceObjectHashes; int64_t nLastWatchdogVoteTime; friend class CMasternodeSync; /// Find an entry CMasternode* Find(const COutPoint& outpoint); bool GetMasternodeScores(const uint256& nBlockHash, score_pair_vec_t& vecMasternodeScoresRet, int nMinProtocol = 0); public: // Keep track of all broadcasts I've seen std::map<uint256, std::pair<int64_t, CMasternodeBroadcast> > mapSeenMasternodeBroadcast; // Keep track of all pings I've seen std::map<uint256, CMasternodePing> mapSeenMasternodePing; // Keep track of all verifications I've seen std::map<uint256, CMasternodeVerification> mapSeenMasternodeVerification; // keep track of dsq count to prevent masternodes from gaming darksend queue int64_t nDsqCount; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { LOCK(cs); std::string strVersion; if(ser_action.ForRead()) { READWRITE(strVersion); } else { strVersion = SERIALIZATION_VERSION_STRING; READWRITE(strVersion); } READWRITE(mapMasternodes); READWRITE(mAskedUsForMasternodeList); READWRITE(mWeAskedForMasternodeList); READWRITE(mWeAskedForMasternodeListEntry); READWRITE(mMnbRecoveryRequests); READWRITE(mMnbRecoveryGoodReplies); READWRITE(nLastWatchdogVoteTime); READWRITE(nDsqCount); READWRITE(mapSeenMasternodeBroadcast); READWRITE(mapSeenMasternodePing); if(ser_action.ForRead() && (strVersion != SERIALIZATION_VERSION_STRING)) { Clear(); } } CMasternodeMan(); /// Add an entry bool Add(CMasternode &mn); /// Ask (source) node for mnb void AskForMN(CNode *pnode, const COutPoint& outpoint, CConnman& connman); void AskForMnb(CNode *pnode, const uint256 &hash); bool PoSeBan(const COutPoint &outpoint); bool AllowMixing(const COutPoint &outpoint); bool DisallowMixing(const COutPoint &outpoint); /// Check all Masternodes void Check(); /// Check all Masternodes and remove inactive void CheckAndRemove(CConnman& connman); /// This is dummy overload to be used for dumping/loading mncache.dat void CheckAndRemove() {} /// Clear Masternode vector void Clear(); /// Count Masternodes filtered by nProtocolVersion. /// Masternode nProtocolVersion should match or be above the one specified in param here. int CountMasternodes(int nProtocolVersion = -1) const; /// Count enabled Masternodes filtered by nProtocolVersion. /// Masternode nProtocolVersion should match or be above the one specified in param here. int CountEnabled(int nProtocolVersion = -1) const; /// Count Masternodes by network type - NET_IPV4, NET_IPV6, NET_ONION // int CountByIP(int nNetworkType); void DsegUpdate(CNode* pnode, CConnman& connman); /// Versions of Find that are safe to use from outside the class bool Get(const COutPoint& outpoint, CMasternode& masternodeRet); bool Has(const COutPoint& outpoint); bool GetMasternodeInfo(const COutPoint& outpoint, masternode_info_t& mnInfoRet); bool GetMasternodeInfo(const CPubKey& pubKeyMasternode, masternode_info_t& mnInfoRet); bool GetMasternodeInfo(const CScript& payee, masternode_info_t& mnInfoRet); /// Find an entry in the masternode list that is next to be paid bool GetNextMasternodeInQueueForPayment(int nBlockHeight, bool fFilterSigTime, int& nCountRet, masternode_info_t& mnInfoRet) const; /// Same as above but use current block height bool GetNextMasternodeInQueueForPayment(bool fFilterSigTime, int& nCountRet, masternode_info_t& mnInfoRet) const; /// Find a random entry masternode_info_t FindRandomNotInVec(const std::vector<COutPoint> &vecToExclude, int nProtocolVersion = -1); std::map<COutPoint, CMasternode> GetFullMasternodeMap() { return mapMasternodes; } bool GetMasternodeRanks(rank_pair_vec_t& vecMasternodeRanksRet, int nBlockHeight = -1, int nMinProtocol = 0); bool GetMasternodeRank(const COutPoint &outpoint, int& nRankRet, int nBlockHeight = -1, int nMinProtocol = 0); void ProcessMasternodeConnections(CConnman& connman); std::pair<CService, std::set<uint256> > PopScheduledMnbRequestConnection(); void ProcessMessage(CNode* pfrom, const string &strCommand, CDataStream& vRecv, CConnman& connman); void DoFullVerificationStep(CConnman& connman); void CheckSameAddr(); bool SendVerifyRequest(const CAddress& addr, const std::vector<CMasternode*>& vSortedByAddr, CConnman& connman); void SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv, CConnman& connman); void ProcessVerifyReply(CNode* pnode, CMasternodeVerification& mnv); void ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerification& mnv); /// Return the number of (unique) Masternodes int size() { return mapMasternodes.size(); } std::string ToString() const; /// Update masternode list and maps using provided CMasternodeBroadcast void UpdateMasternodeList(CMasternodeBroadcast mnb, CConnman& connman); /// Perform complete check and only then update list and maps bool CheckMnbAndUpdateMasternodeList(CNode* pfrom, CMasternodeBroadcast mnb, int& nDos, CConnman& connman); bool IsMnbRecoveryRequested(const uint256& hash) { return mMnbRecoveryRequests.count(hash); } void UpdateLastPaid(const CBlockIndex* pindex); void AddDirtyGovernanceObjectHash(const uint256& nHash) { LOCK(cs); vecDirtyGovernanceObjectHashes.push_back(nHash); } std::vector<uint256> GetAndClearDirtyGovernanceObjectHashes() { LOCK(cs); std::vector<uint256> vecTmp = vecDirtyGovernanceObjectHashes; vecDirtyGovernanceObjectHashes.clear(); return vecTmp;; } bool IsWatchdogActive(); void UpdateWatchdogVoteTime(const COutPoint& outpoint, uint64_t nVoteTime = 0); bool AddGovernanceVote(const COutPoint& outpoint, uint256 nGovernanceObjectHash); void RemoveGovernanceObject(uint256 nGovernanceObjectHash); void CheckMasternode(const CPubKey& pubKeyMasternode, bool fForce); bool IsMasternodePingedWithin(const COutPoint& outpoint, int nSeconds, int64_t nTimeToCheckAt = -1); void SetMasternodeLastPing(const COutPoint& outpoint, const CMasternodePing& mnp); void UpdatedBlockTip(const CBlockIndex *pindex); /** * Called to notify CGovernanceManager that the masternode index has been updated. * Must be called while not holding the CMasternodeMan::cs mutex */ void NotifyMasternodeUpdates(CConnman& connman); }; #endif
// // DetailViewController.swift // Kaipa // // Created by Ariel Waraney on 28/04/22. // import Foundation import UIKit import CoreData class DetailViewController: UIViewController { @IBOutlet weak var itemImage: UIImageView! @IBOutlet weak var itemName: UILabel! @IBOutlet weak var itemSize: UILabel! @IBOutlet weak var itemColor: UILabel! @IBOutlet weak var itemBrand: UILabel! @IBOutlet weak var itemTag: UILabel! @IBOutlet weak var itemFrequency: UILabel! @IBOutlet weak var itemDate: UILabel! @IBOutlet weak var itemFavorite: UIButton! @IBOutlet weak var itemCategory: UILabel! @IBOutlet weak var buttonChoose: UIButton! var img = UIImage() var name = "" var size = "" var color = "" var brand = "" var tag = "" var frequency = 0 var date = Date() var category = "" var favorite = false override func viewDidLoad(){ super.viewDidLoad() tabBarController?.tabBar.isHidden = true title = "Detail" //delete button navbar let delete = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePressed)) navigationItem.rightBarButtonItem = delete itemImage.layer.cornerRadius = 10.0 itemImage.image = img if favorite == true { itemFavorite.setImage(UIImage(systemName: "heart.fill"), for: .normal) } else { itemFavorite.setImage(UIImage(systemName: "heart"), for: .normal) } itemName.text = name itemCategory.text = category itemSize.text = size itemColor.text = color itemBrand.text = brand itemTag.text = tag itemFrequency.text = "\(frequency)" //showing date condition if frequency == 0 { itemDate.text = "-" buttonChoose.setTitle("Choose This Outfit", for: .normal) } else { itemDate.text = "\(convertDateFormatToString(date: date))" buttonChoose.setTitle("Choose This Outfit Again", for: .normal) } } override func viewWillDisappear(_ animated: Bool) { tabBarController?.tabBar.isHidden = false } func convertDateFormatToString(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd MMM yyyy" let resultString = dateFormatter.string(from: date) return resultString } @objc func deletePressed(){ let deleteAlert = UIAlertController(title: "Delete Item?", message: "This step cannot be undone", preferredStyle: .alert) deleteAlert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { (action: UIAlertAction!) in print("Handle Ok logic here") //deleting data selected let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "WearEntity") fetchRequest.predicate = NSPredicate(format: "name = %@", self.name) do { let objectFrom = try context!.fetch(fetchRequest) let objectToDelete = objectFrom[0] as! NSManagedObject context!.delete(objectToDelete) do { try context!.save() } catch { print(error) } } catch let error as NSError { print("Error due to : \(error.localizedDescription)") } })) deleteAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in self.dismiss(animated: true, completion: nil) })) present(deleteAlert, animated: true, completion: nil) } @IBAction func favoritePressed(_ sender: Any) { //user pressing the favorite btn, change the ui if favorite == true { itemFavorite.setImage(UIImage(systemName: "heart"), for: .normal) favorite = false } else { itemFavorite.setImage(UIImage(systemName: "heart.fill"), for: .normal) favorite = true } let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "WearEntity") fetchRequest.predicate = NSPredicate(format: "name = %@", name) do { let object = try context!.fetch(fetchRequest) let objectToUpdate = object[0] as! NSManagedObject objectToUpdate.setValue(favorite, forKey: "isFavoriteStatus") do { try context!.save() } catch { print(error) } } catch let error as NSError { print(error) } } @IBAction func choosedPressed(_ sender: Any) { //update frequency byadding 1 and update date to the current one let newFrequency = frequency + 1 let newDate = Date() let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "WearEntity") fetchRequest.predicate = NSPredicate(format: "name = %@", name) do { let object = try context!.fetch(fetchRequest) let objectToUpdate = object[0] as! NSManagedObject objectToUpdate.setValue(newFrequency, forKey: "frequency") objectToUpdate.setValue(newDate, forKey: "date") objectToUpdate.setValue(true, forKey: "isSelectedStatus") do { try context!.save() displayAlertScreen(title: "Item Selected ✅", msg: "Let's use this outfit for today ✨") } catch { print(error) } } catch let error as NSError { print(error) } } func displayAlertScreen(title: String, msg: String) { let alertController = UIAlertController(title: title, message: msg, preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(alertAction) present(alertController, animated: true, completion: nil) } }
<!doctype HTML> <html> <head> <title>codedamn HTML Playground</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/style.css" /> </head> <body> <section id="container"> <div class="heading"> <h1 id="title"> freeCodeCamp Survey Form </h1> <p id="heading-part">Thank you for taking the time to help us improve the platform</p> </div> <form class="form-details"> <div class="inner-container"> <div class="form-label"> <label for="Name">Name</label> <input type="text" class="name" placeholder="Enter Your Name" required> </div> <div class="form-label"> <label for="Email">Email</label> <input type="email" class="email" placeholder="Enter Your Email" required> </div> <div class="form-label"> <label for="Name">Age (optional)</label> <input type="number" class="age" placeholder="Enter Your Age" required> </div> <div class="form-label"> <label for="drop-details">Which option best describes your current role?</label> <select name="drop-details" id="dropdown"> <option value="volvo">Student</option> <option value="saab">FullTime jOb</option> <option value="mercedes">Fulltime Learner</option> <option value="audi">Other</option> </select> </div> <div class="form-label"> <p>Would you recommend freeCodeCamp to a friend?</p> <label for="Definatly"><input type="radio" id="one" name="formed" value="definitely" > Definately</label> <label for="maybe"><input type="radio" id="two" name="formed" value="maybe" > May Be</label> <label for="Notsure"><input type="radio" id="three" name="formed" value="not-sure" >Not Sure</label> </div> <div class="form-label"> <label for="drop-details">What is your favorite feature of freeCodeCamp?</label> <select name="drop-details" id="dropdown"> <option value="volvo">challenges</option> <option value="saab">Projects</option> <option value="mercedes">Community</option> <option value="audi">Other</option> </select> </div> <div class="form-label"> <p> What would you like to see improved? <span class="clue">(Check all that apply)</span> </p> <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike"> <label for="vehicle1"> Frontend</label><br> <input type="checkbox" id="vehicle2" name="vehicle2" value="Car"> <label for="vehicle2"> Backend</label><br> <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat"> <label for="vehicle3"> Data Analysis</label> </div> <div class="form-label"> <p>Drop Your Opinion</p> <textarea placeholder="Enter Your Opinion" name="" id="" cols="30" rows="10"></textarea> </div> <div id="submit"> <button>Submit</button> </div> </div> </form> </section> </body> </html>
import 'dart:async'; import 'dart:io'; import 'dart:convert' as convert; import 'package:firebase_auth/firebase_auth.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../config/config.dart'; import 'NotificationManager.dart'; import 'package:http/http.dart' as http; class DataService { // plugins late SharedPreferences _prefs; final NotificationManager _notificationManager = NotificationManager(); final FirebaseAuth _auth = FirebaseAuth.instance; // is Connected variable Future<bool> isConnected() async { try { final response = await InternetAddress.lookup('google.com'); if (response.isNotEmpty) { return true; } else { return false; } } on SocketException catch (e) { return false; } catch (e) { return false; } } // Init because the constructor an not be async init() async { _prefs = await SharedPreferences.getInstance(); // await isConnected() ? pushNewAppended() : null; } //constructor DataService(){ } Future<String?> networkGetRequest({required String url}) async { _prefs = await SharedPreferences.getInstance(); return http.get(Uri.http(host,url),headers: { "Authorization":"Bearer ${_prefs.get("token")}" }).then((value){ if(value.statusCode==401){ refreshToken(); return "retry"; } return value.body; }); } Future<String?> networkPostRequest({required String url,required Map<String,dynamic> body}) async { _prefs = await SharedPreferences.getInstance(); final String token = _prefs.get("token")!.toString(); return http.post(Uri.http(host,url),headers: { "Authorization":"Bearer ${token}" },body: body).then((value){ if(value.statusCode==401){ refreshToken(); return "retry"; } return value.statusCode==200||value.statusCode==201?convert.jsonEncode(value.body):null; }); } Future<String> refreshToken() async { String token = await _auth.currentUser!.getIdToken(false).then((value) => value!); if(token!=null){ writeData(key: "token", value: token); return token; }else{ return ""; } } Future<void> writeData({ required String key, required String value }) async { _prefs = await SharedPreferences.getInstance(); _prefs.setString(key, value); } Future<void> writeDataList({ required String key, required List<String> value }) async { _prefs = await SharedPreferences.getInstance(); _prefs.setStringList(key, value); } Future<String?> readData({required String key}) async { _prefs = await SharedPreferences.getInstance(); return _prefs.getString(key); } Future<List<String>?> readDataList({required String key}) async { _prefs = await SharedPreferences.getInstance(); return _prefs.getStringList(key); } }
import React, { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import { ReactComponent as QTLogo } from "../assets/svg/QT.svg"; import Session from "supertokens-auth-react/recipe/session"; import { useSessionContext } from "supertokens-auth-react/recipe/session"; import { doesSessionExist } from "supertokens-auth-react/recipe/session"; import axios from "axios"; function QTNavBar({ handleInputChange }) { const [isLoggedIn, setIsLoggedIn] = useState(false); const [user, setUser] = useState({username: "", profile: {profilePicture: ""}}); const sessionContext = useSessionContext(); useEffect(() => { async function checkIfLoggedIn() { const userIsLoggedIn = await doesSessionExist(); setIsLoggedIn(userIsLoggedIn); if (userIsLoggedIn) { const userId = await Session.getUserId(); const response = await axios.get( `http://localhost:5000/api/v1/users/supertokens/${userId}` ); setUser(response.data); } } checkIfLoggedIn(); }, [sessionContext]); return ( <nav className="navbar navbar-expand-lg bg-primary" data-bs-theme="dark"> <div className="container-fluid"> <Link className="navbar-brand" to="/"> <QTLogo height="60" width="80" className="mx-2" /> QuestTrackr </Link> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarColor01"> <ul className="navbar-nav me-auto"> <li className="nav-item mx-3 col-9"> <input className="form-control" type="search" onChange={handleInputChange} placeholder="Search Your Favorite Games..." /> </li> <li className="nav-item"> <Link className="nav-link" to="/about"> About </Link> </li> <li className="nav-item"> <Link className="nav-link" to="/faq"> FAQ </Link> </li> </ul> </div> <div className="navbar-nav ml-auto"> {isLoggedIn ? ( <ul className="navbar-nav ml-auto align-items-center"> <li className="nav-item"> <Link to="/" className="nav-link px-3" onClick={() => { Session.signOut(); setIsLoggedIn(false); }} > Logout </Link> </li> <Link className="nav-link px-3" to={`/profile/${user.username}`}> <img alt="" src={user.profile.profilePicture} height="50" className="rounded-circle" /> </Link> </ul> ) : ( <Link to="/auth" className="btn btn-secondary"> Login/Register </Link> )} </div> </div> </nav> ); } export default QTNavBar;
from django.contrib import admin from .models import Category, Post, Comment # Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ['title', 'category', 'author', 'created', 'is_active'] list_filter = ['created', 'author__username', 'category', 'is_active'] search_fields = ['title', 'id', 'text', 'created', 'is_active'] list_editable = ['category', 'is_active'] @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug', 'id'] prepopulate_fields = {'slug':('name',)} @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ['comment']
import React, { useState, useRef, useEffect } from "react" import { Link } from "react-router-dom" import Transition from "../utils/transition" import { useAtom } from "jotai" import { clearSessionAtom } from "store/authorization-atom" import useShop from "hooks/use-shop" import { proxyURL } from "utils/urlsigner" function DropdownProfile({ align, shopName = "Demo" }) { const { shop } = useShop() const [, clearSession] = useAtom(clearSessionAtom) const [dropdownOpen, setDropdownOpen] = useState(false) const trigger = useRef(null) const dropdown = useRef(null) const handleLogout = (e) => { e.preventDefault() clearSession() } // close on click outside useEffect(() => { const clickHandler = ({ target }) => { if (!dropdown.current) return if ( !dropdownOpen || dropdown.current.contains(target) || trigger.current.contains(target) ) return setDropdownOpen(false) } document.addEventListener("click", clickHandler) return () => document.removeEventListener("click", clickHandler) }) // close if the esc key is pressed useEffect(() => { const keyHandler = ({ keyCode }) => { if (!dropdownOpen || keyCode !== 27) return setDropdownOpen(false) } document.addEventListener("keydown", keyHandler) return () => document.removeEventListener("keydown", keyHandler) }) return ( <div className="relative inline-flex"> <button ref={trigger} className="inline-flex justify-center items-center group" aria-haspopup="true" onClick={() => setDropdownOpen(!dropdownOpen)} aria-expanded={dropdownOpen} > {shop && shop.image && shop.image != "" && ( <img className="w-8 h-8 rounded-full" src={proxyURL(shop.image, 50, 50)} width="32" height="32" alt="User" /> )} {!(shop && shop.image) && ( <div className="w-8 h-8 flex justify-center items-center rounded-full bg-purple-500 text-xl text-white uppercase"> {shopName.charAt(0)} </div> )} <div className="hidden md:flex items-center truncate"> <span className="truncate ml-2 text-sm font-medium group-hover:text-gray-800"> {shopName.charAt(0).toUpperCase() + shopName.slice(1)} </span> <svg className="w-3 h-3 flex-shrink-0 ml-1 fill-current text-gray-400" viewBox="0 0 12 12" > <path d="M5.9 11.4L.5 6l1.4-1.4 4 4 4-4L11.3 6z" /> </svg> </div> </button> <Transition className={`origin-top-right z-10 absolute top-full min-w-44 bg-white border border-gray-200 py-1.5 rounded shadow-lg overflow-hidden mt-1 ${ align === "right" ? "right-0" : "left-0" }`} show={dropdownOpen} enter="transition ease-out duration-200 transform" enterStart="opacity-0 -translate-y-2" enterEnd="opacity-100 translate-y-0" leave="transition ease-out duration-200" leaveStart="opacity-100" leaveEnd="opacity-0" > <div ref={dropdown} onFocus={() => setDropdownOpen(true)} onBlur={() => setDropdownOpen(false)} > <div className="pt-0.5 pb-2 px-3 mb-1 border-b border-gray-200"> <div className="font-medium text-gray-800"> {shopName.charAt(0).toUpperCase() + shopName.slice(1)} </div> <div className="text-xs text-gray-500 italic">Admin</div> </div> <ul> <li> <Link className="font-medium text-sm text-purple-500 hover:text-purple-600 flex items-center py-1 px-3" to="/settings/account" onClick={() => setDropdownOpen(!dropdownOpen)} > Settings </Link> </li> <li> <button className="font-medium text-sm text-purple-500 hover:text-purple-600 flex items-center py-1 px-3" onClick={(e) => { setDropdownOpen(!dropdownOpen) handleLogout(e) }} > Sign Out </button> </li> </ul> </div> </Transition> </div> ) } export default DropdownProfile
#include <ctype.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef enum { TK_RESERVED, // 記号 TK_NUM, // 整数トークン TK_EOF // 入力の終わりを表すトークン } TokenKind; typedef struct Token Token; struct Token { TokenKind kind; // トークンの型 Token *next; // 次の入力トークン int val; // kindがTK_NUMの場合、その数値 char *str; // トークン文字列 int len; // トークンの長さ }; void error_at(char *loc, char *fmt, ...); void error(char *fmt, ...); bool consume(char *op); void expect(char *op); int expect_number(); bool at_eof(); bool startswith(char *p, char *q); Token *new_token(TokenKind kind, Token *cur, char *str, int len); Token *tokenize(char *p); extern char *user_input; // パーサが読み込むトークン列。連結リストになっているtokenを辿っていく extern Token *token; // 抽象構文木のノードの種類 typedef enum { ND_ADD, // + ND_SUB, // - ND_MUL, // * ND_DIV, // / ND_EQ, // == ND_NE, // != ND_LT, // < ND_LE, // <= ND_GT, // > ND_GE, // >= ND_NUM, // 整数 } NodeKind; // 抽象構文木のノードの型 typedef struct Node Node; struct Node { NodeKind kind; // ノードの型 Node *lhs; // 左辺 left-hand side Node *rhs; // 右辺 right-hand side int val; // kindがND_NUMの場合のみ使う }; Node *expr(); void codegen(Node *node);
package org.jetbrains.bsp.bazel.base import ch.epfl.scala.bsp4j.BuildClientCapabilities import ch.epfl.scala.bsp4j.BuildTargetIdentifier import ch.epfl.scala.bsp4j.InitializeBuildParams import ch.epfl.scala.bsp4j.WorkspaceBuildTargetsResult import org.apache.logging.log4j.LogManager import org.jetbrains.bsp.bazel.install.Install import org.jetbrains.bsp.testkit.client.bazel.BazelTestClient import java.nio.file.Path import kotlin.io.path.Path import kotlin.io.path.name import kotlin.system.exitProcess abstract class BazelBspTestBaseScenario { protected val binary = System.getenv("BIT_BAZEL_BINARY") protected val workspaceDir = System.getenv("BIT_WORKSPACE_DIR") val targetPrefix = calculateTargetPrefix() protected val testClient: BazelTestClient init { installServer() testClient = createClient() } // check: https://github.com/bazelbuild/intellij/blob/adb358670a7fc6ad51808486dc03f4605f83dcd3/aspect/testing/tests/src/com/google/idea/blaze/aspect/integration/BazelInvokingIntegrationTestRunner.java#L132 private fun calculateTargetPrefix(): String { val dirName = Path(binary).parent.name // With bzlmod enabled the directory name is something like: // rules_bazel_integration_test~0.18.0~bazel_binaries~build_bazel_bazel_6_3_2 val bazelPart = if (dirName.contains("~")) dirName.split("~")[3] else dirName val majorVersion = bazelPart.split("_")[3].toIntOrNull() // null for .bazelversion, we can assume that it's > 6, so we can return "@" anyway return if (majorVersion != null && majorVersion < 6) "" else "@" } protected open fun installServer() { Install.main( arrayOf( "-d", workspaceDir, "-b", binary, "-t", "//...", ) ) } private fun processBazelOutput(vararg args: String): String { val command = arrayOf<String>(binary, *args) val process = ProcessBuilder(*command) .directory(Path(workspaceDir).toFile()) .start() val output = process.inputStream.bufferedReader().readText().trim() val exitCode = process.waitFor() if (exitCode != 0) { val error = process.errorStream.bufferedReader().readText().trim() throw RuntimeException("Command '${command.joinToString(" ")}' failed with exit code $exitCode.\n$error") } return output } private fun createClient(): BazelTestClient { log.info("Testing repo workspace path: $workspaceDir") log.info("Creating TestClient...") val capabilities = BuildClientCapabilities(listOf("java", "scala", "kotlin", "cpp")) val initializeBuildParams = InitializeBuildParams( "BspTestClient", "1.0.0", "2.0.0", workspaceDir, capabilities ) val bazelCache = Path(processBazelOutput("info", "execution_root")) val bazelOutputBase = Path(processBazelOutput("info", "output_base")) return BazelTestClient(Path.of(workspaceDir), initializeBuildParams, bazelCache, bazelOutputBase) .also { log.info("Created TestClient done.") } } fun executeScenario() { log.info("Running scenario...") val scenarioStepsExecutionResult = executeScenarioSteps() log.info("Running scenario done.") when (scenarioStepsExecutionResult) { true -> { log.info("Test passed!") exitProcess(SUCCESS_EXIT_CODE) } false -> { log.fatal("Test failed :( ") exitProcess(FAIL_EXIT_CODE) } } } private fun executeScenarioSteps(): Boolean = scenarioSteps() .map { it.executeAndReturnResult() } .all { it } protected fun expectedTargetIdentifiers(): List<BuildTargetIdentifier> = expectedWorkspaceBuildTargetsResult() .targets .map { it.id } protected abstract fun expectedWorkspaceBuildTargetsResult(): WorkspaceBuildTargetsResult protected abstract fun scenarioSteps(): List<BazelBspTestScenarioStep> companion object { private val log = LogManager.getLogger(BazelBspTestBaseScenario::class.java) private const val SUCCESS_EXIT_CODE = 0 private const val FAIL_EXIT_CODE = 1 } }
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Str; use Mews\Purifier\Facades\Purifier; class StoreTouristDestinationRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, mixed> */ public function rules() { return [ 'name' => ['required', 'max:255'], 'slug' => ['required'], 'category_id' => ['required'], 'sub_district_id' => ['required'], 'address' => ['required', 'max:255'], 'manager' => ['required', 'max:255'], 'distance_from_city_center' => ['required', 'max:10'], 'transportation_access' => ['required'], 'facility' => ['required'], 'cover_image' => ['required', 'image', 'mimes:png,jpg,jpeg', 'max:2048'], 'latitude' => ['required', 'max:50'], 'longitude' => ['required', 'max:50'], 'description' => ['required'], 'tourist_attraction_names.*' => ['nullable', 'max:255'], 'tourist_attraction_images.*' => ['nullable', 'mimes:png,jpg'], 'tourist_attraction_captions.*' => ['nullable', 'max:255'], 'facebook_url' => 'nullable', 'instagram_url' => 'nullable', 'twitter_url' => 'nullable', 'youtube_url' => 'nullable', 'media_files' => ['nullable'], ]; } protected function prepareForValidation() { $this->merge([ 'slug' => Str::slug($this->name) . '-' . Str::random(5), ]); } public function passedValidation() { return [ $this->merge([ 'description' => Purifier::clean($this->description), ]), ]; } public function attributes() { return [ 'name' => 'Nama Destinasi Wisata', 'category_id' => 'Kategori', 'sub_district_id' => 'Kecamatan', 'address' => 'Alamat', 'manager' => 'Pengelola', 'distance_from_city_center' => 'Jarak Dari Pusat Kota', 'transportation_access' => 'Akses Transportasi', 'facility' => 'Fasilitas', 'cover_image' => 'Foto Sampul', 'latitude' => 'Latitude / Garis Lintang', 'longitude' => 'Longitude / Garis Bujur', 'description' => 'Deskripsi Destiansi Wisata', 'tourist_attraction_names.*' => 'Nama Atraksi Wisata', 'tourist_attraction_images.*' => 'Foto Atraksi Wisata', 'tourist_attraction_captions.*' => 'Keterangan Atraksi Wisata', 'facebook_url' => 'Alamat URL Facebook', 'instagram_url' => 'Alamat URL Instragram', 'twitter_url' => 'Alamat URL Twitter', 'youtube_url' => 'Alamat URL Youtube', ]; } }
"use client"; import { createClientComponentClient } from "@supabase/auth-helpers-nextjs"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import T from "@/components/translations/translation"; export default function CreateResultButton({ isEnrollmentPhase, participantCount, atLeastOneQuestionnaireCompleted, process, userId, }: { isEnrollmentPhase: boolean; participantCount: number; atLeastOneQuestionnaireCompleted: boolean; process: any; userId: any; }) { const router = useRouter(); const generateResult = async () => { try { let response; if (process == 1) { response = await fetch("/api/generate-result", { method: "POST", }); } else { response = await fetch("/api/generate-result-assessed", { method: "POST", }); } if (response.ok) { console.log("Result generated successfully"); // Update the phase to "enrollment" const supabase = createClientComponentClient(); await supabase .from("app_settings") .update({ isEnrollmentPhase: true }) .eq("user_id", userId); // Redirect to the result page const resultResponse = await response.json(); const resultId = resultResponse.resultId; router.push(`/home/results/${resultId}`); } else { console.error("Error generating result"); } } catch (error) { console.error("Error generating result:", error); } }; let canGenerateResult; if (process == 1) { canGenerateResult = !isEnrollmentPhase && atLeastOneQuestionnaireCompleted && participantCount >= 2; } else { canGenerateResult = !isEnrollmentPhase && atLeastOneQuestionnaireCompleted && participantCount >= 1; } if (!canGenerateResult) { return null; } return ( <Button id="generateResultBtn" variant="login" className="uppercase md:w-1/5 w-full" onClick={generateResult} > <T tkey="participants.buttons-section.buttons.result" /> </Button> ); }
import React, { useEffect, useState } from 'react'; import showdown from 'showdown'; import { ReactSurveyModel, StylesManager, Survey } from 'survey-react'; import 'survey-react/survey.css'; import { getSurveyData } from '../../surveyData'; import { svgData } from '../../svgData'; import { PreAttentiveSvgGenerator } from '../../svgGenerator/PreAttentiveSvgGenerator'; import { CompletedPage } from '../CompletedPage/CompletedPage'; import { SvgShowBox } from '../SvgShowBox/SvgShowBox'; import { TitlePage } from '../TitlePage/TitlePage'; import styles from './SurveyPanel.module.css'; export const SurveyPanel: React.FC = () => { const [survey, setSurvey] = useState(new ReactSurveyModel(getSurveyData())); const [displaySvg, setDisplaySvg] = useState(true); const [currentChartNo, setCurrentChartNo] = useState(0); const [isCompleted, setIsCompleted] = useState(false); const [hasStarted, setHasStarted] = useState(false); const [svgGenerator, setSvgGenerator] = useState( new PreAttentiveSvgGenerator() ); const [svg, setSvg] = useState<JSX.Element>(); const [visibleTime, setVisibleTime] = useState(500); const numberOfSvgs = svgData.length; useEffect(() => { //set initial svg const feature = svgData[0].feature; const time = svgData[0].time; const additionalDistractors = svgData[0].additionalDistractors; setSvg(svgGenerator.generateSvg(9, feature, additionalDistractors)); setVisibleTime(time); setDisplaySvg(true); //survey settings StylesManager.applyTheme('winter'); let converter = new showdown.Converter(); survey.onTextMarkdown.add(function (survey, options) { //convert the mardown text to html var str = converter.makeHtml(options.text); //remove root paragraphs <p></p> str = str.substring(3); str = str.substring(0, str.length - 4); //set html options.html = str; }); return () => {}; }, []); const handleNext = () => { const pageNo = survey.currentPageNo; if (pageNo >= numberOfSvgs - 1) { if (survey.isLastPage) setIsCompleted(true); else survey.nextPage(); } else if ( !displaySvg && currentChartNo !== pageNo && !survey.isCurrentPageHasErrors ) { const feature = svgData[pageNo + 1].feature; const time = svgData[pageNo + 1].time; const additionalDistractors = svgData[pageNo + 1].additionalDistractors; setSvg(svgGenerator.generateSvg(9, feature, additionalDistractors)); setVisibleTime(time); setDisplaySvg(true); } else if (displaySvg) { setDisplaySvg(false); setCurrentChartNo(currentChartNo + 1); if (currentChartNo !== 0) survey.nextPage(); } }; const page = !hasStarted ? ( <TitlePage onStart={() => setHasStarted(true)} /> ) : isCompleted ? ( <CompletedPage data={survey.data}></CompletedPage> ) : displaySvg ? ( <div className={styles.svgShowBoxContainer}> <SvgShowBox visibleTime={visibleTime} onTimeOver={() => handleNext()}> {svg} </SvgShowBox> </div> ) : ( <div className={styles.surveyContainer}> <Survey model={survey} /> <input className={styles.nextButton} type="submit" value="Weiter" onClick={handleNext} /> </div> ); return <div className={styles.container}>{page}</div>; };
import { useSession } from "next-auth/react"; import React, { useEffect, useState } from "react"; import { AiOutlineConsoleSql } from "react-icons/ai"; import { IoHeartOutline, IoHeartDislikeOutline } from "react-icons/io5"; import useSupabase from "../hooks/useSupabase"; const LikeBtn = ({ id, favList }) => { const { data: session } = useSession(); const email = session?.user?.email; const [found, setFound] = useState(false); const [movieData, setMovieData] = useState(null); const [action, setAction] = useState(null); const supabase = useSupabase(); useEffect(() => { favList.map((movie) => { if (String(movie.id) === String(id)) { setFound(true); } }); }, [favList]); const url = `https://api.themoviedb.org/3/movie/${id}?api_key=565e5a5d8e336b7cee4dc5ea476e08f6&language=en-US`; const getMovies = async () => { fetch(url).then((response) => { response.json().then((data) => { setMovieData(data); }); }); }; const setFavs = async (favorites) => { const { data, error } = await supabase .from("favorites") .update({ favorites: favorites }) .eq("user_email", email); }; const getFavs = async () => { const { data: favorites, error } = await supabase .from("favorites") .select("favorites") .eq("user_email", email); if (favorites) { return favorites[0]?.favorites; } }; useEffect(() => { if (movieData && action) { if (action === "add") { pushDb(movieData); setAction(null); } if (action === "remove") { deleteDb(movieData); setAction(null); } } }, [movieData]); const pushDb = (movieData) => { if (movieData) { getFavs().then((favorites) => { const newFavs = [ ...favorites, { id: movieData.id, movieTitle: movieData.title, movieImgURL: "https://image.tmdb.org/t/p/w500" + movieData.poster_path, rating: movieData.vote_average, overview: movieData.overview, pageLink: movieData.id, releaseDate: movieData.releaseDate, }, ]; setFavs(newFavs); setFound(true); }); } }; const deleteDb = (movieData) => { getFavs().then((favorites) => { const deleted = favorites.filter((movie) => { return movie.id !== movieData.id; }); setFavs(deleted); setFound(false); }); }; return ( <> {found ? ( <div className="like-btn" onClick={() => { setAction("remove"); getMovies(); }} > <IoHeartDislikeOutline /> </div> ) : ( <div className="like-btn" onClick={() => { setAction("add"); getMovies(); }} > <IoHeartOutline /> </div> )} </> ); }; export default LikeBtn;
import { IDynamicComponent } from './i-dynamic-component'; import { ViewContainerRef, Injector, ComponentRef } from '@angular/core'; import { IComponentMetaData, COMPONENTMETADATA } from './i-component-meta-data'; import { IComponentDiscovery, COMPONENTDISCOVERY } from '../tokens/component-discovery'; import { IComponentDesignDataStore, COMPONENTDESIGNDATASTORE } from '../tokens/component-design-data-store'; import { DynamicComponentEventEnum } from '../enums/dynamic-component-event.enum'; import { v4 as uuidv4 } from 'uuid'; import { IDynamicComponentOpsat, DYNAMICCOMPONENTOPSAT } from '../tokens/dynamic-component-opsat'; import { IDynamicComponentRecorder, DYNAMICCOMPONENTRECORDER } from '../tokens/dynamic-component-recorder'; import { INotification } from './i-notification'; export function DynamicContainer(containerId?: string) { containerId = containerId || ''; return function (target: Object, propertyName: string) { let _val = null; function setter(val: any) { <DynamicComponent>this.container.set(containerId, val); _val = val; } function getter() { return _val; } Object.defineProperty(target, propertyName, { get: getter, set: setter, enumerable: true, configurable: true }); } } export abstract class DynamicComponent implements IDynamicComponent { public readonly componentId: string; public get title(): string { return this.metaData?.title; } public get notify(): Array<INotification> { return this.metaData?.notify || []; } public get subscribe(): Array<INotification> { return this.metaData?.subscribe || []; } protected metaData: IComponentMetaData; protected container = new Map<string, ViewContainerRef>(); private variableScope: { [key: string]: any } = {}; // 组件变量作用域,为了保证作用域安全,通过setVariable/getVariable操作 private opsat: IDynamicComponentOpsat; private recorder: IDynamicComponentRecorder; private getSuperiorScopeVariable: (key: string) => any; public constructor( protected injector: Injector ) { this.componentId = uuidv4(); this.opsat = this.injector.get(DYNAMICCOMPONENTOPSAT); this.recorder = this.injector.get(DYNAMICCOMPONENTRECORDER); // console.log('uuid', this.componentId); } // public getSuperiorScopeVariable: (key: string) => any; public registryGetSuperiorScopeVariable(fn: (key: string) => any): void { this.getSuperiorScopeVariable = fn; } public getVariable(key: string): void { if (!key) { console.warn(`你在获取一个key为空的variable scope,返回值可能不是你想要的`); return null; } let value: any = this.variableScope[key]; if (!value && this.getSuperiorScopeVariable) { value = this.getSuperiorScopeVariable(key); } return value; } protected abstract async afterRenderer(): Promise<void>; protected abstract async onReceiveMessage(topic: string, data?: any): Promise<void>; protected abstract async initialize(value?: any): Promise<void>; protected async startup(): Promise<void> { if (!this.metaData) { this.metaData = this.injector.get(COMPONENTMETADATA, {}); } const componentDiscoverySrv: IComponentDiscovery = this.injector.get(COMPONENTDISCOVERY); const componentDesignDataStore: IComponentDesignDataStore = this.injector.get(COMPONENTDESIGNDATASTORE); if (this.metaData.key) { let m = await componentDesignDataStore.getMetaData(this.metaData.key).toPromise(); this.metaData = { ...this.metaData, ...m }; } for (let idx: number = 0, len: number = this.metaData.content?.length || 0; idx < len; idx++) { let it = this.metaData.content[idx]; if (it.key) { let m = await componentDesignDataStore.getMetaData(it.key).toPromise(); this.metaData.content[idx] = { ...it, ...m }; } let fac = componentDiscoverySrv.generateComponentFactory(this.metaData.content[idx].control); if (!fac) { console.error(`组件库里面没有找到control为${this.metaData.content[idx].control}的组件,请检查是否注册或者写错`); continue; } const ij = Injector.create([ { provide: COMPONENTMETADATA, useValue: it } ], this.injector); let containerId: string = this.metaData.content[idx].containerId || ''; let vc = this.container.get(containerId); if (!vc) { console.error(`没有找到containerId为 "${containerId}" 的ViewContainerRef,请检查containerId是否写错或者动态组件宿主是否已经提供该Ref`) continue; } let dyc: ComponentRef<IDynamicComponent> = vc.createComponent(fac, null, ij); // 修改afterRenderer属性,在调用前先调用recorder记录下动态生成的组件 const originAfterRenderer = dyc.instance['afterRenderer']; const parentId = this.componentId; Object.defineProperty(dyc.instance, 'afterRenderer', { value: function () { this.recorder.recordDynamicComponent(dyc.instance, parentId); originAfterRenderer.apply(this); } }); dyc.instance.registryGetSuperiorScopeVariable(key => this.getVariable(key)); } this.afterRenderer(); } protected async destroy(): Promise<void> { this.recorder.recordDynamicComponentDestroy(this.componentId); console.log(`${this.componentId} destroy`); } protected setVariable(key: string, value?: any): void { if (!key) { console.warn(`你在设置一个key为空的variable scope,该设置不会生效`); return; } // 重复值不发送事件 if (this.variableScope[key] !== value) { this.publishMessage(DynamicComponentEventEnum.valueChange, { name: key, value: value }); } this.variableScope[key] = value; } protected setVariables(data: any): void { if (!data) { console.warn(`你在设置一个data为空的variable scope,该设置不会生效`); return; } let keys: Array<string> = Object.keys(data); for (let k of keys) { this.setVariable(k, data[k]); } } protected getVariables(): any { return this.variableScope; } protected publishMessage(topic: string, data?: any): void { if (!this.opsat) { return; } this.opsat.publish(topic, this.componentId, data); } }
# Lab 5 - Selecting the data you want # Exercise 1 - Discover the Object in the PowerShell Pipeline. # Step 1: # Run all three cmdlets you discovered in Lab 4, Exercise 1 and record the TypeName # of the Object by pipeing the object to Get-Member. # Step 2: # Open the MSDN document describing the Object from the cmdelt Get-PnpDevice. # Step 3: # Open the MSDN document describing the Object from the cmdelt Get-ADComputer # Step 4: # Open the MSDN document describing the Object from the cmdeltGet-Uptime # Exercise 2 - Extracting the Values of an Object's Properties # Step 1: # Using the first webpage from Ex 1 Step 2, Extract the following. # - The device name. # - A property that will show the class of device. # - Its current status # Step 2: # You Will need the Help file for the cmdlet discovered in Ex 1, Step 3. # Get all computers in the domain. Show only the properties for: # - The computer name # - When the computer account as created. # - When the password was last set. # - The primary group the computer is in. # Step 3: # Using the documentation from the object produced by Get-Uptime, # Show only the hours, minutes, and seconds that this computer has been online.
package doublelinkedlistapp; import java.util.ArrayList; import java.lang.reflect.Array; import java.util.Iterator; /** * * @author Emre */ public class DoubleLinkedList<E> { private Node first, last; private int size = 0; public DoubleLinkedList() { first = last = null; } public DoubleLinkedList(E data) { this(); add(data); } public void add(E data) { insert(data, size); } public void insert(E data, int position) throws IndexOutOfBoundsException { if (size < position || position < 0) { throw new IndexOutOfBoundsException(); } Node traveller = first; for (int i = 0; i < position; i++) { traveller = traveller.next; } Node node = new Node(data); if (first != traveller) { if (traveller != null) { // araya ekleme node.prev = traveller.prev; traveller.prev.next = node; node.next = traveller; traveller.prev = node; } else { // sona ekleme last.next = node; node.prev = last; last = node; } } else { node.next = first; if (first != null) { first.prev = node; } else { last = node; } first = node; } ++size; } public E remove(int position) throws IndexOutOfBoundsException { if (size <= position || position < 0) { throw new IndexOutOfBoundsException(); } Node traveller = first; for (int i = 0; i < position; i++) { traveller = traveller.next; } if (first != traveller) { // aradaki veya sondaki düğümü bağlı listeden çıkar if (traveller.next != null) { traveller.prev.next = traveller.next; traveller.next.prev = traveller.prev; } else { last = traveller.next; last.next = null; } } else { // ilk düğümü bağlı listeden çıkar first = traveller.next; first.prev = null; } traveller.prev = null; traveller.prev = null; --size; return traveller.data; } public E update(int position, E newValue) { if (size < position || position < 0) { throw new IndexOutOfBoundsException(); } int i = 0; E temp = null; for (Node traveller = first; traveller != null; traveller = traveller.next) { if (position == i++) { temp = traveller.data; traveller.data = newValue; } } return temp; } public void update(E oldValue, E newValue) { int i = 0; for (Node traveller = first; traveller != null; traveller = traveller.next) { if (oldValue == traveller.data) { traveller.data = newValue; } } } public E get(int position) throws IndexOutOfBoundsException { if (size < position || position < 0) { throw new IndexOutOfBoundsException(); } int i = 0; for (Node traveller = first; traveller != null; traveller = traveller.next) { if (position == i++) { return traveller.data; } } return null; } public void clear() { first = last = null; size = 0; } public boolean isEmpty() { return first == null; } public int search(E element) { int position = 0; for (Node traveller = first; traveller != null; traveller = traveller.next) { ++position; if (traveller.data.equals(element)) { return position; } } return -1; } public int count() { return size; } public Iterator getEnumator() { ArrayList arr = new ArrayList(); for (Node traveller = first; traveller != null; traveller = traveller.next) { arr.add(traveller.data); } return arr.iterator(); } public E[] toArray(Class<E> type) { int i = 0; E[] arr = (E[]) Array.newInstance(type, size); for (Node traveller = first; traveller != null; traveller = traveller.next) { arr[i++] = traveller.data; } return arr; } private class Node { public E data; public Node next, prev; Node(E data) { next = prev = null; this.data = data; } } }
// import React from 'react'; // import Slider from 'react-slick'; // import 'slick-carousel/slick/slick.css'; // import 'slick-carousel/slick/slick-theme.css'; // import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; // import { faGlobe, faArrowLeft, faArrowRight } from '@fortawesome/free-solid-svg-icons'; // import { faGithub, faYoutube} from '@fortawesome/free-brands-svg-icons'; // const Arrow = ({ onClick, direction }) => ( // <div // className={`absolute ${direction === "left" ? "left-0" : "right-0"} top-1/2 transform -translate-y-1/2 bg-white bg-opacity-50 rounded-full p-2 cursor-pointer`} // onClick={onClick} // > // {direction === "left" ? <FontAwesomeIcon icon={faArrowLeft} /> : <FontAwesomeIcon icon={faArrowRight} />} // </div> // ); // const Projects = ({projects}) => { // const settings = { // infinite: true, // speed: 500, // slidesToShow: 3, // Show 3 slides at a time on large screens // slidesToScroll: 1, // responsive: [ // { // breakpoint: 768, // Breakpoint for phone screens // settings: { // slidesToShow: 1, // slidesToScroll: 1, // }, // }, // ], // prevArrow: <Arrow direction="left" />, // nextArrow: <Arrow direction="right" />, // }; // return ( // <Slider {...settings}> // {projects.map((project, index) => ( // <div className='p-1'> // <div key={index} className="bg-purple-200 p-2 rounded-lg m-0 mx-10"> // <img src={project.image} alt={project.name} className="w-full mb-4 rounded" /> // <h3 className="text-xl font-bold mb-2">{project.name}</h3> // <p className="mb-4">{project.description}</p> // <div className="flex flex-col gap-2"> // <a href={project.githubLink} target="_blank" rel="noopener noreferrer" className="bg-purple-900 text-white py-2 px-4 rounded hover:bg-purple-800 flex items-center justify-center"> // <FontAwesomeIcon icon={faGithub} className="mr-2" /> Source Code // </a> // <a href={project.liveDemoLink} target="_blank" rel="noopener noreferrer" className="bg-purple-900 text-white py-2 px-4 rounded hover:bg-purple-800 flex items-center justify-center"> // <FontAwesomeIcon icon={faGlobe} className="mr-2" /> Live Demo // </a> // <a href={project.videoDemoLink} target="_blank" rel="noopener noreferrer" className="bg-purple-900 text-white py-2 px-4 rounded hover:bg-purple-800 flex items-center justify-center"> // <FontAwesomeIcon icon={faYoutube} className="mr-2" /> Video Demo // </a> // </div> // </div> // </div> // ))} // </Slider> // ); // }; // export default Projects;
<template> <transition name="vc-drawer_animation"> <div v-if="visible" :class="[ 'vc-drawer', { 'vc-drawer__mask': mask }, { 'vc-drawer__center': center } ]" > <div class="vc-drawer_content" v-click-outside="closeDrawer" :style="{ '--max-width': maxWidth }" > <FocusLock :no-focus-guards="true"> <div class="vc-drawer_header"> <h2 class="vc-drawer_title"> <slot name="title" /> </h2> <Button ref="drawerClose" class="vc-drawer__close-btn" icon="multiply" shape="square" color="secondary" variant="ghost" aria-label="close modal" @click="closeDrawer" /> </div> <div class="vc-drawer_body"> <slot /> </div> <div class="vc-drawer_footer"> <slot name="footer" /> </div> </FocusLock> </div> </div> </transition> </template> <script> import FocusLock from 'vue-focus-lock' import vClickOutside from 'v-click-outside' import { Button } from 'components' import { layoutLock } from 'mixins' export default { name: 'Drawer', components: { Button, FocusLock }, directives: { clickOutside: vClickOutside.directive }, mixins: [layoutLock], props: { visible: { type: Boolean, default: false }, mask: { type: Boolean, default: true }, center: { type: Boolean, default: false }, maxWidth: { type: String, default: '40.625rem' } }, watch: { visible() { if (this.visible) { this.toLockLayout() window.addEventListener('keyup', this.handleEscapeKey) } else { this.unlockLayout() } } }, methods: { handleEscapeKey(e) { if (e.code === 'Escape') { this.closeDrawer() e.preventDefault() } }, closeDrawer() { this.$emit('close', false) } }, beforeDestroy() { window.removeEventListener('keyup', this.handleEscapeKey) } } </script> <style lang="scss"> @import 'drawer'; </style>
/** * Type definitions adapted from @types/pdf-parse and pdfjs-dist * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pdf-parse/index.d.ts * https://github.com/mozilla/pdfjs-dist/blob/master/types/src/display/api.d.ts */ declare module 'pdf-parse' { export = PdfParse; declare function PdfParse( dataBuffer: Buffer, options?: PdfParse.Options ): Promise<PdfParse.Result>; declare namespace PdfParse { type Version = | 'default' | 'v1.9.426' | 'v1.10.100' | 'v1.10.88' | 'v2.0.550'; interface Result { numpages: number; numrender: number; info: any; metadata: any; version: Version; text: string; } interface Options { pagerender?: ((pageData: PDFPageProxy) => Promise<string>) | undefined; max?: number | undefined; version?: Version | undefined; } } export type TypedArray = | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; export type BinaryData = TypedArray | ArrayBuffer | Array<number> | string; export type RefProxy = { num: number; gen: number; }; /** * A PDF document and page is built of many objects. E.g. there are objects for * fonts, images, rendering code, etc. These objects may get processed inside of * a worker. This class implements some basic methods to manage these objects. */ declare class PDFObjects { /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this method throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this method * and the object is already resolved, the callback gets called right away. * * @param {string} objId * @param {function} [callback] * @returns {any} */ get(objId: string, callback?: () => void | undefined): any; /** * @param {string} objId * @returns {boolean} */ has(objId: string): boolean; /** * Resolves the object `objId` with optional `data`. * * @param {string} objId * @param {any} [data] */ resolve(objId: string, data?: any): void; clear(): void; #private; } /** * Page getViewport parameters. */ export type GetViewportParameters = { /** * - The desired scale of the viewport. */ scale: number; /** * - The desired rotation, in degrees, of * the viewport. If omitted it defaults to the page rotation. */ rotation?: number | undefined; /** * - The horizontal, i.e. x-axis, offset. * The default value is `0`. */ offsetX?: number | undefined; /** * - The vertical, i.e. y-axis, offset. * The default value is `0`. */ offsetY?: number | undefined; /** * - If true, the y-axis will not be * flipped. The default value is `false`. */ dontFlip?: boolean | undefined; }; /** * Page getTextContent parameters. */ export type getTextContentParameters = { /** * - Replaces all occurrences of whitespace with standard * spaces (0x20). The default value is `false`. */ normalizeWhitespace: boolean; /** * - Do not attempt to combine * same line {@link TextItem }'s. The default value is `false`. */ disableCombineTextItems: boolean; /** * - When true include marked * content items in the items array of TextContent. The default is `false`. */ includeMarkedContent?: boolean | undefined; }; /** * Page text content. */ export type TextContent = { /** * - Array of * {@link TextItem } and {@link TextMarkedContent } objects. TextMarkedContent * items are included when includeMarkedContent is true. */ items: Array<TextItem | TextMarkedContent>; /** * - {@link TextStyle } objects, * indexed by font name. */ styles: { [x: string]: TextStyle; }; }; /** * Page text content part. */ export type TextItem = { /** * - Text content. */ str: string; /** * - Text direction: 'ttb', 'ltr' or 'rtl'. */ dir: string; /** * - Transformation matrix. */ transform: Array<any>; /** * - Width in device space. */ width: number; /** * - Height in device space. */ height: number; /** * - Font name used by PDF.js for converted font. */ fontName: string; /** * - Indicating if the text content is followed by a * line-break. */ hasEOL: boolean; }; /** * Page text marked content part. */ export type TextMarkedContent = { /** * - Either 'beginMarkedContent', * 'beginMarkedContentProps', or 'endMarkedContent'. */ type: string; /** * - The marked content identifier. Only used for type * 'beginMarkedContentProps'. */ id: string; }; /** * Text style. */ export type TextStyle = { /** * - Font ascent. */ ascent: number; /** * - Font descent. */ descent: number; /** * - Whether or not the text is in vertical mode. */ vertical: boolean; /** * - The possible font family. */ fontFamily: string; }; /** * Page render parameters. */ export type RenderParameters = { /** * - A 2D context of a DOM Canvas object. */ canvasContext: unknown; /** * - Rendering viewport obtained by calling * the `PDFPageProxy.getViewport` method. */ viewport: PageViewport; /** * - Rendering intent, can be 'display', 'print', * or 'any'. The default value is 'display'. */ intent?: string | undefined; /** * Controls which annotations are rendered * onto the canvas, for annotations with appearance-data; the values from * {@link AnnotationMode } should be used. The following values are supported: * - `AnnotationMode.DISABLE`, which disables all annotations. * - `AnnotationMode.ENABLE`, which includes all possible annotations (thus * it also depends on the `intent`-option, see above). * - `AnnotationMode.ENABLE_FORMS`, which excludes annotations that contain * interactive form elements (those will be rendered in the display layer). * - `AnnotationMode.ENABLE_STORAGE`, which includes all possible annotations * (as above) but where interactive form elements are updated with data * from the {@link AnnotationStorage }-instance; useful e.g. for printing. * The default value is `AnnotationMode.ENABLE`. */ annotationMode?: number | undefined; /** * - Additional transform, applied just * before viewport transform. */ transform?: any[] | undefined; /** * - The factory instance that will be used * when creating canvases. The default value is {new DOMCanvasFactory()}. */ canvasFactory?: unknown | undefined; /** * - Background to use for the canvas. * Any valid `canvas.fillStyle` can be used: a `DOMString` parsed as CSS * <color> value, a `CanvasGradient` object (a linear or radial gradient) or * a `CanvasPattern` object (a repetitive image). The default value is * 'rgb(255,255,255)'. * * NOTE: This option may be partially, or completely, ignored when the * `pageColors`-option is used. */ background?: string | unknown | undefined; /** * - Overwrites background and foreground colors * with user defined ones in order to improve readability in high contrast * mode. */ pageColors?: unknown | undefined; /** * - * A promise that should resolve with an {@link OptionalContentConfig }created from `PDFDocumentProxy.getOptionalContentConfig`. If `null`, * the configuration will be fetched automatically with the default visibility * states set. */ optionalContentConfigPromise?: Promise<OptionalContentConfig> | undefined; /** * - Map some * annotation ids with canvases used to render them. */ annotationCanvasMap?: Map<string, HTMLCanvasElement> | undefined; printAnnotationStorage?: PrintAnnotationStorage | undefined; }; /** * Page annotation parameters. */ export type GetAnnotationsParameters = { /** * - Determines the annotations that are fetched, * can be 'display' (viewable annotations), 'print' (printable annotations), * or 'any' (all annotations). The default value is 'display'. */ intent?: string | undefined; }; /** * Allows controlling of the rendering tasks. */ export class RenderTask { constructor(internalRenderTask: any); /** * Callback for incremental rendering -- a function that will be called * each time the rendering is paused. To continue rendering call the * function that is the first argument to the callback. * @type {function} */ onContinue: () => void; /** * Promise for rendering task completion. * @type {Promise<void>} */ get promise(): Promise<void>; /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will be rejected when cancelled. * * @param {number} [extraDelay] */ cancel(extraDelay?: number | undefined): void; /** * Whether form fields are rendered separately from the main operatorList. * @type {boolean} */ get separateAnnots(): boolean; #private; } /** * Page getOperatorList parameters. */ export type GetOperatorListParameters = { /** * - Rendering intent, can be 'display', 'print', * or 'any'. The default value is 'display'. */ intent?: string | undefined; /** * Controls which annotations are included * in the operatorList, for annotations with appearance-data; the values from * {@link AnnotationMode } should be used. The following values are supported: * - `AnnotationMode.DISABLE`, which disables all annotations. * - `AnnotationMode.ENABLE`, which includes all possible annotations (thus * it also depends on the `intent`-option, see above). * - `AnnotationMode.ENABLE_FORMS`, which excludes annotations that contain * interactive form elements (those will be rendered in the display layer). * - `AnnotationMode.ENABLE_STORAGE`, which includes all possible annotations * (as above) but where interactive form elements are updated with data * from the {@link AnnotationStorage }-instance; useful e.g. for printing. * The default value is `AnnotationMode.ENABLE`. */ annotationMode?: number | undefined; printAnnotationStorage?: PrintAnnotationStorage | undefined; }; /** * Structure tree node. The root node will have a role "Root". */ export type StructTreeNode = { /** * - Array of * {@link StructTreeNode } and {@link StructTreeContent } objects. */ children: Array<StructTreeNode | StructTreeContent>; /** * - element's role, already mapped if a role map exists * in the PDF. */ role: string; }; /** * Structure tree content. */ export type StructTreeContent = { /** * - either "content" for page and stream structure * elements or "object" for object references. */ type: string; /** * - unique id that will map to the text layer. */ id: string; }; /** * PDF page operator list. */ export type PDFOperatorList = { /** * - Array containing the operator functions. */ fnArray: Array<number>; /** * - Array containing the arguments of the * functions. */ argsArray: Array<any>; }; /** * Proxy to a `PDFPage` in the worker thread. */ export class PDFPageProxy { constructor( pageIndex: any, pageInfo: any, transport: any, ownerDocument: any, pdfBug?: boolean ); _pageIndex: any; _pageInfo: any; _ownerDocument: any; _transport: any; _stats: StatTimer | null; _pdfBug: boolean; /** @type {PDFObjects} */ commonObjs: PDFObjects; objs: PDFObjects; _bitmaps: Set<any>; cleanupAfterRender: boolean; pendingCleanup: boolean; _intentStates: Map<any, any>; destroyed: boolean; /** * @type {number} Page number of the page. First page is 1. */ get pageNumber(): number; /** * @type {number} The number of degrees the page is rotated clockwise. */ get rotate(): number; /** * @type {RefProxy | null} The reference that points to this page. */ get ref(): RefProxy | null; /** * @type {number} The default size of units in 1/72nds of an inch. */ get userUnit(): number; /** * @type {Array<number>} An array of the visible portion of the PDF page in * user space units [x1, y1, x2, y2]. */ get view(): number[]; /** * @param {GetViewportParameters} params - Viewport parameters. * @returns {PageViewport} Contains 'width' and 'height' properties * along with transforms required for rendering. */ getViewport({ scale, rotation, offsetX, offsetY, dontFlip, }?: GetViewportParameters): PageViewport; /** * @param {GetAnnotationsParameters} params - Annotation parameters. * @returns {Promise<Array<any>>} A promise that is resolved with an * {Array} of the annotation objects. */ getAnnotations({ intent }?: GetAnnotationsParameters): Promise<Array<any>>; /** * @returns {Promise<unknown>} A promise that is resolved with an * {unknown} with JS actions. */ getJSActions(): Promise<unknown>; /** * @type {boolean} True if only XFA form. */ get isPureXfa(): boolean; /** * @returns {Promise<unknown | null>} A promise that is resolved with * an {unknown} with a fake DOM object (a tree structure where elements * are {unknown} with a name, attributes (class, style, ...), value and * children, very similar to a HTML DOM tree), or `null` if no XFA exists. */ getXfa(): Promise<unknown | null>; /** * Begins the process of rendering a page to the desired context. * * @param {RenderParameters} params - Page render parameters. * @returns {RenderTask} An object that contains a promise that is * resolved when the page finishes rendering. */ render({ canvasContext, viewport, intent, annotationMode, transform, canvasFactory, background, optionalContentConfigPromise, annotationCanvasMap, pageColors, printAnnotationStorage, }: RenderParameters): RenderTask; /** * @param {GetOperatorListParameters} params - Page getOperatorList * parameters. * @returns {Promise<PDFOperatorList>} A promise resolved with an * {@link PDFOperatorList} object that represents the page's operator list. */ getOperatorList({ intent, annotationMode, printAnnotationStorage, }?: GetOperatorListParameters): Promise<PDFOperatorList>; /** * NOTE: All occurrences of whitespace will be replaced by * standard spaces (0x20). * * @param {getTextContentParameters} params - getTextContent parameters. * @returns {ReadableStream} Stream for reading text content chunks. */ streamTextContent({ disableCombineTextItems, includeMarkedContent, }?: getTextContentParameters): ReadableStream; /** * NOTE: All occurrences of whitespace will be replaced by * standard spaces (0x20). * * @param {getTextContentParameters} params - getTextContent parameters. * @returns {Promise<TextContent>} A promise that is resolved with a * {@link TextContent} object that represents the page's text content. */ getTextContent(params?: getTextContentParameters): Promise<TextContent>; /** * @returns {Promise<StructTreeNode>} A promise that is resolved with a * {@link StructTreeNode} object that represents the page's structure tree, * or `null` when no structure tree is present for the current page. */ getStructTree(): Promise<StructTreeNode>; /** * Destroys the page object. * @private */ private _destroy; /** * Cleans up resources allocated by the page. * * @param {boolean} [resetStats] - Reset page stats, if enabled. * The default value is `false`. * @returns {boolean} Indicates if clean-up was successfully run. */ cleanup(resetStats?: boolean | undefined): boolean; /** * Attempts to clean up if rendering is in a state where that's possible. * @private */ private _tryCleanup; /** * @private */ private _startRenderPage; /** * @private */ private _renderPageChunk; /** * @private */ private _pumpOperatorList; /** * @private */ private _abortOperatorList; /** * @type {unknown} Returns page stats, if enabled; returns `null` otherwise. */ get stats(): unknown; } }
package com.ing.nzy.finance.services; import com.ing.nzy.dto.messages.RechercheCreationEvent; import com.ing.nzy.finance.configurations.MessageQueueConfiguration; import com.ing.nzy.finance.converters.AmendeConverter; import com.ing.nzy.finance.model.Amende; import com.ing.nzy.finance.repositories.AmendeRepository; import com.ing.nzy.dto.InfractionDto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; @Service @RequiredArgsConstructor @Slf4j @Transactional public class AmendeServiceImpl implements AmendeService { private final AmendeRepository amendeRepository; private final AmendeConverter amendeConverter; private final JmsTemplate jmsTemplate; @Override public void ajouterAmende(InfractionDto infractionDto) { // convertir du type infraction au type amende + calcule date echeance + calcule le montant Amende amende = amendeConverter.infractionToAmend(infractionDto); // save to DB amendeRepository.saveAndFlush(amende); } @Override public void reglerAmende(Long amendeId) { Amende amende = amendeRepository.findById(amendeId).orElseThrow(RuntimeException::new); amende.setPayee(true); amendeRepository.saveAndFlush(amende); } @Override public void amendesApresDateEcheance() { amendeRepository .findAll() .stream() .filter(amende -> !amende.getPayee() && amende.getDateEcheance().isAfter(LocalDate.now())) .forEach(amende -> { // envoyer message au ministere de l'interieur pour creer un avis de recherche jmsTemplate.convertAndSend(MessageQueueConfiguration.CREATION_RECHERCHE_TOPIC, RechercheCreationEvent.builder() .amendeDto(amendeConverter.amendeToAmendDto(amende)) .build()); log.debug("Sent Jms Message With Cin {}", amende.getPersonCin()); }); } }
import { Badge, Button, createTheme, IconButton } from "@mui/material"; import { Box } from "@mui/system"; import MenuItem from "@mui/material/MenuItem"; import React from "react"; import "./Navbar.css"; import AccountCircleIcon from "@mui/icons-material/AccountCircle"; // import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";/ import BookmarkBorderIcon from "@mui/icons-material/BookmarkBorder"; import AddShoppingCartIcon from "@mui/icons-material/AddShoppingCart"; import { Link, useNavigate } from "react-router-dom"; import { useAuth } from "../../contexts/AuthContextProvider"; import Tooltip from "@mui/material/Tooltip"; import { ADD } from "../../helpers/consts"; import { getCountProductsInCart, getCountProductsInWish, } from "../../helpers/function"; import { useCart } from "../../contexts/CartContextProvider"; import { useWish } from "../../contexts/WishListContextProvider"; const LowerNavbar = () => { //! ДЛЯ ОТОБРАЖЕНИЯ КОЛИЧЕСТВА В КОРЗИНЕ const { addProductToCart } = useCart(); const [count, setCount] = React.useState(0); React.useEffect(() => { setCount(getCountProductsInCart); }, [addProductToCart]); const { addProductToWish } = useWish(); const [count2, setCount2] = React.useState(0); React.useEffect(() => { setCount2(getCountProductsInWish); }, [addProductToWish]); const navigate = useNavigate(); const theme = createTheme({ breakpoints: { values: { xxs: 325, xs: 380, sm: 430, md: 770, lg: 1200, }, }, }); const { user: { email }, handleLogout, handleSignup, } = useAuth(); return ( <div> <Box className="lowerNav" sx={{ height: "4rem", mt: "3%", width: "100%", }} > <Box sx={{ display: "flex", justifyContent: "center", }} > <Box sx={{ display: "flex", justifyContent: "center", width: "30%", mt: "0.5%", [theme.breakpoints.down("md")]: { mt: "1.5%", }, [theme.breakpoints.down("sm")]: { mt: "3%", }, }} > {email ? ( <MenuItem onClick={handleLogout}> <Tooltip title="Logout"> <AccountCircleIcon sx={{ display: "flex", color: "#9a69cb", }} /> </Tooltip> </MenuItem> ) : ( <Link to="/auth" style={{ textDecoration: "none ", color: "black", display: "flex", }} > <MenuItem onClick={handleSignup}> <Tooltip title="Logout"> <AccountCircleIcon sx={{ margin: "3%", color: "#9a69cb", [theme.breakpoints.down("sm")]: { mt: "-8%", }, [theme.breakpoints.down("xxs")]: { marginLeft: "50%", mt: "-10%", }, }} /> </Tooltip> </MenuItem> </Link> )} <IconButton> <Badge badgeContent={count} color="secondary"> <AddShoppingCartIcon onClick={() => navigate("/cart")} sx={{ margin: "3%", color: "#9a69cb" }} /> </Badge> </IconButton> <Badge badgeContent={count2} color="secondary"> <IconButton onClick={() => navigate("/wish")}> <BookmarkBorderIcon sx={{ margin: "3%", color: "#9a69cb" }} /> </IconButton> </Badge> </Box> {/*ДЛЯ ДОБАВЛЕНИЯ ПРОДУКТА */} {email === ADD ? ( <Button onClick={() => navigate("/admin")} sx={{ color: "#9a69cb" }} > ДОБАВИТЬ </Button> ) : ( <></> )} {/* ДЛЯ ДОБАВЛЕНИЯ ПРОДУКТА ПО URL */} {email === ADD ? ( <Button onClick={() => navigate("/admin2")} sx={{ color: "#9a69cb" }} > ДОБАВИТЬ URL </Button> ) : ( <></> )} </Box> </Box> </div> ); }; export default LowerNavbar;
/** * And gate: out = Not( Nand(a, b) ) * = Nand( Nand(a, b), Nand(a, b) ) * * a b out * -------- * 0 0 0 * 0 1 0 * 1 0 0 * 1 1 1 * */ CHIP And { IN a, b; OUT out; PARTS: Nand(a=a, b=b, out=andAB); Not(in=andAB, out=out); }
import {createApi} from "@reduxjs/toolkit/query/react"; import {axiosBaseQuery} from "../../query/config.api"; import {ICreateApiBody} from "../../models/json"; export const jsonApi = createApi({ reducerPath: 'api/json', baseQuery: axiosBaseQuery(), tagTypes: ['JSON'], endpoints: build => ({ getColumns: build.query({ query: (): any => ({ url: '/columns', method: 'get', providesTags: ['JSON'] }) }), getApi: build.query({ query: (project_id: string): { url: string, method: string } => { return { url: `/projects/${project_id}?paginate`, method: 'get', } }, providesTags: ['JSON'] }), deleteApi: build.mutation({ query: ({id,}: { id: number }) : { url: string, method: string } => { return { url: `/userData/${id}`, method: 'delete', } }, invalidatesTags: ['JSON'] }), showApi: build.query({ query: ({ id }: { id: string }): { url: string, method: string } => { return { url: `/userData/${id}`, method: 'get', } } }), createApi: build.mutation({ query: (data: ICreateApiBody): { url: string, method: string, data: ICreateApiBody } => { return { url: '/userData', method: 'post', data: data } }, invalidatesTags: ['JSON'] }), updateApi: build.mutation({ query: ({data, id}: { data: ICreateApiBody, id: string }): { url: string, method: string, data: ICreateApiBody } => { return { url: `/userData/${id}`, method: 'post', data } }, invalidatesTags: ['JSON'] }), fillData: build.mutation({ query: ({ userId, slug, count }: { userId: string, slug: string, count?: number }): { url: string, method: string, data: { count: number } } => { return { url: `/${userId}/data/${slug}/fill`, method: 'post', data: { count: count ?? 20 } } }, invalidatesTags: ['JSON'] }), }) }) export const { useGetColumnsQuery, useCreateApiMutation, useGetApiQuery, useFillDataMutation, useDeleteApiMutation, useShowApiQuery, useUpdateApiMutation } = jsonApi
/* obs-application.c * * Copyright 2022 Georges Basile Stavracas Neto <georges.stavracas@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * SPDX-License-Identifier: GPL-3.0-or-later */ #include "obs-application.h" #include "obs-audio-controller.h" #include "obs-config-manager.h" #include "obs-log.h" #include "obs-style-manager.h" #include "obs-templates-manager.h" #include "obs-utils.h" #include "obs-window.h" #include <libpanel.h> #include <locale.h> #include <obs.h> #include <util/platform.h> #if defined(__linux__) #include <obs-nix-platform.h> #endif #ifdef GDK_WINDOWING_X11 #include <gdk/x11/gdkx.h> #endif #ifdef GDK_WINDOWING_WAYLAND #include <gdk/wayland/gdkwayland.h> #endif #define PLUGIN_CONFIG_PATH "obs-studio/plugin_config" #define DEFAULT_COLOR_SCHEME \ (obs_color_scheme_to_string(ADW_COLOR_SCHEME_FORCE_DARK)) #define DEFAULT_LANGUAGE "en-US" #define DEFAULT_THEME "resource:///com/obsproject/Studio/GTK4/styles/default" struct _ObsApplication { AdwApplication parent_instance; ObsWindow *window; profiler_name_store_t *profiler; ObsConfigManager *config_manager; ObsAudioController *audio_controller; ObsTemplatesManager *templates_manager; char *locale; }; G_DEFINE_FINAL_TYPE(ObsApplication, obs_application, ADW_TYPE_APPLICATION) typedef struct { obs_task_t task; void *param; GMainLoop *mainloop; } ui_task_t; static gboolean run_ui_task_cb(gpointer user_data) { ui_task_t *ui_task = user_data; ui_task->task(ui_task->param); if (ui_task->mainloop) { g_main_loop_quit(ui_task->mainloop); g_clear_pointer(&ui_task->mainloop, g_main_loop_unref); } return G_SOURCE_REMOVE; } static void ui_task_handler(obs_task_t task, void *param, bool wait) { ui_task_t *ui_task; ui_task = g_new(ui_task_t, 1); ui_task->task = task; ui_task->param = param; ui_task->mainloop = wait ? g_main_loop_new(NULL, FALSE) : NULL; g_idle_add_full(G_PRIORITY_DEFAULT_IDLE, run_ui_task_cb, ui_task, g_free); if (wait) g_main_loop_run(ui_task->mainloop); } static void load_global_defaults(ObsApplication *self) { config_t *config; config = obs_config_manager_open(self->config_manager, OBS_CONFIG_SCOPE_GLOBAL, "global", CONFIG_OPEN_ALWAYS); config_set_default_string(config, "General", "ColorScheme", DEFAULT_COLOR_SCHEME); config_set_default_string(config, "General", "Theme", DEFAULT_THEME); config_set_default_bool(config, "General", "FirstRun", true); #if 0 config_set_default_uint(config, "General", "MaxLogs", 10); config_set_default_int(config, "General", "InfoIncrement", -1); config_set_default_string(config, "General", "ProcessPriority", "Normal"); config_set_default_bool(config, "General", "EnableAutoUpdates", true); config_set_default_bool(config, "General", "ConfirmOnExit", true); #if _WIN32 config_set_default_string(config, "Video", "Renderer", "Direct3D 11"); #else config_set_default_string(config, "Video", "Renderer", "OpenGL"); #endif config_set_default_bool(config, "BasicWindow", "PreviewEnabled", true); config_set_default_bool(config, "BasicWindow", "PreviewProgramMode", false); config_set_default_bool(config, "BasicWindow", "SceneDuplicationMode", true); config_set_default_bool(config, "BasicWindow", "SwapScenesMode", true); config_set_default_bool(config, "BasicWindow", "SnappingEnabled", true); config_set_default_bool(config, "BasicWindow", "ScreenSnapping", true); config_set_default_bool(config, "BasicWindow", "SourceSnapping", true); config_set_default_bool(config, "BasicWindow", "CenterSnapping", false); config_set_default_double(config, "BasicWindow", "SnapDistance", 10.0); config_set_default_bool(config, "BasicWindow", "RecordWhenStreaming", false); config_set_default_bool(config, "BasicWindow", "KeepRecordingWhenStreamStops", false); config_set_default_bool(config, "BasicWindow", "SysTrayEnabled", true); config_set_default_bool(config, "BasicWindow", "SysTrayWhenStarted", false); config_set_default_bool(config, "BasicWindow", "SaveProjectors", false); config_set_default_bool(config, "BasicWindow", "ShowTransitions", true); config_set_default_bool(config, "BasicWindow", "ShowListboxToolbars", true); config_set_default_bool(config, "BasicWindow", "ShowStatusBar", true); config_set_default_bool(config, "BasicWindow", "ShowSourceIcons", true); config_set_default_bool(config, "BasicWindow", "ShowContextToolbars", true); config_set_default_bool(config, "BasicWindow", "StudioModeLabels", true); config_set_default_string(config, "General", "HotkeyFocusType", "NeverDisableHotkeys"); config_set_default_bool(config, "BasicWindow", "VerticalVolControl", false); config_set_default_bool(config, "BasicWindow", "MultiviewMouseSwitch", true); config_set_default_bool(config, "BasicWindow", "MultiviewDrawNames", true); config_set_default_bool(config, "BasicWindow", "MultiviewDrawAreas", true); #ifdef _WIN32 uint32_t winver = GetWindowsVersion(); config_set_default_bool(config, "Audio", "DisableAudioDucking", true); config_set_default_bool(config, "General", "BrowserHWAccel", winver > 0x601); #endif #ifdef __APPLE__ config_set_default_bool(config, "General", "BrowserHWAccel", true); config_set_default_bool(config, "Video", "DisableOSXVSync", true); config_set_default_bool(config, "Video", "ResetOSXVSyncOnExit", true); #endif config_set_default_bool(config, "BasicWindow", "MediaControlsCountdownTimer", true); #endif } static char * massage_locale_to_something_that_makes_libobs_happy(const char *locale) { GStrv split; char *happy_locale; char *aux; split = g_strsplit(locale, ".", 2); happy_locale = g_strdup(split[0]); aux = happy_locale; while ((aux = g_strrstr(aux, "_")) != NULL) *aux = '-'; g_strfreev(split); return happy_locale; } static void update_locale(ObsApplication *self) { const char *locale; config_t *config; config = obs_config_manager_open(self->config_manager, OBS_CONFIG_SCOPE_GLOBAL, "global", CONFIG_OPEN_ALWAYS); locale = config_get_string(config, "General", "Locale"); if (locale) { setlocale(LC_ALL, locale); self->locale = g_strdup(locale); } else { locale = setlocale(LC_MESSAGES, ""); if (!locale) locale = setlocale(LC_ALL, ""); if (!locale) locale = DEFAULT_LANGUAGE; self->locale = massage_locale_to_something_that_makes_libobs_happy( locale); } blog(LOG_INFO, "Locale: %s", self->locale); } static void load_theme(ObsApplication *self) { AdwStyleManager *adw_style_manager; ObsStyleManager *obs_style_manager; const char *color_scheme; const char *theme; config_t *config; config = obs_config_manager_open(self->config_manager, OBS_CONFIG_SCOPE_GLOBAL, "global", CONFIG_OPEN_ALWAYS); theme = config_get_string(config, "General", "Theme"); color_scheme = config_get_string(config, "General", "ColorScheme"); assert(theme != NULL); adw_style_manager = adw_style_manager_get_default(); adw_style_manager_set_color_scheme( adw_style_manager, obs_color_scheme_from_string(color_scheme)); obs_style_manager = obs_style_manager_get_default(); obs_style_manager_load_style(obs_style_manager, theme); } static void obs_application_startup(GApplication *application) { ObsApplication *self = OBS_APPLICATION(application); char path[512]; profiler_start(); profile_register_root("obs_application_startup", 0); G_APPLICATION_CLASS(obs_application_parent_class)->startup(application); panel_init(); obs_templates_manager_load_templates(self->templates_manager); obs_log_init(); obs_set_nix_platform(OBS_NIX_PLATFORM_DRM); if (os_get_config_path(path, sizeof(path), PLUGIN_CONFIG_PATH) < 0) { g_application_quit(application); return; } obs_startup(self->locale, path, self->profiler); obs_set_ui_task_handler(ui_task_handler); obs_load_all_modules(); obs_log_loaded_modules(); obs_post_load_modules(); load_theme(self); obs_audio_controller_initialize(self->audio_controller); gdk_gl_context_clear_current(); } static void obs_application_activate(GApplication *application) { ObsApplication *self = OBS_APPLICATION(application); G_APPLICATION_CLASS(obs_application_parent_class)->activate(application); if (self->window == NULL) self->window = obs_window_new(application); gtk_window_present(GTK_WINDOW(self->window)); } static void obs_application_shutdown(GApplication *application) { ObsApplication *self = OBS_APPLICATION(application); profiler_snapshot_t *snapshot; obs_audio_controller_shutdown(self->audio_controller); obs_shutdown(); G_APPLICATION_CLASS(obs_application_parent_class)->shutdown(application); snapshot = profile_snapshot_create(); profiler_print(snapshot); profiler_print_time_between_calls(snapshot); profiler_free(); } static void obs_application_finalize(GObject *object) { ObsApplication *self = OBS_APPLICATION(object); g_clear_object(&self->audio_controller); g_clear_pointer(&self->profiler, profiler_name_store_free); g_clear_pointer(&self->locale, g_free); g_clear_object(&self->config_manager); G_OBJECT_CLASS(obs_application_parent_class)->finalize(object); } static void obs_application_class_init(ObsApplicationClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS(klass); GApplicationClass *application_class = G_APPLICATION_CLASS(klass); object_class->finalize = obs_application_finalize; application_class->startup = obs_application_startup; application_class->activate = obs_application_activate; application_class->shutdown = obs_application_shutdown; } static void obs_application_init(ObsApplication *self) { self->profiler = profiler_name_store_create(); self->config_manager = obs_config_manager_new(); self->audio_controller = obs_audio_controller_new(); self->templates_manager = obs_templates_manager_new(); obs_log_init(); load_global_defaults(self); update_locale(self); } GApplication *obs_application_new(void) { return g_object_new(OBS_TYPE_APPLICATION, "application-id", "com.obsproject.Studio.GTK4", NULL); } ObsConfigManager *obs_application_get_config_manager(ObsApplication *self) { g_return_val_if_fail(OBS_IS_APPLICATION(self), NULL); return self->config_manager; } ObsAudioController *obs_application_get_audio_controller(ObsApplication *self) { g_return_val_if_fail(OBS_IS_APPLICATION(self), NULL); return self->audio_controller; } ObsTemplatesManager *obs_application_get_templates_manager(ObsApplication *self) { g_return_val_if_fail(OBS_IS_APPLICATION(self), NULL); return self->templates_manager; }
# Java # 目录 # 抽象基类 ## 抽象类简概 - 作用:位于上层的类更具有通用性,甚至可能更加抽象 - 举例:Employee和Student的共同超类为Person - 性质:抽象类不能被实例化 ## 抽象类使用(abstract关键字) - 抽象方法 - 使用abstract关键字,这样就完全不**需要实现超类的方法** ```java public abstract String getDescription(); // no implementation required,不需要实现 ``` - 抽象类 - 为了提高程序的清晰度,包含一个或多个抽象方法的类本身必须被声明为抽象的。 但类即使不含抽象方法,也可以将类声明为抽象类 ```java public abstract class Person { ... public abstract String getDescription(); } ``` 补充 > 除了抽象方法之外,抽象类还可以包含具体数据和具体方法 > > 但许多程序员认为,在抽象类中不能包含具体方法。建议尽量将通用的域和方法(不管是否是抽象的)放在超类(不管是否是抽象类)中 > > 在Java程序设计语言中,抽象方法是一个重要的概念。在接口(interface)一章中将会看到更多的抽象方法 --- ==与C++不同== - Java - ```java public abstract class Person // 抽象基类(关键字强制被声明,目的只是提高程序的清晰度) { ... public abstract String getDescription();// 抽象方法 } ``` - C++ - **只要有一个纯虚函数,这个类就是抽象类**。在C++中,没有提供用于表示抽象类的特殊关键字。 ```c++ class Person { public: virtual string getDescription() = 0; // 纯虚函数 } ```
import GrayCard from "@/components/GrayCard"; import CommentCard from "./CommentCard"; import { useEffect, useState } from "react"; import { usePathname, useSearchParams } from "next/navigation"; import PageBar from "./Pagebar"; import { useRouter } from "next/navigation"; import { Oval } from "react-loader-spinner"; function CommentSection({ postId }: { postId: string }) { const query = useSearchParams(); const router = useRouter(); const path = usePathname(); const [comments, setComments] = useState([]); useEffect(() => { fetch( `/api/post/${postId}/comments?page=${query.get("page") ?? 1}&sort=${ query.get("sort") ?? -1 }` ) .then((res) => res.json()) .then((res) => setComments(res.comments)); }, [postId, query]); return ( <> <div className="flex justify-between"> <h2 className="font-semibold text-xl">Comments: </h2> <select name="comment_sort" id="comment_sort" className="mr-4 bg-gray-700 rounded p-1 font-bold" onChange={(e) => router.replace( path + `?page=${query.get("page")}&sort=${e.target.value}#comments` ) } value={query.get("sort") ?? "1"} > <option value="1">Oldest</option> <option value="-1">Newest</option> </select> </div> <hr className="mt-4 mb-2 border-slate-600" /> {comments.length > 0 ? ( <> {comments.map((comment: any) => { return <CommentCard comment={comment} key={comment._id} />; })} </> ) : ( <div className="flex justify-center my-2"> <Oval height="80" width="80" color="#53bfc5" secondaryColor="53bfc5" ariaLabel="oval-loading" /> </div> )} <PageBar postId={postId} /> </> ); } export default CommentSection;
import 'package:flutter/material.dart'; import 'package:audio_video_progress_bar/audio_video_progress_bar.dart'; import 'package:musik/controllers/audio_manager.dart'; import 'package:musik/utils/colors.dart'; class PersistentPlayerBar extends StatefulWidget { const PersistentPlayerBar({super.key}); @override State<PersistentPlayerBar> createState() => _PersistentPlayerBar(); } class _PersistentPlayerBar extends State<PersistentPlayerBar> { _PersistentPlayerBar(); bool loaded = true; bool playing = true; @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), color: backgroundColor, child: StreamBuilder<Duration>( stream: audioManager.audioPlayer.positionStream, builder: (context, snapshot) { final position = snapshot.data ?? const Duration(); final duration = audioManager.audioPlayer.duration ?? const Duration(); return Column(children: [ ProgressBar( progress: position, total: duration, progressBarColor: buttonColor, baseBarColor: Colors.grey[200], bufferedBarColor: Colors.grey[350], thumbColor: buttonColor, timeLabelPadding: -1, timeLabelTextStyle: const TextStyle(fontSize: 12, color: Colors.white), ), Container( height: 50, width: 50, decoration: const BoxDecoration( shape: BoxShape.circle, color: buttonColor), child: IconButton( onPressed: loaded ? () { if (playing) { audioManager.audioPlayer.pause(); playing = false; } else { audioManager.audioPlayer.play(); playing = true; } } : null, icon: Icon( playing ? Icons.pause : Icons.play_arrow, color: Colors.white, )), ), ]); }, ), ); } }
use std::sync::Arc; use blockifier::transaction::transaction_types::TransactionType; use blockifier::transaction::transactions::DeployAccountTransaction; use pyo3::prelude::*; use starknet_api::core::{ClassHash, ContractAddress, Nonce}; use starknet_api::data_availability::DataAvailabilityMode; use starknet_api::transaction::{ Calldata, ContractAddressSalt, DeployAccountTransactionV1, DeployAccountTransactionV3, Fee, PaymasterData, ResourceBoundsMapping, Tip, TransactionHash, TransactionSignature, }; use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; use crate::py_transaction::{PyDataAvailabilityMode, PyResourceBoundsMapping}; use crate::py_utils::{from_py_felts, py_attr, PyFelt}; #[derive(FromPyObject)] struct PyDeployAccountTransactionV1 { pub max_fee: u128, pub signature: Vec<PyFelt>, pub nonce: PyFelt, pub class_hash: PyFelt, pub contract_address_salt: PyFelt, pub constructor_calldata: Vec<PyFelt>, } impl From<PyDeployAccountTransactionV1> for DeployAccountTransactionV1 { fn from(tx: PyDeployAccountTransactionV1) -> Self { Self { max_fee: Fee(tx.max_fee), signature: TransactionSignature(from_py_felts(tx.signature)), nonce: Nonce(tx.nonce.0), class_hash: ClassHash(tx.class_hash.0), contract_address_salt: ContractAddressSalt(tx.contract_address_salt.0), constructor_calldata: Calldata(Arc::from(from_py_felts(tx.constructor_calldata))), } } } #[derive(FromPyObject)] struct PyDeployAccountTransactionV3 { pub resource_bounds: PyResourceBoundsMapping, pub tip: u64, pub signature: Vec<PyFelt>, pub nonce: PyFelt, pub class_hash: PyFelt, pub contract_address_salt: PyFelt, pub constructor_calldata: Vec<PyFelt>, pub nonce_data_availability_mode: PyDataAvailabilityMode, pub fee_data_availability_mode: PyDataAvailabilityMode, pub paymaster_data: Vec<PyFelt>, } impl TryFrom<PyDeployAccountTransactionV3> for DeployAccountTransactionV3 { type Error = NativeBlockifierInputError; fn try_from(tx: PyDeployAccountTransactionV3) -> Result<Self, Self::Error> { Ok(Self { resource_bounds: ResourceBoundsMapping::try_from(tx.resource_bounds)?, tip: Tip(tx.tip), signature: TransactionSignature(from_py_felts(tx.signature)), nonce: Nonce(tx.nonce.0), class_hash: ClassHash(tx.class_hash.0), contract_address_salt: ContractAddressSalt(tx.contract_address_salt.0), constructor_calldata: Calldata(Arc::from(from_py_felts(tx.constructor_calldata))), nonce_data_availability_mode: DataAvailabilityMode::from( tx.nonce_data_availability_mode, ), fee_data_availability_mode: DataAvailabilityMode::from(tx.fee_data_availability_mode), paymaster_data: PaymasterData(from_py_felts(tx.paymaster_data)), }) } } pub fn py_deploy_account(py_tx: &PyAny) -> NativeBlockifierResult<DeployAccountTransaction> { let version = usize::try_from(py_attr::<PyFelt>(py_tx, "version")?.0)?; let tx = match version { 1 => { let py_deploy_account_tx: PyDeployAccountTransactionV1 = py_tx.extract()?; let deploy_account_tx = DeployAccountTransactionV1::from(py_deploy_account_tx); Ok(starknet_api::transaction::DeployAccountTransaction::V1(deploy_account_tx)) } 3 => { let py_deploy_account_tx: PyDeployAccountTransactionV3 = py_tx.extract()?; let deploy_account_tx = DeployAccountTransactionV3::try_from(py_deploy_account_tx)?; Ok(starknet_api::transaction::DeployAccountTransaction::V3(deploy_account_tx)) } _ => Err(NativeBlockifierInputError::UnsupportedTransactionVersion { tx_type: TransactionType::DeployAccount, version, }), }?; let tx_hash = TransactionHash(py_attr::<PyFelt>(py_tx, "hash_value")?.0); let contract_address = ContractAddress::try_from(py_attr::<PyFelt>(py_tx, "sender_address")?.0)?; Ok(DeployAccountTransaction::new(tx, tx_hash, contract_address)) }
import "./style.css"; const app = document.querySelector<HTMLDivElement>("#app")!; // Main page✅ > Search Results Page > Sign Up Page > Sign in window type Property = { id: number; propertyName: string; location: string; image: string; price: number; availableDates: []; owner: string | ""; }; type user = { id: number; firstName: string; lastName: string; phone: string; email: string; password: string; type: "landlord" | "renter"; }; type State = { properties: Property[]; page: "home" | "search" | "signUp"; modal: "signIn" | ""; user: null | {}; locationSearch: string; stayingPeriod: string; }; let state: State = { page: "home", user: null, modal: "", properties: [], locationSearch: "", stayingPeriod: "", }; function signUp({ firstName, lastName, phone, email, password, type }) { fetch("http://localhost:3010/users", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ firstName, lastName, phone, email, password, type }), }) .then((resp) => resp.json()) .then((data) => { console.log(data); }); } function signIn({ email, password }) { fetch("http://localhost:3010/users") .then((resp) => resp.json()) .then((users) => { let match = users.find((user) => user.email === email); if (match && match.password === password) { state.user = match; state.modal = ""; render(); } else { alert("Invalid username/password"); } }); } function getProperties() { if (state.locationSearch === "") return; fetch(`http://localhost:3010/properties`) .then((response) => response.json()) .then((properties: Property[]) => { state.properties = properties.filter((properties) => properties.location .toLowerCase() .includes(state.locationSearch.toLowerCase()) ); state.page = "search"; render(); }); } function renderHeader() { let headerEl = document.createElement("header"); headerEl.className = "header"; let headerTitleEl = document.createElement("h1"); headerTitleEl.textContent = "Looking.com"; if (state.user === null) { let headerLoginSection = document.createElement("div"); headerLoginSection.className = "header-btns"; let headerLoginBtn = document.createElement("button"); headerLoginBtn.className = "sign-btn"; headerLoginBtn.textContent = "Sign In"; headerLoginBtn.addEventListener("click", function () { state.modal = "signIn"; render(); }); let headerSignUpBtn = document.createElement("button"); headerSignUpBtn.className = "sign-btn"; headerSignUpBtn.textContent = "Sign Up"; headerSignUpBtn.addEventListener("click", function () { state.page = "signUp"; render(); }); headerLoginSection.append(headerLoginBtn, headerSignUpBtn); headerEl.append(headerTitleEl, headerLoginSection); app.append(headerEl); } else { let headerUserSection = document.createElement("div"); headerUserSection.className = "header-account"; let headerUserImg = document.createElement("img"); headerUserImg.src = "./src/assets/images/user.png"; headerUserImg.alt = "profile pic"; headerUserImg.width = 30; let headerUserName = document.createElement("p"); headerUserName.textContent = state.user.firstName; let headerLogoutBtn = document.createElement("button"); headerLogoutBtn.className = "sign-btn"; headerLogoutBtn.textContent = "LOGOUT"; headerLogoutBtn.addEventListener("click", function () { state.user = null; render(); }); headerUserSection.append(headerUserImg, headerUserName, headerLogoutBtn); headerEl.append(headerTitleEl, headerUserSection); app.append(headerEl); } } function renderMainPage() { let mainEl = document.createElement("main"); mainEl.className = "main"; let renterSection = document.createElement("section"); renterSection.className = "landing-page__renter-section"; let renterSectionPEl = document.createElement("p"); renterSectionPEl.textContent = "Find Your Perfect Match®"; let renterSectionH2El = document.createElement("h2"); renterSectionH2El.textContent = "Find the right place for you today!"; let renterSectionSearch = document.createElement("div"); renterSectionSearch.className = "renter-section__search-btn"; let renterSectionSearchInput = document.createElement("input"); renterSectionSearchInput.type = "search"; renterSectionSearchInput.placeholder = "Search by City"; let renterSectionSearchBtn = document.createElement("button"); renterSectionSearchBtn.textContent = "SEARCH"; renterSectionSearchBtn.addEventListener("click", function () { state.locationSearch = renterSectionSearchInput.value; getProperties(); }); renterSectionSearch.append(renterSectionSearchInput, renterSectionSearchBtn); renterSection.append( renterSectionPEl, renterSectionH2El, renterSectionSearch ); let landlordSection = document.createElement("section"); landlordSection.className = "landing-page__landlord-section"; let landlordSectionPEl = document.createElement("p"); landlordSectionPEl.textContent = "Let Your Properties Profit For You®"; let landlordSectionH2El = document.createElement("h2"); landlordSectionH2El.textContent = "List your properties for Free!"; let landlordSectionBtn = document.createElement("button"); landlordSectionBtn.textContent = "List your property"; landlordSection.append( landlordSectionPEl, landlordSectionH2El, landlordSectionBtn ); let descriptionSection = document.createElement("section"); descriptionSection.className = "landing-page__description-section"; let descriptionSectionH3El = document.createElement("h3"); descriptionSectionH3El.textContent = "Why use Looking.com?"; let featuresDiv = document.createElement("div"); featuresDiv.className = "features"; let featureCard = document.createElement("article"); featureCard.className = "feature-card"; let featureCardImg = document.createElement("img"); featureCardImg.src = "./src/assets/images/identity-feature.png"; featureCardImg.alt = ""; let cardTitle = document.createElement("h4"); cardTitle.textContent = "Verified identities"; let cardDescription = document.createElement("p"); cardDescription.textContent = "Users can verify identity through multiple sources so you can search with confidence! Our proprietary fraud detection tool helps keep out the spam.️"; featureCard.append(featureCardImg, cardTitle, cardDescription); let featureCard1 = document.createElement("article"); featureCard1.className = "feature-card"; let featureCardImg1 = document.createElement("img"); featureCardImg1.src = "./src/assets/images/match-feature.png"; featureCardImg1.alt = ""; let cardTitle1 = document.createElement("h4"); cardTitle1.textContent = "A perfect match"; let cardDescription1 = document.createElement("p"); cardDescription1.textContent = "Create your personal profile and get started in minutes! Get specific with things like pet preferences, room features, neighborhood details, and more."; featureCard1.append(featureCardImg1, cardTitle1, cardDescription1); let featureCard2 = document.createElement("article"); featureCard2.className = "feature-card"; let featureCardImg2 = document.createElement("img"); featureCardImg2.src = "./src/assets/images/third-feature.png"; featureCardImg2.alt = ""; let cardTitle2 = document.createElement("h4"); cardTitle2.textContent = "Great for landlords"; let cardDescription2 = document.createElement("p"); cardDescription2.textContent = " Keep track of your properties all in one place. Just list your properties and let the app do the rest and notify you for potential renters. Also enjoy the built-in profit tracker feature."; featureCard2.append(featureCardImg2, cardTitle2, cardDescription2); featuresDiv.append(featureCard, featureCard1, featureCard2); descriptionSection.append(descriptionSectionH3El, featuresDiv); mainEl.append(renterSection, landlordSection, descriptionSection); app.append(mainEl); } function renderSignUpPage() { let formEl = document.createElement("form"); formEl.addEventListener("submit", function () { // event.preventDefault(); const checkedRadioInput = document.querySelector( 'input[name="radio-input"]:checked' ); const type = checkedRadioInput.value; signUp({ firstName: firstNameInput.value, lastName: lastNameInput.value, phone: phoneNrInput.value, email: inputEl.value, password: inputPass.value, type: type, }); }); let singUpContainer = document.createElement("div"); singUpContainer.id = "signup"; singUpContainer.className = "form-container"; let titleSignUp = document.createElement("h2"); titleSignUp.className = "header-title-signUp"; titleSignUp.textContent = "Sign Up"; let hrEl1 = document.createElement("hr"); let emailEl = document.createElement("div"); emailEl.id = "email"; emailEl.className = "form-group"; let labelEl = document.createElement("label"); labelEl.innerHTML = "email-input"; labelEl.textContent = "Enter Your Email"; let inputEl = document.createElement("input"); inputEl.id = "email-input"; inputEl.className = "form-control"; inputEl.type = "text"; emailEl.append(labelEl, inputEl); let emailVerification = document.createElement("div"); emailVerification.id = "email-verification"; emailVerification.className = "form-group"; let labelEl1 = document.createElement("label"); labelEl1.innerHTML = "email-verification"; labelEl1.textContent = "Confirm Your Email"; let inputEl1 = document.createElement("input"); inputEl1.id = "email-verification"; inputEl1.className = "form-control"; inputEl1.type = "text"; emailVerification.append(labelEl1, inputEl1); let passEl = document.createElement("div"); passEl.id = "password"; passEl.className = "form-group"; let requirementsP = document.createElement("p"); requirementsP.className = "password-requirements"; requirementsP.textContent = "Password cannot contain spaces. Password must be at least 8 characteres. It must contain at least 1 digit, 1 lower-case letter and 1 upper-case letter. You can use the following symbols: !, @, #, $, &."; let labelPass = document.createElement("label"); labelPass.innerHTML = "password-input"; labelPass.textContent = "Create A Password"; let inputPass = document.createElement("input"); inputPass.id = "password-input"; inputPass.className = "form-control"; inputPass.type = "password"; passEl.append(labelPass, inputPass, requirementsP); let passVerification = document.createElement("div"); passVerification.id = "password-verification"; passVerification.className = "form-group"; let labelPass2 = document.createElement("label"); labelPass2.innerHTML = "password-verification"; labelPass2.textContent = "Confirm Your Password"; let inputPass2 = document.createElement("input"); inputPass2.id = "password-verification"; inputPass2.className = "form-control"; inputPass2.type = "password"; passVerification.append(labelPass2, inputPass2); let firstName = document.createElement("div"); firstName.className = "form-group"; firstName.id = "first-name"; let firstNameLabel = document.createElement("label"); firstNameLabel.innerHTML = "firstName-input"; firstNameLabel.textContent = "What Is Your Name?"; let firstNameInput = document.createElement("input"); firstNameInput.id = "firstName-input"; firstNameInput.className = "form-control"; firstNameInput.type = "text"; firstName.append(firstNameLabel, firstNameInput); let lastName = document.createElement("div"); lastName.className = "form-group"; lastName.id = "last-name"; let lastNameLabel = document.createElement("label"); lastNameLabel.innerHTML = "lastName-input"; lastNameLabel.textContent = "What Is Your Last Name?"; let lastNameInput = document.createElement("input"); lastNameInput.id = "lastName-input"; lastNameInput.className = "form-control"; lastNameInput.type = "text"; lastName.append(lastNameLabel, lastNameInput); let phoneNr = document.createElement("div"); phoneNr.className = "form-group"; phoneNr.id = "phone-nr"; let phoneNrLabel = document.createElement("label"); phoneNrLabel.innerHTML = "phoneNr-input"; phoneNrLabel.textContent = "Add Your Phone Nr."; let phoneNrInput = document.createElement("input"); phoneNrInput.id = "phoneNr-input"; phoneNrInput.className = "form-control"; phoneNrInput.type = "text"; phoneNr.append(phoneNrLabel, phoneNrInput); let ownerType = document.createElement("div"); ownerType.className = "form-group"; ownerType.id = "owner-type"; let landlordLabel = document.createElement("label"); landlordLabel.innerHTML = "landlord-input"; landlordLabel.textContent = "Landlord"; let landlordInput = document.createElement("input"); landlordInput.id = "landlord-input"; landlordInput.name = "radio-input"; landlordInput.className = "radio-input"; landlordInput.type = "radio"; landlordInput.value = "landlord"; let renterLabel = document.createElement("label"); renterLabel.innerHTML = "renter-input"; renterLabel.textContent = "Renter"; let renterInput = document.createElement("input"); renterInput.id = "renter-input"; renterInput.name = "radio-input"; renterInput.className = "radio-input"; renterInput.type = "radio"; renterInput.value = "renter"; ownerType.append(landlordLabel, landlordInput, renterLabel, renterInput); let nextBtn = document.createElement("button"); nextBtn.id = "next-button"; nextBtn.type = "submit"; nextBtn.classList.add("btn", "btn-primary"); nextBtn.textContent = "Next"; singUpContainer.append( titleSignUp, hrEl1, firstName, lastName, phoneNr, emailEl, emailVerification, passEl, passVerification, ownerType, nextBtn ); formEl.append(singUpContainer); app.append(formEl); } function renderSearchPage() { let searchPageMainEl = document.createElement("main"); searchPageMainEl.className = "search-page__main"; let sidebarDivEl = document.createElement("div"); sidebarDivEl.className = "search-page__sidebar-div"; let sidebarFilterSection = document.createElement("aside"); sidebarFilterSection.className = "sidebar-filter-section"; let searchOptionsBox = document.createElement("div"); searchOptionsBox.className = "search-options-box"; let searchFormEl = document.createElement("form"); searchFormEl.className = "search-form"; searchFormEl.addEventListener("submit", function (e) { e.preventDefault(); state.locationSearch = searchInputField.value; state.stayingPeriod = searchFormStayingPeriod.value; getProperties(); }); let searchFormTitleEl = document.createElement("h2"); searchFormTitleEl.textContent = "Search"; let searchFormLocationEl = document.createElement("label"); searchFormLocationEl.innerHTML = `Location name: <input type="text" placeholder="Where are you going?" name="location" required /> `; let searchInputField = searchFormLocationEl.querySelector("input")!; searchInputField.value = state.locationSearch; let searchFormDateEl = document.createElement("label"); searchFormDateEl.innerHTML = `Check-in month: <select name="month" id="month" required> <option value="">Select</option> <option value="January">January</option> <option value="February">February</option> <option value="March">March</option> <option value="April">April</option> <option value="May">May</option> <option value="June">June</option> <option value="July">July</option> <option value="August">August</option> <option value="September">September</option> <option value="October">October</option> <option value="November">November</option> <option value="December">December</option> </select>`; let searchFormStayingPeriodEl = document.createElement("label"); searchFormStayingPeriodEl.innerHTML = `Period of staying: <select name="staying-period" id="staying-period" required> <option value="">Select</option> <option value="1">1 month</option> <option value="2">2 months</option> <option value="3">3 months</option> <option value="4">4 months</option> <option value="5">5 months</option> <option value="6">6 months</option> <option value="7">7 months</option> <option value="8">8 months</option> <option value="9">9 months</option> <option value="10">10 months</option> <option value="11">11 months</option> <option value="12">12 months</option> </select>`; let searchFormStayingPeriod = searchFormStayingPeriodEl.querySelector<HTMLSelectElement>( "#staying-period" )!; let searchFormBtn = document.createElement("button"); searchFormBtn.type = "submit"; searchFormBtn.textContent = "SEARCH"; searchFormEl.append( searchFormTitleEl, searchFormLocationEl, searchFormDateEl, searchFormStayingPeriodEl, searchFormBtn ); searchOptionsBox.append(searchFormEl); let filterOptionsBox = document.createElement("div"); filterOptionsBox.className = "filter-options-box"; let filterOptionsTitleEl = document.createElement("h2"); filterOptionsTitleEl.textContent = "Filter by:"; let filterOptionsHrEl = document.createElement("hr"); let filterOptionsItemTitleEl = document.createElement("h3"); filterOptionsItemTitleEl.textContent = "Your Budget (per month)"; let filterBudgetBtnsEl = document.createElement("div"); filterBudgetBtnsEl.className = "filter-budget-btns"; let filterBudgetOption1El = document.createElement("label"); filterBudgetOption1El.htmlFor = "budgetChoice1"; filterBudgetOption1El.innerHTML = `<input type="radio" id="budgetChoice1" name="budget" value="150" /> €0 - €150`; let filterBudgetOption2El = document.createElement("label"); filterBudgetOption2El.htmlFor = "budgetChoice2"; filterBudgetOption2El.innerHTML = ` <input type="radio" id="budgetChoice2" name="budget" value="250" /> €150 - €250`; let filterBudgetOption3El = document.createElement("label"); filterBudgetOption3El.htmlFor = "budgetChoice3"; filterBudgetOption3El.innerHTML = `<input type="radio" id="budgetChoice3" name="budget" value="350" /> €250 - €350`; let filterBudgetOption4El = document.createElement("label"); filterBudgetOption4El.htmlFor = "budgetChoice4"; filterBudgetOption4El.innerHTML = `<input type="radio" id="budgetChoice4" name="budget" value="100000" checked /> Show all`; filterBudgetBtnsEl.append( filterBudgetOption1El, filterBudgetOption2El, filterBudgetOption3El, filterBudgetOption4El ); filterOptionsBox.append( filterOptionsTitleEl, filterOptionsHrEl, filterOptionsItemTitleEl, filterBudgetBtnsEl ); sidebarFilterSection.append(searchOptionsBox, filterOptionsBox); sidebarDivEl.append(sidebarFilterSection); let propertiesListSection = document.createElement("section"); propertiesListSection.className = "properties-list-section"; let propertiesListHeading = document.createElement("div"); propertiesListHeading.className = "properties-list-heading"; let propertiesListHeadingH2El = document.createElement("h2"); propertiesListHeadingH2El.textContent = `${state.locationSearch}: ${state.properties.length} properties found`; let propertiesListHeadingSortingEl = document.createElement("select"); propertiesListHeadingSortingEl.name = "sorting"; propertiesListHeadingSortingEl.id = "sorting"; propertiesListHeadingSortingEl.required = true; propertiesListHeadingSortingEl.innerHTML = `<option value="">Sort by: Default</option> <option value="price-incremental"> Sort by: Price(lowest first) </option> <option value="price-decremental"> Sort by: Price(highest first) </option> <option value="alphabetical">Sort by: Alphabetical Order</option>`; propertiesListHeading.append( propertiesListHeadingH2El, propertiesListHeadingSortingEl ); let propertiesListItems = document.createElement("div"); propertiesListItems.className = "properties-list-items"; console.log(state.properties); for (let property of state.properties) { let propertyItemCard = document.createElement("div"); propertyItemCard.className = "property-item-card"; let propertyItemCardImg = document.createElement("img"); propertyItemCardImg.src = property.image; propertyItemCardImg.alt = "property image"; let propertyItemCardInfo = document.createElement("div"); propertyItemCardInfo.className = "property-item-card__info"; let propertyItemUpperCardInfo = document.createElement("div"); propertyItemUpperCardInfo.className = "card__info__upper"; let propertyItemUpperCardInfoTitle = document.createElement("h3"); propertyItemUpperCardInfoTitle.textContent = property.propertyName; let propertyItemUpperCardInfoLocation = document.createElement("p"); propertyItemUpperCardInfoLocation.innerHTML = `<span>Location: </span> ${property.location}`; propertyItemUpperCardInfo.append( propertyItemUpperCardInfoTitle, propertyItemUpperCardInfoLocation ); let propertyItemBottomCardInfo = document.createElement("div"); propertyItemBottomCardInfo.className = "card__info__bottom"; let propertyItemBottomCardInfoPeriod = document.createElement("p"); propertyItemBottomCardInfoPeriod.className = "months-to-pay"; propertyItemBottomCardInfoPeriod.textContent = `${state.stayingPeriod} months`; let propertyItemBottomCardInfoPrice = document.createElement("p"); propertyItemBottomCardInfoPrice.textContent = `€${ property.price * Number(state.stayingPeriod) } Total`; let propertyItemBottomCardInfoBtn = document.createElement("button"); propertyItemBottomCardInfoBtn.textContent = "Make reservation >"; propertyItemBottomCardInfo.append( propertyItemBottomCardInfoPeriod, propertyItemBottomCardInfoPrice, propertyItemBottomCardInfoBtn ); propertyItemCardInfo.append( propertyItemUpperCardInfo, propertyItemBottomCardInfo ); propertyItemCard.append(propertyItemCardImg, propertyItemCardInfo); propertiesListItems.append(propertyItemCard); } propertiesListSection.append(propertiesListHeading, propertiesListItems); searchPageMainEl.append(sidebarDivEl, propertiesListSection); app.append(searchPageMainEl); } function renderSignModal() { let wrapperEl = document.createElement("div"); wrapperEl.className = "modal-wrapper"; let containerDiv = document.createElement("div"); containerDiv.className = "form-container"; containerDiv.id = "login"; let closeButton = document.createElement("button"); closeButton.textContent = "X"; closeButton.className = "modal-close-button"; closeButton.addEventListener("click", function () { state.modal = ""; render(); }); let titleEl = document.createElement("h2"); titleEl.className = "header-title"; titleEl.textContent = "Sign In"; let hrEl = document.createElement("hr"); let formEl = document.createElement("form"); formEl.addEventListener("submit", function (event) { event.preventDefault(); signIn({ email: inputEl.value, password: inputEl2.value }); }); let emailEl = document.createElement("div"); emailEl.id = "email"; emailEl.className = "form-group"; let labelEl = document.createElement("label"); labelEl.innerHTML = "email-input"; labelEl.textContent = "Enter Your Email"; let inputEl = document.createElement("input"); inputEl.id = "emai-input"; inputEl.className = "form-control"; inputEl.type = "text"; emailEl.append(labelEl, inputEl); let passEl = document.createElement("div"); passEl.id = "password"; passEl.className = "form-group"; let labelEl2 = document.createElement("label"); labelEl2.innerHTML = "password-input"; labelEl2.textContent = "Enter Your Password"; let inputEl2 = document.createElement("input"); inputEl2.id = "password-input"; inputEl2.className = "form-control"; inputEl2.type = "password"; passEl.append(labelEl2, inputEl2); let nextBtn = document.createElement("button"); nextBtn.id = "next-button"; nextBtn.classList.add("btn", "btn-primary"); nextBtn.textContent = "Next"; formEl.append(emailEl, passEl, nextBtn); containerDiv.append(closeButton, titleEl, hrEl, formEl); wrapperEl.append(containerDiv); app.append(wrapperEl); } function renderFooter() { let footerEl = document.createElement("footer"); footerEl.className = "footer"; let sidebarEl = document.createElement("aside"); sidebarEl.className = "footer__sidebar"; let sidebarDescEl = document.createElement("div"); sidebarDescEl.className = "footer__sidebar__text"; let sidebarTextPEl = document.createElement("h2"); sidebarTextPEl.textContent = "Looking.com"; let sidebarText1PEl = document.createElement("h3"); sidebarText1PEl.textContent = "In good hands with us!"; sidebarDescEl.append(sidebarTextPEl, sidebarText1PEl); let sidebarSocialsEl = document.createElement("div"); sidebarSocialsEl.className = "footer__sidebar__socials"; let sidebarText2PEl = document.createElement("h4"); sidebarText2PEl.textContent = "Stay connected"; sidebarSocialsEl.append(sidebarText2PEl); let socialsContainer = document.createElement("div"); socialsContainer.className = "socials-container"; let socialsLink1 = document.createElement("a"); socialsLink1.href = `https://www.facebook.com/`; socialsLink1.target = "_blank"; socialsLink1.innerHTML = `<img src="./src/assets/images/facebook-logo.png" alt="facebook logo" />`; let socialsLink2 = document.createElement("a"); socialsLink2.href = `https://www.instagram.com/`; socialsLink2.target = "_blank"; socialsLink2.innerHTML = `<img src="./src/assets/images/instagram-logo.png" alt="instagram logo" />`; let socialsLink3 = document.createElement("a"); socialsLink3.href = `https://www.twitter.com/`; socialsLink3.target = "_blank"; socialsLink3.innerHTML = `<img src="./src/assets/images/twitter-logo.png" alt="twitter logo" />`; let socialsLink4 = document.createElement("a"); socialsLink4.href = `https://www.youtube.com/`; socialsLink4.target = "_blank"; socialsLink4.innerHTML = `<img src="./src/assets/images/youtube-logo.png" alt="youtube logo" />`; socialsContainer.append( socialsLink1, socialsLink2, socialsLink3, socialsLink4 ); sidebarSocialsEl.append(sidebarText2PEl, socialsContainer); sidebarEl.append(sidebarDescEl, sidebarSocialsEl); let footerNavigationContainer = document.createElement("div"); footerNavigationContainer.className = "footer__navigation-container"; let footerNavMenuSection = document.createElement("div"); footerNavMenuSection.className = "footer__nav-menus-section"; let footerNavMenuDiv1 = document.createElement("div"); footerNavMenuDiv1.className = "footer__nav-menu"; let explore = document.createElement("h3"); explore.textContent = "Explore"; let footerNavMenu1 = document.createElement("nav"); let footerUl1 = document.createElement("ul"); let footerLink1 = document.createElement("a"); footerLink1.href = ""; footerLink1.innerHTML = "<li>Home</li>"; let footerLink2 = document.createElement("a"); footerLink2.href = ""; footerLink2.innerHTML = "<li>Services</li>"; footerUl1.append(footerLink1, footerLink2); footerNavMenu1.append(footerUl1); footerNavMenuDiv1.append(explore, footerNavMenu1); let footerNavMenuDiv2 = document.createElement("div"); footerNavMenuDiv2.className = "footer__nav-menu"; let aboutUs = document.createElement("h3"); aboutUs.textContent = "About Us"; let footerNavMenu2 = document.createElement("nav"); let footerUl2 = document.createElement("ul"); let footerLink3 = document.createElement("a"); footerLink3.href = ""; footerLink3.innerHTML = "<li>Careers</li>"; let footerLink4 = document.createElement("a"); footerLink4.href = ""; footerLink4.innerHTML = "<li>Company</li>"; footerUl2.append(footerLink3, footerLink4); footerNavMenu2.append(footerUl2); footerNavMenuDiv2.append(aboutUs, footerNavMenu2); let footerNavMenuDiv3 = document.createElement("div"); footerNavMenuDiv3.className = "footer__nav-menu"; let helpCenter = document.createElement("h3"); helpCenter.textContent = "Help Center"; let footerNavMenu3 = document.createElement("nav"); let footerUl3 = document.createElement("ul"); let footerLink5 = document.createElement("a"); footerLink5.href = ""; footerLink5.innerHTML = "<li>Support</li>"; let footerLink6 = document.createElement("a"); footerLink6.href = ""; footerLink6.innerHTML = "<li>Contact Us</li>"; footerUl3.append(footerLink5, footerLink6); footerNavMenu3.append(footerUl3); footerNavMenuDiv3.append(helpCenter, footerNavMenu3); footerNavMenuSection.append( footerNavMenuDiv1, footerNavMenuDiv2, footerNavMenuDiv3 ); let footerBottomNotesDiv = document.createElement("div"); footerBottomNotesDiv.className = "footer__bottom-notes"; let legalNotesNav = document.createElement("nav"); legalNotesNav.className = "legal-notes"; let legalNotesUl = document.createElement("ul"); legalNotesUl.className = "legal-notes__items"; let legalNoteAEl1 = document.createElement("a"); legalNoteAEl1.href = ""; legalNoteAEl1.innerHTML = "<li>Terms of Use</li>"; let legalNoteAEl2 = document.createElement("a"); legalNoteAEl2.href = ""; legalNoteAEl2.innerHTML = "<li>Privacy</li>"; let legalNoteAEl3 = document.createElement("a"); legalNoteAEl3.href = ""; legalNoteAEl3.innerHTML = "<li>Cookies</li>"; let legalNoteAEl4 = document.createElement("a"); legalNoteAEl4.href = ""; legalNoteAEl4.innerHTML = "<li>Refund Policy</li>"; let legalNoteAEl5 = document.createElement("a"); legalNoteAEl5.href = ""; legalNoteAEl5.innerHTML = "<li>FAQ</li>"; let copyrightPEl = document.createElement("p"); copyrightPEl.textContent = "© 2022 Looking.com LLC. All rights reserved."; legalNotesUl.append( legalNoteAEl1, legalNoteAEl2, legalNoteAEl3, legalNoteAEl4, legalNoteAEl5 ); legalNotesNav.append(legalNotesUl); footerBottomNotesDiv.append(legalNotesNav, copyrightPEl); footerNavigationContainer.append(footerNavMenuSection, footerBottomNotesDiv); footerEl.append(sidebarEl, footerNavigationContainer); app.append(footerEl); } function render() { if (app === null) return; app.textContent = ""; renderHeader(); if (state.page === "home") renderMainPage(); if (state.page === "search") renderSearchPage(); if (state.page === "signUp") renderSignUpPage(); if (state.modal === "signIn") renderSignModal(); renderFooter(); } render();
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { of } from 'rxjs'; import { CartService } from 'src/app/services/cart.service'; import { sample_cart } from 'src/data'; import { CartComponent } from './cart.component'; describe('CartComponent', () => { let component: CartComponent; let fixture: ComponentFixture<CartComponent>; beforeEach(async () => { const cartServiceSpy = jasmine.createSpyObj<CartService>(['getCartObservable']); cartServiceSpy.getCartObservable.and.returnValue(of(sample_cart)); await TestBed.configureTestingModule({ declarations: [ CartComponent ], providers: [{provide: CartService, useValue: cartServiceSpy}], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(CartComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create component', () => { expect(component).toBeTruthy(); }); it('should have items in the cart', () => { expect(component.cart.items.length).toBe(1); }); it('should display image', () => { let img = fixture.debugElement.queryAll(By.css('img')) expect(img.length).toBe(1); }); });
import { ComponentFixture, TestBed } from "@angular/core/testing"; import { MatDialogRef } from '@angular/material/dialog'; import { MatDialogMock } from "src/test/mock/components/mat-dialog.mock"; import { ProjectServiceMock } from "src/test/mock/services/project-service.mock"; import { SnackBarServiceMock } from "src/test/mock/services/snack-bar-service.mock"; import { AddProjectComponent } from "./add-project.component"; import { of, throwError } from 'rxjs'; import { LicenseServiceMock } from "src/test/mock/services/license-service.mock"; import moment from "moment"; import { TestBedConfigBuilder } from '../../../../../test/mock/TestBedConfigHelper.mock'; let addPorjectComponentTestInstance: AddProjectComponent; let fixture: ComponentFixture<AddProjectComponent>; const beforeEachFunction = () => { const configBuilder = new TestBedConfigBuilder().useDefaultConfig(AddProjectComponent); configBuilder.addDeclaration(AddProjectComponent); TestBed.configureTestingModule(configBuilder.getConfig()); fixture = TestBed.createComponent(AddProjectComponent); addPorjectComponentTestInstance = fixture.componentInstance; }; describe('UI verification for add project component', () => { beforeEach(beforeEachFunction); it('should display essential UI components', () => { fixture.detectChanges(); const h1 = fixture.nativeElement.querySelector('#page-title'); const startDate = fixture.nativeElement.querySelector('#start-date-lable'); const submitButton = fixture.nativeElement.querySelector('#submit-project-button'); const projectNameLabel = fixture.nativeElement.querySelector('#project-name-label'); const projectCodeLabel = fixture.nativeElement.querySelector('#project-code-label'); const projectLicenseLabel = fixture.nativeElement.querySelector('#project-license-label'); const cancelButton = fixture.nativeElement.querySelector('#cancel-button'); expect(h1.textContent).toBe('Add Project'); expect(startDate.textContent).toBe('Start Date'); expect(projectNameLabel.textContent).toBe('Project Name'); expect(projectCodeLabel.textContent).toBe('Project Code'); expect(projectLicenseLabel.textContent).toBe('TekVizion 360 Subscription'); expect(cancelButton.textContent).toBe('Cancel'); expect(submitButton.disabled).toBeTrue(); }); }); describe('add projects interactions', () => { beforeEach(beforeEachFunction); it('should call submit', () => { fixture.detectChanges(); spyOn(addPorjectComponentTestInstance,'submit').and.callThrough(); spyOn(addPorjectComponentTestInstance, 'onCancel').and.callThrough(); addPorjectComponentTestInstance.submit(); expect(addPorjectComponentTestInstance.submit).toHaveBeenCalled(); addPorjectComponentTestInstance.onCancel(); expect(addPorjectComponentTestInstance.onCancel).toHaveBeenCalled(); }); it('should enable the submit button on not empty parameters', () => { const addProjectForm = addPorjectComponentTestInstance.addProjectForm; addProjectForm.setValue({ projectName: {test: 'test'}, projectNumber: { test: 'test' }, openDate: moment('16-08-2022', 'DDMMYYYY'), licenseId: { test:'test' } }); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('#submit-project-button').disabled).toBeFalse(); }); it('should disable the submit button with an empty parameter', () => { const addProjectForm = addPorjectComponentTestInstance.addProjectForm; addProjectForm.setValue({ projectName: '', projectNumber: { test: 'test' }, openDate: moment('16-08-2022', 'DDMMYYYY'), licenseId: { test: 'test' } }); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('#submit-project-button').disabled).toBeTrue(); }); it('should reset the Start Date and its limist when calling onLicenseChange()',()=>{ spyOn(addPorjectComponentTestInstance,'onLicenseChange').and.callThrough(); const license = LicenseServiceMock.mockLicenseA; addPorjectComponentTestInstance.licenses = JSON.parse(JSON.stringify(LicenseServiceMock.licensesList.licenses)); addPorjectComponentTestInstance.onLicenseChange(license.id); expect(addPorjectComponentTestInstance.addProjectForm.get('openDate').value).toBe(''); expect(addPorjectComponentTestInstance.addProjectForm.get('openDate').enabled).toBeTrue(); expect(addPorjectComponentTestInstance.minDate).toEqual(new Date(license.startDate + " 00:00:00")); expect(addPorjectComponentTestInstance.maxDate).toEqual(new Date(license.renewalDate + " 00:00:00")); }); }); describe('Dialog calls and interactions', () => { beforeEach(beforeEachFunction); it('should show a message if an error ocurred while a submit failed', () => { const response = {error:"some error message"}; spyOn(ProjectServiceMock, 'createProject').and.returnValue(of(response)); spyOn(SnackBarServiceMock,'openSnackBar').and.callThrough(); fixture.detectChanges(); addPorjectComponentTestInstance.submit(); expect(ProjectServiceMock.createProject).toHaveBeenCalled(); expect(SnackBarServiceMock.openSnackBar).toHaveBeenCalledWith(response.error, 'Error adding project!'); }); it('should show a message if an error was thrown while adding a project after calling submit()', () => { const err = { error:"some error"}; spyOn(ProjectServiceMock, 'createProject').and.returnValue(throwError(err)); spyOn(SnackBarServiceMock,'openSnackBar').and.callThrough(); spyOn(console, 'error').and.callThrough(); fixture.detectChanges(); addPorjectComponentTestInstance.submit(); expect(ProjectServiceMock.createProject).toHaveBeenCalled(); expect(SnackBarServiceMock.openSnackBar).toHaveBeenCalledWith(err.error, 'Error adding project!'); expect(console.error).toHaveBeenCalledWith('error adding a new project', err); expect(addPorjectComponentTestInstance.isDataLoading).toBeFalse(); }); it('should show a message if an error ocurred while loading data ngOnInit()', () => { const err = {error: 'some error'}; spyOn(LicenseServiceMock, 'getLicenseList').and.returnValue(throwError(err)); spyOn(SnackBarServiceMock, 'openSnackBar').and.callThrough(); spyOn(console, 'error').and.callThrough() fixture.detectChanges(); expect(LicenseServiceMock.getLicenseList).toHaveBeenCalled(); expect(SnackBarServiceMock.openSnackBar).toHaveBeenCalledWith(err.error, 'Error requesting subscriptions!'); expect(console.error).toHaveBeenCalledWith('error fetching subscriptions', err); expect(addPorjectComponentTestInstance.isDataLoading).toBeFalse(); }); }); describe('obtaining the data od licenses from ngOnInit()', () => { beforeEach(beforeEachFunction); it('should obtain the list of licenses', () => { fixture.detectChanges(); const res = { error: false, licenses: [{subaccountId: 'ac7a78c2-d0b2-4c81-9538-321562d426c7', id: '16f4f014-5bed-4166-b10a-808b2e6655e3', description: 'DescriptionA', status: 'Active', deviceLimit: '', tokensPurchased: 150, startDate: '2022-08-01', renewalDate: '2022-09-30', subscriptionType: '' }] }; spyOn(LicenseServiceMock, 'getLicenseList').and.returnValue(of(res)) addPorjectComponentTestInstance.ngOnInit(); expect(LicenseServiceMock.getLicenseList).toHaveBeenCalled(); }); }); describe('add-project - FormGroup verification test', () => { beforeEach(beforeEachFunction); it('should create a formGroup with necessary controls', () => { fixture.detectChanges(); expect(addPorjectComponentTestInstance.addProjectForm.get('projectName')).toBeTruthy(); expect(addPorjectComponentTestInstance.addProjectForm.get('projectNumber')).toBeTruthy(); expect(addPorjectComponentTestInstance.addProjectForm.get('openDate')).toBeTruthy(); expect(addPorjectComponentTestInstance.addProjectForm.get('licenseId')).toBeTruthy(); }); it('should make all the controls required', () => { const addProjectForm = addPorjectComponentTestInstance.addProjectForm; addProjectForm.setValue({ projectName: '', projectNumber: '', openDate: '', licenseId: '' }); expect(addProjectForm.get('projectName').valid).toBeFalse(); expect(addProjectForm.get('projectNumber').valid).toBeFalse(); expect(addProjectForm.get('openDate').valid).toBeFalse(); expect(addProjectForm.get('licenseId').valid).toBeFalse(); }); });
import {ModerationCause, ProfileModeration, PostModeration} from '@atproto/api' export interface ModerationCauseDescription { name: string description: string } export function describeModerationCause( cause: ModerationCause | undefined, context: 'account' | 'content', ): ModerationCauseDescription { if (!cause) { return { name: 'Content Warning', description: 'Moderator has chosen to set a general warning on the content.', } } if (cause.type === 'blocking') { if (cause.source.type === 'list') { return { name: `User Blocked by "${cause.source.list.name}"`, description: 'You have blocked this user. You cannot view their content.', } } else { return { name: 'User Blocked', description: 'You have blocked this user. You cannot view their content.', } } } if (cause.type === 'blocked-by') { return { name: 'User Blocking You', description: 'This user has blocked you. You cannot view their content.', } } if (cause.type === 'block-other') { return { name: 'Content Not Available', description: 'This content is not available because one of the users involved has blocked the other.', } } if (cause.type === 'muted') { if (cause.source.type === 'list') { return { name: context === 'account' ? `Muted by "${cause.source.list.name}"` : `Post by muted user ("${cause.source.list.name}")`, description: 'You have muted this user', } } else { return { name: context === 'account' ? 'Muted User' : 'Post by muted user', description: 'You have muted this user', } } } // @ts-ignore Temporary extension to the moderation system -prf if (cause.type === 'post-hidden') { return { name: 'Post Hidden by You', description: 'You have hidden this post', } } return cause.labelDef.strings[context].en } export function getProfileModerationCauses( moderation: ProfileModeration, ): ModerationCause[] { /* Gather everything on profile and account that blurs or alerts */ return [ moderation.decisions.profile.cause, ...moderation.decisions.profile.additionalCauses, moderation.decisions.account.cause, ...moderation.decisions.account.additionalCauses, ].filter(cause => { if (!cause) { return false } if (cause?.type === 'label') { if ( cause.labelDef.onwarn === 'blur' || cause.labelDef.onwarn === 'alert' ) { return true } else { return false } } return true }) as ModerationCause[] } export function isPostMediaBlurred( decisions: PostModeration['decisions'], ): boolean { return decisions.post.blurMedia } export function isQuoteBlurred( decisions: PostModeration['decisions'], ): boolean { return ( decisions.quote?.blur || decisions.quote?.blurMedia || decisions.quote?.filter || decisions.quotedAccount?.blur || decisions.quotedAccount?.filter || false ) } export function isCauseALabelOnUri( cause: ModerationCause | undefined, uri: string, ): boolean { if (cause?.type !== 'label') { return false } return cause.label.uri === uri } export function getModerationCauseKey(cause: ModerationCause): string { const source = cause.source.type === 'labeler' ? cause.source.labeler.did : cause.source.type === 'list' ? cause.source.list.uri : 'user' if (cause.type === 'label') { return `label:${cause.label.val}:${source}` } return `${cause.type}:${source}` }
/* Taks are scheduler scripts that are run inside Snowflake environment. In simple words, a task is a scheduler that can help you to schedule a single sql or a stored procedure. A task can be very useful when combined with Streams to make an end-to-end data pipeline. -- Snowflake ensures only one instance of a task with a schedule is executed at a given time. -- If the task is still sunning when the next scheduled execution time occurs then that scheduled time is skipped. -- Tasks have a max duration of 60 minutes by default. -- Tasks run on a schedule which is defined at the time a task is created. Alternatively, you can establish task dependencies whereby a task can be triggered by a predecessor task. */ // We won't practice on task tree and stored procedure here. USE ROLE SYSADMIN; USE WAREHOUSE PRACTICE_TEST1; USE DATABASE DEMO_DB; USE SCHEMA BANKING; // Example 1 -- Let's create a table called customer_dim -- CREATE OR REPLACE TABLE CUSTOMER_DIM( ID NUMBER, FIRST_NAME VARCHAR, LAST_NAME VARCHAR, DATE_OF_BIRTH DATE, ACTIVE_FLAG BOOLEAN, CITY VARCHAR, INSERT_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) COMMENT = 'CUSTOMER DIMENSION TABLE'; ; SELECT * FROM CUSTOMER_DIM; -- Let's create a sequence object -- // Sequences are used to generate unique numbers across sessions and statements, including concurrent statements. // They can be used to generate values for a primary key or any column that requires a unique value. CREATE OR REPLACE SEQUENCE CUSTOMER_SEQ START 2 INCREMENT 2 COMMENT = 'DEMO SEQUENCE FOR CUSTOMER DIMENSION TABLE'; // Sequences may be accessed in queries as expressions of the form seq_name.NEXTVAL. SELECT CUSTOMER_SEQ.NEXTVAL; // CREATE statements for each task type, that tasks is scheduled CREATE OR REPLACE TASK TASK01 WAREHOUSE = 'PRACTICE_TEST1' SCHEDULE = '1 minute' AS INSERT INTO CUSTOMER_DIM(ID, FIRST_NAME, LAST_NAME, DATE_OF_BIRTH, ACTIVE_FLAG, CITY) VALUES (CUSTOMER_SEQ.nextval, 'F-NAME', 'L-NAME', CURRENT_DATE(), TRUE, 'MY-CITY'); -- Assign to any role for execute task -- // This role can alter the task to resume or suspend USE ROLE ACCOUNTADMIN; GRANT EXECUTE TASK, EXECUTE MANAGED TASK ON ACCOUNT TO ROLE SYSADMIN; -- If you want to check the status of any created Task -- DESCRIBE TASK TASK01; SHOW TASKS; // Example 2 USE ROLE SYSADMIN; USE WAREHOUSE PRACTICE_TEST1; USE DATABASE DEMO_DB; USE SCHEMA BANKING; CREATE OR REPLACE TABLE DEMO_DB.BANKING.PRODUCT ( PROD_ID INT, PROD_DESC VARCHAR(), CATEGORY VARCHAR(30), SEGMENT VARCHAR(20), MFG_ID INT, MFG_NAME VARCHAR(50) ); INSERT INTO DEMO_DB.BANKING.PRODUCT VALUES (1201, 'PROD 1201', 'CATE 1201', 'SEG 1201', 1201, 'MFG 1201'); INSERT INTO DEMO_DB.BANKING.PRODUCT VALUES (1202, 'PROD 1202', 'CATE 1202', 'SEG 1202', 1201, 'MFG 1202'); INSERT INTO DEMO_DB.BANKING.PRODUCT VALUES (1203, 'PROD 1203', 'CATE 1203', 'SEG 1203', 1203, 'MFG 1203'); INSERT INTO DEMO_DB.BANKING.PRODUCT VALUES (1204, 'PROD 1204', 'CATE 1204', 'SEG 1204', 1204, 'MFG 1204'); INSERT INTO DEMO_DB.BANKING.PRODUCT VALUES (1205, 'PROD 1205', 'CATE 1205', 'SEG 1205', 1205, 'MFG 1205'); INSERT INTO DEMO_DB.BANKING.PRODUCT VALUES (1206, 'PROD 1206', 'CATE 1206', 'SEG 1206', 1206, 'MFG 1206'); // Next, we’ll create a sales table and then a stream on the sales table: CREATE OR REPLACE TABLE PRODUCT_SALES( PROD_ID INT, CUSTOMER VARCHAR(), ZIP VARCHAR(), QTY INT, REVENUE DECIMAL(10, 2) ); // We’ll want our table stream to record insert-only values on the sales table: CREATE OR REPLACE STREAM DEMO_DB.BANKING.PRODUCT_SALES_STREAM ON TABLE DEMO_DB.BANKING.PRODUCT_SALES APPEND_ONLY = TRUE; // let's insert the values in Sales table: INSERT INTO PRODUCT_SALES VALUES ( 1201, 'CUST 1201', 123456, 45, 2345.25); INSERT INTO PRODUCT_SALES VALUES ( 1202, 'CUST 1202', 123457, 4, 45.78); INSERT INTO PRODUCT_SALES VALUES ( 1203, 'CUST 1203', 133457, 5, 478.00); INSERT INTO PRODUCT_SALES VALUES ( 1204, 'CUST 1204', 133400, 89, 11478.70); INSERT INTO PRODUCT_SALES VALUES ( 1204, 'CUST 1204', 133400, 89, 11478.70); INSERT INTO PRODUCT_SALES VALUES ( 1205, 'CUST 1205', 189799, 9, 1899.70); // we’ll be able to see that the values we entered into the sales table were then captured in the SALES_STREAM: SELECT * FROM DEMO_DB.BANKING.PRODUCT_SALES_STREAM; /* it’s time to create our sales transaction table which combines the SALES_STREAM with the product table and adds a timestamp so that we can know when the sales data was recorded: */ CREATE OR REPLACE TABLE DEMO_DB.BANKING.PRODUCT_SALES_TRANSACT ( PROD_ID INT, PROD_DESC VARCHAR(), CATEGORY VARCHAR(30), SEGMENT VARCHAR(20), MFG_ID INT, MFG_NAME VARCHAR(50), CUSTOMER VARCHAR(), ZIP VARCHAR(), QTY INT, REVENUE DECIMAL(10, 2), TS TIMESTAMP ); /* We’ll eventually want to automate the creation of the sales transaction table, but first we need to see what happens when we manually insert data. If things work as expected, we’ll proceed to creating a task for the insertion: */ INSERT INTO DEMO_DB.BANKING.PRODUCT_SALES_TRANSACT(PROD_ID, PROD_DESC, CATEGORY, SEGMENT, MFG_ID, MFG_NAME, CUSTOMER, ZIP, QTY, REVENUE, TS) SELECT S.PROD_ID, P.PROD_DESC, P.CATEGORY, P.SEGMENT, P.MFG_ID, P.MFG_NAME, S.CUSTOMER, S.ZIP, S.QTY, S.REVENUE, CURRENT_TIMESTAMP FROM PRODUCT_SALES_STREAM S JOIN PRODUCT P ON S.PROD_ID = P.PROD_ID; SELECT * FROM PRODUCT_SALES_TRANSACT; // Now it’s time to automate the insertion by creating a task: CREATE OR REPLACE TASK DEMO_DB.BANKING.PRODUCT_SALES_TASK WAREHOUSE = PRACTICE_TEST1 SCHEDULE = '1 MINUTE' WHEN SYSTEM$STREAM_HAS_DATA('DEMO_DB.BANKING.PRODUCT_SALES_STREAM') AS INSERT INTO DEMO_DB.BANKING.PRODUCT_SALES_TRANSACT(PROD_ID, PROD_DESC, CATEGORY, SEGMENT, MFG_ID, MFG_NAME, CUSTOMER, ZIP, QTY, REVENUE, TS) SELECT S.PROD_ID, P.PROD_DESC, P.CATEGORY, P.SEGMENT, P.MFG_ID, P.MFG_NAME, S.CUSTOMER, S.ZIP, S.QTY, S.REVENUE, CURRENT_TIMESTAMP FROM PRODUCT_SALES_STREAM S JOIN PRODUCT P ON S.PROD_ID = P.PROD_ID; DESC TASK DEMO_DB.BANKING.PRODUCT_SALES_TASK; ALTER TASK DEMO_DB.BANKING.PRODUCT_SALES_TASK RESUME; /* Now let’s see what happens when we insert values into the sales table. Once we insert values into the sales table, the SALES_STREAM should reflect the newly inserted records. Then the task should insert the new sales records after joining with the product table and generating a timestamp. */ INSERT INTO DEMO_DB.BANKING.PRODUCT_SALES VALUES ( 1201, 'CUST 1201A', 123456, 45, 2345.25); INSERT INTO PRODUCT_SALES VALUES ( 1202, 'CUST 1202A', 123457, 4, 45.78); INSERT INTO PRODUCT_SALES VALUES ( 1203, 'CUST 1203A', 133457, 5, 478.00); INSERT INTO PRODUCT_SALES VALUES ( 1204, 'CUST 1204A', 133400, 89, 11478.70); INSERT INTO PRODUCT_SALES VALUES ( 1204, 'CUST 1204A', 133400, 89, 11478.70); INSERT INTO PRODUCT_SALES VALUES ( 1205, 'CUST 1205A', 189799, 9, 1899.70); SELECT * FROM DEMO_DB.BANKING.PRODUCT_SALES_STREAM; SELECT * FROM DEMO_DB.BANKING.PRODUCT_SALES_TRANSACT; ALTER TASK DEMO_DB.BANKING.PRODUCT_SALES_TASK SUSPEND;
import React, { Component } from "react"; import { Row, Col, Card, CardBody, Container } from "reactstrap"; import { FaEdit,FaTimes,FaTimesCircle } from 'react-icons/fa'; import { withRouter } from "react-router-dom"; import Breadcrumbs from '../../components/Common/Breadcrumb'; import BootstrapTable from 'react-bootstrap-table-next'; import paginationFactory from 'react-bootstrap-table2-paginator'; import 'react-bootstrap-table2-paginator/dist/react-bootstrap-table2-paginator.min.css'; import { CSVLink } from 'react-csv'; import * as XLSX from 'xlsx'; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; class Appointments extends Component { constructor(props) { super(props); this.state = { breadcrumbItems: [ { title: "Tables", link: "#" }, { title: "Responsive Table", link: "#" }, ], data: null, loading: true, error: null, currentPage: 1, appointmentsPerPage: 10, exportData: [], exportDropdownOpen: false, client_id:"", sortOrder: 'asc', // Initial sorting order sortField: 'appointment_id', // Initial sorting field sortDirection: 'asc', // Initial sorting direction sortedColumn: 'appointment_id', // Initial sorted column searchQuery: "", // State for search query access_token:"", }; } componentDidMount() { const access = JSON.parse(localStorage.getItem('access_token')); const id = JSON.parse(localStorage.getItem('client_id')); if (access) { this.setState({ access_token: access }); console.log("hello" + this.state.access_token); this.setState({ client_id: id }, () => { this.getAppointments(); }); } } getAppointments = async () => { const acces = this.state.access_token; try { const { client_id,access_token, } = this.state; const response = await fetch(`http://194.163.40.231:8080/Appointment/All/`, { method: "POST", headers: { "Content-Type": "application/json", // Set the content type to JSON 'Authorization': `Bearer ${access_token}`, }, body: JSON.stringify({client_id}), }); if (!response.ok) { throw new Error("Network response was not ok."); } const data = await response.json(); console.log("Response data:", data); this.setState({ data, loading: false }); } catch (error) { this.setState({ error: 'Error fetching data', loading: false }); } }; handleEdit = (appointment) => { this.props.history.push(`/edit-appointment/${appointment.appointment_id}`, { appointment }); }; handleCancelAppointment = async (appointment_id) => { const { client_id,access_token, } = this.state; const confirmDelete = window.confirm("Cancel this appointment?\nYou won't be able to revert this!"); if (confirmDelete) { try { const response = await fetch(`http://194.163.40.231:8080/Appointment/cancelled/`, { method: "PUT", headers: { "Content-Type": "application/json",'Authorization': `Bearer ${access_token}`, }, body: JSON.stringify({appointment_id,client_id,}), }); if (!response.ok) { throw new Error("Cancellation failed"); } this.getAppointments(); alert("The appointment has been cancelled."); } catch (error) { console.error('Cancelled failed:', error); alert("Cancelled failed"); } } }; handlePageChange = (newPage) => { this.setState({ currentPage: newPage, }); }; prepareExportData = () => { const { data } = this.state; const exportData = data.map((appointment) => ({ 'Appointment ID': appointment.appointment_id, 'Patient ID': appointment.patient_id, 'Patient Name': `${appointment.patient__first_name} ${appointment.patient__last_name}`, 'Doctor ID': appointment.doctor_id, 'Doctor Name': `${appointment.doctor__first_name} ${appointment.doctor__last_name}`, 'Date': appointment.appointment_date, 'Start Time': appointment.start_time, 'End Time': appointment.end_time, 'Status': appointment.status, })); return exportData; }; handleCSVExport = () => { const exportData = this.prepareExportData(); this.setState({ exportData }, () => { this.csvLink.link.click(); }); }; handleExcelExport = () => { const exportData = this.prepareExportData(); const ws = XLSX.utils.json_to_sheet(exportData); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, 'Appointments'); XLSX.writeFile(wb, 'appointments.xlsx'); }; toggleExportDropdown = () => { this.setState((prevState) => ({ exportDropdownOpen: !prevState.exportDropdownOpen, })); }; renderPagination = () => { const { data, currentPage, appointmentsPerPage } = this.state; const totalPages = Math.ceil(data.length / appointmentsPerPage); if (totalPages <= 1) { return null; } const paginationItems = []; for (let i = 1; i <= totalPages; i++) { paginationItems.push( <li key={i} className={`page-item${currentPage === i ? ' active' : ''}`}> <a className="page-link" href="#" onClick={() => this.handlePageChange(i)}> {i} </a> </li> ); } return ( <ul className="pagination justify-content-center"> {paginationItems} </ul> ); }; render() { const { data, loading, error, currentPage, appointmentsPerPage } = this.state; if (loading) { return <div>Loading...</div>; } if (error) { return <div>{error}</div>; } const indexOfLastAppointments = currentPage * appointmentsPerPage; const indexOfFirstAppointments = indexOfLastAppointments - appointmentsPerPage; const currentAppointments = data?.slice(indexOfFirstAppointments, indexOfLastAppointments); const columns = [ { dataField: 'appointment_id', text: 'A.P ID', sort: true }, { dataField: 'patient_id', text: 'Patient ID', sort: true }, { dataField: 'patient__first_name', text: 'Patient Name', formatter: (cell, row) => `${cell} ${row.patient__last_name}` }, { dataField: 'doctor_id', text: 'Doctor ID', sort: true }, { dataField: 'doctor__first_name', text: 'Doctor Name', formatter: (cell, row) => `${cell} ${row.doctor__last_name}` }, { dataField: 'appointment_date', text: 'Date', sort: true }, { dataField: 'start_time', text: 'Start Time', sort: true }, { dataField: 'end_time', text: 'End Time', sort: true }, { dataField: 'status', text: 'Status', sort: true }, { dataField: 'actions', text: 'Actions', formatter: (cell, row) => ( <> <FaEdit style={{ color: "purple" }} className="cursor-pointer" onClick={() => this.handleEdit(row)} data-toggle="tooltip" // Enable Bootstrap tooltip title="Edit" // Set the tooltip text /> <FaTimes style={{ color: "red" }} className="cursor-pointer mx-2" onClick={() => this.handleCancelAppointment(row.appointment_id)} data-toggle="tooltip" // Enable Bootstrap tooltip title="Cancel" // Set the tooltip text /> </> ), }, ]; return ( <React.Fragment> <div className="page-content"> <Container fluid> <Breadcrumbs title="Appointments" breadcrumbItems={this.state.breadcrumbItems} /> <Row> <Col xs={12}> <Card> <CardBody> <div className="d-flex justify-content-between align-items-center mb-3"> <Dropdown isOpen={this.state.exportDropdownOpen} toggle={this.toggleExportDropdown}> <DropdownToggle caret> Export </DropdownToggle> <DropdownMenu> <DropdownItem onClick={this.handleCSVExport}>Export as CSV</DropdownItem> <DropdownItem onClick={this.handleExcelExport}>Export as Excel</DropdownItem> </DropdownMenu> </Dropdown> </div> <div className="table-responsive"> <BootstrapTable keyField="appointment_id" data={currentAppointments} columns={columns} pagination={paginationFactory()} /> </div> {this.renderPagination()} </CardBody> </Card> </Col> </Row> </Container> </div> <CSVLink data={this.state.exportData} filename={"appointments.csv"} className="hidden" ref={(r) => (this.csvLink = r)} target="_blank" /> </React.Fragment> ); } } export default withRouter(Appointments);
import { useQuery } from "@tanstack/react-query"; import { Issue } from "../interfaces"; import { githubApi } from "../api/githubApis"; export const getIssueInfo = async (issueNumber: number): Promise<Issue> => { const { data } = await githubApi.get<Issue>(`/issues/${issueNumber}`); return data; } export const getIssueComments = async (issueNumber: number): Promise<Issue[]> => { const { data } = await githubApi.get(`/issues/${issueNumber}/comments`); return data; }; export const useIssue = (issueNumber: number) => { const issueQuery = useQuery({ queryKey: ["issue", issueNumber], queryFn: () => getIssueInfo(issueNumber) }); const issueCommentsQuery = useQuery({ queryKey: ["issue", issueNumber, 'comments'], queryFn: () => getIssueComments(issueNumber), enabled: (issueQuery.data?.comments ?? 0) > 0 }); return { issueQuery, issueCommentsQuery }; };
(in-package :weblocks) (export 'string-widget) (defwidget string-widget () ((content :type string :accessor string-widget-content :initarg :content) (escape-p :type boolean :accessor string-widget-escape-p :initarg :escape-p :initform t :documentation "Whether to escape the output for HTML."))) (defmethod render-widget-body ((widget string-widget) &rest args &key id class &allow-other-keys) (declare (ignore args)) (let ((content (if (string-widget-escape-p widget) (escape-string (string-widget-content widget)) (string-widget-content widget)))) (with-html (:p :id id :class class (str content))))) (defmethod make-widget ((obj string)) "Create a widget from a string." (make-instance 'string-widget :content obj))
<?php namespace App; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Log; use LaravelFCM\Facades\FCM; use LaravelFCM\Message\PayloadDataBuilder; use LaravelFCM\Message\PayloadNotificationBuilder; use LaravelFCM\Message\Topics; class Announcement extends Model { use SoftDeletes; protected static function boot() { parent::boot(); static::addGlobalScope('order', function (Builder $builder) { $builder->orderBy('id', 'desc'); }); static::created(function ($announcement) { if ($announcement->send_notification) { $notificationBuilder = new PayloadNotificationBuilder($announcement->organization->name . ': ' . $announcement->title); $notificationBuilder->setBody($announcement->details) ->setSound('default'); $notification = $notificationBuilder->build(); $topic = new Topics(); $topic->topic('organization_' . $announcement->organization_id); $dataBuilder = new PayloadDataBuilder(); $dataBuilder->addData([ 'organization_id' => $announcement->organization_id, 'type' => 'Announcements', 'id' => $announcement->id, ]); $data = $dataBuilder->build(); $topicResponse = FCM::sendToTopic($topic, null, $notification, $data); $topicResponse->isSuccess(); $topicResponse->shouldRetry(); $topicResponse->error(); } }); } /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'organization_id', 'title', 'details', 'url', 'image', 'send_notification' ]; /** * The number of models to return for pagination. * * @var int */ protected $perPage = 10; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'integer', 'organization_id' => 'integer', 'send_notification' => 'boolean' ]; public function organization() { return $this->belongsTo(\App\Organization::class); } public function scopeFilter($query, array $filters) { $query->when($filters['search'] ?? null, function ($query, $search) { $query->where(function ($query) use ($search) { $query->where('title', 'like', '%' . $search . '%') ->orWhere('details', 'like', '%' . $search . '%'); }); }); } }
nplots, reftel, IF_index, npage General visibility plotting and editing command. PARAMETERS ---------- nplots - (Optional) Default=0 (All baselines to each station). The number of baselines to be displayed per page. This may be changed interactively. Since only the baselines of one station are displayed on one page, the maximum number of plots per page at a given time is 1 less than the number of stations in the sub-array being displayed. reftel - (Optional) Default="" A baseline specification or the form [sub-array-index:][antenna_name_1][ antenna_name_2] On interactive devices this specifies which baseline should be plotted first. On non-interactive devices it specifies the range of baselines to be plotted. For instance on a non-interactive device "1:" means plot all baselines of sub-array 1, whereas on an interactive device, it means, start plotting baselines for the first available antenna of sub-array 1. For further details of baseline specifications, read the antenna_names help topic. IF_index - (Optional) Default = The first sampled IF. The index of the IF to start plotting visibilities from. npage - (Optional) Default = 0 (with requests no page limit). The maximum number of pages to plot when plotting to a non-interactive device. CONFIGURATION VARIABLES ----------------------- vflags - This is a string variable that over-rides the default display attributes. It is particularly useful when displaying to a hard-copy device, where interactive changes to the default attributes can not be made. By default vflags="". In this case vplot substitutes the equivalent of vflags="efmb3". When vflags is not "", all toggled attributes are initially set to off, and the contents of the vflags string determine which of the attributes get turned back on. The entries in the vflags string are the keys used in interactive mode to toggle the respective attributes on and off, and are interpretted exactly as though you had pressed them interactively. This means that if an option appears twice in vflags the second instance cancels the first! The available keys are listed further below. For example after typing: vflags="efm1" Subsequent use of vplot after typing this will initially plot visibilities with error-bars (e), will show flagged-data (f), will show the model (m), and only display amplitudes (1). CONTEXT ------- This command can be used in non-interactive mode to display visibility data on a hard-copy device, or interactively to examine and/or edit visibilities. When displayed, flagged data appear as red '+' symbols, un-flagged data as green points and the model as a continuous light-blue line. In addition, if a visibility is flagged by a selfcal correction flag, but not by a normal visibility flag, it is displayed as a blue 'x' symbol. Only visibilities from a single IF are displayed at one time, but the selected IF can be changed interactively, or preset on the command line. HARD COPY MODE -------------- If this command is invoked when the PGPLOT output device is a hard-copy device, such as a laser printer, one can specify which baselines to plot and how to arrange them. This is illustrated in the following examples: 1. Plot all of the baselines in the observation, grouped by telescope name and sub-array, displaying 5 baselines per page. This could take some time so be prepared to wait. 0> vplot 5 2. Plot all baselines from sub-array 1, at 5 baselines per page. 0> vplot 5, 1 3. Plot all HSTK baselines of sub-array 2 in IF 3, again at 5 baselines per page. 0> vplot 5, 2:HSTK, 3 4. Plot all HSTK baselines of sub-array 2, starting from baseline HSTK-BONN, using as many plots per page as there are telescopes in sub-array 2 (minus 1). 0> vplot 0, 2:hstk bonn INTERACTIVE MODE ---------------- If the display device has a cursor, then an interactive session will be invoked. In this mode, one page of baselines is initially plotted and mouse-keys and keyboard keys are used to guide the task through plotting and data editing. Once vplot has been invoked, move the cursor into the display window and press the 'H' key on your keyboard. Whenever this is pressed during the vplot session a list of key bindings will be displayed in the terminal window from which vplot was invoked. Most keys are case-insensitive, such that both 'H' and 'h' have the same effect. On standard PGPLOT conforming devices with a mouse or other cursor control device, mouse buttons are treated as equivalent to the following keyboard keys: Left button = 'A' (This is the normal key for selecting positions). Middle button = 'D' (This is used to cancel incomplete select ranges). Right button = 'X' (Use this to exit vplot). Note that on a windowing system, the cursor must be within the display window before pressing keyboard keys (and mouse buttons) will be noticed. However, after pressing a key that needs more complex answers, such as the entry of the number of baselines to display or the entry of a telescope name, the cursor should be moved to the original text window where a prompt will be displayed to guide your entry. MOVING ABOUT BETWEEN BASELINES ------------------------------ n - (Lower-case n) Display next set of baselines p - (Lower-case p) Display preceding set of baselines Pressing 'n' in vplot causes the Next set of baselines of the current telescope to be displayed from the current sub-array. Once all baselines to that telescope have been displayed, pressing 'n' will proceed to display those of the next telescope in the observation. Once all telescopes have been displayed in this manner, pressing 'n' will display start to display baselines from the next sub-array. So by repeatedly pressing 'n' you will see all baselines in every sub-array of the observation. The 'p' key works identically but shows the Previous set of baselines. N - (Upper-case n) Display baselines from the next sub-array. P - (Upper-case p) Display baselines from the previous sub-array. Upper-case 'N' and 'P' provide a means to jump to the next or previous sub-arrays without having to view all of the intermediate baselines. T - Specify reference telescope from the keyboard (text screen) To move to another telescope without having to wade through all the baselines of previous telescopes in the observation, press 'T'. Back on the text screen you will be prompted for the name of the telescope. The name entered may be any unambiguous abbreviation of the full telescope name. eg BOLOGNA and BONN are ambiguous up to BO. BOL or BON are the shortest names that could be used to refer to them. A optional second telescope name may also be entered on the same input line, separated from the first by spaces or a hyphen, in which case the combination of the two telescope names will be used to designate the first baseline to be displayed to the new reference telescope. If the required telescope(s) are from a different sub-array than the one currently being displayed, then specify the sub-array number preceding the first telescope name and separated from it with a colon. Thus BONN-BOL selects baseline BONN-BOLOGNA in the currently displayed sub-array, while 3:BONN-BOL selects baseline BONN-BOLOGNA in sub-array 3. MOVING BETWEEN IFs ------------------ Visibilities are only displayed from one IF at a time. The identity of this IF is displayed above the collection of plots. To move onto the next or previous IF in which any channels were selected with the 'select' command, use the following keys: ] - Move to the next sampled IF. [ - Move to the previous sampled IF. The title above the plots will change to indicate which IF is being displayed. CHANGING HOW BASELINES ARE DISPLAYED ------------------------------------ The following keys toggle attributes on or off. The display will not be re-plotted immediately whenever one of these is toggled, so you can press a sequence of toggle keys before re-displaying with the new attributes. When the sequence is complete, simply press any key that is not in the list below, such as the RETURN key and the display will be updated with the new attributes. M - Toggle display of model visibilities F - Toggle display of flagged visibilities E - Toggle display of error bars 1 - Plot only amplitudes. 2 - Plot only phases. 3 - Plot both amplitudes and phases. B - Toggle breaking the plot into scans (where present) V - Toggle inclusion of flagged data in auto-scaling - - Toggle between the default of displaying absolute amplitudes and/or phases, and the option of displaying the amplitudes and/or phases of the vector difference between the data and the current model. NB. By default, a scan is taken to be any set of integrations which is separated by more than an hour from its nearest neighbors. This can be changed with the 'scangap' command. CHANGING THE NUMBER OF BASELINES DISPLAYED ------------------------------------------ S - Select number of sub-plots per page To change the number of baselines displayed, press the 'S' key. You will be prompted for a number on the text screen. The first baseline plotted will be the same as before, but only the requested number will follow. CHANGING THE DISPLAYED UT RANGE ------------------------------- U - select UT range to be displayed (hit U twice for full range) Press 'U' to request a change in the displayed UT range. You will then be expected either to press 'U' again to display the whole UT range, or to move the cursor to the start UT of the required range and press 'A' (left mouse button), then move the cursor to the end UT of the required range and press 'A' again. The plot will then be re-displayed over the new range and all subsequent plots will be displayed over this range. At any point before the UT range selection has been completed, pressing the 'D' key (middle mouse button) will quietly abort the selection. SWITCHING BETWEEN TIME SYSTEMS ------------------------------ G - Toggle between displaying the default Universal Coordinated Time and Greenwhich Means Sidereal Time along the X axis of the plot. CHANGING THE DISPLAYED AMPLITUDE OR PHASE RANGE ----------------------------------------------- Z - Select amplitude or phase range to be displayed. Press 'Z' to zoom in on a selected amplitude or phase range. You should then either to press 'Z' again to revert to the default range, or move the cursor to the first (top or bottom) amplitude or phase value of the required vertical range and press 'A' (left mouse button), then move the cursor up or down to the end of the required range and press 'A' again. The plot will then be re-displayed over the new range and all subsequent plots will be displayed over this range. At any point before the selection has been completed, pressing the 'D' key (middle mouse button) will quietly abort the selection. CHANGING WHETHER REDUNDANT BASELINES ARE DISPLAYED -------------------------------------------------- By default, for each reference telescope that it plots, vplot displays all of the baselines that include that telescope. This is recommended because it aids in finding telescope dependent errors. However, it does result in you seeing each baseline twice if you step through all antennas. This can be annoying if you have a very large number of baselines. For this reason vplot also provides the option to only show each baseline once, by only showing baselines in which the second antenna of the baseline comes later in the antenna listing than the reference antenna. Thus for the first antenna you see all of the baselines for that antenna, but for the second you see one less baseline, and so on, until by the time you reach the last antenna, there are no baselines to be plotted. O - Toggle telescope ordering to only show non-redundant baselines. EDITING DATA ------------ There are two main modes for editing and it is important to select the right one before proceeding. Station based edits flag or un-flag the selected visibilities on ALL baselines that include the current reference telescope. If you have more than one baseline displayed at a time, then this will be evident, as the selected visibilities will change color on all the displayed baselines. Baseline based editing only affects the baseline in which the selection was made. - (SPACE BAR) Toggles station based vs. baseline based editing. The current editing mode is displayed above the plots on the right-hand side of the display and can be toggled by pressing the SPACE-BAR. It is also possible to further specify the scope of edits. I - Toggle IF editing scope. W - Toggle spectral-line editing scope. By default, edits are applied to all polarizations, spectral-line channels and IFs related to the selected visibility. To specify that edits only be applied to the displayed IF, press the 'I' key. To specify that edits be only applied to the channels that were specified with the 'select' command, press the 'W' key. The mode line above the collection of plots, describes which of these editing modes is in effect. A - Flag or unflag the nearest visibility to the cursor. (Left mouse button) Pressing 'A' on the keyboard or the left mouse button near a displayed visibility point causes the status of that visibility to be toggled from un-flagged to flagged or vice versa. If flagged data are displayed, then toggling an un-flagged visibility will produce a red cross signifying its new flagged status. Otherwise the point will magically disappear, but can be seen subsequently if the display of flagged data is enabled. C - Flag all data inside select box R - Restore data inside select box If you wish to flag or un-flag an extended region of data, point by point editing is tedious. The Clip and Restore keys, 'C 'and 'R' enable you to edit all points inside a square box selected with the cursor. To use this facility, press the respective key and then move the cursor to one corner of the required region and press 'A' (left mouse button). Then move the cursor to the opposite corner of the required region and again press 'A'. The selected points will be re-displayed with their changed statuses. Note that it is especially important to know whether station or baseline based editing is required before doing this since in station based editing restoring a region that you have just clipped may restore points on related baselines that were originally clipped for other reasons. FLAGGING A WHOLE SCAN --------------------- To flag a whole scan on a given baseline, move the cursor into the selected scan on the baseline to be edited and press the 'Z' (ie. zap) key. All points on that baseline within the scan will be flagged, even those not in the currently displayed UT range. In this context a scan is either a single scan obtained after using the 'B' (break-into-scans) key, or the whole UT time range otherwise. Note that the current station/baseline editing mode has no effect on the behavior of this command - so only one baseline will be flagged at a time. ENDING A vplot SESSION ---------------------- To end a vplot session, press 'X' or the right mouse button. If substantial editing was performed in vplot then it is advisable to use the wmerge command to save the modified file before continuing to map the data. MISCELLANEOUS features ---------------------- The following interactive key bindings have not bee discussed above. L - When you press this key the current plot is re-displayed. + - This key toggles whether the cursor is shown as a small cross or as a cross-hair that extends the full width and height of the display. Currently only the /xserve and /xwindow PGPLOT devices support this feature. RELATED COMMANDS ---------------- scangap - Change the time gap used to delimit neighboring scans. radplot - Display visibility amplitude vs. UV radius. projplot - Display visibility amplitude/phase vs. projected UV distance. uvplot - Display the sampling of the UV plane. tplot - Display the time-sampling of each telescope. corplot - Display accumulated self-calibration corrections. cpplot - Display observed and model closure phases interactively.
import { Between, DataSource, LessThanOrEqual } from 'typeorm'; import { Cardano, NetworkInfoProvider, epochSlotsCalcFactory } from '@cardano-sdk/core'; import { CurrentPoolMetricsEntity, PoolRegistrationEntity, PoolRetirementEntity, PoolRewardsEntity, STAKE_POOL_REWARDS, StakePoolEntity, StakePoolRewardsJob } from '@cardano-sdk/projection-typeorm'; import { MissingProgramOption } from '../Program/errors'; import { RewardsComputeContext, WorkerHandlerFactory } from './types'; import { ServiceNames } from '../Program/programs/types'; import { accountActiveStake, poolDelegators, poolRewards } from './stakePoolRewardsQueries'; import { computeROS } from '../StakePool/TypeormStakePoolProvider/util'; import { missingProviderUrlOption } from '../Program/options/common'; import { networkInfoHttpProvider } from '@cardano-sdk/cardano-services-client'; /** The version of the algorithm to compute rewards. */ export const REWARDS_COMPUTE_VERSION = 1; /** Gets from **db-sync** the _active stake_. */ const getPoolActiveStake = async (context: RewardsComputeContext) => { const { db, delegatorsIds, epochNo, ownersIds } = context; context.memberActiveStake = 0n; context.activeStake = 0n; for (const delegatorId of delegatorsIds!) { const { rows, rowCount } = await db.query<{ value: string }>({ name: 'get_active_stake', text: accountActiveStake, values: [epochNo, delegatorId] }); if (rowCount > 0) { const amount = BigInt(rows[0].value); context.activeStake += amount; if (!ownersIds!.includes(delegatorId)) context.memberActiveStake += amount; } } }; /** Gets from **db-sync** the _delegators_ (`stake_address.id` arrays). */ const getPoolDelegators = async (context: RewardsComputeContext) => { context.delegatorsIds = []; context.membersIds = []; context.ownersIds = []; const { db, delegatorsIds, epochNo, membersIds, ownersIds, poolHashId, registration } = context; const { owners } = registration!; const { rows } = await db.query<{ addr_id: string; owner: boolean }>({ name: 'get_delegators', text: poolDelegators, values: [epochNo, poolHashId, owners] }); context.delegators = rows.length; for (const { addr_id, owner } of rows) { delegatorsIds.push(addr_id); if (owner) ownersIds.push(addr_id); else membersIds.push(addr_id); } }; /** Gets from **db-sync** the `pool_hash.id`. */ const getPoolHashId = async (context: RewardsComputeContext) => { const { db, stakePool } = context; const result = await db.query<{ id: string }>({ name: 'get_hash_id', text: 'SELECT id FROM pool_hash WHERE view = $1', values: [stakePool.id] }); if (result.rowCount !== 1) throw new Error('Expected exactly 1 row'); context.poolHashId = result.rows[0].id; }; /** Gets from **db-sync** the _rewards_. */ const getPoolRewards = async (context: RewardsComputeContext) => { const { db, epochNo, poolHashId } = context; const result = await db.query<{ amount: string; type: string }>({ name: 'get_rewards', text: poolRewards, values: [epochNo, poolHashId] }); context.leaderRewards = 0n; context.memberRewards = 0n; context.rewards = 0n; for (const { amount, type } of result.rows) { const biAmount = BigInt(amount); if (type === 'leader') context.leaderRewards += biAmount; if (type === 'member') context.memberRewards += biAmount; context.rewards += biAmount; } }; /** * Checks if the job for previous epoch already completed accessing the **pg-boss** `job` table. * * In case previous job is not yet completed, `throw`s an `Error`. */ const checkPreviousEpochCompleted = async (dataSource: DataSource, epochNo: Cardano.EpochNo) => { // Epoch no 0 doesn't need to wait for any jobs about previous epoch if (epochNo === 0) return; const queryRunner = dataSource.createQueryRunner(); try { const result: { completed: string }[] = await queryRunner.query( 'SELECT COUNT(*) AS completed FROM pgboss.job WHERE name = $1 AND singletonkey = $2 AND state = $3', [STAKE_POOL_REWARDS, epochNo - 1, 'completed'] ); if (result[0]?.completed !== '1') throw new Error('Previous epoch rewards job not completed yet'); } finally { await queryRunner.release(); } }; /** * Checks if a given pool needs to compute the rewards in a given epoch based on its status in that epoch. * * It also adds the `registration` to the `context`. * * @param context the computation context * @returns `true` if the pool has rewards to compute, `false` otherwise */ const hasRewardsInEpoch = async (context: RewardsComputeContext) => { const { dataSource, epochNo, lastSlot, stakePool } = context; const { id } = stakePool; const registration = await dataSource.getRepository(PoolRegistrationEntity).findOne({ order: { blockSlot: 'DESC' }, where: { blockSlot: LessThanOrEqual(lastSlot), stakePool: { id } } }); if (!registration) return false; const retirements = await dataSource.getRepository(PoolRetirementEntity).count({ where: { blockSlot: Between(registration.blockSlot!, lastSlot), retireAtEpoch: LessThanOrEqual(epochNo), stakePool: { id } } }); if (retirements !== 0) return false; context.registration = registration; return true; }; /** * Computes the rewards for a given stake pool in a given epoch; stores it into the DB * and updates ROS and lastROS for the stake pool in its metrics. * * @param context the computation context */ const epochRewards = async (context: RewardsComputeContext) => { const { dataSource, lastRosEpochs, logger, stakePool } = context; const { id } = stakePool; if (await hasRewardsInEpoch(context)) { logger.info(`Going to compute epoch rewards for stake pool ${id}`); await getPoolHashId(context); await getPoolDelegators(context); await getPoolRewards(context); await getPoolActiveStake(context); const { registration } = context; context.pledge = registration!.pledge!; context.version = REWARDS_COMPUTE_VERSION; logger.debug(`Going to upsert epoch rewards for stake pool ${id}`); await dataSource.getRepository(PoolRewardsEntity).upsert(context, ['epochNo', 'stakePoolId']); logger.debug(`Epoch rewards for stake pool ${id} saved`); } const [ros] = await computeROS(context); const [lastRos] = await computeROS({ ...context, epochs: lastRosEpochs }); logger.debug(`Going to refresh ROS metrics for stake pool ${id}`); await dataSource.getRepository(CurrentPoolMetricsEntity).upsert({ lastRos, ros, stakePool: { id } }, ['stakePoolId']); logger.debug(`ROS metrics for stake pool ${id} saved`); }; /** Gets the last slot of the epoch. */ const getLastSlot = async (provider: NetworkInfoProvider, epochNo: Cardano.EpochNo) => { const epochSlotsCalc = epochSlotsCalcFactory(provider); const { firstSlot, lastSlot } = await epochSlotsCalc(epochNo); return { epochLength: (lastSlot - firstSlot + 1) * 1000, lastSlot }; }; /** Creates a `stakePoolRewardsHandler`. */ export const stakePoolRewardsHandlerFactory: WorkerHandlerFactory = (options) => { const { dataSource, db, lastRosEpochs, logger, networkInfoProviderUrl } = options; // Introduced following code repetition as the correct form is source of a circular-deps:check failure. // Solving it would require an invasive refactoring action, probably better to defer it. // if (!lastRosEpochs) throw new MissingProgramOption(STAKE_POOL_REWARDS, Descriptions.LastRosEpochs); if (!lastRosEpochs) throw new MissingProgramOption(STAKE_POOL_REWARDS, 'Number of epochs over which lastRos is computed'); if (!networkInfoProviderUrl) throw missingProviderUrlOption(STAKE_POOL_REWARDS, ServiceNames.NetworkInfo); const provider = networkInfoHttpProvider({ baseUrl: networkInfoProviderUrl, logger }); return async (data: StakePoolRewardsJob) => { const { epochNo } = data; logger.info(`Starting stake pools rewards job for epoch ${epochNo}`); await checkPreviousEpochCompleted(dataSource, epochNo); const { epochLength, lastSlot } = await getLastSlot(provider, epochNo); for (const stakePool of await dataSource.getRepository(StakePoolEntity).find()) await epochRewards({ dataSource, db, epochLength, epochNo, lastRosEpochs, lastSlot, logger, stakePool }); }; };
import datetime from rest_framework.views import APIView from rest_framework.response import Response class ImagicaSpecificOutputAPIView(APIView): def get(self, request, file_name, normalization_version, model_version, post_processing_version): """ Get deals data from Imagica service **Example Response** { "FileName": "string", "GeneratedAt": "datetime", "DocumentCreatedAt": "datetime", "NormalizationVersion": "string", "PostProcessingVersion": "string", "ModelVersion": "string", "Data": [ { "ImagicaDealNumber": "int", "TRADE_DATE": "string", "UNDERLYING_NAME": "string", "CURRENCY": "string", "INSTRUMENT_NAME": "string", "EXERCISE_TYPE": "string", "OPTION_TYPE": "string", "BUY/SELL": "string", "PRODUCT_PRICE": "float", "PRODUCT_QUANTITY": "float", "STRIKE": "float", "MATURITY_DATE": "string", "BROKER_FEES": "float", "BROKER_FEES_CCY": "string", "CONTRACT": "string", "MARKET": "string" } ], "Error": "string" } """ return Response({ "FileName": file_name, "GeneratedAt": datetime.datetime.now(), "DocumentCreatedAt": datetime.datetime.now(), "NormalizationVersion": normalization_version, "ModelVersion": model_version, "PostProcessingVersion": post_processing_version, "Data": [], "Error": "File Not Found" })
"use client" import { useState, useEffect } from 'react'; interface Cliente { id: number; nome: string; email: string; telefone: string; coordenada_x: number; coordenada_y: number; } interface Rota { id: 'inicio' | 'fim' | number; coordenada_x: number; coordenada_y: number; } function formatarTelefone(telefone: any) { const numeros = telefone.replace(/\D/g, ''); const comParenteses = numeros.replace(/(\d{2})(\d+)/, '($1) $2'); return comParenteses.slice(0, 14); } export default function Home() { const [clientes, setClientes] = useState<Cliente[]>([]); const [rota, setRota] = useState<Rota[]>([]); const [form, setForm] = useState({ nome: '', email: '', telefone: '', coordenada_x: 0, coordenada_y: 0 }); const [filtro, setFiltro] = useState(''); const [isModalOpen, setIsModalOpen] = useState(false); const [clienteEditando, setClienteEditando] = useState<Cliente | null>(null); const clientesFiltrados = clientes.filter(cliente => { return cliente.nome?.toLowerCase().includes(filtro.toLowerCase()) || cliente.email?.toLowerCase().includes(filtro.toLowerCase()) || cliente.telefone?.toLowerCase().includes(filtro.toLowerCase()); }); useEffect(() => { fetch('/api/clientes') .then(response => response.json()) .then(data => setClientes(data)); }, []); const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { const { name, value } = e.target; setForm(prevForm => ({ ...prevForm, [name]: value })); }; const handlePhoneInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { const { name, value } = e.target; setForm((prevForm) => ({ ...prevForm, [name]: formatarTelefone(value), })); }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); fetch('/api/clientes', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(form), }) .then(response => response.json()) .then(data => { setClientes(prevClientes => [...prevClientes, data]); setForm({ nome: '', email: '', telefone: '', coordenada_x: 0, coordenada_y: 0 }); }) .catch(error => console.error('Erro ao cadastrar cliente:', error)); }; const handleCalculateRoute = () => { fetch('/api/calcular-rota') .then(response => response.json()) .then(data => { setRota(data) setIsModalOpen(true) }); }; const handleCloseModal = () => { setIsModalOpen(false); }; const handleDeleteCliente = async (id: number) => { try { await fetch(`/api/clientes/${id}`, { method: 'DELETE', }); setClientes(clientes.filter(cliente => cliente.id !== id)); } catch (error) { console.error('Erro ao deletar cliente:', error); } }; const handleStartEditCliente = (cliente: Cliente) => { setClienteEditando(cliente); }; const handleCancelEdit = () => { setClienteEditando(null); }; const handleSaveEdit = async (e: React.FormEvent) => { e.preventDefault(); if (!clienteEditando) { return } try { const response = await fetch(`/api/clientes/${clienteEditando.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ nome: clienteEditando.nome, email: clienteEditando.email, telefone: clienteEditando.telefone, coordenada_x: clienteEditando.coordenada_x, coordenada_y: clienteEditando.coordenada_y, }), }); if (!response.ok) { throw new Error('Problema ao atualizar o cliente'); } const updatedCliente = await response.json(); setClientes(clientes.map(cliente => cliente.id === updatedCliente.id ? updatedCliente : cliente)); setClienteEditando(null); } catch (error) { console.error('Falha ao salvar as edições:', error); } }; return ( <div className="container mx-auto p-4"> <h1 className="text-4xl font-bold text-center text-gray-800 mb-10">Gerenciamento de Clientes</h1> <div className="mb-8"> <h2 className="text-2xl font-semibold mb-5 text-gray-700">Cadastrar Novo Cliente</h2> <form onSubmit={handleSubmit} className="mb-8 p-6 bg-white shadow rounded-lg"> <input type="text" name="nome" placeholder="Nome" value={form.nome} onChange={handleInputChange} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" /> <input type="email" name="email" placeholder="Email" value={form.email} onChange={handleInputChange} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" /> <input type="text" name="telefone" placeholder="DDD + Telefone" value={form.telefone} onChange={handlePhoneInputChange} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" maxLength={14} /> <input type="number" name="coordenada_x" placeholder="Coordenada X" value={form.coordenada_x} onChange={handleInputChange} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" /> <input type="number" name="coordenada_y" placeholder="Coordenada Y" value={form.coordenada_y} onChange={handleInputChange} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" /> <button type="submit" disabled={!form.nome || !form.email || !form.telefone || !form.coordenada_x || !form.coordenada_y} className="bg-blue-500 hover:bg-blue-600 text-white p-3 rounded-lg w-full transition duration-200"> Cadastrar </button> </form> </div> <div className="mb-8"> <h2 className="text-2xl font-semibold mb-5 text-gray-700">Lista de Clientes</h2> <input type="text" placeholder="Filtrar por nome, e-mail ou telefone" value={filtro} onChange={(e) => setFiltro(e.target.value)} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" /> <div className="mb-8 p-6 bg-white shadow rounded-lg"> {clientesFiltrados.map(cliente => ( <div key={cliente.id} className="mb-4 p-4 rounded border border-gray-200 shadow-sm bg-gray-50"> <p>nome: {cliente.nome}</p> <p>email: {cliente.email}</p> <p>telefone: {cliente.telefone}</p> <div> <button onClick={() => handleStartEditCliente(cliente)} className="bg-yellow-500 text-white px-4 py-2 rounded hover:bg-yellow-600 mr-2" > Editar </button> <button onClick={() => handleDeleteCliente(cliente.id)} className="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600" > Apagar </button> </div> </div> ))} <div> <button onClick={handleCalculateRoute} className="bg-blue-500 hover:bg-blue-600 text-white p-3 rounded-lg w-full transition duration-200"> Calcular Rota </button> {isModalOpen && ( <div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center"> <div className="bg-white p-6 rounded shadow-lg"> {rota.length > 0 && ( <div className="... suas classes tailwind ..."> <h2 className="text-xl font-semibold my-3">Rota Calculada</h2> {rota.map((ponto, index) => ( <div key={index}> {typeof ponto.id === 'number' ? ( <p> {clientes.find(cliente => cliente.id === ponto.id)?.nome} - X: {ponto.coordenada_x}, Y: {ponto.coordenada_y} </p> ) : null} </div> ))} </div> )} <button onClick={handleCloseModal} className="bg-red-500 text-white px-4 py-2 rounded"> Fechar </button> </div> </div> )} </div> </div> </div> { clienteEditando && ( <div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center p-4"> <div className="bg-white p-6 rounded shadow-lg max-w-lg w-full"> <form onSubmit={(e) => { e.preventDefault(); }} className="bg-white p-6 rounded-lg shadow max-w-lg w-full" > <input type="text" name="nome" placeholder="Nome" value={clienteEditando.nome} onChange={(e) => setClienteEditando({ ...clienteEditando, nome: e.target.value })} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" required /> <input type="email" name="email" placeholder="Email" value={clienteEditando.email} onChange={(e) => setClienteEditando({ ...clienteEditando, email: e.target.value })} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" required /> <input type="tel" name="telefone" placeholder="Telefone" value={clienteEditando.telefone} onChange={(e) => setClienteEditando({ ...clienteEditando, telefone: e.target.value })} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" /> <input type="number" name="coordenada_x" placeholder="Coordenada X" value={clienteEditando.coordenada_x.toString()} onChange={(e) => setClienteEditando({ ...clienteEditando, coordenada_x: parseFloat(e.target.value) })} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" /> <input type="number" name="coordenada_y" placeholder="Coordenada Y" value={clienteEditando.coordenada_y.toString()} onChange={(e) => setClienteEditando({ ...clienteEditando, coordenada_y: parseFloat(e.target.value) })} className="border-gray-300 p-3 mb-4 rounded-lg w-full text-gray-700 border-2" /> <div className="flex justify-end gap-4"> <button type="button" onClick={handleCancelEdit} className="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600" > Cancelar </button> <button type="submit" onClick={handleSaveEdit} className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600" > Salvar Edições </button> </div> </form> </div> </div> ) } </div> ); }
/* * Copyright © 2023 THALES. All rights reserved. */ import Foundation import UIKit import SwiftUI import D1 import LocalAuthentication /// Digital card detail ViewModel. class DigitalCardDetailViewModel: CardViewModel { @Published public var digitalCard: D1.DigitalCard? private var digitalCardId: String private var deleteCallback: () -> Void // MARK: - Life Cycle /// Creates a new CardViewModel instance. /// - Parameter cardId: Card ID. init(_ cardId: String, _ digitalCardId: String, _ deleteCallback: @escaping () -> Void) { self.digitalCardId = digitalCardId self.deleteCallback = deleteCallback super.init(cardId) } // MARK: - Public API /// Retrieves the digital card. public func getDigitalCard() { D1Push.shared().getDigitalCard(cardId: self.virtualCardId, digitaCardId: self.digitalCardId) { (digitalCard: DigitalCard?, error: D1Error?) in if let error = error { self.bannerShow(caption: "Error during get digital card.", description: error.localizedDescription, type: .error) return } if let digitalCard = digitalCard { self.digitalCard = digitalCard self.cardState = digitalCard.state.rawValue self.displayCardId = self.showCardId() } } } /// Suspends the digital card. public func suspendDigitalCard() { if let digitalCard = self.digitalCard { progressShow(caption: "Operation in progress") D1Push.shared().suspendDigitalCard(cardId: self.virtualCardId, digitalCard: digitalCard) { (isSuccess: Bool?, error: D1Error?) in self.progressHide() if let error = error { self.bannerShow(caption: "Error during suspend digital card.", description: error.localizedDescription, type: .error) } // reload card self.getDigitalCard() } } } /// Resumes the digital card. public func resumeDigitalCard() { if let digitalCard = self.digitalCard { progressShow(caption: "Operation in progress") D1Push.shared().suspendDigitalCard(cardId: self.virtualCardId, digitalCard: digitalCard) { (isSuccess: Bool?, error: D1Error?) in self.progressHide() if let error = error { self.bannerShow(caption: "Error during resume digital card.", description: error.localizedDescription, type: .error) } // reload card self.getDigitalCard() } } } /// Deletes the digital card. public func deleteDigitalCard() { if let digitalCard = self.digitalCard { progressShow(caption: "Operation in progress") D1Push.shared().deleteDigitalCard(cardId: self.virtualCardId, digitalCard: digitalCard) { (isSuccess: Bool?, error: D1Error?) in self.progressHide() if let error = error { self.bannerShow(caption: "Error during delete digital card.", description: error.localizedDescription, type: .error) } if let isSuccess = isSuccess { if (isSuccess) { // reload digital card list self.deleteCallback() } } } } } /// Activates the digital card. public func activateCard() { progressShow(caption: "Operation in progress") D1Push.shared().activateDigitalCard(cardId: digitalCardId) { (error:D1Error?) in self.progressHide() if let error = error { self.bannerShow(caption: "Error during activate digital card.", description: error.localizedDescription, type: .error) return } self.bannerShow(caption: "Card activated.", description: "", type: .info) } } // MARK: - Override override func showCardId() -> String { return self.digitalCard?.cardID ?? "" } }
/** console.cpp * Defines functions to implement the Console class. * More documentation on the functions in the header file. */ #include "console.h" #include <termios.h> #include <unistd.h> #include <stdio.h> #include <chrono> #include <iomanip> #include <iostream> #include <sstream> #include <thread> using namespace std; Console& Console::getInstance() { static Console c; return c; } string Console::read(const string &prompt) { // set the prompt and write it to std::cout { unique_lock<mutex> lck{m_console_mtx}; // acquire mutex for access to std::cout and m_prompt m_prompt = prompt; std::cout << m_prompt; } while(true) { int next_char = getchar(); // wait for user to enter next character unique_lock<mutex> lck{m_console_mtx}; // acquire mutex for access to std::cout and member variables bool user_done_typing = false; switch(next_char) { case kDelete: // delete the last character the user typed, if any if(m_user_input.size()) { m_user_input.pop_back(); // move cursor back one character // overwrite character with empty space // move cursor back one character again std::cout << "\b \b"; } break; case kNewLine: // the user hit "enter" user_done_typing = true; break; default: // store and display the character user typed m_user_input.append(1, static_cast<char>(next_char)); // append 1 next_char std::cout << static_cast<char>(next_char); } std::cout.flush(); // avoid buffering if(user_done_typing) { std::cout << std::endl; string to_return = m_user_input; // reset the prompt and user input strings m_user_input.clear(); m_prompt.clear(); return to_return; } } } void Console::write(const string &s) { unique_lock<mutex> lck(m_console_mtx); // acquire mutex for access to std::cout and m_prompt const size_t current_input_size = m_prompt.size() + m_user_input.size(); // if a read() is not in progress, simply write the string to cout if(!current_input_size) { std::cout << s << std::endl; return; } // Since a read is in progress, the prompt and user input is being displayed // at the bottom of the terminal. We must erase the prompt and user input // and write the string. Now that the string has been written, we can restore // the prompt and user input that we erased. // The erase and restoration of the user prompt and user input occurs // extremely fast // move cursor to the start of the prompt and user input std::cout << '\r' // overwrite the remaining line with empty character space << std::setfill(' ') << std::setw(current_input_size) << "" // move cursor to start of line again << '\r'; std::cout << std::setw(0) // write the intended message << s << std::endl // write the user prompt and input again << m_prompt << m_user_input << std::flush; } Console::Console() { struct termios old_attr; tcgetattr(STDIN_FILENO, &old_attr); struct termios new_attr = old_attr; // clear ICANON and ECHO flag // clearing ICANON bit - input from the user will be available immediately // after it is typed instead of being buffered // clearing ECHO bit - input is NOT written back to the terminal // automatically (will be done manually) new_attr.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &new_attr); }
#!/usr/bin/perl # $File: //depot/libOurNet/BBS/script/bbscomd $ $Author: autrijus $ # $Revision: #1 $ $Change: 3790 $ $DateTime: 2003/01/24 19:08:46 $ $VERSION = '1.62_01'; $REVISION = "rev$1\[\@$2\]" if ('$Revision: #1 $ $Change: 3790 $' =~ /(\d+)[^\d]+(\d+)/); =head1 NAME bbscomd - OurNet BBS Remote Access Daemon =head1 SYNOPSIS B<bbscomd> S<[ B<-acdfgGhsx> ]> S<[ B<-b> I<addr> ]> S<[ B<-p> I<port> ]> S<[ B<-u> I<key> ] > S<[ B<-l> I<logfile> ]> S<[ B<-t> I<timeout> ]> S< I<backend> [ I<argument>... ]> =head1 DESCRIPTION The bbscomd starts a I<OurNet::BBS::Server> daemon listening on the specified port (default 7979). Remote users could then start using the I<OurNet> backend or I<OurNet::BBS::Client> to connect like this: use OurNet::BBS; my $Remote_BBS = OurNet::BBS->new(OurNet => 'remote.org'); If the C<-f> flag is specified, bbscomd will fork a new process to run as daemon. The C<-d> flag turns on debugging. The C<-u> specifies the pgp keyid or userid used in authorization. If C<-a> is supplied, the server will serve in the I<authenticated> mode with additional permission controls. Similarly, C<-c> disallows insecure cipher modes. The C<-g> flag allows server to assume C<guest> as the user ID on a failed Authentication (fallback to AUTH_NONE), with corresponding permissions. Similarly, the C<-G> flag allows the client to authenticate as B<ANY> user they wanted to; because of the security risk, this flag automatically specifies C<-b localhost> for you. Note that this does not assume the behaviour of C<-g>; you'll have to specify C<-gG> explicitly to turn on both settings. The C<-s> flag permits single-connection only. This is primary used for single-user situations. The C<-x> flag assumes default settings on Win32. It's not meant to be used on other platforms. If you don't want to bind all available IPs, specify one using the C<-b> flag. The C<-t> flag sets the C<connection-timeout> option to the Server object, which causes a child connection to terminate after an inactivity for I<timeout> seconds. If you want to keep a B<Net::Daemon> styled log file, specify the file name to C<-l>. Please refer to L<OurNet::BBS> modules for more information on usage. =head1 EXAMPLES Starting a typical MELIX daemon, require authentication, but allowing unprivileged guest access: % bbscomd -acfg -u melix MELIX /home/melix 2997 350 Starting a localhost-only bridge at port 8080 to another I<OurNet> node, with debugging output: % bbscomd -d -b 127.0.0.1 -p 8080 OurNet localhost =cut use strict; use warnings; use Getopt::Std; use OurNet::BBS; use OurNet::BBS::Server; $|++; my %args; if (!@ARGV) { die << "."; OurNet BBS Remote Access Daemon v$main::VERSION-$main::REVISION Usage: $0 [-acdfghx] [-b <addr>] [-p <port>] [-u <key>] <backend> [ <argument>... ] Type '$0 -h' to see available argument and options. Copyright 2001-2002 by Autrijus Tang <autrijus\@autrijus.org>. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See <http://www.perl.com/perl/misc/Artistic.html>. . } getopts('acgGb:p:t:u:fdhsx', \%args); exec('perldoc', $0) if defined $args{h}; my ($auth, $ciph, $port, $logfile, $timeout, $key, $fork, $debug, $addr, $guest, $anyuser, $single) = @{args}{qw/a c p l t u f d b g G s/}; $guest = $guest ? 'guest' : undef; $guest = "*$guest" if $anyuser; $auth = defined($auth) ? $guest ? 7 : 6 : 0; $ciph = $key ? 6 : 2 if defined $ciph; $port ||= 7979; if ($args{x}) { @ARGV = ( 'MELIX', -e 'c:/cygwin/home/melix' ? 'c:/cygwin/home/melix' : 'c:/program files/melix/home/melix' ); } no warnings 'once'; $OurNet::BBS::DEBUG = $debug; $OurNet::BBS::Server::LocalAddr = $addr if defined $addr; %OurNet::BBS::Server::Options = ( 'logfile' => $logfile, 'connection-timeout' => $timeout, ); if ($single) { $OurNet::BBS::Server::Mode = 'single'; } my $BBS = OurNet::BBS->new(@ARGV) or die "Cannot link to BBS: @ARGV\n"; print "entering in debug mode, expect lots of outputs\n" if $OurNet::BBS::DEBUG; my $pass = ''; if ($key) { require Term::ReadKey; Term::ReadKey::ReadMode('noecho'); print "enter passphrase for <$key>: "; $pass = scalar <STDIN>; Term::ReadKey::ReadMode('restore'); print "\n"; } if (!$fork or !fork()) { print "BBSCOM Daemon starting at port $port...\n"; $BBS->daemonize($port, $key, $pass, $ciph, $auth, $guest) or die "Failed to daemonize: $!\n"; } __END__ =head1 SEE ALSO L<OurNet::BBS>, L<RPC::PlServer>, L<Net::Daemon> =head1 AUTHORS Autrijus Tang E<lt>autrijus@autrijus.orgE<gt> =head1 COPYRIGHT Copyright 2001-2002 by Autrijus Tang E<lt>autrijus@autrijus.orgE<gt>. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L<http://www.perl.com/perl/misc/Artistic.html> =cut
import { useQuery } from "react-query"; import { Helmet } from "react-helmet"; import React, { useEffect, useState } from "react"; import { useParams } from "react-router"; import { Link, Route, Routes, useMatch } from "react-router-dom"; import { useLocation } from "react-router-dom"; import styled from "styled-components"; import Chart from "./Chart"; import Price from "./Price"; import { fetchCoinInfo, fetchCoinTickers } from "../api"; interface InfoData { id: string; name: string; symbol: string; rank: number; is_new: boolean; is_active: boolean; type: string; logo: string; description: string; message: string; open_source: boolean; started_at: string; development_status: string; hardware_wallet: boolean; proof_type: string; org_structure: string; hash_algorithm: string; links: object; links_extended: object; whitepaper: object; first_data_at: string; last_data_at: string; } interface PriceData { id: string; name: string; symbol: string; rank: number; circulating_supply: number; total_supply: number; max_supply: number; beta_value: number; first_data_at: string; last_updated: any; quotes: { USD: { ath_date: string; ath_price: number; market_cap: number; market_cap_change_24h: number; percent_change_1h: number; percent_change_1y: number; percent_change_6h: number; percent_change_7d: number; percent_change_12h: number; percent_change_15m: number; percent_change_24h: number; percent_change_30d: number; percent_change_30m: number; percent_from_price_ath: number; price: number; volume_24h: number; volume_24h_change_24h: number; }; }; } const Container = styled.div` padding: 0px 20px; max-width: 480px; margin: 0 auto; `; const Header = styled.header` height: 15vh; display: flex; justify-content: center; align-items: center; font-size: 48px; `; const Title = styled.h1` color: ${(props) => props.theme.accentColor}; `; const Overview = styled.div` display: flex; justify-content: space-between; background-color: rgba(0, 0, 0, 0.5); padding: 10px 20px; border-radius: 10px; `; const OverviewItem = styled.div` display: flex; flex-direction: column; align-items: center; flex-basis: 100%; span:first-child { font-size: 12px; font-weight: 400; text-transform: uppercase; margin-bottom: 5px; } span:nth-child(2) { font-size: 18px; } `; const Description = styled.p` margin: 20px 0; `; const Tabs = styled.div` display: flex; align-items: center; justify-content: space-between; margin-top: 20px; gap: 10px; `; const Tab = styled.span<{ isActive: boolean }>` background-color: rgba(0, 0, 0, 0.5); flex: 1; text-align: center; border-radius: 10px; padding: 7px 0; color: ${(props) => (props.isActive ? props.theme.accentColor : "white")}; a { display: block; } `; export default function Coin() { const { coinId } = useParams(); const location = useLocation(); const { state } = location; const priceMatch = useMatch(`/:coinId/price`); const chartMatch = useMatch(`/:coinId/chart`); const [date, setDate] = useState(new Date()); // const [loading, setLoading] = useState(true); // const [info, setInfo] = useState<InfoData>(); // const [price, setPrice] = useState<PriceData>(); // useEffect(() => { // (async () => { // const infoData = await (await fetch(`https://api.coinpaprika.com/v1/coins/${coinId}`)).json(); // const priceData = await ( // await fetch(`https://api.coinpaprika.com/v1/tickers/${coinId}`) // ).json(); // console.log(infoData); // console.log(priceData); // setInfo(infoData); // setPrice(priceData); // setLoading(false); // setDate(new Date(priceData.last_updated)); // console.log(date.toLocaleString()); // })(); // }, []); const { isLoading: infoLoading, data: infoData } = useQuery<InfoData>( ["info", coinId], () => fetchCoinInfo(coinId!), { refetchInterval: 300000, } ); const { isLoading: tickersLoading, data: tickersData } = useQuery<PriceData>( ["tickers", coinId], () => fetchCoinTickers(coinId!), { refetchInterval: 300000, } ); console.log(infoData); console.log(tickersData); const loading = infoLoading || tickersLoading; return ( <Container> <Helmet> <title>{state?.name ? state.name : loading ? "Loading..." : infoData?.name}</title> </Helmet> <Link to={"/"}>홈으로</Link> <Header> <Title>{state?.name ? state.name : loading ? "Loading..." : infoData?.name}</Title> </Header> <Overview> <OverviewItem> <span>Rank</span> <span>{infoData?.rank}</span> </OverviewItem> <OverviewItem> <span>Symbol</span> <span>${infoData?.symbol}</span> </OverviewItem> <OverviewItem> <span>최대 공급량</span> <span>{tickersData?.max_supply}</span> </OverviewItem> </Overview> <Description>업데이트: {new Date(tickersData?.last_updated).toLocaleString()}</Description> <Description>{infoData?.description}</Description> <Overview> <OverviewItem> <span>유통 공급량</span> <span>{tickersData?.circulating_supply}</span> </OverviewItem> <OverviewItem> <span>변동(7일)</span> <span>{tickersData?.quotes.USD.percent_change_7d}%</span> </OverviewItem> <OverviewItem> <span>가격</span> <span>${tickersData?.quotes.USD.price.toFixed(3)}</span> </OverviewItem> </Overview> <Tabs> <Tab isActive={chartMatch !== null}> <Link to={`/${coinId}/chart`}>차트</Link> </Tab> <Tab isActive={priceMatch !== null}> <Link to={`/${coinId}/price`}>가격</Link> </Tab> </Tabs> <Routes> <Route path="chart" element={<Chart coinId={coinId!} />} /> <Route path="price" element={<Price coinId={coinId!} />} /> </Routes> </Container> ); }
<?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use App\Traits\Filter; use App\Traits\Uuid; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\Pivot; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; use Yajra\Acl\Traits\HasRoleAndPermission; class User extends Authenticatable { use Uuid, Filter; use HasApiTokens, HasFactory, Notifiable; use HasRoleAndPermission; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; protected $with = ['roles']; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; protected function password(): Attribute { return new Attribute( get: fn ($value) => $value, set: fn ($value) => bcrypt($value), ); } /** * User can belong many roles. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function roles(): BelongsToMany { /** @var class-string $model */ $model = config('acl.role'); return $this->belongsToMany($model) ->withTimestamps() ->using(new class extends Pivot { use Uuid; }); } }
import viewer # Assuming viewer is a module you have defined elsewhere import numpy as np import matplotlib.pyplot as plt import os import imageio from tqdm import tqdm import nibabel as nib import SimpleITK as sitk import cv2 def readNIftI(which='Labels', set='testing', directory=None): """ Reads NIfTI files (Labels, Masks, or Images) and converts them to numpy arrays. Args: which (str, optional): Type of NIfTI file to read ('Labels', 'Mask', 'Images'). Raises: NotImplementedError: If the specified type is not supported. """ type_mapping = { 'Labels': '_3C', 'Mask': '_1C', 'Images': '' } key = type_mapping.get(which) if key is None: raise NotImplementedError(f"'{which}' is not a supported type.") imgs = [] tags = [] if not directory: directory = f'{set}Set/{set}{which}/' for path in tqdm(os.listdir(directory)): tags.append(path.split(".nii")[0]) path = os.path.join(directory, path) img = np.array(nib.nifti1.load(path).dataobj) imgs.append(img) return imgs, tags
import nodemailer from 'nodemailer'; import Mailgen from 'mailgen'; import ENV from '../config.js' // https://ethereal.email/create let nodeConfig = { host: "smtp.ethereal.email", port: 587, secure: false, // true for 465, false for other ports auth: { user: ENV.EMAIL, // generated ethereal user pass: ENV.PASSWORD, // generated ethereal password }, } let transporter = nodemailer.createTransport(nodeConfig); let MailGenerator = new Mailgen({ theme: "default", product: { name: "Mailgen", link: 'https://mailgen.js' } }) /** POST: http://localhost:4001/api/registerMail * @param: { "username" : "example123", "userEmail" : "admin123", "text" : "", "subject" : "" } */ export const registerMail = async (req, res) => { const { username, userEmail, text, subject} = req.body; // body of the email var email = { body: { name: username, intro: text || 'Its Himanshu', outro: 'himanshu.varni@gmail.com' } } var emailBody = MailGenerator.generate(email) let message = { from : ENV.EMAIL, to: userEmail, sub: subject || 'signup successfull', html: emailBody } // send mail transporter.sendMail(message) .then(() => { return res.status(200).send({ msg: "You should receive an email from us."}) }) .catch(error => res.status(500).send({ error })) }
/** * @file index file of Pager component * @date 2022-01-06 * @author dualless * @lastModify lidaoping 2022-01-06 */ /* <------------------------------------ **** DEPENDENCE IMPORT START **** ------------------------------------ */ /** This section will include all the necessary dependence for this tsx file */ import React, { useEffect, useState } from 'react'; import classnames from '~/Utils/classNames'; import styles from './style.scss'; import Icon from '~/Components/Icon'; /* <------------------------------------ **** DEPENDENCE IMPORT END **** ------------------------------------ */ /* <------------------------------------ **** INTERFACE START **** ------------------------------------ */ /** This section will include all the interface for this tsx file */ interface PaginationProps { count: number; size?: number; maxLength?: number; current: number; type?: 'solid' | 'default'; onChange?: (number: number) => void; } /* <------------------------------------ **** INTERFACE END **** ------------------------------------ */ /* <------------------------------------ **** FUNCTION COMPONENT START **** ------------------------------------ */ const Pagination: React.FC<PaginationProps> = ({ count, size = 5, maxLength = 7, current, type = 'default', onChange, }): JSX.Element => { /* <------------------------------------ **** STATE START **** ------------------------------------ */ /************* This section will include this component HOOK function *************/ const [firstArr, setFirstArr] = useState<number[]>([]); const [centerArr, setCenterArr] = useState<number[]>([]); const [lastArr, setLastArr] = useState<number[]>([]); // all page const pageCount = Math.ceil(count / size); const isFirstPage = current == 1; const isLastPage = current === pageCount; useEffect(() => { createArr(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [current]); /* <------------------------------------ **** STATE END **** ------------------------------------ */ /* <------------------------------------ **** PARAMETER START **** ------------------------------------ */ /************* This section will include this component parameter *************/ const pageItemClassName = (active: boolean) => { return classnames([ styles.pagination_pageItem, styles['pagination_pageItem_' + type], { [styles.active]: active }, ]); }; /* <------------------------------------ **** PARAMETER END **** ------------------------------------ */ /* <------------------------------------ **** FUNCTION START **** ------------------------------------ */ // create array item const createArr = () => { let i = 0; const first: number[] = []; const center: number[] = []; const last: number[] = []; while (++i <= pageCount) { // if page max all page if (pageCount > maxLength && first.length + center.length + last.length < maxLength) { const currentCeilGap = Math.ceil(maxLength / 2); const currentFloorGap = Math.floor(maxLength / 2); if (current < currentCeilGap) { first.push(i); } else if (current >= currentCeilGap && current <= pageCount - currentCeilGap) { if (maxLength % 2 == 0) { center.push(i + current - currentFloorGap + 1); } else { center.push(i + current - currentFloorGap); } } else if (current > pageCount - currentCeilGap) { last.push(i + pageCount - currentCeilGap - currentFloorGap + 1); } if (first.length == 0) first.push(1); if (last.length == 0) last.push(pageCount); } else if (pageCount <= maxLength) { first.push(i); } } setFirstArr(first); setCenterArr(center); setLastArr(last); }; // create pager item const createPaginationItem = (arr: number[]) => { return arr.map((value) => { return ( <li key={value} className={pageItemClassName(value === current)} onClick={() => handleSelectPage(value)} > {value} </li> ); }); }; const handleChange = (number: number) => { onChange?.(number); }; const handleChangeList = (number: number) => { handleChange(number); }; const handlePrevPage = () => { if (isFirstPage) { return; } handleChange(current - 1); }; const handleNextPage = () => { if (isLastPage) { return; } handleChange(current + 1); }; const handlePrevList = () => { if (isFirstPage) { return; } handleChangeList(1); }; const handleNextList = () => { if (isLastPage) { return; } handleChangeList(pageCount); }; const handleSelectPage = (value: number) => { handleChange(value); }; /************* This section will include this component general function *************/ /* <------------------------------------ **** FUNCTION END **** ------------------------------------ */ /************* This section will include this component general function *************/ /* <------------------------------------ **** FUNCTION END **** ------------------------------------ */ return ( <div className={styles.pagination_container}> <div className={classnames([ styles.pagination_prevFirstPageContainer, styles['pagination_prevFirstPageContainer_' + type], { disabled: isFirstPage }, ])} onClick={() => handlePrevList()} > <Icon type={'verticalRightOutlined'} /> </div> <div className={classnames([ styles.pagination_prevPageContainer, styles['pagination_prevPageContainer_' + type], { disabled: isFirstPage }, ])} onClick={() => handlePrevPage()} > <Icon type={'leftOutlined'} /> </div> <ul className={styles.pagination_pages}> {createPaginationItem(firstArr)} {pageCount > maxLength && current > Math.ceil(maxLength / 2) && ( <li className={styles.pagination_point}>...</li> )} {createPaginationItem(centerArr)} {pageCount > maxLength && current < pageCount - Math.floor(maxLength / 2) && ( <li className={styles.pagination_point}>...</li> )} {createPaginationItem(lastArr)} </ul> <div className={classnames([ styles.pagination_nextPageContainer, styles['pagination_nextPageContainer_' + type], { disabled: isLastPage }, ])} onClick={() => handleNextPage()} > <Icon type={'rightOutlined'} /> </div> <div className={classnames([ styles.pagination_nextLastPageContainer, styles['pagination_nextLastPageContainer_' + type], { disabled: isLastPage }, ])} onClick={() => handleNextList()} > <Icon type={'verticalLeftOutlined'} /> </div> </div> ); }; export default Pagination; /* <------------------------------------ **** FUNCTION COMPONENT END **** ------------------------------------ */
import { Order } from '../../src/types'; //Imports the order type from src folder. import products from './products'; // Imports the default export from products. import dayjs from 'dayjs'; //Imports the default export from dayjs const now = dayjs(); //assigns dayjs to a variable named now const orders: Order[] = [ //Assigns an array of orders to orders { id: 23123, //assigns an id number to order created_at: now.subtract(1, 'hour').toISOString(), //time the order was placed subtracted by an hour, it converts the time to ISO format total: 670.0, //total of the order status: 'Packing', //order status user_id: '1', //id of user who placed order order_items: [ //items that were ordered { id: 1, //id of item ordered order_id: 23123, //id of order being placed size: '10', //size of the item quantity: 2, //how many are being placed product_id: products[0].id, //gets the first item in the products array products: products[0], //assigns the products array to the first one. }, { id: 2, order_id: 23123, size: '9', quantity: 1, product_id: products[1].id, products: products[1], }, ], }, { id: 32145, created_at: now.subtract(3, 'days').toISOString(), //the day the order was created minus 3 days. Using ISO format total: 240.0, status: 'Delivered', user_id: '1', order_items: [ { id: 1, order_id: 32145, size: '10', quantity: 2, product_id: products[3].id, products: products[3], }, ], }, { id: 23445, created_at: now.subtract(3, 'weeks').toISOString(), //the day the order was created minus 3 weeks. Using ISO format total: 1480.0, status: 'Delivered', user_id: '1', order_items: [ { id: 1, order_id: 23445, size: '10', quantity: 1, product_id: products[3].id, products: products[3], }, { id: 2, order_id: 23445, size: '10', quantity: 1, product_id: products[7].id, products: products[7], }, { id: 3, order_id: 23445, size: '10', quantity: 1, product_id: products[8].id, products: products[8], }, ], }, ]; export default orders; //exports orders array as the default so other modules can call the function
import pandas as pd from prettytable import PrettyTable # Cargar el archivo Excel # Se asume que el archivo está en el mismo directorio que este script o se proporcionará la ruta completa. archivo_excel = "roque.xlsx" df = pd.read_excel(archivo_excel) # Auditoría # 1. Contar propiedades (filas) y comparar con un valor dado num_propiedades = len(df) # El valor a comparar se solicitará al usuario mediante input en el entorno real de ejecución valor_comparar = int(input("Ingrese el número de propiedades esperado: ")) comparacion = num_propiedades == valor_comparar # 2. Verificar si hay celdas vacías en "OWNER FULL NAME" owner_full_name_vacias = df['OWNER FULL NAME'].isnull().any() # 3. Verificar si hay celdas vacías en "ADDRESS" address_vacias = df['ADDRESS'].isnull().any() # 4. Verificar celdas con valor 0 en "SCORE" o "BUYBOX SCORE" score_cero = df['SCORE'].eq(0).any() buybox_score_cero = df['BUYBOX SCORE'].eq(0).any() # 5. Buscar tags prohibidos en "TAGS" tags_prohibidos = ['Liti', 'DNC', 'donotmail', 'Takeoff', 'Undeli', 'Return', 'Dead', 'Do Not Mail'] df['TAGS'] = df['TAGS'].fillna('') # Asegurarse de que no hay NaNs para evitar errores en la búsqueda tags_encontrados = any(df['TAGS'].str.contains('|'.join(tags_prohibidos), case=False, na=False)) # 6. Buscar valores específicos en "OWNER FULL NAME" valores_especificos = ['Given Not', 'Record', 'Available', 'Bank', 'Church', 'School', 'Cemetery', 'Not given', 'University', 'College', 'Owner', 'Hospital', 'County', 'City of'] valores_en_owner_full_name = any(df['OWNER FULL NAME'].str.contains('|'.join(valores_especificos), case=False, na=False)) # 7. Comparar "ADDRESS" con "MAILING ADDRESS" cuando "ABSENTEE" sea 1 o 2 absentee_condiciones = df[(df['ADDRESS'] == df['MAILING ADDRESS']) & df['ABSENTEE'].isin([1, 2])] # 8. Revisar "ACTION PLANS" para casos urgentes con "SCORE" menor a 585 casos_urgentes = df[(df['ACTION PLANS'].str.contains('urgent', case=False, na=False)) & (df['SCORE'] < 585)] # Análisis # 1. Tabla de "ACTION PLANS" tabla_action_plans = df['ACTION PLANS'].value_counts().reset_index() tabla_action_plans.columns = ['Action Plan', 'Frecuencia'] tabla_action_plans['Porcentaje'] = (tabla_action_plans['Frecuencia'] / num_propiedades) * 100 # 2. Tabla de "ESTIMATED MARKET VALUE" bins = [0, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000, float('inf')] labels = ['0-100k', '100k-200k', '200k-300k', '300k-400k', '400k-500k', '500k-600k', '600k-700k', '700k-800k', '800k-900k', '900k-1M', '1M+'] df['Market Value Range'] = pd.cut(df['ESTIMATED MARKET VALUE'], bins=bins, labels=labels, right=False) tabla_market_value = df['Market Value Range'].value_counts().sort_index().reset_index() tabla_market_value.columns = ['Market Value Range', 'Número de Propiedades'] tabla_market_value['Porcentaje'] = (tabla_market_value['Número de Propiedades'] / num_propiedades) * 100 # Resultados (Estos se adaptarían a print o retorno de valores según la necesidad) # Nota: La ejecución directa y la interacción con el usuario mediante input están comentadas dado que no se pueden ejecutar en este entorno. print(f"Comparación de cantidad de propiedades con valor ingresado: {comparacion}") print(f"Celdas vacías en 'OWNER FULL NAME': {'Sí' if owner_full_name_vacias else 'No'}") print(f"Celdas vacías en 'ADDRESS': {'Sí' if address_vacias else 'No'}") print(f"Celdas con valor 0 en 'SCORE' o 'BUYBOX SCORE': {'Sí' if score_cero or buybox_score_cero else 'No'}") print(f"Tags prohibidos encontrados en 'TAGS': {'Sí' if tags_encontrados else 'No'}") print(f"Valores específicos en 'OWNER FULL NAME': {'Sí' if valores_en_owner_full_name else 'No'}") print(f"Propiedades con 'ADDRESS' igual a 'MAILING ADDRESS' y 'ABSENTEE' 1 o 2: {'Sí' if not absentee_condiciones.empty else 'No'}") print(f"Casos urgentes con 'SCORE' menor a 585: {'Sí' if not casos_urgentes.empty else 'No'}") print(tabla_action_plans) print(tabla_market_value) import pandas as pd from prettytable import PrettyTable def formatear_numero(n): """Formatea el número con comas como separadores de miles.""" return "{:,.0f}".format(n).replace(",", ".") def formatear_porcentaje(p): """Formatea el porcentaje con dos decimales.""" return "{:.2f}%".format(p * 100) def calcular_acumulado(serie): """Calcula el porcentaje acumulado de una serie.""" return serie.cumsum() def analizar_y_presentar(df): total_props = len(df) # Análisis y presentación para ZIP print("Análisis de ZIP:") analizar_columna(df, 'ZIP', total_props) # Análisis y presentación para SCORE print("\nAnálisis de SCORE:") score_bins = range(0, 1001, 50) # Ajusta según sea necesario score_labels = [f"{i}-{i+49}" for i in score_bins[:-1]] df['SCORE Range'] = pd.cut(df['SCORE'], bins=score_bins, labels=score_labels, right=False) analizar_columna(df, 'SCORE Range', total_props, 'Rango de SCORE') # Análisis y presentación para PROPERTY TYPE print("\nAnálisis de PROPERTY TYPE:") analizar_columna(df, 'PROPERTY TYPE', total_props) def analizar_columna(df, columna, total_props, nombre_columna=None): if not nombre_columna: nombre_columna = columna tabla = PrettyTable() tabla.field_names = [nombre_columna, "Número de Propiedades", "Porcentaje", "Acumulado"] counts = df[columna].value_counts().sort_index() porcentajes = counts / total_props acumulado = calcular_acumulado(porcentajes) for valor, count in counts.items(): porcentaje = porcentajes[valor] acum = acumulado[valor] tabla.add_row([valor, formatear_numero(count), formatear_porcentaje(porcentaje), formatear_porcentaje(acum)]) print(tabla) # Supongamos que df es tu DataFrame cargado de 'roque.xlsx' analizar_y_presentar(df)
@extends('layouts.adminMain') @section('content') <div class="content-wrapper"> <section class="content"> <div class="container-fluid"> @if ($message=Session::get('success')) <div class="alert-success alert-block"> <button type="button" class="close" data-dismiss="alert"></button> <strong>{{$message}}</strong> </div> @endif <div class="row"> <div class="col-12"> <h1 class="m-0">Orders</h1> <hr> <table class="table table-bordered"> <thead> <tr> <th>Id</th> <th>Name</th> <th>country</th> <th>address</th> <th>mobile</th> <th>total</th> <th>payment</th> <th>ordered at</th> <th>status</th> <th colspan="2">Actions</th> </tr> </thead> <tbody> @foreach ($orders as $order) <tr> <td>{{ $order['id'] }}</td> <td><a href="{{url('admin/orders/'.$order['id'])}}"><u>{{ $order['first_name'] }} {{ $order['last_name'] }}</u></a></td> <td>{{ $order['country'] }}</td> <td>{{ $order['address1'] }}</td> <td>{{ $order['mobile'] }}</td> <td>{{ $order['total'] }}</td> <td>{{ $order['payment'] }}</td> <td>{{ $order['created_at'] }}</td> <td>{{ $order['status'] }}</td> <td scope="col"> <a class="btn btn-success" href="{{url('admin/orders/'.$order['id'].'/edit')}}"> <h6>Edit status/products</h6></a> </td> <td scope="col"> <form action="{{url('admin/orders/'.$order['id'])}}" method="post"> @method('DELETE') @csrf <button class="btn btn-danger" onclick="return confirm('Are you sure ?');"> <h6 class="fa fa-trash text-white"></h6> </button> </form> </td> </tr> @endforeach </tbody> </table> {!! $orders->links() !!} </div> </div> </div> </section> </div>
import React, { useState, useEffect, useRef } from "react"; import { RadioGroup, Tab } from "@headlessui/react"; import { useParams } from "react-router-dom"; import classNames from "classnames"; import { createOrder, getProductBySlug } from "api"; import { Color, Product, User } from "types"; import ProductImage from "components/ProductImage"; import CardInfoSection from "components/CardInfoSection"; import { downloadImage, getImageBlog } from "utils/cardImage"; const ProductDetail: React.FC = () => { const { productSlug } = useParams(); const [product, setProduct] = useState<Product>(); const [selectedImageIndex, setSelectedImageIndex] = useState<number>(0); const [selectedColor, setSelectedColor] = useState<Color>(); const [userData, setUserData] = useState<User | undefined>(); const frontCardRef = useRef(null); const backCardRef = useRef(null); const isProductCard = product && product.isProductCard; const handleGetProduct = async (slug?: string) => { if (slug) { const product = await getProductBySlug(slug); if (product) { setProduct(product); setSelectedColor(product.colors[0]); } } }; const downloadDesign = () => { if (frontCardRef.current) { downloadImage(frontCardRef.current, "front.png"); } if (backCardRef.current) { downloadImage(backCardRef.current, "back.png"); } }; const handleCreateOrder = async (e: any) => { e.preventDefault(); try { const metadata = {} as any; let files = [] as any if (isProductCard) { if (backCardRef.current) { files = [await getImageBlog(backCardRef?.current)]; } else { await setSelectedImageIndex(1) files.push(await getImageBlog(backCardRef?.current)) } } else { metadata.color = selectedColor?.name; } if (product) { const order = { metadata, productId: product.id, }; await createOrder(order, files); } } catch (e) { console.error(e); } }; useEffect(() => { handleGetProduct(productSlug); }, [productSlug]); if (!product) { return <p>Loading</p>; } return ( <div className="bg-white"> <div className="mx-auto max-w-2xl py-16 px-4 sm:py-24 sm:px-6 lg:max-w-7xl lg:px-8"> <div className="lg:grid lg:grid-cols-2 lg:items-start lg:gap-x-8"> {/* Image gallery */} <Tab.Group as="div" className="flex flex-col-reverse" selectedIndex={selectedImageIndex} // @ts-ignore onChange={setSelectedImageIndex} > {/* Image selector */} <div className="mx-auto mt-6 hidden w-full max-w-2xl sm:block lg:max-w-none"> <Tab.List className="grid grid-cols-4 gap-6"> {product.images.map((image) => ( <Tab key={image.src} className="relative flex h-24 cursor-pointer items-center justify-center rounded-md bg-white text-sm font-medium uppercase text-gray-900 hover:bg-gray-50 focus:outline-none focus:ring focus:ring-opacity-50 focus:ring-offset-4" > {({ selected }) => ( <> <span className="sr-only"> {image.name} </span> <span className="absolute inset-0 overflow-hidden rounded-md"> <img src={image.src} alt="" className="h-full w-full object-cover object-center" /> </span> <span className={classNames( selected ? "ring-indigo-500" : "ring-transparent", "pointer-events-none absolute inset-0 rounded-md ring-2 ring-offset-2" )} aria-hidden="true" /> </> )} </Tab> ))} </Tab.List> </div> <Tab.Panels className="aspect-w-1 aspect-h-1 w-full"> {product.images.map((image) => ( <Tab.Panel key={image.id}> <ProductImage previewRef={image.isFront ? frontCardRef : backCardRef} image={image} userData={userData} showUserData={!image.isFront} /> </Tab.Panel> ))} </Tab.Panels> </Tab.Group> <div className="mt-10 px-4 sm:mt-16 sm:px-0 lg:mt-0"> <h1 className="text-3xl font-bold tracking-tight text-gray-900"> {product.name} </h1> <div className="mt-3"> <h2 className="sr-only">Product information</h2> <p className="text-3xl tracking-tight text-gray-900"> ${product.price} </p> </div> <div className="mt-6"> <h3 className="sr-only">Description</h3> <div className="space-y-6 text-base text-gray-700" dangerouslySetInnerHTML={{ __html: product.description }} /> </div> <form className="mt-6"> {/* Colors */} <div> {(product.colors || []).length > 0 && ( <h3 className="text-sm text-gray-600">Color</h3> )} <RadioGroup value={selectedColor} onChange={setSelectedColor} className="mt-2" > <span className="flex items-center space-x-3"> {product.colors.map((color) => { return ( <RadioGroup.Option key={color.name} value={color} className={({ active, checked }) => classNames( color.selectedColor, active && checked ? "ring ring-offset-1" : "", !active && checked ? "ring-2" : "", "-m-0.5 relative p-0.5 rounded-full flex items-center justify-center cursor-pointer focus:outline-none" ) } > <span aria-hidden="true" className={classNames( color.bgColor ? color.bgColor : "bg-black", "h-8 w-8 border border-black border-opacity-10 rounded-full" )} /> </RadioGroup.Option> ); })} </span> </RadioGroup> </div> {isProductCard && ( <CardInfoSection userData={userData} setUserData={setUserData} downloadDesign={downloadDesign} /> )} <div className="sm:flex-col1 mt-10 flex justify-between"> <button onClick={(e) => handleCreateOrder(e)} className="flex max-w-xs flex-1 items-center justify-center rounded-md border border-transparent bg-indigo-600 py-3 px-8 text-base font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-gray-50 sm:w-full" > Order </button> </div> <div className="sm:flex-col1 mt-10 flex"></div> </form> </div> </div> </div> </div> ); }; export default ProductDetail;
import React, { useState, useRef } from 'react'; import { useSelector } from 'react-redux'; import { format, parseISO } from 'date-fns'; import translate, { dateLanguage } from '../../locales'; import { unformatNumber, formatPhone, formatCPF } from '../../util/format'; import { SubmitButton, Input, GenderContainer, ButtonContainer, GenderLabel, TextButton, TextButtonText, DateInput, } from './styles'; import { handleChangeText, handleBlur, handleSubmit, } from '../validation/validations/profileValidation'; export default function ProfileForm({ handleFormSubmit, loading }) { const profile = useSelector(state => state.user.profile); const [fieldErrors, setFieldErrors] = useState({}); const [touched, setTouched] = useState({}); const [form, setForm] = useState({ name: profile.name, phone: formatPhone(profile.phone), email: profile.email, oldPassword: '', password: '', passwordConfirmation: '', }); const phoneRef = useRef(); const emailRef = useRef(); const oldPasswordRef = useRef(); const passwordRef = useRef(); const passwordConfirmationRef = useRef(); async function onChangeText(id, value) { const { errors, text } = await handleChangeText(form, id, value); if (errors) { setFieldErrors(errors); } else { if (id === 'oldPassword') { const { oldPassword, password, ...rest } = fieldErrors; setFieldErrors(rest); } else if (id === 'password') { const { password, passwordConfirmation, ...rest } = fieldErrors; setFieldErrors(rest); } else { const { [id]: _, ...rest } = fieldErrors; setFieldErrors(rest); } } setForm({ ...form, [id]: text }); } async function onBlur(id) { if (!touched[id]) { setTouched({ ...touched, [id]: true }); const errors = await handleBlur(form); if (errors) { console.log(errors) setFieldErrors(errors); } else { const { [id]: _, ...rest } = fieldErrors; setFieldErrors(rest); } } } async function onSubmit() { const errors = await handleSubmit(form); if (!errors) { handleFormSubmit({ ...form, phone: unformatNumber(form.phone), }); } else { let alltouched; Object.keys(errors).forEach( key => (alltouched = { ...alltouched, [key]: true }), ); setTouched(alltouched); setFieldErrors(errors); } } return ( <> <Input icon="user" placeholder="First name" autoCorrect={false} autoCapitalize="words" onChangeText={text => onChangeText('name', text)} onBlur={() => onBlur('name')} value={form.name} returnKeyType="next" onSubmitEditing={() => phoneRef.current.focus()} error={fieldErrors.name && touched.name && fieldErrors.name} /> <Input icon="phone" placeholder="Phone" ref={phoneRef} keyboardType="phone-pad" maxLength={15} autoCorrect={false} onChangeText={text => onChangeText('phone', text)} onBlur={() => onBlur('phone')} value={form.phone} returnKeyType="next" onSubmitEditing={() => emailRef.current.focus()} error={fieldErrors.phone && touched.phone && fieldErrors.phone} /> <Input icon="envelope" placeholder="Email" ref={emailRef} autoCorrect={false} onChangeText={text => onChangeText('email', text)} onBlur={() => onBlur('email')} value={form.email} returnKeyType="next" onSubmitEditing={() => oldPasswordRef.current.focus()} error={fieldErrors.email && touched.email && fieldErrors.email} /> <Input icon="lock" secureTextEntry placeholder="Enter your password" ref={oldPasswordRef} onChangeText={text => onChangeText('oldPassword', text)} onBlur={() => onBlur('oldPassword')} value={form.oldPassword} returnKeyType="next" onSubmitEditing={() => passwordRef.current.focus()} error={ fieldErrors.oldPassword && touched.oldPassword && fieldErrors.oldPassword } /> <Input icon="lock" secureTextEntry placeholder="Enter your new password" ref={passwordRef} onChangeText={text => onChangeText('password', text)} onBlur={() => onBlur('password')} value={form.password} returnKeyType="next" onSubmitEditing={() => passwordConfirmationRef.current.focus()} error={fieldErrors.password && touched.password && fieldErrors.password} /> <Input icon="lock" secureTextEntry placeholder="Confirm the password" ref={passwordConfirmationRef} onChangeText={text => onChangeText('passwordConfirmation', text)} onBlur={() => onBlur('passwordConfirmation')} value={form.passwordConfirmation} returnKeyType="send" onSubmitEditing={handleFormSubmit} error={ fieldErrors.passwordConfirmation && touched.passwordConfirmation && fieldErrors.passwordConfirmation } /> <SubmitButton onPress={onSubmit} loading={loading}> Save </SubmitButton> </> ); }
import time def decorator_time(fn): def wrapper(*args): print(fn) t0 = time.time() for i in range(100): result = fn(*args) dt = (time.time() - t0) / 100 print(f"Delta time: {dt:.10f}") return result return wrapper def power(n=2): return 10_000_000 ** n def in_build_pow(): return pow(10_000_000, 100) power = decorator_time(power) in_build_pow = decorator_time(in_build_pow) #print(power()) #in_build_pow def counter(func): count = 0 def wrapper(*args, **kwargs): nonlocal count count += 1 print(f"Function was called {count} times") return func(*args, **kwargs) return wrapper @counter def big_letters(word: str) -> str: return word.upper() #print(big_letters("hello")) #print(big_letters("bye")) #print(big_letters("see you soon")) def save_in_dict(func): dct = dict() def wrapper(n): nonlocal dct result = dct.setdefault(n, func(n)) print(f"Function was called witn {n}") print(dct) return result return wrapper @save_in_dict def f(n): return n * 123456789 print(f(5)) print(f(3)) print(f(1)) print(f(0)) print(f(5))
const { ObjectId } = require("mongodb"); class CartService { constructor(client) { this.Cart = client.db().collection("carts"); this.Account = client.db().collection("accounts"); this.Product = client.db().collection("products"); } extractCartData(payload) { const cart = { account_id: payload.account_id, product_list:[ { prod_id: payload.product_list[0].prod_id, prod_name: payload.product_list[0].prod_name, prod_price: payload.product_list[0].prod_price, prod_img: payload.product_list[0].prod_img, prod_num: payload.product_list[0].prod_num, } ], }; //Remove undefined fields Object.keys(cart).forEach( (key) => cart[key] === undefined && delete cart[key] ); return cart; } async create(payload) { const cart = this.extractCartData(payload); const cursor = await this.Cart.findOne({ "account_id": cart.account_id }); console.log(cursor) if(cursor == null){ const result = await this.Cart.insertOne(cart); console.log(result.value) return result.value; } else { const aval = await this.Cart.findOne({"account_id":cart.account_id,"product_list.prod_id":cart.product_list[0].prod_id}) // console.log(aval) const tmp = await this.Cart.aggregate([ {$unwind : '$product_list'}, {$match: { 'product_list.prod_id': cart.product_list[0].prod_id, "account_id":cart.account_id } }, ]).toArray(); console.log(tmp) if(aval == null){ const result = await this.Cart.updateOne( { "account_id": cart.account_id }, { $push: { product_list: cart.product_list[0] } } ) return result.value; } else { const result = await this.Cart.updateOne( { "account_id":aval.account_id, }, { $set: { "product_list.$[elem].prod_num": cart.product_list[0].prod_num + tmp[0].product_list.prod_num }}, { arrayFilters: [ { "elem.prod_id": cart.product_list[0].prod_id } ]} ) console.log(result.value) return result.value; } } } async find(filter) { const cursor = await this.Cart.find(filter); return await cursor.toArray(); } async findByUserId(userid) { // console.log(userid) const result = await this.Cart.findOne({ "account_id": userid }); return result; } async findByAdress(address) { return await this.find({ address: { $regex: new RegExp(address), $options: "i"}, }); } async findById(id) { return await this.Cart.findOne({ _id: ObjectId.isValid(id) ? new ObjectId(id) : null, }); } async update(id, payload) { const filter = { _id: ObjectId.isValid(id) ? new ObjectId(id) : null, }; const result = await this.Cart.findOneAndUpdate( filter, { $set: payload}, { returnDocument: "after"} ); return result.value; } async delete(id) { const result = await this.Cart.findOneAndDelete({ _id: ObjectId.isValid(id) ? new ObjectId(id) : null, }); return result.value; } async deleteAllProduct(user_id){ const result = await this.Cart.updateOne( { "account_id": user_id }, { $set: { product_list: [] } } ); return result.value; } async deleteProduct(id,product_id) { const filter = await this.Cart.findOne({ _id: ObjectId.isValid(id) ? new ObjectId(id) : null, }); const update = [] for (let i = 0; i < filter.product_list.length; i++){ if(filter.product_list[i].prod_id != product_id){ update.push(filter.product_list[i]) } } // console.log(filter) const result = await this.Cart.updateOne( { "account_id": filter.account_id }, { $set: { product_list: update } }); console.log("555555555555") console.log(result.value) return result.value; } } module.exports = CartService;
import { expect, describe,it, beforeEach} from 'vitest' import { hash } from 'bcryptjs'; import { inMemoryRepository } from '@/repositories/in-memory/in-memory-users-repository'; import { GetUserProfileUseCase } from './getUserProfileUseCase'; import { ResourceNotFoundError } from './errors/resource-not-found-error'; let userRepository: inMemoryRepository; let sut: GetUserProfileUseCase; describe('Get User Profile Use Case', () => { beforeEach(()=>{ userRepository = new inMemoryRepository(); sut = new GetUserProfileUseCase(userRepository); }); it('should be able to get user profile', async () => { const createdUser = await userRepository.create( { name: 'John Doe', email: 'john@john.com', password_hash: await hash('123456', 6), } ); const {user} = await sut.execute({ userId: createdUser.id }); // expect(user.id).toEqual(expect.any(String)); expect(user.name).toEqual('John Doe'); }); it('should not be able to get user profile with wrong id', async () => { expect(() => sut.execute({ userId:'wrong-id' })).rejects.toBeInstanceOf(ResourceNotFoundError); }); });
package { import flash.display.MovieClip; import flash.display.Bitmap; import flash.display.BitmapData; import flash.geom.Point; import flash.geom.Rectangle; public class Test extends MovieClip { public function Test() { var bmd: BitmapData = createImage(); var otherBmd: BitmapData = createImage(); var bitmap: Bitmap = new Bitmap(bmd); // Testing bmd against bmd, aligns both images so both points overlap and checks for any opaque overlap trace("/// hitTest with bmd"); test(bmd, new Point(0, 0), 0, bmd, new Point(0, 0), 0); test(bmd, new Point(1, 1), 0xFF, bmd, new Point(3, 3), 0xA0); test(bmd, new Point(2, 1), 0xA0, bmd, new Point(1, 3), 0xA0); test(bmd, new Point(3, 1), 0xA0, bmd, new Point(1, 2), 0xFF); test(bmd, new Point(0, 0), 0xA0, bmd, new Point(1, 0), 0xFF); test(bmd, new Point(1, 1), 0xFF, bmd, new Point(1, 1), 0xFF); test(bmd, new Point(-1, -1), 0xA0, bmd, new Point(1, 1), 0xA0); trace(""); trace("/// hitTest with other bmd"); test(bmd, new Point(0, 0), 0, otherBmd, new Point(0, 0), 0); test(bmd, new Point(1, 1), 0xFF, otherBmd, new Point(3, 3), 0xA0); test(bmd, new Point(2, 1), 0xA0, otherBmd, new Point(1, 3), 0xA0); test(bmd, new Point(3, 1), 0xA0, otherBmd, new Point(1, 2), 0xFF); test(bmd, new Point(0, 0), 0xA0, otherBmd, new Point(1, 0), 0xFF); test(bmd, new Point(1, 1), 0xFF, otherBmd, new Point(1, 1), 0xFF); trace(""); // Testing bmd against bitmap, same as above trace("/// hitTest with bitmap"); test(bmd, new Point(0, 0), 0, bitmap, new Point(0, 0), 0); test(bmd, new Point(1, 1), 0xFF, bitmap, new Point(3, 3), 0xA0); test(bmd, new Point(2, 1), 0xA0, bitmap, new Point(1, 3), 0xA0); test(bmd, new Point(3, 1), 0xA0, bitmap, new Point(1, 2), 0xFF); trace(""); // Testing bmd against rect, offsets the rect by -firstPoint and then looks for any opaque pixel inside rect trace("/// hitTest with rect"); test(bmd, new Point(0, 0), 0xA0, new Rectangle(2, 2, 2, 2)); test(bmd, new Point(0, 0), 0xFF, new Rectangle(0, 0, 3, 4)); test(bmd, new Point(0, 0), 0xFF, new Rectangle(2, 2, 1, 1)); test(bmd, new Point(2, 2), 0xFF, new Rectangle(4, 4, 1, 1)); test(bmd, new Point(-1, 0), 0xA0, new Rectangle(2, 2, 5, 5)); test(bmd, new Point(-10, 10), 0x00, new Rectangle(0, 0, 1, 1)); trace(""); // Testing bmd against point, offsets the point by -firstPoint and then checks if that pixel is opaque trace("/// hitTest with point"); test(bmd, new Point(0, 0), 0xA0, new Point(2, 2)); test(bmd, new Point(0, 0), 0xFF, new Point(0, 0)); test(bmd, new Point(0, 0), 0xFF, new Point(2, 2)); test(bmd, new Point(2, 2), 0xFF, new Point(4, 4)); test(bmd, new Point(3, 3), 0xFF, new Point(-1, -1)); test(bmd, new Point(-1, -1), 0xA0, new Point(2, 2)); test(bmd, new Point(-1, -1), 0xA0, new Point(0, 0)); test(bmd, new Point(-10, -10), 0x00, new Point(0, 0)); trace(""); trace("/// Error cases") try { test(bmd, new Point(0, 0), 0x00, bmd, null); } catch (error: Error) { trace("- Error " + error.errorID); } try { test(bmd, new Point(0, 0), 0x00, {}); } catch (error: Error) { trace("- Error " + error.errorID); } } // BMD looks like: ('-' is no alpha, 'x' is 0xA0, 'X' is 0xFF) /* 0 1 2 3 4 * 0 - - - - - * 1 - x x x - * 2 - x X x - * 3 - x x x - * 4 - - - - - */ function createImage():BitmapData { var bmd: BitmapData = new BitmapData(5, 5, true, 0); for (var x = 1; x <= 3; x++) { for (var y = 1; y <= 3; y++) { bmd.setPixel32(x, y, 0xA0FFFFFF); } } bmd.setPixel32(2, 2, 0xFFFFFFFF); return bmd; } function formatPoint(point: Point): String { if (point) { return "new Point(" + point.x + ", " + point.y + ")"; } else { return "null"; } } function formatRectangle(rect: Rectangle): String { if (rect) { return "new Rectangle(" + rect.x + ", " + rect.y + ", " + rect.width + ", " + rect.height + ")"; } else { return "null"; } } function formatObject(bmd: BitmapData, object: Object): String { if (object === bmd) { return "bmd"; } else if (object is Point) { return formatPoint(object as Point); } else if (object is Rectangle) { return formatRectangle(object as Rectangle); } else if (object is BitmapData) { return "otherBitmapData"; } else if (object is Bitmap) { return "otherBitmap"; } else if (object === null) { return "null"; } else { return "{}"; } } function test(bmd: BitmapData, firstPoint:Point, firstAlphaThreshold:uint, secondObject:Object, secondBitmapDataPoint:Point = null, secondAlphaThreshold:uint = 1) { trace("// bmd.hitTest(" + formatPoint(firstPoint) + ", " + firstAlphaThreshold + ", " + formatObject(bmd, secondObject) + ", " + formatPoint(secondBitmapDataPoint) + ", " + secondAlphaThreshold + ")"); trace(bmd.hitTest(firstPoint, firstAlphaThreshold, secondObject, secondBitmapDataPoint, secondAlphaThreshold)); trace(""); } } }
--- title: Kotlin 和基于令牌的身份验证:高级主题和最佳实践 description: published: true date: 2023-01-31T03:36:19.502Z tags: editor: markdown dateCreated: 2023-01-31T03:36:17.908Z --- > 本文已使用 **Google Cloud Translation API 自动翻译**。 某些文档最好以原文阅读。{.is-info} - [Kotlin and Token-based Authentication: Advanced Topics and Best Practices***English** version of this document is available*](/en/Knowledge-base/Kotlin/kotlin-and-token-based-authentication-advanced-topics-and-best-practices) {.links-list} # 介绍 Kotlin 是一种具有类型干扰的静态类型通用编程语言。它旨在与 Java 互操作,并且可以在 Java 虚拟机 (JVM) 上运行。 Kotlin 是 Apache 2.0 许可下的开源项目。 基于令牌的身份验证是用户提供令牌(通常以文本字符串的形式)的过程,然后使用该令牌来验证其身份。使用基于令牌的身份验证有很多优势,我们将在本文中讨论这些优势。此外,我们将提供一些在 Kotlin 中实现基于令牌的身份验证的技巧和最佳实践。 # 基于令牌的身份验证的优点 使用基于令牌的身份验证有许多优点: - **代币是无状态的**。这意味着它们可以轻松扩展,因为无需跟踪哪个用户与哪个令牌相关联。此外,它使它们更安全,因为无需在令牌本身中存储任何敏感信息。 - **令牌比传统的身份验证方法更易于使用**。例如,如果您使用令牌对网站上的用户进行身份验证,他们只需在登录时提供令牌即可。他们无需记住用户名和密码。 - **令牌可以很容易地撤销**。如果用户的令牌被泄露,它可以简单地被撤销并颁发一个新的。无需更改密码或采取任何其他操作。 # 在 Kotlin 中实现基于令牌的身份验证的技巧 在 Kotlin 中实现基于令牌的身份验证时,需要牢记以下几点: - **使用安全的随机数生成器生成令牌**。这将有助于确保代币真正随机且不可预测。 - **确保令牌已正确编码**。这将有助于防止任何潜在的安全问题。 - **确保令牌已正确验证**。这包括验证令牌的签名并确保它未被篡改。 - **确保正确存储令牌**。这包括将它们存储在安全位置并确保它们被正确加密。 # 结论 在本文中,我们讨论了基于令牌的身份验证的优势,并提供了一些在 Kotlin 中实现它的技巧。基于令牌的身份验证是一种安全有效的用户身份验证方法,我们希望本文对理解其工作原理有所帮助。
using Code420.UIOrchestrator.Server.Components.BaseComponents.IconButtonBase; using Code420.UIOrchestrator.Server.Components.BaseComponents.ToolTipBase; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using Syncfusion.Blazor.Popups; namespace Code420.UIOrchestrator.Server.Components.CompositeComponents.HelpButton { /// <summary> /// <para> /// Composite component consisting of an <see cref="IconButtonBase"/> component /// and a <see cref="ToolTipBase"/> component. /// </para> /// <para> /// The help button is displayed in the parent container and when hovered, /// the tooltip is displayed. The component can be used as-is but is typically /// used by topic-specific Help System components. /// </para> /// <para> /// Styling for the child components should be consistent across the application. /// For this reason the styling is hard-coded in the component though should /// reference theming elements as appropriate. /// </para> /// <para> /// The styling for the <see cref="TooltipContent"/> should be defined in the /// consuming component since the content is specific to the consuming component. /// </para> /// <para> /// The <see cref="CssClass"/> parameter is provided to mitigate styling conflicts /// in the situation when the consuming component also contains one of this component's /// children (e.g., <see cref="IconButtonBase"/>). The suffixes <c>__button</c> and /// <c>__tooltip</c> are added to the CSSClass parameters for the <see cref="IconButtonBase"/> /// and <see cref="ToolTipBase"/> child components, respectively. /// </para> /// <para> /// The component does not provide access to any event handlers for the child component. /// </para> /// <para> /// Methods are provided for basic manipulation of the child components /// (e.g., <see cref="OpenTooltipAsync"/> and <see cref="EnableIconButtonAsync"/>). /// </para> /// </summary> /// <remarks> /// The following parameters must be set:<br /> /// <see cref="TooltipContent"/> -- Define the content displayed in the tooltip<br /> /// </remarks> /// <remarks> /// Consider setting the following parameters:<br /> /// <see cref="CssClass"/> -- Provides CSS isolation for the toast. /// </remarks> public partial class HelpButton : ComponentBase { #region Component Parameters #region Base Parameters /// <summary> /// Boolean value indicating if the help button is disabled. /// Default value is false. /// </summary> [Parameter] public bool ButtonDisabled { get; set; } /// <summary> /// Contains the <see cref="RenderFragment" /> composing the tooltip contents. /// This parameter is required. /// </summary> [Parameter] [EditorRequired] public RenderFragment TooltipContent { get; set; } #endregion #region CSS Parameters /// <summary> /// String value containing CSS class definition(s) that will be injected in the HTML. /// Injecting a class will provide styling segregation when multiple icon buttons are /// on the same page. /// Default value is <c>help-button</c>. /// </summary> /// <remarks> /// The parameter is provided to mitigate styling conflicts in the situation when the /// consuming component also contains one of this component's children /// (e.g., <see cref="IconButtonBase"/>). The suffixes <c>__button</c> and /// <c>__tooltip</c> are added to the CSSClass parameters for the <see cref="IconButtonBase"/> /// and <see cref="ToolTipBase"/> child components, respectively. /// </remarks> [Parameter] public string CssClass { get; set; } = "help-button"; /// <summary> /// String containing the CSS <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/margin">margin</a> /// value used for the help button. /// The margin CSS shorthand property sets the margin area on all four sides of an element. /// Default value is: <c>0px</c> on all sides. /// </summary> [Parameter] public string ButtonMargin { get; set; } = "0px"; /// <summary> /// String containing the CSS <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/padding">padding</a> /// value used for the help button. /// The padding CSS shorthand property sets the padding area on all four sides of an element at once. /// Default value is: <c>0px</c> on all sides. /// </summary> [Parameter] public string ButtonPadding { get; set; } = "0px"; /// <summary> /// String value specifying the CSS height value of the Tooltip. /// When the Tooltip content gets overflowed due to the height value, /// then the scroll mode will be enabled. When set to auto, the Tooltip /// height gets auto adjusted to display its content within the viewable screen. /// Default value is <c>auto</c>. /// </summary> [Parameter] public string TooltipHeight { get; set; } = "auto"; /// <summary> /// String value specifying the CSS width value of the Tooltip. /// When set to <c>auto</c>, the Tooltip width gets auto adjusted to display its content /// within the viewable screen. /// Default value is <c>auto</c>. /// </summary> [Parameter] public string TooltipWidth { get; set; } = "auto"; #endregion #endregion #region Instance Variables private IconButtonBase helpIconButton; private ToolTipBase tooltipBase; #endregion #region Public Methods Providing Access to the Underlying Components to the Consumer #region Public Methods for the TooltipBase /// <summary> /// Used to hide the Tooltip with a specific animation effect. /// </summary> /// <param name="animation"> /// <see cref="Syncfusion.Blazor.Popups.TooltipAnimationSettings"/> settings for /// tooltip close action. /// </param> public async Task CloseTooltipAsync(TooltipAnimationSettings animation = null) => await tooltipBase.CloseAsync(animation); /// <summary> /// Used to show the Tooltip on the specified target with specific animation settings. /// You can also pass the additional arguments like target element in which the tooltip /// should appear and animation settings for the tooltip open action. /// </summary> /// <param name="element"> /// Target element in which the tooltip should appear. /// </param> /// <param name="animation"> /// <see cref="Syncfusion.Blazor.Popups.AnimationModel"/> settings for the tooltip open action. /// </param> public async Task OpenTooltipAsync(ElementReference? element = null, TooltipAnimationSettings animation = null) => await tooltipBase.OpenAsync(element, animation); /// <summary> /// Refresh the tooltip component when the target element is dynamically used. /// </summary> public async Task RefreshTooltipAsync() => await tooltipBase.RefreshAsync(); /// <summary> /// Dynamically refreshes the tooltip element position based on the target element. /// </summary> /// <param name="target"> /// The target element. /// </param> public async Task RefreshTooltipPositionAsync(ElementReference? target = null) => await tooltipBase.RefreshPositionAsync(target); #endregion #region Public Methods for IconButtonBase /// <summary> /// Set icon button state to enabled. /// </summary> public async Task EnableIconButtonAsync() => await helpIconButton.EnableAsync(); /// <summary> /// Set icon button state to disabled. /// </summary> public async Task DisableIconButtonAsync() => await helpIconButton.DisableAsync(); /// <summary> /// Set focus to the icon button. /// </summary> public async Task FocusIconButtonAsync() => await helpIconButton.FocusAsync(); /// <summary> /// /// </summary> /// <returns> /// Boolean value containing the current setting of the /// <see cref="ToolTipBase.IsSticky"/> parameter. /// </returns> public bool IsTooltipSticky() => tooltipBase.IsSticky; #endregion #endregion } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0,viewport-fit:cover"> <title>相册</title> <style> * {margin: 0;padding:0} ul { list-style: none; } html,body,#app { width: 100%; height: 100%; overflow: hidden; } #header { position: fixed; top: 0; left: 0; z-index:5; width: 100vw; height: 10vh; background: rgba(0,0,0,.8); color: #fff; text-align: center; line-height: 10vh; } #header h1 { font-size: 20px; font-weight: normal; } .album-list { display: flex; flex-wrap: wrap; justify-content: space-around; padding-top: 10vh; } .album-list li { margin: 3vw 0; width: 44vw; height: 44vw; background: url(img/loadingImg.gif) no-repeat center center; } .album-list li img { display: block; width: 100%; height:100%; border-radius: 3vw; opacity: 0; transition: opacity .3s; } .album-footer { position: absolute; bottom: -20vh; width: 100vw; height: 20vh; font: 16px/20vh 'Microsoft YaHei'; text-align: center; opacity: 0; transition: opacity 1s; } #scrollBar { position: absolute; right: 0; top: 0; width: 4px; border-radius: 2px; background-color: deeppink; } #bigImage { position: absolute; left: 0; top: 0; z-index: 10; width: 100vw; height: 100vh; background: #eee; transform: scale(0); transition: transform 1s; } .bigimage-header { position: relative; width: 100vw; height: 10vh; background: rgba(0,0,0,.8); color: #fff; text-align: center; line-height: 10vh; } .bigimage-header h2 { font-size: 20px; font-weight: normal; } #bigImage img { display: block; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; width: 80vw; height: 80vw; } .close-btn { position: absolute; right: 10px; top: 0; bottom: 0; margin-top: auto; margin-bottom: auto; width: 40px; height: 40px; text-align: center; line-height: 40px; font-size: 30px; } </style> </head> <body> <div id="app"> <header id="header"> <h1>三国女将</h1> </header> <ul class="album-list"> <div class="album-footer">上滑加载</div> </ul> <div id="scrollBar"></div> <div id="bigImage"> <header class="bigimage-header"> <h2>大图预览</h2> <span class="close-btn">&times;</span> </header> <img src="img/1.jpg" alt="大图"> </div> </div> <script src="js/transformcss.js"></script> <script src="js/gesture.js"></script> <script src="js/touchscroll.js"></script> <script> (function () { //阻止默认事件 var app = document.querySelector('#app'); app.addEventListener('touchstart', function (event) { event.preventDefault(); }); //获取元素 var albumList = document.querySelector('.album-list'); var albumFooter = document.querySelector('.album-footer'); var scrollBar = document.querySelector('#scrollBar'); var bigImageNode = document.querySelector('#bigImage'); var bigImage = bigImageNode.querySelector('img'); var closeBtn = bigImageNode.querySelector('.close-btn'); var isCompleted = false; //标记数据是否加载完毕 var isMove = false; //标记触点有没有移动 // 定义数组,存储所有的图片信息 var imageData = []; for (var i = 0; i < 40; i ++) { imageData.push((i%18+1)+'.jpg'); } //定义加载图片的初始索引 var start = 0; // 定义每次加载的图片数量 var length = 12; // 加载第一波数据 createAlbumItem(); // 设置页面可以滑动 touchscroll(app, albumList, scrollBar, { start: function(){ isMove = false; //表示还没有移动 }, move: function(){ //标记发生了移动 isMove = true; //懒加载判断 lazyLoad(); // 如果到达临界点 上划加载显示 if (transformCss(albumList, 'translateY') < app.clientHeight - albumList.offsetHeight) { albumFooter.style.opacity = 1; } }, end: function(){ //隐藏上划提示文字 albumFooter.style.opacity = 0; // 数据是否是加载完毕的 if (isCompleted) { albumFooter.innerText = '你已经到底了'; return; } // 如果到达临界点 加载新的数据 if (transformCss(albumList, 'translateY') < app.clientHeight - albumList.offsetHeight) { // 加载数据 createAlbumItem(); // 停止回弹过渡的定时器 clearInterval(albumList.intervalId); // 加载完数据,计算滚动条的高度 albumList.sliderScale = app.clientHeight / albumList.offsetHeight; scrollBar.style.height = app.clientHeight * albumList.sliderScale + 'px'; } } }); // 点击每个相册元素 li 展开大图预览 使用事件委派 // 保证新增的相册图片,也可以点击放大 albumList.addEventListener('touchend', function (event) { // 判断只有点击的元素是 li的时候。才执行逻辑 if (event.target.nodeName !== 'IMG') { return; } //如果手指移动了,不执行当前的逻辑了 if (isMove) { return; } //设置大图图片 bigImage.src = event.target.src; // 设置变换的原点 以每个小图的中心 var x = event.target.getBoundingClientRect().left + event.target.offsetWidth/2; var y = event.target.getBoundingClientRect().top + event.target.offsetHeight/2; bigImageNode.style.transformOrigin = x+'px '+y+'px'; // 大图显示 transformCss(bigImageNode, 'scale', 1); // 让大图缩放比例和旋转恢复默认 transformCss(bigImage, 'scale', 1); transformCss(bigImage, 'rotate', 0); }); //大图缩放和旋转 // gesture(bigImage, { // start: function(){ // //获取当下旋转角度和缩放比例 // bigImage.startScale = transformCss(bigImage, 'scale'); // bigImage.startRotation = transformCss(bigImage, 'rotate'); // }, // change: function(event){ // //缩放 // transformCss(bigImage, 'scale', bigImage.startScale * event.scale); // //旋转 // transformCss(bigImage, 'rotate', bigImage.startRotation + event.rotation); // } // }); // 点击关闭,关闭大图预览 closeBtn.addEventListener('touchend', function () { transformCss(bigImageNode, 'scale', 0); }); /** * 创建相册的成员 */ function createAlbumItem() { var end = start + length; // 下一次取值的索引 for (var i = start; i < end; i ++) { //判断数组加载完毕 if (i > imageData.length - 1) { isCompleted = true; //标记加载完毕 break; } // 创建li元素 var liNode = document.createElement('li'); // li添加自定义数据 //liNode.setAttribute('data-src', 'img/'+imageData[i]) liNode.dataset.src = 'img/'+imageData[i]; // 把li添加到ul中 albumList.appendChild(liNode); } start = end; // 重新设置获取图片的起始索引 // 创建完成之后,调用图片懒加载 lazyLoad(); } /** * 实现图片懒加载 */ function lazyLoad() { // 获取所有的相册元素 var albumItems = document.querySelectorAll('.album-list li'); // 遍历所有的相册元素 albumItems.forEach(function (albumItem) { // 判断图片是否已经加载过 if (albumItem.isLoaded) { return; } //判断li具体视口顶部的距离 是否 小于视口高度 if (albumItem.getBoundingClientRect().top < document.documentElement.clientHeight) { //创建 var imgNode = document.createElement('img'); //设置图片地址 imgNode.src = albumItem.dataset.src; // 如果图片加载完毕 imgNode.addEventListener('load', function () { this.style.opacity = 1; }); //如果图片加载失败 imgNode.addEventListener('error', function () { this.src = 'img/noimage.png'; }); // 把图片添加到 li中 albumItem.appendChild(imgNode); // 标记已经加载过图片 albumItem.isLoaded = true; } }); } })(); </script> </body> </html>
import AdminWrapper from "../../../components/Others/AdminWrapper"; import { useSelector, useDispatch } from "react-redux"; import { useState, useEffect } from "react"; import useToast from "../../../hooks/useToast"; import { useNavigate } from "react-router-dom"; import { setLogout } from "../../../state"; import { DndContext, DragOverlay, KeyboardSensor, PointerSensor, TouchSensor, useSensor, useSensors, defaultDropAnimationSideEffects } from "@dnd-kit/core"; import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from "@dnd-kit/sortable"; import { restrictToVerticalAxis } from "@dnd-kit/modifiers"; import AdminEquipeCard from "../../../components/Equipe/AdminEquipeCard"; import AdminEquipeCardOverlay from "../../../components/Equipe/AdminEquipeCardOverlay"; import "../../../styles/tableaudebord/TeamAdmin.css"; import AddEquipeForm from "../../../components/Equipe/AddEquipeForm"; import EditEquipeForm from "../../../components/Equipe/EditEquipeForm"; function TeamAdmin() { const token = useSelector((state) => state.token); const navigate = useNavigate(); const dispatch = useDispatch(); const notify = useToast(); const [addEquipeItem, setAddEquipeItem] = useState(false); const [editMemberIndex, setEditMemberIndex] = useState(-1); const [team, setTeam] = useState([]); const [memberOverlay, setMemberOverlay] = useState({}); const [activeId, setActiveId] = useState(null); const sensors = useSensors( useSensor(PointerSensor), useSensor(TouchSensor), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, }) ); const getTeamByOrder = async () => { try { const response = await fetch("/api/admin/team", { method: "GET", headers: { Authorization: "Bearer " + token, }, }); const data = await response.json(); if (data.code === 500 || data.code === 429) { notify("error", data.error); } if (data.code === 403) { notify("error", data.error); dispatch(setLogout()); navigate("/identification"); } if (data) { setTeam(data); } } catch (error) { navigate("error"); console.error(error); } }; useEffect(() => { getTeamByOrder(); }, []); const updateOrderMemberById = async (id, order_id) => { try { const response = await fetch("/api/admin/team/order/" + id, { method: "PATCH", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token, }, body: JSON.stringify({ order_id: order_id }), }); const data = await response.json(); if (data.code === 500) { notify("error", data.error); } if (data.code === 403) { notify("error", data.error); dispatch(setLogout()); navigate("/identification"); } } catch (err) { console.error(err); } }; const handleDragStart = (e) => { setActiveId(e.active.id); }; const handleDragEnd = async (event) => { try { const { active, over } = event; if (active.id !== over.id) { const activeDraggableIndex = team.findIndex((t) => t.id === parseInt(active.id)); const overDraggableIndex = team.findIndex((t) => t.id === parseInt(over.id)); setTeam(([...items]) => { return arrayMove(items, activeDraggableIndex, overDraggableIndex); }); const activeDraggable = team.find((t) => t.id === parseInt(active.id)); const overDraggable = team.find((t) => t.id === parseInt(over.id)); await updateOrderMemberById(active.id, overDraggable.order_id); await updateOrderMemberById(over.id, activeDraggable.order_id); setActiveId(null); getTeamByOrder(); } } catch (error) { console.log(error); } }; const deleteMemberTeam = async (id) => { try { if (!confirm("Voulez-vous supprimer ce membre ?")) return; const response = await fetch("/api/admin/team/" + id, { method: "DELETE", headers: { Authorization: "Bearer " + token }, }); const data = await response.json(); if (data.code === 500) { notify("error", data.error); } if (data.code === 403) { notify("error", data.error); dispatch(setLogout()); navigate("/identification"); } if (data.code === 200) { notify("success", data.message); getTeamByOrder(); } } catch (error) { console.error(error); } }; const handleDeleteMemberTeam = (id) => { deleteMemberTeam(id); }; useEffect(() => { const activeMember = team.find((v) => v.id === activeId); setMemberOverlay(activeMember); }, [activeId, setMemberOverlay]); if (team.error) { return; } const dropAnimationConfig = { sideEffects: defaultDropAnimationSideEffects({ styles: { active: { opacity: "0.4", }, }, }), }; return ( <AdminWrapper title="Gestion De L'Équipe"> <button className="addEquipeBtn" onClick={() => setAddEquipeItem(!addEquipeItem)}> <svg fill="rgb(5, 142, 34)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"> <path d="M256 48C141.31 48 48 141.31 48 256s93.31 208 208 208 208-93.31 208-208S370.69 48 256 48zm80 224h-64v64a16 16 0 01-32 0v-64h-64a16 16 0 010-32h64v-64a16 16 0 0132 0v64h64a16 16 0 010 32z" /> </svg> </button> {addEquipeItem && <AddEquipeForm setClose={() => setAddEquipeItem(!addEquipeItem)} reloadEquipes={() => getTeamByOrder()} />} <DndContext sensors={sensors} onDragStart={handleDragStart} onDragEnd={handleDragEnd} onDragCancel={() => setActiveId(null)} modifiers={[restrictToVerticalAxis]}> <SortableContext items={team} strategy={verticalListSortingStrategy}> {team.length > 0 && team.map((equipe, index) => ( <div key={index}> <div key={index}> <AdminEquipeCard equipe={equipe} handleEditEquipe={() => setEditMemberIndex(index)} deleteHandleEquipe={() => handleDeleteMemberTeam(equipe.id)} /> </div> {editMemberIndex === index && <EditEquipeForm equipe={equipe} setClose={() => setEditMemberIndex(-1)} reloadEquipes={() => getTeamByOrder()} />} </div> ))} <DragOverlay dropAnimation={dropAnimationConfig} className="dragOverlay"> {activeId && <AdminEquipeCardOverlay equipe={memberOverlay} />} </DragOverlay> </SortableContext> </DndContext> </AdminWrapper> ); } export default TeamAdmin;
#include <stdio.h> #include <stdlib.h> int n = 0; typedef struct Node { int info; struct Node *link; } * node; node create(node nn) { nn = (node)malloc(sizeof(struct Node)); printf("Enter info\n"); scanf("%d", &nn->info); nn->link = nn; n++; return nn; } node insertfront(node p) { node nn; nn = create(nn); if (p == NULL) return nn; nn->link = p->link; p->link = nn; return p; } node insertrear(node p) { node t = p, nn; nn = create(nn); if (p == NULL) return nn; nn->link = p->link; p->link = nn; return nn; } void dis(node p) { node t = p; if (p == NULL) { printf("Empty\n"); return; } printf("Displaying Nodes\n"); do { t = t->link; printf("%d ", t->info); } while (t != p); printf("\n"); } node deletefront(node p) { node nd; if (p == NULL) return p; n--; nd = p->link; printf("Deleted is %d\n", nd->info); p->link = nd->link; free(nd); if (n == 0) // n=1 (1-1=0) return NULL; return p; } node deleterear(node p) { node t = p, q = NULL; if (p == NULL) return p; n--; do { q = t; t = t->link; } while (t != p); printf("Deleted is %d\n", t->info); if (q == p) { free(p); return NULL; } q->link = p->link; free(t); return q; } int search(node p, int key) { int i = 1; node t = p->link; do { if (t->info == key) return i; t = t->link; i++; } while (t != p->link); return -1; } void sort(node p) { node t; int i, j; for (i = 0; i < n - 1; i++) { t = p->link; for (j = 0; j < n - i - 1; j++) { if (t->info > t->link->info) { int temp = t->info; t->info = t->link->info; t->link->info = temp; } t = t->link; } } } node insertbyorder(node p) { node nn, t, q = p; nn = create(nn); if (p == NULL) return nn; t = p->link; do { if (t->info < nn->info) { q = t; t = t->link; } else break; } while (t != p->link); q->link = nn; nn->link = t; if (p->info < nn->info) return nn; return p; } node insertbypos(node p, int pos) { node t = p, q = NULL, nn; int i = 1; nn = create(nn); if (pos == 1 && n == 1) return nn; if (pos == 1) { nn->link = p->link; p->link = nn; return p; } t = t->link; do { q = t; i++; t = t->link; } while (t != p->link && i != pos); q->link = nn; nn->link = t; if (pos == n) // n is incremented in create function So here n means n+1th pos return nn; return p; } node deletebyele(node p) { node t = p->link, q = p; int ele; printf("Enter the element to be deleted\n"); scanf("%d", &ele); do { if (t->info != ele) { q = t; t = t->link; } else break; } while (t != p); if (t->info != ele) { printf("Element not found\n"); return p; } n--; if (p->info == ele) p = q; q->link = t->link; printf("Deleted is %d\n", t->info); free(t); if (n == 0) return NULL; return p; } node deletebypos(node p, int pos) { int i = 1; node t = p->link, q = p; n--; do { if (i != pos) { q = t; t = t->link; i++; } else break; } while (t != p); if (pos == n + 1) p = q; q->link = t->link; printf("Deleted is %d\n", t->info); free(t); if (n == 0) return NULL; return p; } node reverse(node p) { node l, q, r; q = p->link; l = q->link; r = 0; while (q != p) { r = q; q = l; l = l->link; q->link = r; } l->link = q; return l; } int main() { node p = NULL; int ch, key, pos; while (1) { printf("\n1:Insert front\n2:Insert rear\n3:Display\n4:Delete front\n5:Delete rear\n6:Search\n7:Sort\n8:Insert by order\n9:Insert by position\n10:Delete by key\n11:Delete by position\n12:Reverse\n"); printf("Enter your choice\n"); scanf("%d", &ch); switch (ch) { case 1: p = insertfront(p); dis(p); break; case 2: p = insertrear(p); dis(p); break; case 3: dis(p); break; case 4: p = deletefront(p); dis(p); break; case 5: p = deleterear(p); dis(p); break; case 6: if (p == NULL) { printf("Empty\n"); break; } printf("Enter the element to be searched\n"); scanf("%d", &key); pos = search(p, key); if (pos == -1) printf("%d is not found\n", key); else printf("%d is found at %d position\n", key, pos); break; case 7: sort(p); printf("Sorting\n"); dis(p); break; case 8: sort(p); p = insertbyorder(p); dis(p); break; case 9: printf("Enter the position\n"); scanf("%d", &pos); if (pos > 0 && pos <= n + 1) { p = insertbypos(p, pos); dis(p); } else printf("Invalid position\n"); break; case 10: if (p == NULL) { printf("Empty\n"); break; } p = deletebyele(p); dis(p); break; case 11: if (p == NULL) { printf("Empty\n"); break; } printf("Enter the position\n"); scanf("%d", &pos); if (pos > 0 && pos <= n) { p = deletebypos(p, pos); dis(p); } else printf("Invalid position\n"); break; case 12: if (p == NULL) break; p = reverse(p); dis(p); break; default: exit(0); } } return 0; }
-- Nom de la base : Parking_campus -- Nom du fichier : vues_statistique.sql -- Nom de SGBD : ORACLE Version 7.0 -- Date de creation : 20/11/2022 03:32 -- !!!!!! VOUS DEVEZ EXECUTER CES FICHIERS AVANT: -- !!!!!! - base.sql --moyenne du nombre de places disponibles par parking. --somme totale des places disponibles via tous les parkings --division par le nombre de parking --donnera le nombre de places dispos / parking. create or replace view moyenne_nbr_places_parking as select NUMERO_PARKING, NOM_PARKING, sum(NBR)/count(*) as moyenne_places_dispos from( select NUMERO_PARKING, NOM_PARKING, count(NUMERO_PLACE) as NBR from( select NUMERO_PARKING, NOM_PARKING, NUMERO_PLACE from PARKINGS natural join POSITIONS minus select NUMERO_PARKING, NOM_PARKING, NUMERO_PLACE from STATIONNEMENTS natural join POSITIONS natural join PARKINGS ) group by NUMERO_PARKING, NOM_PARKING) group by NUMERO_PARKING, NOM_PARKING; --la durée moyenne de stationnement d'un véhicule par parking. --on fixe un parking, on fait: la somme des durees de stationnements --de tous les vehicules dans ce parking --/ nombre de vehicules stationnant là-bas; cela donnerait --la durée moyenne de stationnement d'un véhicule par parking. create or replace view duree_moy_stat_vehicule__p as select NUMERO_PARKING, sum(HORAIRE_SORTIE-DATE_STATIONNEMENT)/count(NUMERO_IMMATRICULATION) as duree_moy from STATIONNEMENTS natural join POSITIONS natural join PARKINGS natural join VEHICULES group by NUMERO_PARKING; --par parking, on fait la somme des durres de stationnements (en jour) --on divise par le nbr_vehicules qui stationnent là (ou déjà & parti) --ça nous donne la nombre moyen exprimant la durée de stationnement --d'un véhicule par parking. --le cout moyen de stationnement d'un vehicule par mois --on va calculer pour un vehicule le nombre de stationnements --et la somme des tarifs pendant tous ses stationnements --puis le diviser par le premier --ceci donnerait un tarif moyen d'un stationnement de vehicule par mois. create or replace view cout_moyen_stat_v__mois as select NUMERO_IMMATRICULATION, ((sum(TARIF_HORAIRE)/count(NUMERO_PLACE))*30)/sum(HORAIRE_SORTIE-DATE_STATIONNEMENT) as tarif_mensuel__horaire___moyen from VEHICULES natural join STATIONNEMENTS natural join POSITIONS natural join PARKINGS group by NUMERO_IMMATRICULATION; --par vehicule, on fait la somme de tous les tarifs horaires --division --par le nombre de stationnement => tarif moyen par stationnement.(par heure --aussi) --au debut cela donne sur une duree --sortie->duree(en jours) --y->mois(30, convention) --y donne sortie*mois/duree. --classement des parkings les moins utilises create or replace view classement_parkings_moins as select NUMERO_PARKING, NOM_PARKING from( select NUMERO_PARKING, NOM_PARKING, count(NUMERO_PLACE) as NBR_PLACES_UTILISEES from PARKINGS natural join POSITIONS group by NUMERO_PARKING, NOM_PARKING order by count(NUMERO_PLACE) asc ); --classement des parking les plus rentables par commune et par mois --on va calculer la somme des tarifs horaires des vehicules stationnant --dans ce parking. --remarque: pas besoin d'ajouter vehicules en plus dans les jointures --en suites. create or replace view parkings_classement__rs as select NUMERO_PARKING, NOM_PARKING, sum(tarif_horaire)*30/sum(HORAIRE_SORTIE-DATE_STATIONNEMENT) as rentabilitee_mensuelle from STATIONNEMENTS cross join POSITIONS natural join PARKINGS natural join COMMUNES group by NUMERO_PARKING, NOM_PARKING order by rentabilitee_mensuelle desc; --classement des communes les plus demandes par semaine --on va calculer le nombre de stationnements par parking se situant dans --une commune et on va appliquer la formule --*7/duree pour avoir le nombre de stationnements par semaine --et non pas sur toute la duree de la duree de la base totale. create or replace view communes_plus_demandees__s as select CODE_POSTAL, NOM_COMMUNE from( select CODE_POSTAL, NOM_COMMUNE, count(ID_STATIONNEMENT)*7/sum(HORAIRE_SORTIE-DATE_STATIONNEMENT) as nbr_stationnements from COMMUNES natural join PARKINGS natural join POSITIONS natural join STATIONNEMENTS group by CODE_POSTAL, NOM_COMMUNE order by nbr_stationnements desc);
<?php * Copyright (c) 2018 Zindex Software * * Licensed under the MIT License namespace Opis\Closure; use Closure; use Serializable; use SplObjectStorage; use ReflectionObject; /** * Provides a wrapper for serialization of closures */ class SerializableClosure implements Serializable { /** * @var Closure Wrapped closure * * @see \Opis\Closure\SerializableClosure::getClosure() */ protected $closure; /** * @var ReflectionClosure A reflection instance for closure * * @see \Opis\Closure\SerializableClosure::getReflector() */ protected $reflector; /** * @var mixed Used at deserialization to hold variables * * @see \Opis\Closure\SerializableClosure::unserialize() * @see \Opis\Closure\SerializableClosure::getReflector() */ protected $code; /** * @var string Closure's ID */ protected $reference; /** * @var string Closure scope */ protected $scope; /** * @var ClosureContext Context of closure, used in serialization */ protected static $context; /** * @var ISecurityProvider|null */ protected static $securityProvider; /** Array recursive constant*/ const ARRAY_RECURSIVE_KEY = '¯\_(ツ)_/¯'; /** * Constructor * * @param Closure $closure Closure you want to serialize */ public function __construct(Closure $closure) { $this->closure = $closure; if (static::$context !== null) { $this->scope = static::$context->scope; $this->scope->toserialize++; } } /** * Get the Closure object * * @return Closure The wrapped closure */ public function getClosure() { return $this->closure; } /** * Get the reflector for closure * * @return ReflectionClosure */ public function getReflector() { if ($this->reflector === null) { $this->reflector = new ReflectionClosure($this->closure, $this->code); $this->code = null; } return $this->reflector; } /** * Implementation of magic method __invoke() */ public function __invoke() { return call_user_func_array($this->closure, func_get_args()); } /** * Implementation of Serializable::serialize() * * @return string The serialized closure */ public function serialize() { if ($this->scope === null) { $this->scope = new ClosureScope(); $this->scope->toserialize++; } $this->scope->serializations++; $scope = $object = null; $reflector = $this->getReflector(); if($reflector->isBindingRequired()){ $object = $reflector->getClosureThis(); static::wrapClosures($object, $this->scope); if($scope = $reflector->getClosureScopeClass()){ $scope = $scope->name; } } elseif($reflector->isScopeRequired()) { if($scope = $reflector->getClosureScopeClass()){ $scope = $scope->name; } } $this->reference = spl_object_hash($this->closure); $this->scope[$this->closure] = $this; $use = $this->transformUseVariables($reflector->getUseVariables()); $code = $reflector->getCode(); $this->mapByReference($use); $ret = \serialize(array( 'use' => $use, 'function' => $code, 'scope' => $scope, 'this' => $object, 'self' => $this->reference, )); if(static::$securityProvider !== null){ $ret = '@' . json_encode(static::$securityProvider->sign($ret)); } if (!--$this->scope->serializations && !--$this->scope->toserialize) { $this->scope = null; } return $ret; } /** * Transform the use variables before serialization. * * @param array $data The Closure's use variables * @return array */ protected function transformUseVariables($data) { return $data; } /** * Implementation of Serializable::unserialize() * * @param string $data Serialized data * @throws SecurityException */ public function unserialize($data) { ClosureStream::register(); if (static::$securityProvider !== null) { if ($data[0] !== '@') { throw new SecurityException("The serialized closure is not signed. ". "Make sure you use a security provider for both serialization and unserialization."); } $data = json_decode(substr($data, 1), true); if (!is_array($data) || !static::$securityProvider->verify($data)) { throw new SecurityException("Your serialized closure might have been modified and it's unsafe to be unserialized. " . "Make sure you use the same security provider, with the same settings, " . "both for serialization and unserialization."); } $data = $data['closure']; } elseif ($data[0] === '@') { throw new SecurityException("The serialized closure is signed. ". "Make sure you use a security provider for both serialization and unserialization."); } $this->code = \unserialize($data); // unset data unset($data); $this->code['objects'] = array(); if ($this->code['use']) { $this->scope = new ClosureScope(); $this->code['use'] = $this->resolveUseVariables($this->code['use']); $this->mapPointers($this->code['use']); extract($this->code['use'], EXTR_OVERWRITE | EXTR_REFS); $this->scope = null; } $this->closure = include(ClosureStream::STREAM_PROTO . '://' . $this->code['function']); if($this->code['this'] === $this){ $this->code['this'] = null; } if ($this->code['scope'] !== null || $this->code['this'] !== null) { $this->closure = $this->closure->bindTo($this->code['this'], $this->code['scope']); } if(!empty($this->code['objects'])){ foreach ($this->code['objects'] as $item){ $item['property']->setValue($item['instance'], $item['object']->getClosure()); } } $this->code = $this->code['function']; } /** * Resolve the use variables after unserialization. * * @param array $data The Closure's transformed use variables * @return array */ protected function resolveUseVariables($data) { return $data; } /** * Wraps a closure and sets the serialization context (if any) * * @param Closure $closure Closure to be wrapped * * @return self The wrapped closure */ public static function from(Closure $closure) { if (static::$context === null) { $instance = new static($closure); } elseif (isset(static::$context->scope[$closure])) { $instance = static::$context->scope[$closure]; } else { $instance = new static($closure); static::$context->scope[$closure] = $instance; } return $instance; } /** * Increments the context lock counter or creates a new context if none exist */ public static function enterContext() { if (static::$context === null) { static::$context = new ClosureContext(); } static::$context->locks++; } /** * Decrements the context lock counter and destroy the context when it reaches to 0 */ public static function exitContext() { if (static::$context !== null && !--static::$context->locks) { static::$context = null; } } /** * @param string $secret */ public static function setSecretKey($secret) { if(static::$securityProvider === null){ static::$securityProvider = new SecurityProvider($secret); } } /** * @param ISecurityProvider $securityProvider */ public static function addSecurityProvider(ISecurityProvider $securityProvider) { static::$securityProvider = $securityProvider; } /** * Remove security provider */ public static function removeSecurityProvider() { static::$securityProvider = null; } /** * @return null|ISecurityProvider */ public static function getSecurityProvider() { return static::$securityProvider; } /** * Wrap closures * * @internal * @param $data * @param ClosureScope|SplObjectStorage|null $storage */ public static function wrapClosures(&$data, SplObjectStorage $storage = null) { static::enterContext(); if($storage === null){ $storage = static::$context->scope; } if($data instanceof Closure){ $data = static::from($data); } elseif (is_array($data)){ if(isset($data[self::ARRAY_RECURSIVE_KEY])){ return; } $data[self::ARRAY_RECURSIVE_KEY] = true; foreach ($data as $key => &$value){ if($key === self::ARRAY_RECURSIVE_KEY){ continue; } static::wrapClosures($value, $storage); } unset($value); unset($data[self::ARRAY_RECURSIVE_KEY]); } elseif($data instanceof \stdClass){ if(isset($storage[$data])){ $data = $storage[$data]; return; } $data = $storage[$data] = clone($data); foreach ($data as &$value){ static::wrapClosures($value, $storage); } unset($value); } elseif (is_object($data) && ! $data instanceof static){ if(isset($storage[$data])){ $data = $storage[$data]; return; } $instance = $data; $reflection = new ReflectionObject($instance); if(!$reflection->isUserDefined()){ $storage[$instance] = $data; return; } $storage[$instance] = $data = $reflection->newInstanceWithoutConstructor(); do{ if(!$reflection->isUserDefined()){ break; } foreach ($reflection->getProperties() as $property){ if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){ continue; } $property->setAccessible(true); $value = $property->getValue($instance); if(is_array($value) || is_object($value)){ static::wrapClosures($value, $storage); } $property->setValue($data, $value); }; } while($reflection = $reflection->getParentClass()); } static::exitContext(); } /** * Unwrap closures * * @internal * @param $data * @param SplObjectStorage|null $storage */ public static function unwrapClosures(&$data, SplObjectStorage $storage = null) { if($storage === null){ $storage = static::$context->scope; } if($data instanceof static){ $data = $data->getClosure(); } elseif (is_array($data)){ if(isset($data[self::ARRAY_RECURSIVE_KEY])){ return; } $data[self::ARRAY_RECURSIVE_KEY] = true; foreach ($data as $key => &$value){ if($key === self::ARRAY_RECURSIVE_KEY){ continue; } static::unwrapClosures($value, $storage); } unset($data[self::ARRAY_RECURSIVE_KEY]); }elseif ($data instanceof \stdClass){ if(isset($storage[$data])){ return; } $storage[$data] = true; foreach ($data as &$property){ static::unwrapClosures($property, $storage); } } elseif (is_object($data) && !($data instanceof Closure)){ if(isset($storage[$data])){ return; } $storage[$data] = true; $reflection = new ReflectionObject($data); do{ if(!$reflection->isUserDefined()){ break; } foreach ($reflection->getProperties() as $property){ if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){ continue; } $property->setAccessible(true); $value = $property->getValue($data); if(is_array($value) || is_object($value)){ static::unwrapClosures($value, $storage); $property->setValue($data, $value); } }; } while($reflection = $reflection->getParentClass()); } } /** * Internal method used to map closure pointers * @internal * @param $data */ protected function mapPointers(&$data) { $scope = $this->scope; if ($data instanceof static) { $data = &$data->closure; } elseif (is_array($data)) { if(isset($data[self::ARRAY_RECURSIVE_KEY])){ return; } $data[self::ARRAY_RECURSIVE_KEY] = true; foreach ($data as $key => &$value){ if($key === self::ARRAY_RECURSIVE_KEY){ continue; } elseif ($value instanceof static) { $data[$key] = &$value->closure; } elseif ($value instanceof SelfReference && $value->hash === $this->code['self']){ $data[$key] = &$this->closure; } else { $this->mapPointers($value); } } unset($value); unset($data[self::ARRAY_RECURSIVE_KEY]); } elseif ($data instanceof \stdClass) { if(isset($scope[$data])){ return; } $scope[$data] = true; foreach ($data as $key => &$value){ if ($value instanceof SelfReference && $value->hash === $this->code['self']){ $data->{$key} = &$this->closure; } elseif(is_array($value) || is_object($value)) { $this->mapPointers($value); } } unset($value); } elseif (is_object($data) && !($data instanceof Closure)){ if(isset($scope[$data])){ return; } $scope[$data] = true; $reflection = new ReflectionObject($data); do{ if(!$reflection->isUserDefined()){ break; } foreach ($reflection->getProperties() as $property){ if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){ continue; } $property->setAccessible(true); $item = $property->getValue($data); if ($item instanceof SerializableClosure || ($item instanceof SelfReference && $item->hash === $this->code['self'])) { $this->code['objects'][] = array( 'instance' => $data, 'property' => $property, 'object' => $item instanceof SelfReference ? $this : $item, ); } elseif (is_array($item) || is_object($item)) { $this->mapPointers($item); $property->setValue($data, $item); } } } while($reflection = $reflection->getParentClass()); } } /** * Internal method used to map closures by reference * * @internal * @param mixed &$data */ protected function mapByReference(&$data) { if ($data instanceof Closure) { if($data === $this->closure){ $data = new SelfReference($this->reference); return; } if (isset($this->scope[$data])) { $data = $this->scope[$data]; return; } $instance = new static($data); if (static::$context !== null) { static::$context->scope->toserialize--; } else { $instance->scope = $this->scope; } $data = $this->scope[$data] = $instance; } elseif (is_array($data)) { if(isset($data[self::ARRAY_RECURSIVE_KEY])){ return; } $data[self::ARRAY_RECURSIVE_KEY] = true; foreach ($data as $key => &$value){ if($key === self::ARRAY_RECURSIVE_KEY){ continue; } $this->mapByReference($value); } unset($value); unset($data[self::ARRAY_RECURSIVE_KEY]); } elseif ($data instanceof \stdClass) { if(isset($this->scope[$data])){ $data = $this->scope[$data]; return; } $instance = $data; $this->scope[$instance] = $data = clone($data); foreach ($data as &$value){ $this->mapByReference($value); } unset($value); } elseif (is_object($data) && !$data instanceof SerializableClosure){ if(isset($this->scope[$data])){ $data = $this->scope[$data]; return; } $instance = $data; $reflection = new ReflectionObject($data); if(!$reflection->isUserDefined()){ $this->scope[$instance] = $data; return; } $this->scope[$instance] = $data = $reflection->newInstanceWithoutConstructor(); do{ if(!$reflection->isUserDefined()){ break; } foreach ($reflection->getProperties() as $property){ if($property->isStatic() || !$property->getDeclaringClass()->isUserDefined()){ continue; } $property->setAccessible(true); $value = $property->getValue($instance); if(is_array($value) || is_object($value)){ $this->mapByReference($value); } $property->setValue($data, $value); } } while($reflection = $reflection->getParentClass()); } } }
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'; import type { PayloadAction } from '@reduxjs/toolkit'; import axios from 'axios'; export interface pizzaState { items: any[]; status: string; } export const fetchPizzas = createAsyncThunk( 'pizza/fetchPizzaStatus', async (params: any) => { const { currentPage, categoryId, sortType, search } = params; const { data } = await axios.get( `https://660adfa5ccda4cbc75dbf990.mockapi.io/pizzas?page=${currentPage}&limit=8&${ categoryId > 0 ? `category=${categoryId}` : `` }&sortBy=${sortType}&order=desc${search}` ); return data; } ); const initialState: pizzaState = { items: [], status: 'loading', }; export const pizzaSlice = createSlice({ name: 'pizza', initialState, reducers: { setItems(state, action) { state.items = action.payload; }, }, extraReducers: builder => { builder.addCase(fetchPizzas.pending, state => { state.status = 'LOADING'; state.items = []; }); builder.addCase(fetchPizzas.fulfilled, (state, action) => { state.items = action.payload; state.status = 'SUCCESS'; }); builder.addCase(fetchPizzas.rejected, (state, action) => { state.status = 'ERROR'; state.items = []; }); }, }); export const selectPizzaData = (state: any) => state.pizza; export const { setItems } = pizzaSlice.actions; export default pizzaSlice.reducer;
<template> <div> <loading :active.sync="isLoading"></loading> <div class="text-right my-4"> <button class="btn btn-primary" @click="getOrderList" title="如果沒有資料請點選重新讀取">取得訂單列表</button> </div> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>購買時間</th> <th>Email</th> <th>購買項目</th> <th class="text-center">應付金額</th> <th class="text-center">是否付款</th> </tr> </thead> <tbody> <tr v-for="item in orders" :key="item.id"> <th>{{ new Date(item.create_at*1000).getFullYear()}} / {{new Date(item.create_at*1000).getMonth() + 1 }} / {{new Date(item.create_at*1000).getDate() }}</th> <td>{{ item.user.email }}</td> <td> <span v-for="(product, i) in item.products" :key="i"> {{ product.product.title }} {{ product.qty }}/{{ product.product.unit }} <br /> </span> </td> <td class="text-right">{{ item.total | currency}}</td> <td class="text-success text-center" v-if="item.is_paid">完成付款</td> <td class="text-center" v-else>尚未付款</td> </tr> </tbody> </table> </div> <Pagination :pagenation="paginations" @changeCurrPage="getOrderList"></Pagination> </div> </template> <script> import $ from "jquery"; import Pagination from "./Pagination"; export default { data() { return { paginations: {}, orders: [] }; }, methods: { getOrderList(page = 1) { const vm = this; const api = `${process.env.API_PATH}/api/${process.env.CUSTOM_PATH}/admin/orders?page=${page}`; vm.$store.dispatch("pushLoadingStatu", true); vm.$http.get(api).then(response => { if (response.data.success) { vm.orders = response.data.orders; vm.paginations = response.data.pagination; } vm.$store.dispatch("pushLoadingStatu", false); }); } }, components: { Pagination }, computed: { isLoading() { return this.$store.state.status.isLoading; } }, created() { this.getOrderList(); } }; </script>
import { Context } from "hono"; import { publicKey } from "./handleUserRegistration"; import { userWeeklyAvailability, users } from "../db/schema"; import { db } from ".."; import jwt from '@tsndr/cloudflare-worker-jwt' import { and, eq } from "drizzle-orm"; export const daysofWeek = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] as const; type DayOfWeek = typeof daysofWeek[number]; type Payload = { [Key in DayOfWeek]: [Array<[string, string]>, boolean]; }; // make sure to remove unavailable in frontend export async function handleWeeklyScheduleUpdate(ctx: Context) { try { const { payload }: { payload: Payload } = await ctx.req.json(); const token = ctx.req.header('Authorization') if (typeof (token) === "undefined") return ctx.json({ "message": "Token not provided", "success": false }) const isValidToken = await jwt.verify(token, publicKey, "RS256"); const decodedToken = jwt.decode<{ payload: { sub: string } }, {}>(token) const userId = decodedToken.payload?.payload.sub; if (typeof (userId) === "undefined" || !isValidToken) { return ctx.json({ "Message": "Invalid Token", "success": false }) } console.log(payload); console.log(isValidToken); console.log(userId); let todaysDate = new Date().toISOString().split('T')[0]; const keys: DayOfWeek[] = Object.keys(payload) as DayOfWeek[]; const checkUserExistence = await db.select().from(users).where(eq(users.userId, userId)) if (checkUserExistence.length === 0) { return ctx.json({ "message": "User has logged in but has not entered credentials", "redirect": true, "success": false }) } await Promise.all(keys.map(async (day: DayOfWeek) => { await db.delete(userWeeklyAvailability).where(and(eq(userWeeklyAvailability.userId, userId), eq(userWeeklyAvailability.day, day))) })) await Promise.all(keys.map(async (day: DayOfWeek) => { const eachDaysAvailability = payload[day][0].map(async (time) => { await db.insert(userWeeklyAvailability).values({ userId, day, availableFrom: time[0], availableTill: time[1], updatedAt: todaysDate }) }) await Promise.all(eachDaysAvailability); })) return ctx.json({ "Message": "Successfully Updated Availability", "success": true }) } catch (err) { console.log(err) return ctx.json({ "Message": "Something Went Wrong ", "success": false }) } }
<!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>Survey Form</title> <link rel="stylesheet" href="./styles.css"> </head> <body> <div class="container"> <header class="header"> <h1 id="title"> Albert & Newton Survey Form </h1> <p id="description" class="description">Kindly take time to fill our survey form</p> </header> <form id="survey-form"> <div class="form-group"> <label for="name" id="name-label">Name</label> <input type="text" class="form-control" name="name" id="name" placeholder="Enter your name" required> </div> <div class="form-group"> <label for="email" id="email-label">Email</label> <input type="email" class="form-control" name="email" id="email" placeholder="Enter your email" required> </div> <div class="form-group"> <label for="number" id="number-label">Age<span class="hint">(optional)</span></label> <input type="number" class="form-control" name="age" id="number" placeholder="Your Age" min="14" max="99" required> </div> <div class="form-group"> <p>Which language do you program in?</p> <select name="role" id="dropdown" class="form-control" required> <option disabled selected value>Select an option</option> <option value="python">Python</option> <option value="ruby">Ruby</option> <option value="javascript">Javascript</option> <option value="php">PHP</option> </select> </div> <div class="form-group"> <p>Would you advice your friend to start programming?</p> <label> <input type="radio" name="user-recommend" value="definitely" class="input-radio" checked />Definitely </label> <label> <input type="radio" name="user-recommend" value="maybe" class="input-radio"/>Maybe </label> <label> <input type="radio" name="user-recommend" value="not-at-all" class="input-radio"/>Not at all </label> </div> <div class="form-group"> <p>Which IT field do you love working on?</p> <select name="mostLike" id="most-like" class="form-control" required> <option disabled selected value>Select an option</option> <option value="frontend">Frontend</option> <option value="backend">Backend</option> <option value="data-science">Data Science</option> <option value="cyber-security">Cyber Security</option> </select> </div> <div class="form-group"> <p>What would you like to see improved in the future?<span class="hint">(Check all that apply)</span></p> <label> <input type="checkbox" name="prefer" value="front-end-projects" class="input-checkbox" />Front-end Projects </label> <label> <input type="checkbox" name="prefer" value="back-end-projects" class="input-checkbox"/>Back-end Projects </label> <label> <input type="checkbox" name="prefer" value="challenges" class="input-checkbox"/>Challenges </label> <label> <input type="checkbox" name="prefer" value="data-visualisation" class="input-checkbox" />Data Visualisation </label> <label> <input type="checkbox" name="prefer" value="open-source-community" class="input-checkbox"/>Open Source Community </label> <label> <input type="checkbox" name="prefer" value="tech-meetups" class="input-checkbox"/>Tech Meetups </label> <label> <input type="checkbox" name="prefer" value="more-courses" class="input-checkbox"/>More Courses </label> </div> <div class="form-group"> <p>Any comments or suggestions you have?</p> <textarea name="comment" id="comments" class="input-textarea" placeholder="Enter your comment or suggestion here..."></textarea> </div> <div class="form-group"> <button type="submit" id="submit" class="submit-button">Submit</button> </div> </form> </div> </body> </html>
<h1 class="container"> <form> <table> <tr> <td> <mat-form-field appearance="fill"> <mat-label>Type of data</mat-label> <mat-select [(ngModel)]='selected_endpoint' name='selected_endpoint' required> <mat-option *ngFor="let endpoint of endpoints" value="{{endpoint}}"> {{endpoint}} </mat-option> </mat-select> </mat-form-field> </td> <td> <mat-form-field appearance="fill"> <mat-label>Method</mat-label> <mat-select required [(ngModel)]='selected_method' name='selected_method'> <mat-option *ngFor="let method of methods" value="{{method}}"> {{method}} </mat-option> </mat-select> </mat-form-field> </td> <td> <mat-form-field appearance="fill"> <mat-label>Aditional data</mat-label> <input matInput [(ngModel)]='introduced_data' name='introduced_data'> <mat-hint>Required for PUT method</mat-hint> </mat-form-field> </td> <td> <input type="button" value="submit" (click)="takeInfo($event)"> </td> </tr> </table> <ul style="list-style-type:{{show}}">{{message1}} <li>{{message2}}</li> <li>{{message3}}</li> <li>{{message4}}</li> </ul> </form> </h1>
#ifndef lists_h #define lists_h #include <stddef.h> /** * struct listint_node - Represents a node in a singly linked list * @n: Stores an integer value * @next: Points to the next node in the linked list * * Description: Defines the structure of a node within a singly linked list. */ typedef struct listint_node { int n; struct listint_node *next; } listint_t; /** * struct listnodes - singly linked list node * @ptr: A pointer to a `listint_t` node, storing an integer value. * @next: A pointer to the next node in the list. * * Decription: structure represents node in a singly linked list */ typedef struct listnodes { listint_t *ptr; struct listnodes *next; } listnode_t; int _putchar(char c); size_t print_listint(const listint_t *h); size_t listint_len(const listint_t *h); listint_t *add_nodeint(listint_t **head, const int n); listint_t *add_nodeint_end(listint_t **head, const int n); void free_listint(listint_t *head); void free_listint2(listint_t **head); int pop_listint(listint_t **head); listint_t *get_nodeint_at_index(listint_t *head, unsigned int index); int sum_listint(listint_t *head); #endif
package dentisthandler import ( "ck-2/internal/application/service" "ck-2/internal/domain" "ck-2/pkg/web" "errors" "reflect" "strconv" "github.com/gin-gonic/gin" ) type dentistHandler struct { dentistGroup gin.RouterGroup dentistService service.Dentist } func (d *dentistHandler) ConfigureDentistRouter() { d.dentistGroup.POST("", d.post) d.dentistGroup.GET("/:id", d.get) d.dentistGroup.GET("", d.getAll) d.dentistGroup.PUT(":id", d.put) d.dentistGroup.PATCH(":id", d.patch) d.dentistGroup.DELETE(":id", d.delete) } func (d *dentistHandler) post(ctx *gin.Context) { var dentist domain.CreateDentist err := ctx.ShouldBindJSON(&dentist) if err != nil { web.Failure(ctx, 400, err) return } err = d.dentistService.Post(dentist) if err != nil { web.Failure(ctx, 500, err) return } ctx.Status(201) } func (d *dentistHandler) get(ctx *gin.Context) { id := ctx.Param("id") if id == "" { web.Failure(ctx, 400, errors.New("no id sent")) return } idConverted, err := strconv.Atoi(id) if err != nil { web.Failure(ctx, 400, errors.New("incorrect id sent. must be a number")) return } dentist, err := d.dentistService.Get(idConverted) if err != nil { web.Failure(ctx, 500, errors.New("errors getting entity")) return } if reflect.DeepEqual(dentist, domain.Dentist{}) { web.Failure(ctx, 404, errors.New("entity not found")) return } ctx.JSON(200, dentist) } func (d *dentistHandler) getAll(ctx *gin.Context) { dentists, err := d.dentistService.GetAll() if err != nil { web.Failure(ctx, 500, err) return } ctx.JSON(200, dentists) } func (d *dentistHandler) put(ctx *gin.Context) { var dentist domain.UpdateDentist id := ctx.Param("id") if id == "" { web.Failure(ctx, 400, errors.New("no id sent")) return } idConverted, err := strconv.Atoi(id) if err != nil { web.Failure(ctx, 400, errors.New("incorrect id sent. must be a number")) return } err = ctx.ShouldBindJSON(&dentist) if err != nil { web.Failure(ctx, 400, err) return } _, err = d.dentistService.Get(idConverted) if err != nil { web.Failure(ctx, 500, errors.New("errors getting entity")) return } if reflect.DeepEqual(dentist, domain.UpdateDentist{}) { web.Failure(ctx, 404, errors.New("entity not found")) return } err = d.dentistService.Put(idConverted, domain.UpdateDentist{Name: dentist.Name, Surname: dentist.Surname, Registry: dentist.Registry}) if err != nil { web.Failure(ctx, 500, err) return } ctx.Status(204) } func (d *dentistHandler) patch(ctx *gin.Context) { var dentist domain.PatchDentistName id := ctx.Param("id") if id == "" { web.Failure(ctx, 400, errors.New("no id sent")) return } idConverted, err := strconv.Atoi(id) if err != nil { web.Failure(ctx, 400, errors.New("incorrect id sent. must be a number")) return } err = ctx.ShouldBindJSON(&dentist) if err != nil { web.Failure(ctx, 400, err) return } _, err = d.dentistService.Get(idConverted) if err != nil { web.Failure(ctx, 500, errors.New("errors getting entity")) return } if reflect.DeepEqual(dentist, domain.PatchDentistName{}) { web.Failure(ctx, 404, errors.New("entity not found")) return } err = d.dentistService.Patch(idConverted, domain.PatchDentistName{Name: dentist.Name}) if err != nil { web.Failure(ctx, 500, err) return } ctx.Status(204) } func (d *dentistHandler) delete(ctx *gin.Context) { id := ctx.Param("id") if id == "" { web.Failure(ctx, 400, errors.New("no id sent")) return } idConverted, err := strconv.Atoi(id) if err != nil { web.Failure(ctx, 400, errors.New("incorrect id sent. must be a number")) return } dentist, err := d.dentistService.Get(idConverted) if err != nil { web.Failure(ctx, 500, errors.New("errors getting entity")) return } if reflect.DeepEqual(dentist, domain.Dentist{}) { web.Failure(ctx, 404, errors.New("entity not found")) return } err = d.dentistService.Delete(idConverted) if err != nil { web.Failure(ctx, 500, err) return } ctx.Status(204) } func NewDentistHandler(routerGroup *gin.RouterGroup, service service.Dentist) dentistHandler { return dentistHandler{*routerGroup, service} }
<!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>Roccat Gaming</title> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css"> <!-- Animate --> <link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" /> <!-- font Roboto --> <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=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> <script src="https://kit.fontawesome.com/28138817e3.js" crossorigin="anonymous"></script> </head> <body> <!-- Navbar --> <header class="fixed-top"> <nav class="navbar navbar-expand-md"> <div class="container-fluid"> <a class="navbar-brand" href="#"><img src="img/source/ROCCAT_2x_542b0322-17bd-4c40-b6e7-b176ca9461df_600x.png" class="img-fluid" alt=""></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"> <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">mice</a> </li> <li class="nav-item"> <a class="nav-link" href="#">keyboards</a> </li> <li class="nav-item"> <a class="nav-link" href="#">headsets</a> </li> <li class="nav-item"> <a class="nav-link" href="#">mousepads</a> </li> <li class="nav-item"> <a class="nav-link" href="#">accessories</a> </li> <li class="nav-item"> <a class="nav-link" href="#">blog</a> </li> <li class="nav-item"> <a class="nav-link" href="#">content creators</a> </li> </ul> </div> </div> </nav> </header> <!-- Hero-section --> <section id="hero"> <div class="container"> <h1>Flip the <span>switch</span></h1> </div> </section> <!-- Video --> <section id="video"> <video id="myVideo" autoplay muted preload="auto" loop src="img/ARCTICWHITE_LOOP.mp4"></video> <a onclick="pauseVid()"><i id="icon" class="far fa-pause-circle"></i></a> </section> <!-- Featured section --> <section id="featured"> <div class="container-fluid"> <div class="row"> <div class="col-md-4 featured-item first" data-aos="fade-up" data-aos-duration="1000"> <img class="keyboard" src="img/source/keyboard.png" alt=""> <h3>vulcan <span>tkl pro</span></h3> <p>Tenkeyless form factor <br> Titan Switch Optical<br> AIMO intelligent lighting engine<br> Mixer-style media controls<br> Detachable braided USB-C cable</p> <button href="">More information</button> </div> <div class="col-md-4 featured-item" data-aos="fade-up" data-aos-delay="70" data-aos-duration="1000"> <img src="img/source/mouse.png" alt=""> <h3>Burst <span>pro</span></h3> <p>Extreme lightweight shell - only 68g<br> Titan Switch Optical speed & precision<br> PhantomFlex cable virtually disappears<br> Detachable braided USB-C cable <br> Heat-treated pure PTFE glides</p> <button href="">More information</button> </div> <div class="col-md-4 featured-item" data-aos="fade-up" data-aos-delay="70" data-aos-duration="1000"> <img src="img/source/headphones.png" alt=""> <h3>Elo <span>7.1 Air</span></h3> <p>Self-Adjusting Metal Headband<br> Glasses Friendly Memory Foam Cushions<br> Supreme stereo sound <br> Crystal clear truSpeal mic technology<br> Cross-platform Compatibility</p> <button href="">More information</button> </div> </div> </div> </section> <!-- Products --> <section id="products"> <div class="container"> <h2>At ROCCAT, we're passionate about developing premium gaming hardware that makes you play better. German engineering since 2007.</h2> <div class="row text-left"> <div class="col-md-6 keyboard block" data-aos="fade-right"> <div class="product-item"> <h4>Vulcan Pro</h4> <p>Optical RGB Gaming Keyboard</p> </div> <div class="overlay"> <a href="#">Learn More</a> </div> </div> <div class="col-md-6 headphones block" data-aos="fade-left"> <div class="product-item"> <h4>ELO 7.1 Usb</h4> <p>Surround Sound RGB Gaming Headset</p> </div> <div class="overlay"> <a href="#">Learn More</a> </div> </div> <div class="col-md-6 column"> <div class="row second"> <div class="col-md-12 keyboard-white" data-aos="fade-up"> <div class="product-item"> <h4>VULCAN TKL</h4> <p>Compact Mechanical Gaming Keyboard</p> </div> <div class="overlay"> <a href="#">Learn More</a> </div> </div> <div class="col-md-12 pad" data-aos="fade-up"> <div class="product-item"> <h4>SENSE AIMO XXL</h4> <p>RGB Illumination Gaming Mousepad</p> </div> <div class="overlay"> <a href="#">Learn More</a> </div> </div> </div> <div class="overlay"> <a href="#">Learn More</a> </div> </div> <div class="col-md-6 mouse block" data-aos="fade-left"> <div class="product-item"> <h4>Burst Pro</h4> <p>Extreme Lightweight Optical Mouse</p> </div> <div class="overlay"> <a href="#">Learn More</a> </div> </div> </div> </div> </section> <!-- Newsletter --> <section id="newsletter"> <div class="container"> <h3 class="light">Always be the first to know.</h3> <h4>Sign up for our Newsletter</h4> <input placeholder="Your e-mail address" type="text" /> </div> </section> <!-- Instagram --> <section id="instagram"> <div class="container-fluid"> <h1 class="">SETUP PROUD?</h1> <p>Share your ROCCAT setup with us. Mention <b>@roccat</b> in your photos and we will post the best pictures on our website.</p> <div class="row"> <div class="col-md-4 insta1" data-aos="fade-right"> <a href="#"> <div class="overlay"> <i class="fab fa-instagram"></i> </div> </a> </div> <div class="col-md-4 insta2"> <a href="#"> <div class="overlay"> <i class="fab fa-instagram"></i> </div> </a> </div> <div class="col-md-4 insta3" data-aos="fade-left"> <a href="#"> <div class="overlay"> <i class="fab fa-instagram"></i> </div> </a> </div> <div class="col-md-4 insta4" data-aos="fade-right"> <a href="#"> <div class="overlay"> <i class="fab fa-instagram"></i> </div> </a> </div> <div class="col-md-4 insta5"> <a href="#"> <div class="overlay"> <i class="fab fa-instagram"></i> </div> </a> </div> <div class="col-md-4 insta6" data-aos="fade-left"> <a href="#"> <div class="overlay"> <i class="fab fa-instagram"></i> </div> </a> </div> </div> </div> </section> <!-- Footer --> <footer class="footer-section"> <div class="container"> <div class="footer-cta pt-5 pb-5"> <div class="row"> <div class="col-xl-4 col-md-4 mb-30"> <div class="single-cta"> <i class="fas fa-map-marker-alt"></i> <div class="cta-text"> <h4>Find us</h4> <span>1010 Avenue, sw 54321, chandigarh</span> </div> </div> </div> <div class="col-xl-4 col-md-4 mb-30"> <div class="single-cta"> <i class="fas fa-phone"></i> <div class="cta-text"> <h4>Call us</h4> <span>9876543210 0</span> </div> </div> </div> <div class="col-xl-4 col-md-4 mb-30"> <div class="single-cta"> <i class="far fa-envelope-open"></i> <div class="cta-text"> <h4>Mail us</h4> <span>mail@info.com</span> </div> </div> </div> </div> </div> <div class="footer-content pt-5 pb-5"> <div class="row"> <div class="col-xl-4 col-lg-4 mb-50"> <div class="footer-widget"> <div class="footer-logo"> <a href="index.html"><img src="img/source/ROCCAT_2x_542b0322-17bd-4c40-b6e7-b176ca9461df_600x.png" class="img-fluid" alt="logo"></a> </div> <div class="footer-text"> <p>Lorem ipsum dolor sit amet, consec tetur adipisicing elit, sed do eiusmod tempor incididuntut consec tetur adipisicing elit,Lorem ipsum dolor sit amet.</p> </div> <div class="footer-social-icon"> <span>Follow us</span> <a href="#"><i class="fab fa-facebook-f facebook-bg"></i></a> <a href="#"><i class="fab fa-twitter twitter-bg"></i></a> <a href="#"><i class="fab fa-google-plus-g google-bg"></i></a> </div> </div> </div> <div class="col-xl-4 col-lg-4 col-md-6 mb-30"> <div class="footer-widget"> <div class="footer-widget-heading"> <h3>Useful Links</h3> </div> <ul> <li><a href="#">Mice</a></li> <li><a href="#">Keyboards</a></li> <li><a href="#">Headsets</a></li> <li><a href="#">Mousepads</a></li> <li><a href="#">Contact</a></li> <li><a href="#">About us</a></li> <li><a href="#">Creators</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Contact us</a></li> <li><a href="#">Accessories</a></li> </ul> </div> </div> <div class="col-xl-4 col-lg-4 col-md-6 mb-50"> <div class="footer-widget"> <div class="footer-widget-heading"> <h3>Subscribe</h3> </div> <div class="footer-text mb-25"> <p>Don’t miss to subscribe to our new feeds, kindly fill the form below.</p> </div> <div class="subscribe-form"> <form action="#"> <input type="text" placeholder="Email Address"> <button><i class="fab fa-telegram-plane"></i></button> </form> </div> </div> </div> </div> </div> </div> <div class="copyright-area"> <div class="container"> <div class="row"> <div class="col-xl-12 col-lg-12 text-center text-lg-center"> <div class="copyright-text"> <p>Copyright &copy; 2022, by Ivan Dj.</a></p> </div> </div> </div> </div> </div> </footer> <!-- Animate --> <script src="https://unpkg.com/aos@next/dist/aos.js"></script> <script> AOS.init(); var vid = document.getElementById("myVideo"); var paused = vide.pause var getIcon = document.getElementById("icon"); function playVid() { vid.play(); } function pauseVid() { if (!vid.paused) { vid.pause(); } else { vid.play(); } } </script> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> </body> </html>