text
stringlengths
184
4.48M
import { useEffect, useState } from "react"; import { getBrands } from "api/get-brands"; import { getModels } from "api/get-models"; import { toast } from "react-toastify"; export type UseModelsParams = { brandCode: string | null; } export type Model = { codigo: number; nome: string; } export function useModels({ brandCode }: UseModelsParams) { const [models, setModels] = useState<Model[]>([]) const [isLoadingModels, setIsLoadingModels] = useState(false) useEffect(() => { async function getModelsRequest() { if(!brandCode) { return null } setIsLoadingModels(true) try { const data = await getModels({ brand: brandCode }) setModels(data) setIsLoadingModels(false) } catch { toast.error('Error ao carregar modelos, tente novamente.') setIsLoadingModels(false) setModels([]) } } getModelsRequest() }, [brandCode]) return { models, isLoadingModels, } }
#define CATCH_CONFIG_MAIN #include "../AddShare.h" #include <catch2/catch.hpp> #include <cstdint> static constexpr uint64_t PRIME = 8088322049ULL; static constexpr uint64_t NUM_PARTIES = 10; static const std::string SEED = "SHARE_SEED"; TEST_CASE("Additive Share test (33 bit)", "[addshare]") { static constexpr uint64_t value = 1234567890; AddShare share(PRIME); share.seed_rng(SEED); share.preprocess(NUM_PARTIES); auto shares = share.share(value, NUM_PARTIES); REQUIRE(shares.size() == NUM_PARTIES); REQUIRE(share.reconstruct(shares) == value); shares.erase(shares.begin()); REQUIRE(share.reconstruct(shares) != value); } TEST_CASE("Additive Share test (33 bit) -- add", "[addshare]") { static constexpr uint64_t value1 = 1234567890; static constexpr uint64_t value2 = 8028422012ULL; AddShare share(PRIME); share.seed_rng(SEED); share.preprocess(NUM_PARTIES); auto shares1 = share.share(value1, NUM_PARTIES); auto shares2 = share.share(value2, NUM_PARTIES); auto shares_r = shares1; for (auto &it : shares_r) { auto s = shares2.find(it.first); REQUIRE(s != shares2.end()); it.second = share.field_add(it.second, s->second); } REQUIRE(shares1.size() == NUM_PARTIES); REQUIRE(shares2.size() == NUM_PARTIES); REQUIRE(shares_r.size() == NUM_PARTIES); REQUIRE(share.reconstruct(shares_r) == share.field_add(value1, value2)); } TEST_CASE("Additive Share test (33 bit) -- multiply plain", "[addshare]") { static constexpr uint64_t value1 = 1234567890; static constexpr uint64_t value2 = 8028422012ULL; AddShare share(PRIME); share.seed_rng(SEED); share.preprocess(NUM_PARTIES); auto shares = share.share(value1, NUM_PARTIES); auto shares_r = shares; for (auto &it : shares_r) { it.second = share.field_mul(it.second, value2); } REQUIRE(shares.size() == NUM_PARTIES); REQUIRE(shares_r.size() == NUM_PARTIES); REQUIRE(share.reconstruct(shares_r) == share.field_mul(value1, value2)); }
--- title: plannerAssignedToTaskBoardTaskFormat 资源类型 description: '**plannerAssignedToTaskBoardTaskFormat** 资源表示用于在任务板 (的 AssignedTo 视图中正确呈现任务的信息) 用户组织的视图。 每个任务都有一个 **与之关联的 plannerAssignedToTaskBoardTaskFormat** 对象。' ms.localizationpriority: medium author: TarkanSevilmis ms.prod: planner doc_type: resourcePageType ms.openlocfilehash: f244c9ff4cd4e9801c1ecef0e1e1170e35f699c0 ms.sourcegitcommit: 6c04234af08efce558e9bf926062b4686a84f1b2 ms.translationtype: MT ms.contentlocale: zh-CN ms.lasthandoff: 09/12/2021 ms.locfileid: "59044389" --- # <a name="plannerassignedtotaskboardtaskformat-resource-type"></a>plannerAssignedToTaskBoardTaskFormat 资源类型 命名空间:microsoft.graph **plannerAssignedToTaskBoardTaskFormat** 资源表示用于在任务板 (的 AssignedTo 视图中正确呈现任务的信息) 用户组织的视图。 每个 [任务](plannertask.md) 都有一个 **与之关联的 plannerAssignedToTaskBoardTaskFormat** 对象。 ## <a name="methods"></a>方法 | 方法 | 返回类型 |说明| |:---------------|:--------|:----------| |[获取 plannerAssignedToTaskBoardTaskFormat](../api/plannerassignedtotaskboardtaskformat-get.md) | [plannerAssignedToTaskBoardTaskFormat](plannerassignedtotaskboardtaskformat.md) |读取 **plannerAssignedToTaskBoardTaskFormat 对象的属性和** 关系。| |[更新](../api/plannerassignedtotaskboardtaskformat-update.md) | [plannerAssignedToTaskBoardTaskFormat](plannerassignedtotaskboardtaskformat.md) |更新 **plannerAssignedToTaskBoardTaskFormat** 对象。 | ## <a name="properties"></a>属性 | 属性 | 类型 |说明| |:---------------|:--------|:----------| |id|String| 只读。 资源的 ID。 长度为 28 个字符,区分大小写。 [格式验证](planner-identifiers-disclaimer.md)在服务上完成。| |orderHintsByAssignee|[plannerOrderHintsByAssignee](plannerorderhintsbyassignee.md)|用于为任务板 AssignedTo 视图上的任务进行排序的提示字典。每个条目的键是任务分配到的用户之一,值为排序提示。[此处](planner-order-hint-format.md)概述了各值的格式。| |unassignedOrderHint|字符串|当任务未分配给任何人,或 orderHintsByAssignee 字典未向分配到任务的用户提供排序提示时,用于为任务板 AssignedTo 视图上的任务进行排序的提示值。[此处](planner-order-hint-format.md)概述了此格式。| ## <a name="relationships"></a>关系 无 ## <a name="json-representation"></a>JSON 表示形式 下面是资源的 JSON 表示形式。 <!--{ "blockType": "resource", "optionalProperties": [], "baseType": "microsoft.graph.entity", "@odata.type": "microsoft.graph.plannerAssignedToTaskBoardTaskFormat" }--> ```json { "id": "String (identifier)", "orderHintsByAssignee": {"@odata.type": "microsoft.graph.plannerOrderHintsByAssignee"}, "unassignedOrderHint": "String" } ``` <!-- uuid: 8fcb5dbc-d5aa-4681-8e31-b001d5168d79 2015-10-25 14:57:30 UTC --> <!-- { "type": "#page.annotation", "description": "plannerAssignedToTaskBoardTaskFormat resource", "keywords": "", "section": "documentation", "tocPath": "" }-->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Fork Me! FCC: Test Suite Template</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <header class="header"> <h1 id="title" class="text-isAligned-center">GioEmmy Survey Form</h1> <p id="description" class="description text-isAligned-center"> Please answer a few question to help us improve our website </p> </header> <form id="survey-form"> <div class="form-group"> <label id="name-label" for="name">Name</label> <input type="text" name="name" id="name" class="form-control" placeholder="Enter your name" required/> </div> <div class="form-group"> <label id="email-label" for="email">Email</label> <input type="email" name="email" id="email" class="form-control" placeholder="Enter your Email" required /> </div> <div class="form-group"> <label id="number-label" for="number" >Age<span class="optional">optional</span></label> <input type="number" name="age" id="number" min="10" max="99" class="form-control" placeholder="Age"/> </div> <div class="form-group"> <p>We would love to know who you are?</p> <select id="dropdown" name="role" class="form-control" required> <option disabled selected value>Select your description</option> <option value="buyer">buyer</option> <option value="seller">Seller</option> <option value="marketer">Marketer</option> <option value="other">Other</option> <option value="no-preference">Prefer not to say</option> </select> </div> <div class="form-group"> <p>Would you recommend GioEmmy products to a friend?</p> <label> <input name="user-recommend" value="definitely" type="radio" class="input-radio" checked/>Definitely </label> <label> <input name="user-recommend" value="maybe" type="radio" class="input-radio"/>Maybe</label> <label> <input name="user-recommend" value="not-sure" type="radio" class="input-radio" />Not sure</label> </div> <div class="form-group"> <p> which is your best products on GioEmmy website? </p> <select id="most-like" name="mostLike" class="form-control" required> <option disabled selected value>Select an option</option> <option value="gadgets">Gadgets</option> <option value="mobile-phone">Mobile Phones</option> <option value="computer">computer and accssory</option> <option value="clothing">clothing</option> </select> </div> <div class="form-group"> <p> What would you like us to improve? <span class="optional">(Check all that apply)</span> </p> <label> <input name="prefer" value="delivering" type="checkbox" class="input-checkbox"/>Quick method of delivering products </label> <label> <input name="prefer" value="price-of-products" type="checkbox" class="input-checkbox"/>Price of products </label> <label> <input name="prefer" value="improved-shopping-list" type="checkbox" class="input-checkbox"/>improved shopping lists </label> <label> <input name="prefer" value="accessibility-features" type="checkbox" class="input-checkbox"/>accessibility features </label> <label> <input name="prefer" value="comments" type="checkbox" class="input-checkbox"/>comments </label> <label> <input name="prefer" value="forum" type="checkbox" class="input-checkbox"/>Forum for buyers and sellers </label> <label> <input name="prefer" value="discount" type="checkbox" class="input-checkbox"/>increased discount </label> <label> <input name="prefer" value="others" type="checkbox" class="input-checkbox"/>Others </label> <div class="form-group"> <p>Any comments or suggestions?</p> <textarea id="comments" class="input-textarea" name="comment" placeholder="Enter your comment here..."> </textarea> </div> <div class="form-group"> <button type="submit" id="submit" class="button">Submit</button> </div> </form> <script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script> <!-- <label id="name-label" for="name">Name</label> <input type="text" name="name" id="name" class="form-control" placeholder="Enter your name" required/> </div> Hello Camper! For now, the test suite only works in Chrome! Please read the README below in the JS Editor before beginning. Feel free to delete this message once you have read it. Good luck and Happy Coding! - The freeCodeCamp Team --> <script src="js/index.js"></script> </body> </html>
import { ClockType, EditingDailyStampTime, fetchDailyStampTime, postStamp, PostStampRequest, STAMP_SOURCE, } from '../../domain/models/attendance/DailyStampTime'; import { AppDispatch } from '../modules/AppThunk'; import * as commonActions from '../actions/app'; import * as stampWidgetActions from '../actions/stampWidget'; import * as dailyStampTimeResultActions from './DailyStampTimeResult'; /** * 打刻情報を取得する */ export const initDailyStampTime = () => (dispatch: AppDispatch) => { return fetchDailyStampTime() .then((result) => { // 打刻情報を適用する dispatch(stampWidgetActions.applyDailyStampTime(result)); }) .catch((err) => dispatch(commonActions.catchApiError(err, { isContinuable: true })) ); }; /** * 打刻を実行(送信)する */ export const submitStamp = ( stampWidget: EditingDailyStampTime, options: | { withGlobalLoading?: boolean; onStampSuccess?: () => void; } | null | undefined ) => (dispatch: AppDispatch) => { // NOTE: 本来発生しえない/mode未定だと打刻ボタンが非活性なので if (stampWidget.mode === null || stampWidget.mode === undefined) { // eslint-disable-next-line prefer-promise-reject-errors return Promise.reject(); } const { withGlobalLoading, onStampSuccess } = options || {}; const postParams: PostStampRequest = { mode: stampWidget.mode, comment: stampWidget.message, }; const commonPostProcess = () => postStamp(postParams, STAMP_SOURCE.WEB); const postProcess = withGlobalLoading ? commonActions.withLoading(commonPostProcess) : commonPostProcess; // ユーザー操作を防止する dispatch(stampWidgetActions.blockOperation()); return dispatch(postProcess) .then((result) => dispatch( dailyStampTimeResultActions.confirmToComplementInsufficientingRestTime( result ) ) ) .then(() => { if (onStampSuccess && onStampSuccess instanceof Function) { onStampSuccess(); } }) .catch((err) => dispatch(commonActions.catchApiError(err, { isContinuable: true })) ) .then(() => { dispatch(initDailyStampTime()); }); }; /** * 出勤・退勤を切り替える * @param {String} clockType */ export const switchClockType = (clockType: ClockType) => (dispatch: AppDispatch) => { dispatch(stampWidgetActions.switchClockType(clockType)); }; /** * メッセージを更新する * @param {String} message * @returns {{type: String, payload: Object}} */ export const updateMessage = (message: string) => (dispatch: AppDispatch) => { dispatch(stampWidgetActions.updateMessage(message)); };
import { createContext, useMemo, useReducer } from 'react' import { CssBaseline, Dialog, Drawer, Snackbar, Theme, ThemeProvider, } from '@mui/material' import { Error } from '@/components/ui/Error' import { uiReducer } from './reducer' import { State, UIContextType } from './types' export const uiContext = createContext<UIContextType | undefined>(undefined) type Props = { theme: Theme children?: React.ReactNode } const initialState: State = { snackbarState: { open: false, message: '', autoHideDuration: 4000, }, drawerState: { open: false, component: null, }, dialogState: { open: false, component: null, }, error: null, } export function UIProvider({ theme, children }: Props) { const [state, dispatch] = useReducer(uiReducer, initialState) const handleDrawerClose = () => { dispatch({ type: 'HIDE_DRAWER' }) } const handleDialogClose = () => { dispatch({ type: 'HIDE_DIALOG' }) } const handleSnackbarClose = (_: unknown, reason?: string) => { if (reason === 'clickaway') { return } dispatch({ type: 'HIDE_SNACKBAR' }) } const value: UIContextType = useMemo( () => ({ showDrawer(component) { dispatch({ type: 'SHOW_DRAWER', payload: component }) }, hideDrawer: handleDrawerClose, showDialog(component) { dispatch({ type: 'SHOW_DIALOG', payload: component }) }, hideDialog: handleDialogClose, showSnackbar(params) { dispatch({ type: 'SHOW_SNACKBAR', payload: params }) }, showError(params) { dispatch({ type: 'SHOW_ERROR', payload: params }) }, hideError() { dispatch({ type: 'HIDE_ERROR' }) }, }), [dispatch] ) const { drawerState, dialogState, snackbarState, error } = state return ( <ThemeProvider theme={theme}> <CssBaseline /> <uiContext.Provider value={value}> {children} <Drawer css={theme => ({ zIndex: theme.zIndex.drawer + 2, })} anchor="right" open={drawerState.open} onClose={handleDrawerClose} elevation={1} > {drawerState.component} </Drawer> <Dialog open={dialogState.open} onClose={handleDialogClose} maxWidth={'xl'} > {dialogState.component} </Dialog> <Snackbar open={snackbarState.open} onClose={handleSnackbarClose} autoHideDuration={snackbarState.autoHideDuration} anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }} message={snackbarState.message} /> {error && <Error message={error.message} snackbar />} </uiContext.Provider> </ThemeProvider> ) }
#pragma once // Copyright (c) 2015 Tony Kirke. License MIT (http://www.opensource.org/licenses/mit-license.php) // from directory: spuc_templates #include <spuc/spuc_types.h> #include <spuc/complex.h> #include <spuc/iir_allpass1_halfband.h> #include <spuc/timing_nco.h> #include <spuce/filters/lagrange.h> namespace SPUC { //! \file //! \brief A resampling block using interpolator, halfband filter and NCO // //! \brief A resampling block using interpolator, halfband filter and NCO // //! Resampling block //! This class uses //! an interpolator //! a halfband filter (for decimating by 2) //! and a NCO //! samples are input with each call to update, //! but output samples are available when the //! ready bit is set //! The halfband filter is a simple IIR filter based on //! two first order allpass filters. //! The interpolator is a Lagrange interpolating FIR //! \author Tony Kirke //! \ingroup templates examples template <class Numeric> class resampler { public: bool ready; long sample2; spuce::lagrange<Numeric> interp; timing_nco symbol_nco; //! Symbol NCO Numeric resampled; iir_allpass1_halfband<Numeric> half; //! Halfband filter (decimate by 2) resampler(void) : interp(4), half(0.25, 0.75) { resampled = (Numeric)0; ready = 0; } Numeric update(Numeric input_data, long symbol_loop, long sym_clk) { float_type time1, time2; Numeric resampled1, resampled2; Numeric half_out; // Sampling NCO // Determine if 2nd sample should be processed sample2 = symbol_nco.run(symbol_loop, sym_clk); time1 = symbol_nco.get_off1(); time2 = symbol_nco.get_off2(); resampled1 = interp.update(input_data, time1); resampled2 = interp.rephase(time2); half_out = half.clock(resampled1); if (half.ready()) { ready = 1; resampled = half_out; } else { ready = 0; resampled = (Numeric)0; } // if 2nd sample should be used, send it through // the decimating halfband filter, // then check is output is ready if (sample2) { half_out = half.clock(resampled2); if (half.ready()) { ready = 1; resampled = half_out; } } return (resampled); } }; } // namespace SPUC
# monitoreo-oyameles [![DOI](https://zenodo.org/badge/333581041.svg)](https://zenodo.org/badge/latestdoi/333581041) (English below) Datos y análisis del monitoreo participativo del estado de salud de árboles de oyamel en el Parque Nacional Desierto de los Leones y sus zonas de influencia en Bienes Comunales Santa Rosa Xochiac, cuyo resumen de resultados [puede verse aquí](scripts/2_resumen_monitoreo_no_code.pdf). Estos resultados forman parte del proyecto 308488 *Monitoreo y manejo para la conservación de bosques aledaños a la CDMX afectados por contaminación atmosférica* de la convocatoria FORDECYT 2019-5, y son uno de los insumos de la elaboración de la propuesta en extenso de la convocatoria Proyectos Nacionales de Investigación e Incidencia para la Sustentabilidad de los Sistemas Socioecológicos. El monitoreo fue realizado por brigadistas de Bienes Comunales Santa Rosa Xochiac durante diciembre 2020 y enero 2021. En total se muestrearon 48 parcelas de 10 x 10 m dentro del polígono del Parque Nacional Desierto de los Leones y Santa Rosa Xochiac. Dentro de cada parcela se censaron todos los árboles de oyamel superiores a 20 cm de alto o 0.5 cm de dimámetro, con un total de más de 1,700 árboles muestreados. Ver sección "Formularios kobo" para detalles. Los datos se tomaron con la aplicación kobo-toolbox instalada en los servidores de la conabio (kobo.conabio.gob.mx). Todos los árboles fueron etiquetados en campo con etiquetas de madera biodegradables. Todos las fotografías fueron revisadas manualmente como parte del control de calidad. Se realizó un taller de retroalimentación con la comunidad de Bienes Comunales Santa Rosa Xochiac donde se discutieron tanto los resultados del monitoreo como oportunidades de mejora en su impliementación en campo. ## Datos Los datos corresponden al resultado del muestreo participativo realizado con kobo-conabio y a datos espaciales utilizados para contextualizar espacialmente los resultados. Los datos se encuentran organizados de la siguente forma: ### `data/kobo` Datos crudos: * **muestreo\_dic2020\_raw.txt** Datos crudos resultado de exportar los datos del formulario de kobo CX\_Colecta_Censo\_2020. Este formulario se ocupó para levantar información de todos los árboles de oyamel presentes dentro de 48 parcelas de 10x10 m en diciembre 2020 y enero 2021. La información fue levantada en campo por 13 brigadistas de Santa Rosa Xochiac. * **parcelas\_dic2020\_raw.txt** Datos crudos resultado de exportar los datos del formulairo de kobo CX\_Parcelas\_censo\_oyameles. Este formulario se ocupó para levantar información general de las 48 parcelas muestreadas en diciembre y enero 2021. La información fue levantada por Alicia Mastretta. Una vez que los datos son limpiados y organizados por el script [scripts/1\_preprocesamiento\_datos\_kobo.Rmd](scripts/1_preprocesamiento_datos_kobo.Rmd) se producen los siguientes archivos: * **muestreo\_dic2020\_tidy.txt**: datos de las 48 parcelas tras el procesamiento de limpieza. * **parcelas\_dic2020\_tidy.txt**: además de los datos originales, incluye la suma de árboles bajo cada categoría de salud (sano, daño por ozno, entre otros). ### `data/kobo_images` Contiene las fotografías tomadas en campo de cada árbol. Por el momento este contenido sólo está disponible localmente en los servidores de la CONABIO. ### `data/spatial` Contiene en formato shapefile los archivos: * __CDMX.\*__ polígono de la CDMX * __Desierto\_Leones\_Geo\_ITRF08.*__ polígono del Parque Nacional Desierto de los Leones. Mismos que fueron utilizados junto con imágenes satelitales de google (ver `scripts/2_resumen_monitoreo.Rmd` y `scripts/3_figuras_propuesta.Rmd`) para realizar los mapas del reporte y la propuesta en extenso. ## Análisis y reporte de resultados Los datos se procesaron con los siguientes scripts. De cada script existe también una versión html del mismo nombre que muestra el código y los resultados. ### [scripts/1\_preprocesamiento\_datos\_kobo](scripts/1_preprocesamiento_datos_kobo.Rmd): Toma los datos crudos generados en kobo (*_raw.txt) y realiza un proceso de control de calidad con los siguientes pasos generales: * Revisión de errores comunes (eg. valores fuera de rango) * Examinar y limpiar datos de salud de los árboles * Examinar y limpiar datos del daño por ozono * Examinar y limpiar notas sobre reforestación * Reformatear datos a formato "largo" para análisis y exportar datos (*_tidy.txt) ### [scripts/2\_resumen\_monitoreo](scripts/2_resumen_monitoreo.Rmd): Utiliza los datos limpios (*_tidy.txt) para hacer un reporte del monitoreo participativo que incluye: * La distribución geográfica del estado de salud de los árboles por parcela * Distribución del daño ozono segun altitud y latitud * Estado de salud de árboles individuales según: origen (natural, reforestado), exposición (cubierto/expuesto), altura, diámetro, edad * Porcentaje de daño del árbol dañado por ozono en áboles individuales según: origen (natural, reforestado), exposición (cubierto/expuesto), altura, diámetro y edad. ### [scripts/3\_figuras\_propuesta](scripts/3_figuras_propuesta.Rmd): Utiliza los datos limpios (*_tidy.txt) para hacer el subconjunto de figuras del reporte que se utilizaron para la propuesta en extenso. ### [scripts/4\_figures\_Monitoring-Paper.Rmd](scripts/4_figures_Monitoring-Paper.Rmd): Análisis y figuras para el artículo *Evaluating pollution-related damage and restoration success in urban forests with participatory monitoring and digital tools* Conservation Biology. https://doi.org/10.1111/cobi.14112. ## Formularios kobo Los formularios kobo utilizados se encuentran en el directorio `/kobo_forms`. Los formularios se presentan en formato .xlsx, lo que permite importarlos en el servidor web de kobo, y en formato .pdf, lo que permite visualizar más fácilmente las preguntas. ### Formulario CX\_Colecta\_Censo\_2020 Formulario utilizado por las personas brigadistas para la recolección de datos de árboles individuales dentro de las parcelas. De cada árbol se tomaron coordenadas geográficas, datos dasométricos, fenológicos y de salud, origen (reforestado/natural), exposición (expuesto/cubierto) si habían sido utilizados como fuente de semilla, fotografías y muestras de tejido que fueron preservadas en sílica gel. Ver versión pdf para la lista de preguntas completas. ### Formulario CX\_Parcelas\_censo\_oyameles Formulario utilizado por el equipo académico para el levantamiento de datos de las parcelas. De cada parcela se tomaron datos sobre la cobertura forestal y arbustiva, suelo, especies vegetales dominantes, pendiente y relieve. # English [![DOI](https://zenodo.org/badge/333581041.svg)](https://zenodo.org/badge/latestdoi/333581041) Data and analysis of the participatory monitoring of the health status of oyamel trees in the Desierto de los Leones National Park and its areas of influence in Bienes Comunales Santa Rosa Xochiac, whose summary of results [can be seen here](scripts/2_resumen_monitoreo_no_code.pdf). These results are part of project 308488 *Monitoring and management for the conservation of forests surrounding CDMX affected by air pollution* of the FORDECYT 2019-5 CONACYT grant, and are one of the inputs for the preparation of the full proposal for PRONACES. The monitoring was carried out by brigade members of Santa Rosa Xochiac Bienes Comunales during December 2020 and January 2021. In total, 48 plots of 10 x 10 m were sampled within the polygon of the Desierto de los Leones and Santa Rosa Xochiac. Within each plot, all fir trees greater than 20 cm tall or 0.5 cm in diameter were censused, with a total of more than 1,700 sampled trees. See the "Kobo Forms" section for details. The data was taken with the kobo-toolbox application installed on the CONABIO servers (kobo.conabio.gob.mx). All trees were tagged in the field with biodegradable wooden tags. All photographs were manually reviewed as part of quality control. A feedback workshop was held with the Bienes Comunales Santa Rosa Xochiac community where both the monitoring results and opportunities for improvement in its implementation in the field were discussed. ## Data The data correspond to the result of the participatory sampling carried out with kobo-conabio and to spatial data used to spatially contextualize the results. The data is organized as follows: ### `data/kobo` Raw data: * **muestreo\_dic2020\_raw.txt** Raw data resulting from exporting the data from the kobo CX\_Collecta_Censo\_2020 form. This form was used to collect information on all fir trees present within 48 plots of 10x10 m in December 2020 and January 2021. The information was collected in the field by 13 brigade members from Santa Rosa Xochiac. * **parcelas\_dic2020\_raw.txt** Raw data resulting from exporting the data from the kobo CX formulary\_Plots\_census\_oyameles. This form was used to collect general information on the 48 plots sampled in December and January 2021. The information was collected by Alicia Mastretta. Once the data is cleaned and organized by the script [scripts/1\_preprocessing\_data\_kobo.Rmd](scripts/1_preprocessing_data_kobo.Rmd) the following files are produced: * **muestreo\_dic2020\_tidy.txt**: data from the 48 plots after cleaning processing. * **parcelas\_dic2020\_tidy.txt**: in addition to the original data, it includes the sum of trees under each health category (healthy, ozone damage, among others). ### `data/kobo_images` It contains the photographs taken in the field of each tree. At the moment this content is only available locally on the CONABIO servers. ### `data/spatial` It contains the files in shapefile format: * __CDMX.\*__ CDMX polygon * __Desierto\_Leones\_Geo\_ITRF08.*__ polygon of the Desierto de los Leones National Park. These were used together with google satellite images (see scripts/2_resumen_monitoreo.Rmd` and `scripts/3_figuras_propuesta.Rmd`) to make the maps of the report and the full proposal. ## Analysis and reporting of results The data was processed with the following scripts. For each script there is also an html version of the same name that shows the code and the results. ### [scripts/1\_preprocesamiento\_datos\_kobo](scripts/1_preprocesamiento_datos_kobo.Rmd): Take the raw data generated in kobo (*_raw.txt) and perform a quality control process with the following general steps: * Review of common errors (eg. values ​​out of range) * Browse and clean tree health data * Examine and clean ozone damage data * Examine and clean notes on reforestation * Reformat data to "long" format for analysis and export data (*_tidy.txt) ### [scripts/2\_resumen\_monitoreo](scripts/2_resumen_monitoreo.Rmd): Use the clean data (*_tidy.txt) to make a participatory monitoring report that includes: * The geographical distribution of the state of health of the trees by plot * Distribution of ozone damage according to altitude and latitude * Health status of individual trees according to: origin (natural, reforested), exposure (covered/exposed), height, diameter, age * Percentage of tree damage damaged by ozone in individual trees according to: origin (natural, reforested), exposure (covered/exposed), height, diameter, and age. ### [scripts/3\_figuras\_propuesta](scripts/3_figuras_propuesta.Rmd): Use the clean data (*_tidy.txt) to make the subset of report figures that were used for the full proposal. ### [scripts/4\_figures\_Monitoring-Paper.Rmd](4\_figures\_Monitoring-Paper.Rmd): Analysis and figures for the article *Evaluating pollution-related damage and restoration success in urban forests with participatory monitoring and digital tools* Conservation Biology. https://doi.org/10.1111/cobi.14112. ## Kobo Forms The kobo forms used are located in the `/kobo_forms` directory. The forms are presented in .xlsx format, which allows you to import them into the kobo web server, and in .pdf format, which makes it easier to view the questions. ### Form CX\_Collection\_Census\_2020 Form used by brigade members to collect data on individual trees within the plots. Geographic coordinates, dasometric, phenological and health data, origin (reforested/natural), exposure (exposed/covered) if they had been used as a seed source, photographs and tissue samples that were preserved in silica gel were taken from each tree. See pdf version for the list of complete questions. ### Form CX\_Colecta\_Censo\_2020 Form used by the academic team to collect data from the plots. Data on forest and shrub cover, soil, dominant plant species, slope, and relief were collected from each plot.
transform_design_flies = function(design_df, intensity_df) { # Inputs: # design_df: a data.frame (not tibble) with the design to be transformed. Its colnames should be c("R", "O", "Y", "G", "B", "P", "UV", "intensity", "cs"). The last column can be differently named, but it should identify the choice set and be numeric. # intensity_df: data.frame with the intensity values # Returns a list with the following objects: # design_orig: Original design but with one row identifying each choice set # designL_exp: The transformed values of the left side # designR_exp: The transformed values of the right side # design_software: A dataframe with the structure that Frank needs # design_with_mixture: A dataframe where each row is a choice set, and it includes the original design and the folder name where it's going to be saved. This is used for the mapping and reading of the counts later. q = 7 n_pv = 1 n_var = q + n_pv S = max(design_df[, n_var +1]) J = nrow(design_df)/S if(J != 2) stop("J should be 2") if(ncol(design_df) != n_var+1) stop("Design should have 9 columns") ## Left design_origL <- design_df[seq(1, J*S, J), 1:n_var] colnames(design_origL) <- c('R_left', 'O_left', 'Y_left', 'G_left', 'B_left', 'P_left', 'UV1_left', 'intensityL') # calibration mL <- (intensity_df[n_var, 'L'] + intensity_df[n_var+1, 'L']) / 2 deltaL <- (intensity_df[n_var, 'L'] - intensity_df[n_var+1, 'L']) / 2 design_origL$intensityL_actual <- design_origL$intensityL*deltaL + mL # experiment design left designL_exp <- data.frame(matrix(nrow = S, ncol = n_var-1)) for (i in 1:S) { for (j in 1:(n_var-1)) { designL_exp[i,j] <- round(design_origL[i,j]*design_origL[i, 'intensityL_actual'] / intensity_df[j, 'L']*99, 2) } } colnames(designL_exp) <- c('R', 'O', 'Y', 'G', 'B', 'P', 'UV1') # original design right design_origR <- design_df[seq(2, J*S, J), 1:n_var] colnames(design_origR) <- c('R_right', 'O_right', 'Y_right', 'G_right', 'B_right', 'P_right', 'UV1_right', 'intensityR') # calibration right mR <- (intensity_df[n_var, 'R'] + intensity_df[n_var+1, 'R']) / 2 deltaR <- (intensity_df[n_var, 'R'] - intensity_df[n_var+1, 'R']) / 2 design_origR$intensityR_actual <- design_origR$intensityR*deltaR + mR # experiment design right designR_exp <- data.frame(matrix(nrow = S, ncol = n_var-1)) for (i in 1:S) { for (j in 1:(n_var-1)) { designR_exp[i,j] <- round(design_origR[i,j]*design_origR[i, 'intensityR_actual'] / intensity_df[j, 'R']*99, 2) } } colnames(designR_exp) <- c('R', 'O', 'Y', 'G', 'B', 'P', 'UV1') # combine design_orig <- cbind(design_origL[,1:n_var], design_origR[,1:n_var]) design_orig$chid <- seq(1,S,1) # # combine swapped # design_orig_swapped <- cbind(design_origR[,1:n_var], design_origL[,1:n_var]) # colnames(design_orig_swapped) <- c('R_left', 'O_left', 'Y_left', 'G_left', 'B_left', 'P_left', 'UV1_left', 'intensityL', 'R_right', 'O_right', 'Y_right', 'G_right', 'B_right', 'P_right', 'UV1_right', 'intensityR') # design_orig_swapped$chid <- seq(1,S,1) expL <- data.frame(matrix(nrow = S, ncol = 2*n_var)) colnames(expL) <- c('R', '', 'O', '', 'Y', '', 'G', '', 'B', '', 'P', '', 'UV1', '', 'UV2', '') # left: set values for (i in 1:S) { for (j in 1:(n_var-1)) { if (design_origL[i,j] == 0) { expL[i,2*j-1] = 'F' } else { expL[i,2*j-1] = 'T' } expL[i,2*j] = designL_exp[i,j] }} # left: drop UV2 - always F expL[, (2*n_var)-1] = 'F' expL[, (2*n_var)] = 0 # right expR <- data.frame(matrix(nrow = S, ncol = 2*n_var)) colnames(expR) <- c('R', '', 'O', '', 'Y', '', 'G', '', 'B', '', 'P', '', 'UV1', '', 'UV2', '') for (i in 1:S) { for (j in 1:(n_var-1)) { if (design_origR[i,j] == 0) { expR[i,2*j-1] = 'F' } else { expR[i,2*j-1] = 'T' } expR[i,2*j] = designR_exp[i,j] }} expR[, (2*n_var)-1] = 'F' expR[, (2*n_var)] = 0 # convert design to fit the software: replicate rows to allow for wash-out period and set 'F 0' exp <- cbind(expL, expR) exp_rep <- exp[rep(seq_len(nrow(exp)), each = 2), ] for (i in seq(2, J*S, 2)) { for (j in seq(1, ncol(exp_rep), 2)) { exp_rep[i,j] = 'F' } for (k in seq(2, ncol(exp_rep), 2)) { exp_rep[i,k] = '0' } } exp_setting <- data.frame(rep(c(1200, 300), S), rep(c(10, 300), S), rep(80000, 2*S), rep(140000, 2*S)) colnames(exp_setting) <- c('LED', 'Image', 'Exposure1', 'Exposure2') exp_rep <- cbind(exp_setting, exp_rep) # make connections between two designs # 1. round to integers expL_round <- data.frame(lapply(expL, function(x) if(is.numeric(x)) round(x, 0) else x)) expR_round <- data.frame(lapply(expR, function(x) if(is.numeric(x)) round(x, 0) else x)) colnames(expL_round) <- c('R', '', 'O', '', 'Y', '', 'G', '', 'B', '', 'P', '', 'UV1', '', 'UV2', '') colnames(expR_round) <- c('R', '', 'O', '', 'Y', '', 'G', '', 'B', '', 'P', '', 'UV1', '', 'UV2', '') exp_round <- cbind(expL_round, expR_round) # 2. append settings into a long string exp_round$name <- rep(' ', S) for (i in 1:S) { exp_round[i,4*n_var+1] <- paste(exp_round[i,], collapse = '') } exp_round$name <- substr(exp_round$name, 1, nchar(exp_round$name)-1) exp_round$chid <- seq(1,S,1) design_with_mixture <- merge(exp_round[, c('chid', 'name')], design_orig, by = 'chid') %>% dplyr::select(-chid) %>% dplyr::rename( intensity_left = intensityL, intensity_right = intensityR, UV_left = UV1_left, UV_right = UV1_right, folder = name ) out <- list() out$design_orig <- design_orig # out$design_origL <- design_origL # out$design_origR <- design_origR # out$design_orig_swapped <- design_orig_swapped out$designL_exp <- designL_exp out$designR_exp <- designR_exp out$design_software <- exp_rep # out$design_exp_with_name <- exp_round out$design_with_mixture <- design_with_mixture return(out) }
import 'package:flutter/material.dart'; import 'package:hire_app/core/l10n/app_localizations.g.dart'; import 'package:hire_app/core/styles/tokens.dart'; import 'package:hire_app/core/utils/extensions/date_extension.dart'; import 'package:hire_app/core/widgets/widgets.dart'; import 'package:hire_app/features/home/domain/entities/service_entity.dart'; class ScheduleItem extends StatelessWidget { const ScheduleItem({ required this.date, required this.showDate, required this.services, required this.description, super.key, }); final bool showDate; final DateTime date; final String description; final List<ServiceEntity> services; @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (showDate) ...[ Text( date.weekdayDayMonth(l10n), style: TextStyle( fontSize: Tokens.fontSize.ref16, ), ), SizedBox(height: Tokens.size.ref2), ], Clickable( onTap: () {}, color: Tokens.colors.primary, padding: EdgeInsets.all(Tokens.size.ref3), decoration: BoxDecoration( color: Tokens.colors.primary, borderRadius: BorderRadius.circular(Tokens.radius.normal), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: services.map((e) { return Text( '• ${e.name}', style: TextStyle( color: Tokens.colors.background, fontSize: Tokens.fontSize.ref16, ), ); }).toList(), ), const Spacer(), Text( date.hourAndMinute(), style: TextStyle( color: Tokens.colors.background, fontSize: Tokens.fontSize.ref10, fontWeight: FontWeight.bold, ), ), ], ), SizedBox(height: Tokens.size.ref3), Text( description, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( color: Tokens.colors.background, fontSize: Tokens.fontSize.ref10, ), ), ], ), ), ], ); } }
/* Artifact Three: Databases */ /* Database Name: animalshelterdb This SQL file shows the steps taken to create and query from a database named 'animalshelterdb' You can also export the data from this table into data mining tools such as JMP and sofastats The information within this database can act as a real-life example when maintaining a patient database for an animal shelter DB Tool: MySQL Workbench 8.0 Statistics Tool: SOFAstats v1.5.4 Author: Angela Ruhstorfer SNHU CS 499: Computer Science Capstone */ /* Create MySQL database `named animalshelterdb` */ CREATE SCHEMA `animalshelterdb`; /* Create `animal` table within `animalshelterdb` database */ CREATE TABLE `animalshelterdb`.`animal` ( `id` INT NOT NULL, `name` VARCHAR(45) NOT NULL, `type` VARCHAR(45) NOT NULL, `gender` VARCHAR(45) NOT NULL, `age_years` INT NOT NULL, `vet_id` INT NOT NULL, `adoption_status` VARCHAR(45) NOT NULL, `Animalcol` VARCHAR(45) NOT NULL, PRIMARY KEY (`id`)) COMMENT = 'Table of Animals within the SNHU Animal Shelter'; /* Remove additonal `Animalcol` column from `animal` table */ ALTER TABLE `animalshelterdb`.`animal` DROP COLUMN `Animalcol`; /* Add data points into `animal` table */ INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('01', 'Joy', 'Dog', 'F', '6', '07', 'ADOPTED'); INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('02', 'Callie', 'Cat', 'F', '2', '04', 'AVAILABLE'); INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('03', 'Jax', 'Dog', 'M', '8', '09', 'ADOPTION PENDING'); INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('04', 'Nila', 'Dog', 'F', '1', '05', 'AVAILABLE'); INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('05', 'George', 'Cat', 'M', '4', '01', 'AVAILABLE'); INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('06', 'Cheeks', 'Rabbit', 'M', '1', '10', 'ADOPTION PENDING'); INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('07', 'Milo', 'Dog', 'M', '4', '03', 'AVAILABLE'); INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('08', 'Willow', 'Horse', 'F', '10', '06', 'AVAILABLE'); INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('09', 'Troy', 'Dog', 'M', '2', '02', 'ADOPTED'); INSERT INTO `animalshelterdb`.`animal` (`id`, `name`, `type`, `gender`, `age_years`, `vet_id`, `adoption_status`) VALUES ('10', 'Cherri', 'Cat', 'F', '1', '08', 'AVAILABLE'); /* Create `vet_record` table within `animalshelterdb` database */ CREATE TABLE `animalshelterdb`.`vet_record` ( `vet_id` INT NOT NULL AUTO_INCREMENT, `bloodwork` VARCHAR(45) NOT NULL, `rabies_vaccine` VARCHAR(45) NOT NULL, `fixed` VARCHAR(45) NOT NULL, `dental_cleaning` VARCHAR(45) NOT NULL, `grooming` VARCHAR(45) NOT NULL, `deworming` VARCHAR(45) NOT NULL, `ready_for_adoption` VARCHAR(45) NOT NULL, PRIMARY KEY (`vet_id`)); COMMENT = 'Table of vet records for the animals within the SNHU Animal Shelter'; /* Add data points into `vet_record` table */ INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('01', 'y', 'y', 'n', 'n', 'y', 'n', 'n'); INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('02', 'y', 'y', 'n', 'y', 'y', 'y', 'y'); INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('03', 'y', 'y', 'y', 'n', 'n', 'y', 'Y'); INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('04', 'y', 'y', 'y', 'n', 'n', 'y', 'Y'); INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('05', 'n', 'n', 'y', 'y', 'n', 'n', 'N'); INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('06', 'y', 'y', 'n', 'y', 'y', 'y', 'Y'); INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('07', 'y', 'y', 'Y', 'Y', 'Y', 'Y', 'Y'); INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('08', 'y', 'y', 'y', 'n', 'n', 'y', 'Y'); INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('09', 'y', 'n', 'y', 'y', 'y', 'y', 'N'); INSERT INTO `animalshelterdb`.`vet_record` (`vet_id`, `bloodwork`, `rabies_vaccine`, `fixed`, `dental_cleaning`, `grooming`, `deworming`, `ready_for_adoption`) VALUES ('10', 'n', 'y', 'n', 'n', 'y', 'y', 'N'); /* Update 3 records in the 'vet.record' table to match other values in 'lowercase' answers */ UPDATE `animalshelterdb`.`vet_record` SET `ready_for_adoption` = 'n' WHERE (`vet_id` = '10'); UPDATE `animalshelterdb`.`vet_record` SET `ready_for_adoption` = 'n' WHERE (`vet_id` = '5'); UPDATE `animalshelterdb`.`vet_record` SET `ready_for_adoption` = 'n' WHERE (`vet_id` = '9'); /* Create `animal_picture` table within `animalshelterdb` database */ CREATE TABLE `animalshelterdb`.`animal_picture` ( `pic_id` INT NOT NULL, `description` VARCHAR(45) NOT NULL, `pic_date` VARCHAR(45) NOT NULL, PRIMARY KEY (`pic_id`)) COMMENT = 'Table of pictures taken of animals within the shelter to post to the adoption site.'; /* Add data points into `animal_picture` table */ INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('01', 'Playing in the grass!', 'June'); INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('02', 'Loves kids!', 'May'); INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('03', 'Enjoys cuddling on the couch.', 'November'); INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('04', 'Shy with new people.', 'July'); INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('05', 'Gorgeous blue eyes!', 'May'); INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('06', 'Swimming in the lake with foster mom!', 'August'); INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('07', 'Fresh treats are their favorite.', 'February'); INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('08', 'Always ready to play!', 'September'); INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('09', 'Pleasant on walks in the park.', 'September'); INSERT INTO `animalshelterdb`.`animal_picture` (`pic_id`, `description`, `pic_date`) VALUES ('10', 'Friendly with other animals!', 'March'); /* Edit 'animal' table to include new 'pic_id' column */ ALTER TABLE `animalshelterdb`.`animal` ADD COLUMN `pic_id` INT NOT NULL AFTER `vet_id`; /* Add data values to 'pic id' column in 'animal' table */ UPDATE `animalshelterdb`.`animal` SET `pic_id` = '3' WHERE (`id` = '2'); UPDATE `animalshelterdb`.`animal` SET `pic_id` = '7' WHERE (`id` = '5'); UPDATE `animalshelterdb`.`animal` SET `pic_id` = '8' WHERE (`id` = '6'); UPDATE `animalshelterdb`.`animal` SET `pic_id` = '5' WHERE (`id` = '8'); UPDATE `animalshelterdb`.`animal` SET `pic_id` = '6' WHERE (`id` = '1'); UPDATE `animalshelterdb`.`animal` SET `pic_id` = '4' WHERE (`id` = '3'); UPDATE `animalshelterdb`.`animal` SET `pic_id` = '9' WHERE (`id` = '4'); UPDATE `animalshelterdb`.`animal` SET `pic_id` = '2' WHERE (`id` = '7'); UPDATE `animalshelterdb`.`animal` SET `pic_id` = '10' WHERE (`id` = '10'); UPDATE `animalshelterdb`.`animal` SET `pic_id` = '1' WHERE (`id` = '9'); /* Use 'animalshelterdb' database and show the tables within it */ USE animalshelterdb; SHOW TABLES; /* Use 'animalshelterdb' database and show columns within the 'animal' table */ USE animalshelterdb; SHOW COLUMNS FROM animal /* Find and display animals that are ready to adopt with their picture description */ SELECT animal.id, animal.name, animal_picture.description, animal.adoption_status, vet_record.ready_for_adoption FROM animal, vet_record, animal_picture WHERE animal.pic_id = animal_picture.pic_id AND vet_record.ready_for_adoption = 'y' AND animal.adoption_status = 'AVAILABLE'
<?php namespace App\Http\Controllers\Auth\Admin; use App\Http\Controllers\Controller; use App\Mail\ForgetPasswordAdmin; use App\Models\ResetPassword; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Str; use Carbon\Carbon; class ForgotPassword extends Controller { public function showForgetPasswordForm() { return view('admin.auth.forgetPassword'); } public function submitForgetPasswordForm(Request $request) { $request->validate([ 'email' => 'required|email|exists:users', ]); $token = Str::random(64); ResetPassword::create([ 'email' => $request->email, 'token' => $token, 'created_at' => Carbon::now() ]); Mail::to($request->email)->send(new ForgetPasswordAdmin($token)); return back()->with('message', 'We have e-mailed your password reset link!'); } public function showResetPasswordForm($token) { return view('admin.auth.forgetPasswordLink', ['token' => $token]); } public function submitResetPasswordForm(Request $request) { $request->validate([ 'email' => 'required|email|exists:users', 'password' => 'required|string|min:6|confirmed', 'password_confirmation' => 'required' ]); $updatePassword = DB::table('password_resets') ->where([ 'email' => $request->email, 'token' => $request->token ]) ->first(); if (!$updatePassword) { return back()->withInput()->with('error', 'Invalid token!'); } $user = User::where('email', $request->email) ->update(['password' => \Hash::make($request->password)]); DB::table('password_resets')->where(['email' => $request->email])->delete(); return redirect('/auth/cws')->with('message', 'Your password has been changed!'); } }
Certainly, Lester. Let's break down each question into step-by-step algorithms: ### 1. Quick Sort Algorithm for Sorting Names **Algorithm:** 1. **Define the Quick Sort Function:** - Inputs: Array of names `names[]`, start index `start`, end index `end`. - Base condition: If `start` is greater than or equal to `end`, return. - Call a partition function and get the partition index `pIndex`. - Recursively call the quick sort function for the left partition (`names`, `start`, `pIndex - 1`). - Recursively call the quick sort function for the right partition (`names`, `pIndex + 1`, `end`). 2. **Partition Function:** - Choose the end element as the pivot. - Initialize a variable `pIndex` at the start index. - Loop through the array from `start` to `end - 1`. - If an element is less than the pivot, swap it with the element at `pIndex`, and increment `pIndex`. - Swap the pivot element with the element at `pIndex`. - Return `pIndex`. 3. **Main Function:** - Initialize an array of names. - Call the quick sort function with the array, 0 as start index, and the length of the array minus 1 as the end index. ### 2. File Handling with Reader/Writer **Algorithm:** 1. **Create a File Writer:** - Initialize a `FileWriter` object with the desired file path. - Write data to the file using the `write` method. - Close the `FileWriter`. 2. **Create a File Reader:** - Initialize a `FileReader` object with the same file path. - Read data from the file using a loop and the `read` method. - Display the read data. - Close the `FileReader`. ### 3. Read and Write Using `FileInputStream` and `FileOutputStream` **Algorithm:** 1. **Setup FileInputStream:** - Create a `FileInputStream` object for the source file. - Handle `FileNotFoundException`. 2. **Setup FileOutputStream:** - Create a `FileOutputStream` object for the destination file. - Handle `FileNotFoundException`. 3. **Read and Write:** - Use a loop to read data from the `FileInputStream`. - Write the read data to the `FileOutputStream`. - Handle `IOException`. 4. **Close Streams:** - Close both `FileInputStream` and `FileOutputStream`. ### 4. Display File Content with Line Numbers **Algorithm:** 1. **Open the File:** - Use `BufferedReader` with `FileReader` to open the file. 2. **Read and Display Lines:** - Initialize a line counter. - Read each line in a loop. - For each line, increment the counter and display the line number followed by the line content. 3. **Close the File:** - Close the `BufferedReader`. ### 5. Count Characters, Lines, and Words in a File **Algorithm:** 1. **Open the File:** - Use `BufferedReader` with `FileReader`. 2. **Initialize Counters:** - Initialize counters for characters, lines, and words. 3. **Read and Count:** - Read the file line by line. - For each line, increment the line counter. - Split the line into words and increment the word counter. - Count the characters in each line and increment the character counter. 4. **Display Counts:** - Display the number of characters, words, and lines. 5. **Close the File:** - Close the `BufferedReader`. These algorithms provide a high-level overview of the programs. When implementing in Java, you'll need to add the necessary imports and handle any exceptions appropriately.
<div class="dashboard"> <div class="sidenav"> <app-sidenav></app-sidenav> </div> <div class="body"> <div class="content "> <div class="header text-center"> <h1>All Users In Your Department</h1> </div> <div class="msg"> <span *ngIf="success" class="alert alert-success text-center">User has been removed successfully</span> <span *ngIf="!mailSent" class="alert alert-danger text-center">User has been deleted but failed to send mail</span> <span *ngIf="fail" class="alert alert-danger text-center">Failed to remove user: Unknown Error</span> <span *ngIf="accessChangesuccess" class="alert alert-success text-center"> Access Changed Successfully</span> <span *ngIf="accessChangeFailure" class="alert alert-danger text-center"> Access Change Failed</span> </div> <div class="container animate__animated animate__fadeIn"> <table class="table table-striped hover" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger"> <thead> <tr> <th>Sl No</th> <th>Name</th> <th>Phone</th> <th>Email</th> <th>Department</th> <th>User Type</th> <th>Operations</th> </tr> </thead> <tbody> <tr *ngFor="let user of allUsers; let i=index"> <td>{{i+1}}</td> <td>{{user.NAME}}</td> <td>{{user.MOBILE_NO}}</td> <td>{{user.EMAIL}}</td> <td>{{user.DEP_CODE}}</td> <td>{{user.USERTYPE}}</td> <td class="ops"> <button style="cursor: pointer;" mat-raised-button color="primary" (click)="changeAccess(i)">Change Access</button> <a data-toggle="modal" style="cursor: pointer;" [attr.data-target]="'#section'+i"><mat-icon color="warn">delete</mat-icon></a> </td> </tr> </tbody> </table> </div> </div> <div *ngFor="let user of allUsers; let i=index;"> <div class="modal fade" id="{{'section' + i}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">{{user.NAME}}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h6>Are you sure you want to delete user - {{user.NAME}}</h6> <small class="text-info">It will send an email to the user with your Name and Email ID with intimation of account deletion</small> </div> <div class="modal-footer"> <button type="button" class="btn btn-success" data-dismiss="modal">No, Cancel</button> <button type="button" class="btn btn-danger" data-dismiss="modal" (click)="deleteUser((user.USERNAME))">Yes Delete!</button> </div> </div> </div> </div> </div> </div> </div>
<?php declare(strict_types=1); namespace App\Http\Controllers\Backend\System; use App\Contracts\RoleRepositoryInterface; use App\Http\Controllers\Controller; use App\Http\Requests\RoleRequest; use App\Models\Permission; use Flasher\SweetAlert\Prime\SweetAlertFactory; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\Support\Renderable; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; class RoleBackendController extends Controller { public function __construct( protected readonly RoleRepositoryInterface $repository, protected readonly SweetAlertFactory $factory ) { } public function index(): Renderable { $roles = $this->repository->getRoles(); return view('backend.domain.roles.index', compact('roles')); } public function create(): Factory|View|Application { $permissions = Permission::query()->get(); return view('backend.domain.roles.create', compact('permissions')); } public function store(RoleRequest $request): RedirectResponse { $this->repository->stored(attributes: $request, flash: $this->factory); return redirect()->route('admins.roles.index'); } public function edit(int $id): Factory|View|Application { $role = $this->repository->showRole(key: $id); $roleHasPermissions = $role->permissions->pluck('id')->toArray(); $permissions = Permission::query()->get(); return view('backend.domain.roles.edit', compact('role', 'permissions', 'roleHasPermissions')); } public function update(int $id, RoleRequest $request): RedirectResponse { $this->repository->updated(key: $id, attributes: $request, flash: $this->factory); return redirect()->route('admins.roles.index'); } public function destroy(int $id): RedirectResponse { $this->repository->deleted(key: $id, flash: $this->factory); return back()->with('success', 'The role has remove with successfull'); } }
/** * Exercise 4 - Conception mistakes * * In our game of Set!, Cards are created in the constructor of the class Game. The class Game is responsible for the * lifecycle of the cards. * * 1. Explain why we could use the design pattern Singleton to create the cards. What would be the advantages and * disadvantages of using the design pattern Singleton? Change the code to use the design pattern Singleton. * (https://refactoring.guru/design-patterns/singleton) * * 2. Change the classes using Game to use the central instance of Game instead of creating a new instance of Game. * Update the UML diagram. * * 3. (optional) Make the game playable in the console. You can use the example code below to get started with the * console interaction. */ import * as readline from "readline/promises"; import { stdin as input, stdout as output } from "process"; (async () => { const rl = readline.createInterface({ input: input, output: output }); const exampleUserInput = await rl.question("What is your name? "); console.log(`Hello ${exampleUserInput}!`); rl.close(); })();
// 42. Trapping Rain Water pub struct Solution; impl Solution { pub fn trap(height: Vec<i32>) -> i32 { //sliding window //[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] let mut left = 0; let mut right = height.len() - 1; let mut l_height = height[left]; let mut r_height = height[right]; let mut water = 0; while left < right { if l_height > r_height { // right height is less than left height // shift right to the left right -= 1; if height[right] < r_height { water += r_height - height[right]; } else { r_height = height[right]; } } else { //left height is less or equal to right height // shift left to the right left += 1; if height[left] < l_height { water += l_height - height[left]; } else { l_height = height[left]; } } } water } } #[cfg(test)] mod tests { use super::*; #[test] fn test1() { assert_eq!(Solution::trap(vec![0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]), 6); } #[test] fn test2() { assert_eq!(Solution::trap(vec![4, 2, 0, 3, 2, 5]), 9); } }
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Blog Post</title> <link href="${pageContext.request.contextPath}/resources/css/bootstrap.css" rel="stylesheet"> <link href="${pageContext.request.contextPath}/resources/css/starter-template.css" rel="stylesheet"> <script src="${pageContext.request.contextPath}/resources/js/jquery-3.5.1.min.js" type="text/javascript"></script> <script src="${pageContext.request.contextPath}/resources/js/bootstrap.min.js"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top"> <div class="container"> <a class="navbar-brand" href="#">Start Bootstrap</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </div> </nav> <!-- Page Content --> <div class="container"> <h1>blog post</h1> <c:if test="${empty blogposts}"> No Blog post is found <br/> </c:if> <br/> <form action="${pageContext.request.contextPath}/searchByTitle" method="post"> <table> <tr><td>Title</td><td><input name="title" type="text"/></td></tr> <tr><td colspan="2"><input type="submit" value="Search"/></td></tr> </table> </form> <c:if test="${not empty blogposts}"> <table style="width:650px" class="table table-striped"> <c:forEach var="blogpost" items="${blogposts}"> <tr> <td>Blog post id</td> <td><c:out value="${blogpost.id}"></c:out></td> </tr> <tr> <td>title</td> <td><c:out value="${blogpost.title}"></c:out></td> </tr> <tr> <td>Content</td> <td><div style = "white-space: pre"><c:out value="${blogpost.content}"></c:out></div></td> </tr> <tr> <td>Draft</td> <td><c:out value="${blogpost.draft}"></c:out></td> </tr> <tr><td colspan="2"></td></tr> <tr><td colspan="2"></td></tr> </c:forEach> </table> </c:if> <a href="${pageContext.request.contextPath}/draftblogposts">Find draft blog posts</a> <a href="${pageContext.request.contextPath}">Back</a><br> <a href="${pageContext.request.contextPath}/newblogpost.html">Enter a new blog post</a> </div> </body> </html>
<template> <v-container class="text-center"> <v-row class="d-flex justify-space-around"> <v-col cols="12" md="6" class="my-auto hidden-sm-and-down"> <div class="d-flex flex-column align-center "> <v-img src="../assets/loginPageSideImg.svg" width="100%"></v-img> </div> </v-col> <v-col cols="12" md="6" sm="9" class="px-13 mt-8"> <div class="d-flex flex-column align-center"> <v-img src="../assets/logo.png" width="150"></v-img> </div> <h1 class="mt-6 mb-4 text-h5 ml-3 font-weight-medium">Login</h1> <v-form> <v-text-field v-model="loginData.userID" :rules="validation.required" label="E-mail or Username" required @keypress.enter="validate" ></v-text-field> <v-text-field v-model="loginData.password" :append-icon="show1 ? 'mdi-eye' : 'mdi-eye-off'" :type="show1 ? 'text' : 'password'" name="input-10-1" label="Password" :rules="validation.required" @click:append="show1 = !show1" required @keypress.enter="validate" ></v-text-field> <div class="text-end mb-2"> <small><router-link to="/forgetPassword"><a>Forgot Password? </a></router-link> </small> </div> <div class="d-flex flex-column align-center py-3 buttons_padding"> <v-btn rounded color="#9f75b4" large class="sign_btn white--text" @click="validate" > Login </v-btn> <div class="d-flex flex-column align-center"> <p><span>or</span></p> </div> <v-btn rounded color="secondary" large class="sign_btn"> <v-icon class="mx-2">mdi-google</v-icon> Login with Google </v-btn> </div> <small>Not Register Yet? <router-link to="/signup"><a>Sign Up</a></router-link></small> </v-form> </v-col> </v-row> </v-container> </template> <script> import * as validations from '../validations' export default { name: "LoginPage", created(){ this.validation = validations }, methods: { validate() { if(this.loginData.userID && this.loginData.password){ this.$store.dispatch('loginValidation', this.loginData) } }, }, data: () => ({ show1: false, validation: '', loginData: { userID: '', password: '' } }), }; </script> <style scoped> p { width: 35%; text-align: center; border-bottom: 1px solid #000; line-height: 0.1em; margin: 20px 0 20px; } p span { background: #fff; padding: 0 10px; } .sign_btn { width: 18rem; } @media only screen and (max-width: 600px) { .sign_btn { width: 15rem; } .l_name { padding-top: 0px; } .f_name { padding-bottom: 0px; } } </style>
import { FrequentlyAskedQuestion, frequentlyAskedQuestion } from '../../../../data'; import { createTRPCRouter, procedure } from '../../../trpc/base'; import { ServerState } from '../../../../services/mongo/state'; import { v4 as uuidv4 } from 'uuid'; import { z } from 'zod'; const state = new ServerState<{ questions: FrequentlyAskedQuestion[] }>('content:faq', { /** Initial data; do not edit! */ questions: [ { id: uuidv4(), question: `What is a hackathon?`, answer: `<Button color="grape">Testing!</Button>` }, { id: uuidv4(), question: `Can I participate?`, answer: '[answer]' }, { id: uuidv4(), question: `Sounds cool, but how much does it cost?`, answer: '[answer]' }, { id: uuidv4(), question: `What should I bring?`, answer: '[answer]' }, { id: uuidv4(), question: `Do I need to come with a team?`, answer: '[answer]' }, { id: uuidv4(), question: `How many people per team?`, answer: '[answer]' }, ] }) export const faqRouter = createTRPCRouter({ list: procedure.public .query(async () => { const questions = await state.get('questions'); return { questions } }), /** Inserts a FAQ entry */ insert: procedure.protected({ content: { write: true } }) .input(( z.object({ /** The position to insert into. Defaults to the end of the list. */ position: z.number().optional(), }).merge(frequentlyAskedQuestion.omit({ id: true })) )) .mutation(async ({ input }) => { const questions = [...(await state.get('questions'))]; const { position, ...rest } = input; const question: FrequentlyAskedQuestion = { id: uuidv4(), ...rest, } if (input.position) { questions.splice(input.position, 0, question) } else { questions.push(question); } state.set('questions', questions); return { questions } }), /** Updates a FAQ entry */ update: procedure.protected({ content: { write: true } }) .input(( z.object({ id: z.string(), /** Apply an offset to the position of this FAQ entry */ relativePosition: z.number().optional(), }).merge(frequentlyAskedQuestion.omit({ id: true }).partial()) )) .mutation(async ({ input }) => { }), /** Arranges the FAQs according to the specified order */ arrange: procedure.protected({ content: { write: true } }) .input(z.object({ /** A list of IDs in the desired order */ order: z.array(z.string()) })) .mutation(async ({ input }) => { }), /** Deletes a FAQ entry */ remove: procedure.protected({ content: { delete: true } }) .input(z.object({ id: z.string() })) .mutation(async ({ input }) => { }), })
<?php namespace Database\Seeders; use App\Models\User; use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; class UserSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { $atasan = User::create([ 'name' =>'atasan', 'email' => 'atasan@gmail.com', 'nip' => '18401347509175', 'golongan' => 'IIC', 'jabatan' => 'Kepala Program Studi', 'unitkerja' => 'Bisnis dan Informatika', 'role' => '2', 'password' => bcrypt('atasan123'), ]); $atasan->assignRole('atasan'); $atasan = User::create([ 'name' =>'atasan2', 'email' => 'atasan2@gmail.com', 'nip' => '18401347509177', 'golongan' => 'IIIC', 'jabatan' => 'Kepala Program Studi', 'unitkerja' => 'Teknik Sipil', 'role' => '2', 'password' => bcrypt('atasan123'), ]); $atasan->assignRole('atasan'); $admin = User::create([ 'name' =>'admin', 'email' => 'admin@gmail.com', 'nip' => '18401347509175', 'golongan' => 'IIC', 'jabatan' => 'Kepala Program Studi', 'unitkerja' => 'Bisnis dan Informatika', 'role' => '1', 'password' => bcrypt('admin123'), ]); $admin->assignRole('admin'); $pegawai = User::create([ 'name' =>'pegawai', 'email' => 'user@gmail.com', 'nip' => '18401347509175', 'golongan' => 'IIC', 'jabatan' => 'Kepala Program Studi', 'unitkerja' => 'Bisnis dan Informatika', 'password' => bcrypt('user123'), ]); $pegawai->assignRole('pegawai'); } }
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ToastrService } from 'ngx-toastr'; import { EmployeesModel } from 'src/app/core/models/employees.model'; import { EmployeesService } from 'src/app/core/services/employees.service'; @Component({ selector: 'app-intranet-model-employees', templateUrl: './edit.component.html', styleUrls: ['./edit.component.css'] }) export class EmployeesEditComponent implements OnInit { form: FormGroup; loading = false; titulo = 'Agregar Empleado'; id: string | undefined; constructor(private fb: FormBuilder, private employeesService: EmployeesService, private toastr: ToastrService) { this.form = this.fb.group({ names: ['', Validators.required], first_surname: [''], last_surname: [''], dni: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(8)]], status_id: [''] }) } async ngOnInit(): Promise<void>{ await this.getEmployee() } save() { if(this.id === undefined) { this.saveEmployee(); } else { this.editEmployee(this.id); } } editEmployee(id: string) { const data: any = { names: this.form.value.names, first_surname: this.form.value.first_surname, last_surname: this.form.value.last_surname, dni: this.form.value.dni, status_id: this.form.value.status_id, } this.loading = true; this.employeesService.edit(id, data).then(() =>{ this.loading = false; this.titulo = `Editando ${data.names} ${data.first_surname} ${data.last_surname}`; this.form.reset(); this.id = undefined; this.toastr.info('El Empleado fue actualizado con exito!', 'Registro Actualizado'); }, error => { console.log(error); }) } saveEmployee() { const data: EmployeesModel = { id_employees: new Date().getTime(), names: this.form.value.names, first_surname: this.form.value.first_surname, last_surname: this.form.value.last_surname, dni: this.form.value.dni, status_id: 1, } this.loading = true; this.employeesService.create(data).then(() => { this.loading = false; this.toastr.success('El empleado fue registrada con exito!', 'Empleado Registrado') this.form.reset(); }, error => { this.loading = false; this.toastr.error('Opps.. ocurrio un error', 'Error'); console.log(error); }) } private async getEmployee(){ this.employeesService.getEmployee().subscribe(data => { this.id = data.id; this.titulo = `Editando ${data.names} ${data.first_surname} ${data.last_surname}`; this.form.patchValue({ names: data.names, first_surname: data.first_surname, last_surname: data.last_surname, dni: data.dni, status_id: data.status_id, }) }) } }
import { ReactElement } from "react"; import { FieldErrors, SubmitHandler, UseFormHandleSubmit, UseFormRegister, } from "react-hook-form"; export interface projectType { image: string[]; name: string; description: string; tech: string[]; links: linkType[]; } export interface linkType { desc: string; link: string; image: string; } export interface formFieldsType { firstName: string; email: string; telegram: string; message: string; } export interface formType { register: UseFormRegister<formFieldsType>; isValid: boolean; handleSubmit: UseFormHandleSubmit<formFieldsType, undefined>; onSubmit: SubmitHandler<formFieldsType>; errors: FieldErrors<formFieldsType>; } export interface getTextType { setText: (lng: "en" | "ru" | "by") => void; getText: (path: string) => string; getTextComponent: (path: string) => ReactElement; }
// Node Deps import axios from 'axios' import type { AxiosInstance, Method } from 'axios' import { effect } from 'vue' import consola from 'consola' // Pinia Stores import { useNotificationStore } from '~/store/notification' export const useAsyncQuery = () => { const runtimeConfig = useRuntimeConfig() const notificationStore = useNotificationStore() const apiUrl = ref(runtimeConfig.public.apiUrl) const requestInstance = ref<AxiosInstance | null>(null) const showError = (errorMessage: string) => { useClientOnly(() => { notificationStore.openErrorNotification(errorMessage) }) useServerOnly(() => { consola.error(errorMessage) }) } const getApiUrl = (path: string) => { if (runtimeConfig.public.proxyEnabled) { return import.meta.server ? process.env.API_URL + path.replace('/api', '') : path } return runtimeConfig.public.apiUrl + path.replace('/api', '') } const createInstance = () => { const instance = axios.create() instance.defaults.baseURL = apiUrl.value instance.interceptors.response.use( response => response, error => showError(error.message), ) instance.defaults.headers['Content-Type'] = 'application/json' return instance } effect(() => { if (!requestInstance.value) { requestInstance.value = createInstance() } }) return async <T>(method: Method, url: string, payload?: unknown): Promise<T | null> => { const requestUrl = getApiUrl(url) if (!requestInstance.value) { return null } try { const response = await requestInstance .value .request({ method, url: requestUrl, data: payload, }) return response.data as T } catch (error) { showError((error as Error).message ?? 'An error occurred') return null } } }
const { Schema, model } = require('mongoose'); // Schema to create User model const userSchema = new Schema( { username: { type:String, required:true, unique:true, trimed:true }, email: { type: String, required: true, unique: true, match: [ /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/, 'Please enter a valid email address' ] }, thoughts: [ { type: Schema.Types.ObjectId, ref: 'Thought' } ], friends: [ { type: Schema.Types.ObjectId, ref: 'User' } ], }, { toJSON: { virtuals: true, }, // id: false, } ); userSchema.virtual('friendCount').get(function() { return this.friends.length; }); const User = model('User', userSchema); module.exports = User;
/* * Copyright (c) 2022 legoru / goroleo <legoru@me.com> * * This software is distributed under the <b>MIT License.</b> * The full text of the License you can read here: * https://choosealicense.com/licenses/mit/ * * Use this as you want! )) */ package lib.lOpenSaveDialog; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileNotFoundException; import static lib.lOpenSaveDialog.LOpenSaveDialog.osPanel; import static lib.lOpenSaveDialog.OpenSavePanel.current; import static lib.lOpenSaveDialog.OpenSavePanel.fsv; /** * The list of the files in the current folder. It is an inheritor of the ListView and provides only specific methods and routines. */ public class FilesList extends ListView { /** * The parent panel for access its possibilities. */ private final FilesPanel filesPanel; /** * Creates the Files List. * * @param owner is a Files Panel */ public FilesList(FilesPanel owner) { super(); filesPanel = owner; setItemHeight(25); } /** * Sets the current folder. It scans the current folder and adds to the FileList children folders and files with the default extension. * * @param folder current folder */ public void setFolder(File folder) { setCurrentItem(null); if (!getList().isEmpty()) { getList().clear(); } if (folder != null) { File[] files = fsv.getFiles(folder, true); for (File f : files) { if (f.isDirectory() || OpenSavePanel.DEFAULT_EXT.equalsIgnoreCase( FileItem.extractFileExt(f))) { addNewItem(f); } } doSort(); refreshView(); } } /** * Handles a mouse click on an item. * * @param item an item has clicked * @param button number of a mouse button * @param clickCount number of clicks */ public void clickItem(FileItem item, int button, int clickCount) { if (osPanel.isFoldersPanelVisible()) { osPanel.showFoldersPanel(false); return; } if (button == 1) { // left mouse button if (clickCount == 2) { // two clicks if (item.isFolder()) { // click on a folder item if (item.isLink()) { // item is a link to another folder try { File f = fsv.getLinkLocation(item.getFile()); if (f != null && f.isDirectory()) { current.setFolder(f); } } catch (FileNotFoundException ex) { // do nothing } } else { // item is not link but still a folder and clicks count is 2 current.setFolder(item.getFile()); } } else { // item is not a folder and clicks count is 2 osPanel.confirmAndClose(); } } else { // clicks count is 1 setCurrentItem(item); } } } @Override public void onItemClicked(FileItem item, MouseEvent e) { clickItem(item, e.getButton(), e.getClickCount()); } @Override public void onItemPressed(FileItem item) { if (!filesPanel.isFocusOwner()) filesPanel.requestFocus(); } @Override public void onItemEntered(FileItem item) { if (!osPanel.isFoldersPanelVisible()) { setMouseOverItem(item); } } @Override public void onItemExited(FileItem item) { setMouseOverItem(null); } @Override public void setCurrentItem(FileItem file) { super.setCurrentItem(file); if (file != null) filesPanel.chooseFile(file.getFile()); } @Override public void addItemToView(FileItem item) { item.setLabelWidths(filesPanel.getColumnWidth(2), filesPanel.getColumnWidth(3)); add(item); } }
using Framework.Core.Base; using Framework.Core.Domain; using Microsoft.Extensions.DependencyInjection; using Serilog; using System.Globalization; using WeatherZapto.Application; using WeatherZapto.Model; using Zapto.Component.Common.Services; using Zapto.Component.Common.Models; namespace Zapto.Component.Common.ViewModels { public interface IWeatherViewModel : IBaseViewModel { Task<(WeatherModel? model, bool hasError)> GetWeatherModel(); Task<WeatherModel?> GetWeatherModel(LocationModel location); } public class WeatherViewModel : BaseViewModel, IWeatherViewModel { #region Properties private IApplicationWeatherService ApplicationWeatherService { get; } private IApplicationOWService ApplicationOWService { get; } private IZaptoLocalStorageService LocalStorageService { get; } #endregion #region Constructor public WeatherViewModel(IServiceProvider serviceProvider) : base(serviceProvider) { this.ApplicationWeatherService = serviceProvider.GetRequiredService<IApplicationWeatherService>(); this.ApplicationOWService = serviceProvider.GetRequiredService<IApplicationOWService>(); this.LocalStorageService = serviceProvider.GetRequiredService<IZaptoLocalStorageService>(); } #endregion #region Methods public async Task<(WeatherModel? model, bool hasError)> GetWeatherModel() { WeatherModel? model = null; bool hasError = false; try { ZaptoUser user = await this.AuthenticationService.GetAuthenticatedUser(); if (user != null) { string? culture = await this.LocalStorageService.GetItemAsync<string>("culture"); Log.Debug($"Culture : {culture}"); if (string.IsNullOrEmpty(culture) == false) { this.IsLoading = true; ZaptoWeather? weather = await this.ApplicationWeatherService.GetCurrentWeather(user.LocationName, user.LocationLongitude, user.LocationLatitude, culture); if (weather != null) { model = new WeatherModel() { Temperature = weather.Temperature, TemperatureMax = this.GetTemperatureMax(weather), TemperatureMin = this.GetTemperatureMin(weather), FeelsLike = weather.FeelsLike, Pressure = weather.Pressure, WeatherText = weather.WeatherText, WindSpeed = weather.WindSpeed, WindDirection = weather.WindDirection, Location = weather.Location, }; using (Stream stream = await this.ApplicationOWService.GetCurrentWeatherImage(weather.Icon)) { byte[]? byteArray = (stream as MemoryStream)?.ToArray(); if (byteArray != null) { string? b64String = Convert.ToBase64String(byteArray); model.Image = "data:image/png;base64," + b64String; } } } } } } catch (Exception ex) { Log.Debug($"{ClassHelper.GetCallerClassAndMethodName()} - {ex.ToString()}"); hasError = true; this.NavigationService.ShowMessage("Weather Service Exception", ZaptoSeverity.Error); } finally { this.IsLoading = false; } return (model, hasError); } public async Task<WeatherModel?> GetWeatherModel(LocationModel location) { WeatherModel? model = null; try { if ((location != null) && (location.Latitude != null) && (location.Longitude != null)) { string? culture = await this.LocalStorageService.GetItemAsync<string>("culture"); Log.Debug($"Culture : {culture}"); if (string.IsNullOrEmpty(culture) == false) { this.IsLoading = true; ZaptoWeather? weather = await this.ApplicationWeatherService.GetCurrentWeather(location.Location, location.Longitude.ToString(), location.Latitude.ToString(), culture); if (weather != null) { model = new WeatherModel() { Temperature = weather.Temperature, FeelsLike = weather.FeelsLike, Pressure = weather.Pressure, WeatherText = weather.WeatherText, WindSpeed = weather.WindSpeed, WindDirection = weather.WindDirection, Location = weather.Location, }; using (Stream stream = await this.ApplicationOWService.GetCurrentWeatherImage(weather.Icon)) { byte[]? byteArray = (stream as MemoryStream)?.ToArray(); if (byteArray != null) { string? b64String = Convert.ToBase64String(byteArray); model.Image = "data:image/png;base64," + b64String; } } } } } } catch (Exception ex) { Log.Debug($"{ClassHelper.GetCallerClassAndMethodName()} - {ex.ToString()}"); this.NavigationService.ShowMessage("Weather Service Exception", ZaptoSeverity.Error); } finally { this.IsLoading = false; } return model; } private string GetTemperatureMax(ZaptoWeather weather) { string max = string.Empty; if ((string.IsNullOrEmpty(weather.TemperatureMax) == false) && (string.IsNullOrEmpty(weather.Temperature) == false)) { if (double.Parse(weather.Temperature.Replace('.', ','), NumberStyles.Number) > double.Parse(weather.TemperatureMax.Replace('.', ','), NumberStyles.Number)) { max = weather.Temperature; } else { max = weather.TemperatureMax; } } return max; } private string GetTemperatureMin(ZaptoWeather weather) { string min = string.Empty; if ((string.IsNullOrEmpty(weather.TemperatureMin) == false) && (string.IsNullOrEmpty(weather.Temperature) == false)) { if (double.Parse(weather.Temperature.Replace('.', ','), NumberStyles.Number) < double.Parse(weather.TemperatureMin.Replace('.', ','), NumberStyles.Number)) { min = weather.Temperature; } else { min = weather.TemperatureMin; } } return min; } #endregion } }
#HTML HTML (Hypertext Markup Language) is the standard markup language used to create and structure content on the World Wide Web. It is a fundamental technology in web development and acts as the backbone for building web pages. Here's an overview of HTML: ## Structure of HTML HTML documents are made up of elements, which are enclosed in tags. Each element is responsible for defining different parts of a web page. The basic structure of an HTML document includes: - `<!DOCTYPE html>`: This declaration defines the document type and version. - `<html>`: The root element that encloses the entire HTML document. - `<head>`: Contains metadata about the document, such as the title, character encoding, and links to external resources like stylesheets and scripts. - `<title>`: Sets the title of the web page, which appears in the browser's title bar or tab. - `<body>`: Contains the visible content of the web page, including text, images, links, and more. ## HTML Elements HTML provides a wide range of elements to structure content. Some commonly used HTML elements include: - `<h1>`, `<h2>`, `<h3>`, ... `<h6>`: Headings that define the hierarchy and importance of text. - `<p>`: Paragraphs to organize and separate text. - `<a>`: Anchor tags for creating hyperlinks to other web pages or resources. - `<img>`: Images for displaying graphics and visuals. - `<ul>`, `<ol>`, and `<li>`: Lists, both unordered and ordered, to organize information. - `<div>` and `<span>`: Generic container elements used for grouping and styling content. ## Attributes HTML elements can also have attributes, which provide additional information or properties for elements. For example: - `src` for specifying the source of an image (`<img src="image.jpg">`). - `href` for defining the destination of a hyperlink (`<a href="https://www.example.com">Link</a>`). - `class` and `id` for adding [CSS](/wiki/CSS) and JavaScript hooks to elements. ## HTML and Web Development HTML is just one part of web development. It provides the structure and content for web pages. To enhance the visual and interactive aspects of web pages, [CSS](/wiki/CSS) (Cascading Style Sheets) is used for styling, and JavaScript is used for interactivity and behavior. The combination of HTML, CSS, and JavaScript forms the basis of modern web development, allowing developers to create dynamic and engaging websites and web applications. As web technology continues to evolve, HTML also advances with new versions. HTML5, for instance, introduced many new features and elements that enhance multimedia support, form handling, and more. HTML remains an essential skill for web developers, as it lays the foundation for creating the web content we interact with on a daily basis.
#include "public.h" #include <yt/yt/ytlib/api/native/public.h> #include <yt/yt/ytlib/object_client/object_service_proxy.h> #include <yt/yt/ytlib/chunk_client/chunk_owner_ypath_proxy.h> #include <yt/yt/ytlib/query_client/query_service_proxy.h> #include <yt/yt/client/api/client.h> #include <yt/yt/client/chunk_client/read_limit.h> #include <yt/yt/client/table_client/comparator.h> #include <yt/yt/core/misc/common.h> #pragma once namespace NYT::NChunkClient { //! This class fetches chunk specs from master and processes the responses //! (possibly locating foreign chunks). class TMasterChunkSpecFetcher : public TRefCounted { public: DEFINE_BYREF_RW_PROPERTY(std::vector<NProto::TChunkSpec>, ChunkSpecs); public: TMasterChunkSpecFetcher( const NApi::NNative::IClientPtr& client, const NApi::TMasterReadOptions& masterReadOptions, NNodeTrackerClient::TNodeDirectoryPtr nodeDirectory, const IInvokerPtr& invoker, int maxChunksPerFetch, int maxChunksPerLocateRequest, const std::function<void(const TChunkOwnerYPathProxy::TReqFetchPtr&, int /*tableIndex*/)>& initializeFetchRequest, const NLogging::TLogger& logger, bool skipUnavailableChunks = false); void Add( NObjectClient::TObjectId objectId, NObjectClient::TCellTag externalCellTag, i64 chunkCount, int tableIndex = 0, const std::vector<TReadRange>& ranges = {TReadRange()}); TFuture<void> Fetch(); //! Returns fetched chunk specs ordered by table index. std::vector<NProto::TChunkSpec> GetChunkSpecsOrderedNaturally() const; NNodeTrackerClient::TNodeDirectoryPtr GetNodeDirectory() const; private: NApi::NNative::IClientPtr Client_; NApi::TMasterReadOptions MasterReadOptions_; NNodeTrackerClient::TNodeDirectoryPtr NodeDirectory_; IInvokerPtr Invoker_; int MaxChunksPerFetch_; int MaxChunksPerLocateRequest_; std::function<void(const TChunkOwnerYPathProxy::TReqFetchPtr&, int)> InitializeFetchRequest_; NLogging::TLogger Logger; bool SkipUnavailableChunks_; i64 TotalChunkCount_ = 0; int TableCount_ = 0; struct TCellState { NObjectClient::TObjectServiceProxy::TReqExecuteBatchWithRetriesPtr BatchReq; int ReqCount = 0; std::vector<int> TableIndices; std::vector<int> RangeIndices; std::vector<NProto::TChunkSpec> ChunkSpecs; std::vector<NProto::TChunkSpec*> ForeignChunkSpecs; }; THashMap<NObjectClient::TCellTag, TCellState> CellTagToState_; TCellState& GetCellState(NObjectClient::TCellTag cellTag); void DoFetch(); void DoFetchFromCell(NObjectClient::TCellTag cellTag); }; DEFINE_REFCOUNTED_TYPE(TMasterChunkSpecFetcher) //! This class fetches dynamic table chunk specs directly from tablet cells //! also optionally retrieving sample keys. //! Restrictions: //! - fetcher currently works only with sorted dynamic tables; //! - no retries are performed at all (i.e. when some tablets are missing, they //! are invalidated in tablet mount cache but no retry after invalidation happens). class TTabletChunkSpecFetcher : public TRefCounted { public: DEFINE_BYREF_RW_PROPERTY(std::vector<NProto::TChunkSpec>, ChunkSpecs); using TRequest = NQueryClient::NProto::TReqFetchTabletStores; using TSubrequest = NQueryClient::NProto::TReqFetchTabletStores::TSubrequest; public: struct TOptions { NApi::NNative::IClientPtr Client; //! Row buffer that is used when samples are requested. //! May be nullptr only if no samples are requested. NTableClient::TRowBufferPtr RowBuffer; //! This callback will be invoked for each request to particular node. //! It may be used to specify required extension tags or for something else. std::function<void(TRequest*)> InitializeFetchRequest; //! Codec used for compressing RPC responses. NCompression::ECodec ResponseCodecId = NCompression::ECodec::Lz4; }; TTabletChunkSpecFetcher( TOptions options, const IInvokerPtr& invoker, const NLogging::TLogger& logger); void Add( const NYPath::TYPath& path, i64 chunkCount, int tableIndex = 0, const std::vector<TReadRange>& ranges = {TReadRange()}); TFuture<void> Fetch(); private: const TOptions Options_; const IInvokerPtr Invoker_; const NLogging::TLogger& Logger; i64 TotalChunkCount_ = 0; int TableCount_ = 0; //! Used only for logging. static constexpr const int MissingTabletIdCountLimit = 5; struct TNodeState { //! Each subrequest consists of a bunch of ranges of single tablet. //! This vector stores subrequests for all tablets residing on this node. std::vector<TSubrequest> Subrequests; //! Tablet infos are stored for possible further invalidation in table mount cache //! (in case when subrequest fails with NTabletClient::EErrorCode::NoSuchTablet error). std::vector<NTabletClient::TTabletInfoPtr> Tablets; std::vector<NProto::TChunkSpec> ChunkSpecs; std::vector<NTabletClient::TTabletId> MissingTabletIds; }; THashMap<TString, TNodeState> NodeAddressToState_; void AddSorted( const NTabletClient::TTableMountInfo& tableMountInfo, int tableIndex, const std::vector<TReadRange>& ranges); void DoFetch(); void DoFetchFromNode(const TString& address); }; DEFINE_REFCOUNTED_TYPE(TTabletChunkSpecFetcher) } // namespace NYT::NChunkClient
<div class="signin"> <p-card class="signin-card signup-card"> <ng-template pTemplate="header"> <h4 class="signin-card-title">SIGN-UP</h4> </ng-template> <div class="signin-card-body"> <form class="form" [formGroup]="registerForm" (ngSubmit)="onSubmit()"> <div class="mb-3"> <div class="p-field"> <label for="signin-username" class="label-login">Username</label> <input id="signin-username" class="signin-cred" type="username" aria-describedby="username1-help" pInputText formControlName="userName" /> <p class="text-danger mt-1"> {{ validInput(registerForm.get("userName")) }} </p> </div> </div> <div class="mb-3"> <div class="p-field"> <label for="signin-password" class="label-login">Password</label> <input id="signin-password" class="signin-cred" type="password" aria-describedby="password-help" pInputText formControlName="password" /> <p class="text-danger mt-1"> {{ validInput(registerForm.get("password")) }} </p> </div> </div> <div class="mb-3"> <div class="p-field"> <label for="signin-password" class="label-login" >Confirm Password</label > <input id="signin-password" class="signin-cred" type="password" aria-describedby="password-help" pInputText formControlName="confirmPassword" /> <p class="text-danger mt-1"> {{ validInput(registerForm.get("confirmPassword")) }} </p> </div> </div> <div class="d-flex justify-content-center"> <button pButton type="button" label="Create Account" type="submit" [disabled]="registerForm.invalid" ></button> </div> <div class="mb-1 mt-1"> <p class="d-flex justify-content-center"> If you have already an account </p> <a class="d-flex justify-content-center" routerLink="/signin"> SignIn Account </a> </div> </form> </div> </p-card> </div>
// // ContentView.swift // HabitTracker // // Created by Miłosz Tabaka on 01/11/2022. // import SwiftUI struct ContentView: View { @StateObject var activities = Activities() @State private var showingAddActivity = false var body: some View { NavigationView { List { ForEach(activities.items) { item in NavigationLink { DetailView(activity: item, activities: activities) } label: { VStack(alignment: .leading) { Text(item.title) } } } .onDelete(perform: removeItems) } .navigationTitle("Habit Tracker") .toolbar { Button { showingAddActivity = true } label: { Image(systemName: "plus") } } .sheet(isPresented: $showingAddActivity) { AddActivity(activities: activities) } } } func removeItems(at offsets: IndexSet) { activities.items.remove(atOffsets: offsets) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
package week5 import org.apache.log4j.{Level, Logger} import org.apache.spark.{SparkContext, SparkConf} import org.apache.spark.streaming.{Milliseconds, Seconds, StreamingContext} import org.apache.spark.streaming.StreamingContext._ import org.apache.spark.storage.StorageLevel object NetworkWordCount { def main(args: Array[String]) { Logger.getLogger("org.apache.spark").setLevel(Level.WARN) Logger.getLogger("org.eclipse.jetty.server").setLevel(Level.OFF) val conf = new SparkConf().setAppName("NetworkWordCount").setMaster("local[2]") val sc = new SparkContext(conf) val ssc = new StreamingContext(sc, Seconds(5)) val lines = ssc.socketTextStream("localhost", 9999, StorageLevel.MEMORY_AND_DISK_SER) val words = lines.flatMap(_.split(",")) val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _) wordCounts.print() ssc.start() ssc.awaitTermination() } }
"use client"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { CopyToClipboard } from "react-copy-to-clipboard"; import { FaDownload } from "react-icons/fa"; import Image from "next/image"; import { Wallpaper } from "@/types/wallpaper"; import { toast } from "sonner"; import Loading from "../loading"; import ListLoading from "../list-loading"; interface Props { wallpapers: Wallpaper[] | null; loading: boolean; } export default function ({ wallpapers, loading }: Props) { return ( <section> <div className="mx-auto w-full max-w-7xl px-0 py-2 md:px-10 md:py-8 lg:py-8"> {loading ? <ListLoading /> : <div className="flex flex-col items-stretch"> <div className="gap-x-8 [column-count:1] grid md:grid-cols-3 md:gap-x-4 md:[column-count:3]"> <> {wallpapers && wallpapers.map((wallpaper: Wallpaper, idx: number) => { return ( <div key={idx} className="rounded-xl overflow-hidden mb-4 inline-block border border-solid border-[#cdcdcd] md:mb-8 lg:mb-10" > <Image src={wallpaper.img_url} alt={wallpaper.img_description} width={350} height={200} loading="lazy" /> <div className="px-5 py-8 sm:px-6"> <p className="flex-col text-[#808080]"> {wallpaper.img_description} </p> <div className="flex items-center mb-5 mt-6 flex-wrap gap-2 md:mb-6 lg:mb-8"> <Badge variant="secondary"> {wallpaper.img_size} </Badge> <div className="flex-1"></div> <Avatar> <AvatarImage src={wallpaper.created_user?.avatar_url} alt={wallpaper.created_user?.nickname} /> <AvatarFallback> {wallpaper.created_user?.nickname} </AvatarFallback> </Avatar> </div> <div className="flex flex-wrap items-center justify-between gap-4"> <a href={wallpaper.img_url} className="flex items-center max-w-full gap-2.5 text-sm font-bold uppercase text-black" > <p>Download</p> <p className="text-sm"> <FaDownload /> </p> </a> <CopyToClipboard text={wallpaper.img_description} onCopy={() => toast.success("Copied")} > <Button>Copy Prompt</Button> </CopyToClipboard> </div> </div> </div> ); })} </> </div> </div> } </div> </section> ); }
import { graphql, useStaticQuery } from 'gatsby'; import React from 'react'; import { Helmet } from 'react-helmet'; const query = graphql` { site { siteMetadata { description siteUrl title } } } `; const SEO = ({ children, location, description, title, image }) => { const data = useStaticQuery(query); const { siteMetadata } = data.site; return ( <Helmet titleTemplate={`%s - ${siteMetadata.title}`}> <html lang='en' /> <title>{title}</title> {/* Favicon */} <link rel='icon' type='image/svg+xml' href='/favicon.svg' /> <link rel='alternate icon' href='/favicon.ico' /> {/* Meta tags */} <meta name='viewport' content='width=device-width, initial-scale=1.0' /> <meta http-equiv='Content-Type' content='text/html;charset=UTF-8' /> <meta charSet='utf-8' /> <meta name='description' content={siteMetadata.description} /> {/* Open Graph */} {location && <meta property='og:url' content={location.href} />} <meta property='og:image' content={image || '/logo.svg'} /> <meta property='og:title' content={title} key='ogtitle' /> <meta property='og:site_name' content={siteMetadata.title} key='ogsitename' /> <meta property='og:description' content={description} key='ogdesc' /> {children} </Helmet> ); }; export default SEO;
--- title: 205. Isomorphic Strings level: medium categories: - Hash Table - String feature_text: | ## LeetCode 205. Isomorphic Strings Post by ailswan Oct.30, 2023 feature_image: "https://picsum.photos/2560/600?image=872" python_code: > class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if len(s) != len(t): return False dic = {} visited = set() for i in range(len(s)): if s[i] in dic: if dic[s[i]] != t[i]: return False else: if t[i] in visited: return False else: dic[s[i]] = t[i] visited.add(t[i]) return True --- ### Problem Statement **link:** https://leetcode.com/problems/isomorphic-strings/ https://leetcode.cn/problems/isomorphic-strings/ Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. **Example:** **Input:** `s = "egg", t = "add"` **Output:** `true` **Input:** `s = "foo", t = "bar"` **Output:** `false` **Input:** `s = "paper", t = "title"` **Output:** `true` ### Solution Approach To determine if two strings are isomorphic, ensure a one-to-one mapping between their characters without any overlaps. #### Algorithm 1. Length Check: Ensure both strings have equal lengths. 2. Map Characters: Utilize a dictionary to relate characters from s to t, and a set to note which characters from t are already mapped. 3. Verify Mapping: For each character in s, ensure it maps uniquely to a character in t. If all mappings are consistent, the strings are isomorphic.
import http.HttpTasksManager; import http.KVServer; import managers.StatusTask; import managers.exceptions.TasksValidateException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import tasks.Epic; import tasks.SimpleTask; import tasks.Subtask; import java.io.IOException; import java.net.URI; import java.time.Duration; import java.time.LocalDateTime; import static org.junit.jupiter.api.Assertions.assertEquals; class HttpTasksManagerTest extends FileBackedTasksManagerTest { static KVServer server; @BeforeEach public void startManager() throws IOException { server = new KVServer(); server.start(); tasksManager = new HttpTasksManager(URI.create("http://localhost:8081")); LocalDateTime epic1LocalDateTime = LocalDateTime.of(2010, 1, 1, 1, 22, 0); Duration epic1Duration = Duration.ofMinutes(90); epic1 = new Epic("Эпик1", "Проверочный", StatusTask.NEW, epic1LocalDateTime, epic1Duration); LocalDateTime subtask1LocalDateTime = LocalDateTime.of(2010, 1, 2, 2, 7, 0); Duration subtask1Duration = Duration.ofMinutes(90); subtask1 = new Subtask("подзадача1", "проверочная", StatusTask.NEW, subtask1LocalDateTime, subtask1Duration, epic1Id); LocalDateTime subtask2LocalDateTime = LocalDateTime.of(2010, 1, 3, 1, 9, 0); Duration subtask2Duration = Duration.ofMinutes(1000); subtask2 = new Subtask("подзадача2", "проверочная", StatusTask.NEW, subtask2LocalDateTime, subtask2Duration, epic1Id); LocalDateTime subtask3LocalDateTime = LocalDateTime.of(2010, 1, 9, 5, 5, 0); Duration subtask3Duration = Duration.ofMinutes(600); subtask3 = new Subtask("подзадача3", "проверочная", StatusTask.NEW, subtask3LocalDateTime, subtask3Duration, epic1Id); LocalDateTime task1LocalDateTime = LocalDateTime.of(2010, 1, 11, 8, 7, 0); Duration task1Duration = Duration.ofMinutes(450); task1 = new SimpleTask("задача1", "проверочная", StatusTask.NEW, task1LocalDateTime, task1Duration); LocalDateTime task2LocalDateTime = LocalDateTime.of(2010, 1, 22, 6, 9, 0); Duration task2Duration = Duration.ofMinutes(150); task2 = new SimpleTask("задача2", "тестовая2", StatusTask.NEW, task2LocalDateTime, task2Duration); LocalDateTime epic2LocalDateTime = LocalDateTime.of(2010, 1, 24, 7, 8, 0); Duration epic2Duration = Duration.ofMinutes(90); epic2 = new Epic("Эпик2", "Проверочный", StatusTask.NEW, epic2LocalDateTime, epic2Duration); tasksManager.removeAllTasks(); tasksManager.removeAllSubtasks(); tasksManager.removeAllEpics(); } @AfterEach void stop() { server.stop(); } @Test void saveLoadFile() throws TasksValidateException { epic1Id = tasksManager.addEpic(epic1); subtask1.setEpicId(epic1Id); tasksManager.addSubtask(subtask1); task1Id = tasksManager.addTask(task1); //System.out.println(tasksManager.getTask(task1Id)); //System.out.println(tasksManager.getEpic(epic1Id)); HttpTasksManager httpTasksManager = HttpTasksManager.loadFromServer(URI.create("http://localhost:8081")); assertEquals(tasksManager.getAllTasks(), httpTasksManager.getAllTasks(), "Задачи не совпадают!"); assertEquals(tasksManager.getAllSubtasks(), httpTasksManager.getAllSubtasks(), "Подзадачи не совпадают!"); assertEquals(tasksManager.getAllEpics(), httpTasksManager.getAllEpics(), "Эпики не совпадают!"); server.stop(); } }
"use strict"; var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var session = require('express-session'); var cors = require('cors'); const { mongoDB } = require('./Utils/constant'); const mongoose = require('mongoose'); const User = require('../backend/Models/User/UsersModel'); const RestaurantModel = require('../backend/Models/Restaurant/RestaurantModel'); const OrderModel = require('../backend/Models/Order/OrderModel') const kafka = require('../backend/kafka/client'); const restaurantModel = require('../backend/Models/Restaurant/RestaurantModel'); //use cors to allow cross origin resource sharing app.use(cors({ origin: 'http://localhost:3000', credentials: true })); app.use(cors({ origin: 'http://localhost:3001', credentials: true })); //use express session to maintain session data app.use(session({ secret: 'cmpe273_kafka_passport_mongo', resave: false, // Forces the session to be saved back to the session store, even if the session was never modified during the request saveUninitialized: false, // Force to save uninitialized session to db. A session is uninitialized when it is new but not modified. duration: 60 * 60 * 1000,    // Overall duration of Session : 30 minutes : 1800 seconds activeDuration: 5 * 60 * 1000 })); app.use(bodyParser.json()); //Allow Access Control app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); res.setHeader('Access-Control-Allow-Credentials', 'true'); res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'); res.setHeader('Cache-Control', 'no-cache'); next(); }); var options = { useNewUrlParser: true, useUnifiedTopology: true, poolSize: 500, bufferMaxEntries: 0 }; mongoose.connect(mongoDB, options, (err, res) => { if (err) { console.log(err); console.log(`MongoDB Connection Failed`); } else { console.log(`MongoDB Connected`); } }); //---------------------------------------------------------------- USER's APIS Starts------------------------------------------// // app.get('/logout', (req, res) => { // Cookies.remove('UE_user_email'); // Cookies.remove('UE_usertype'); // }) //KAFKA DONE //User Login app.post('/user/login1', (req, res) => { console.log(req.body); kafka.make_request("login", req.body, function (err, results) { if (err) { console.log("Inside err"); res.json({ status: "error", msg: "System Error, Try Again.", }); } else { console.log("Inside router post"); console.log(results); res.status(200).send(results); } }); }); // app.post('/user/login', (req, res) => { // }); app.post('/user/login', (req, res) => { // console.log(req.body); console.log('Inside login api... '); User.findOne({ email: req.body.email, password: req.body.password }, (error, user) => { if (error) { res.writeHead(500, { 'Content-Type': 'text/plain' }) res.end("Error Occured"); } if (user) { res.cookie('UE_user_email', req.body.email, { maxAge: 90000000, httpOnly: false, path: '/' }); res.cookie('UE_usertype', 'customer', { maxAge: 90000000, httpOnly: false, path: '/' }); res.writeHead(200, { 'Content-Type': 'text/plain' }) console.log("User login api 200 status") res.end("User login api 200 status"); } else { // console.log(user); res.writeHead(401, { 'Content-Type': 'text/plain' }) res.end("Invalid Credentials"); } }); }); //Place Order from CUST app.post('/user/placeOrder', (req, res) => { console.log('Inside placeOrder api | Req body is: ', req.body.order_data); kafka.make_request("palceorder", req.body.order_data, function (err, results) { if (err) { console.log("Inside err"); res.json({ status: "error", msg: "System Error, Try Again.", }); } else { console.log("Inside router post"); console.log(results); res.status(200).send(results); } }); // console.log(req.body); // console.log('Inside place order api...'); // let newOrder = new OrderModel({ // u_email : req.body.email, // r_email : req.body.restaurant_email, // r_name : req.body.restaurant_name, // order_status : req.body.order_status, // order_type : req.body.order_type, // delivery_address : req.body.delivery_address, // instruction: req.body.instruction, // bill : req.body.bill, // item : req.body.items // }) // newOrder.save((err, order) => { // if (err) { // console.log(err); // res.writeHead(500, { // 'Content-Type': 'text/plain' // }) // res.end("Error Occured"); // } else { // res.writeHead(200, { // 'Content-Type': 'text/plain' // }) // console.log("User login api 200 status",order) // res.end("order"); // } // }); }) //DONE //User Signup app.post('/user/signup', (req, res) => { var NewUser = User({ email: req.body.email, password: req.body.password, name: req.body.name, phone: req.body.phone, address: req.body.address, city: req.body.city }); User.findOne({ email: req.body.email }, (error, email) => { if (error) { res.writeHead(500, { 'Content-Type': 'text/plain' }) res.end("Error in 500", error); } if (email) { res.writeHead(400, { 'Content-Type': 'text/plain' }) res.end("E-mail id already exsits"); } else { NewUser.save((error, data) => { if (error) { res.writeHead(500, { 'Content-Type': 'text/plain' }) console.log("error code 500") res.end(); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }) res.end("User added successfully!"); } }); } }); }); //User Landing Page Customer app.get('/user/home', async function (req, res) { try { RestaurantModel.find({}, { name: 1, email: 1, city: 1, address: 1, delivery_type: 1, food_type: 1 }, (err, result) => { if (err) { console.log("error" + err); res.end({ message: "Email id does not exsist" }); } else { console.log("Sorted results: " + finalList); res.end(result); } } ) } catch (e) { console.log(e); } }); app.get('/save-new-rest', (req, res) => { const newDoc = new RestaurantModel({ email: 'abc@gmail.com', password: 'Abc@123', name: 'Panda Express', phone: '+11231231231', city: 'San Jose', delivery_type: 'delivery', zip_code: '95112', state: 'California', menu: [ { category_name: "Starters", category_items: [ { item_name: "Large Curly Fry", description: "Seasoned, curly-cut fried potatoes", price: 4.49, dish_type: 'veg' }, { item_name: "Large Bacon Ultimate Cheeseburger Combo", description: "Bacon Ultimate Cheeseburger™, large French Fries, and your choice of large drink.", price: 12.35, dish_type: 'non_veg' }, { item_name: "Large Jack's Spicy Chicken® Combo", description: "Bacon Ultimate Cheeseburger™, large French Fries, and your choice of large drink.", price: 11.98, dish_type: 'non_veg' }, { item_name: "Large French Fry", description: "Crispy, golden fried potatoes", price: 4.24, dish_type: 'veg' }, { item_name: "Stuffed Jalapenos", description: "Breaded spicy Jalapenos stuffed with blend of melted cheeses, served with Buttermilk Ranch Dipping Sauce upon request", price: 5.74, dish_type: 'veg' }, { item_name: "Teriyaki Rice Bowl 1", description: "Rice prepared with teriyaki sauce along with soy sauce, water, honey, brown sugar, rice vinegar, sesame oil, ginger, garlic, and cornstarch.", price: 12.74, dish_type: 'vegan' } ] }, { category_name: "Entrees", category_items: [ { item_name: "Large Curly Fry", description: "Seasoned, curly-cut fried potatoes", price: 4.49, dish_type: 'veg' }, { item_name: "Large Bacon Ultimate Cheeseburger Combo", description: "Bacon Ultimate Cheeseburger™, large French Fries, and your choice of large drink.", price: 12.35, dish_type: 'non_veg' }, { item_name: "Large Jack's Spicy Chicken® Combo", description: "Bacon Ultimate Cheeseburger™, large French Fries, and your choice of large drink.", price: 11.98, dish_type: 'non_veg' }, { item_name: "Large French Fry", description: "Crispy, golden fried potatoes", price: 4.24, dish_type: 'veg' }, { item_name: "Stuffed Jalapenos", description: "Breaded spicy Jalapenos stuffed with blend of melted cheeses, served with Buttermilk Ranch Dipping Sauce upon request", price: 5.74, dish_type: 'veg' }, { item_name: "Teriyaki Rice Bowl 2", description: "Rice prepared with teriyaki sauce along with soy sauce, water, honey, brown sugar, rice vinegar, sesame oil, ginger, garlic, and cornstarch.", price: 12.74, dish_type: 'vegan' } ] } ] }) newDoc.save() .then((result) => { let msg = 'Mongo insert sucessful for customer signup for username: ' + req.body.username + '. Doc id: ' + (result._id).toString(); console.log(msg); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end((result._id).toString()) }) .catch((err) => { console.log(err); }) }) app.get('/update-doc111', (req, res) => { RestaurantModel.updateOne({ email: req.query.email }, { city: 'San Jose', password: 'Abc@123', name: "Jack in the box", delivery_type: 'pickup', zip_code: '95112', state: 'California', phone: '+11231231231', menu: [ { category_name: "Starters", category_items: [ { item_name: "Large Curly Fry", description: "Seasoned, curly-cut fried potatoes", price: 4.49, dish_type: 'veg' }, { item_name: "Large Bacon Ultimate Cheeseburger Combo", description: "Bacon Ultimate Cheeseburger™, large French Fries, and your choice of large drink.", price: 12.35, dish_type: 'non_veg' }, { item_name: "Large Jack's Spicy Chicken® Combo", description: "Bacon Ultimate Cheeseburger™, large French Fries, and your choice of large drink.", price: 11.98, dish_type: 'non_veg' }, { item_name: "Large French Fry", description: "Crispy, golden fried potatoes", price: 4.24, dish_type: 'veg' }, { item_name: "Stuffed Jalapenos", description: "Breaded spicy Jalapenos stuffed with blend of melted cheeses, served with Buttermilk Ranch Dipping Sauce upon request", price: 5.74, dish_type: 'veg' }, { item_name: "Teriyaki Rice Bowl 1", description: "Rice prepared with teriyaki sauce along with soy sauce, water, honey, brown sugar, rice vinegar, sesame oil, ginger, garlic, and cornstarch.", price: 12.74, dish_type: 'vegan' } ] }, { category_name: "Entrees", category_items: [ { item_name: "Large Curly Fry", description: "Seasoned, curly-cut fried potatoes", price: 4.49, dish_type: 'veg' }, { item_name: "Large Bacon Ultimate Cheeseburger Combo", description: "Bacon Ultimate Cheeseburger™, large French Fries, and your choice of large drink.", price: 12.35, dish_type: 'non_veg' }, { item_name: "Large Jack's Spicy Chicken® Combo", description: "Bacon Ultimate Cheeseburger™, large French Fries, and your choice of large drink.", price: 11.98, dish_type: 'non_veg' }, { item_name: "Large French Fry", description: "Crispy, golden fried potatoes", price: 4.24, dish_type: 'veg' }, { item_name: "Stuffed Jalapenos", description: "Breaded spicy Jalapenos stuffed with blend of melted cheeses, served with Buttermilk Ranch Dipping Sauce upon request", price: 5.74, dish_type: 'veg' }, { item_name: "Teriyaki Rice Bowl 2", description: "Rice prepared with teriyaki sauce along with soy sauce, water, honey, brown sugar, rice vinegar, sesame oil, ginger, garlic, and cornstarch.", price: 12.74, dish_type: 'vegan' } ] } ] }) .then((result) => { if (result) { console.log('Update successful. Result: ', result); } else { console.log('Update failed'); } res.send(result); }) .catch((err) => { console.log(err); }) }) // User Search Bar app.post('/user/search', (req, res) => { let searchStringRegex = new RegExp(req.body.general_search_string, "i"); RestaurantModel.find({ $or: [ { name: searchStringRegex }, { city: searchStringRegex }, { 'menu.category_name': searchStringRegex }, { 'menu.category_items.item_name': searchStringRegex }, { 'menu.category_items.dish_type': searchStringRegex } ] }, { email: 1, name: 1, zip_code: 1, street_address: 1, menu: 1, city: 1, delivery_fee: 1, delivery_time: 1, delivery_mode: 1, isFavoriteRest: 1, rating: 1 } ) .then((result) => { if (result) { console.log('DATA FOUND: ', result); } else { console.log('NO DATA'); } res.send(result); }) .catch((err) => { console.log(err); }) }); //User Orders Page app.get('/user/order', (req, res) => { orderModel.find({ u_mail: req.body.email }, { r_name: 1, order_status: 1, order_type: 1, delivery_address: 1, instruction: 1, bill: 1, item: 1 }, (error, order) => { if (error) { res.writeHead(500, { 'Content-Type': 'text/plain' }) res.end(); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }) console.log(JSON.stringify("Order Data retrived!", order)); res.end(JSON.stringify("Order placed retrived!", order)); } }); }); app.post('/rest/order', (req, res) => { console.log(req.body.email); OrderModel.find({ "r_email": req.body.email }, { r_name: 1, order_status: 1, order_type: 1, delivery_address: 1, instruction: 1, bill: 1, item: 1 }, (error, order) => { if (error) { res.writeHead(500, { 'Content-Type': 'text/plain' }) res.end(); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }) console.log((order)); res.end(JSON.stringify(order)); } }); }); app.get('/user/restaurant_suggestions', (req, res) => { console.log('GET restaurant_suggestions input request parameters: ', req.query); if (req.query.city) { console.log('City param received in restaurant_suggestions api input...'); let citySearchStringRegex = new RegExp(req.query.city, "i"); RestaurantModel.find({}) .then((result) => { if (result) { console.log('DATA FOUND: ', result); // let result1 = { // restaurant_id: result._id, // username: result.username, // zipcode: result.zipcode, // restaurant_name: result.name, // city: result.city, // delivery_fee: result.delivery_fee, // delivery_time: result.delivery_time, // street_address: result.street_address, // rating: result.rating, // isFavoriteRest: result.isFavoriteRest // } res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(JSON.stringify(result)); } else { console.log('NO DATA'); res.writeHead(201, { 'Content-Type': 'text/plain' }); res.end('NO DATA FOUND'); } }) .catch((err) => { console.log(err); }) } else { let searchStringRegex = new RegExp(req.query.general_search_string, "i"); // userDetailsModel.find({ $or: [ {name: searchStringRegex}, {city: searchStringRegex}, {'menu.category_name': searchStringRegex}, {'menu.category_items.item_name': searchStringRegex}, {'menu.category_items.dish_type': searchStringRegex} ] }, {username: 1, usertype: 1, name: 1, zipcode: 1, street_address: 1, menu: 1, city: 1, delivery_fee: 1, delivery_time: 1, delivery_mode: 1, isFavoriteRest: 1, rating: 1, _id:1}) userDetailsModel.find({ $and: [ { $or: [{ name: searchStringRegex }, { city: searchStringRegex }, { 'menu.category_name': searchStringRegex }, { 'menu.category_items.item_name': searchStringRegex }, { 'menu.category_items.dish_type': searchStringRegex }] }, { usertype: 'restaurant' } ] }, { username: 1, usertype: 1, name: 1, zipcode: 1, street_address: 1, menu: 1, city: 1, delivery_fee: 1, delivery_time: 1, delivery_mode: 1, isFavoriteRest: 1, rating: 1, _id: 1 }) .then((result) => { if (result) { console.log('DATA FOUND: ', result); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(JSON.stringify(result)); } else { console.log('NO DATA'); res.writeHead(201, { 'Content-Type': 'text/plain' }); res.end(result); } }).catch((err) => { console.log(err); }) } }) // //Add to Favourite // app.get('/user/order', (req, res) => { // Cust.findOne({ email: email }, (err, cust) => { // if (err) { // console.log(err); // //callback(null, "Error"); // } else { // User.find({ // "rest._id": msg.rest_id // }, (err, fav) => { // if (err) { // console.log(err); // //callback(null, "Error"); // } else { // if (fav.length > 110) { // ???????????????????????????????????????? why 110 ?????????????????????????????????????? // console.log("###############", fav.length); // //callback(null, "Already added to Fav"); // } else { // console.log("here if not ", fav.length); // User.rest.push(newFav); // User.save(); // //callback(null, cust); // } // } // }); // } // }); // }); //Pending //New Order app.get('/user/order/new', (req, res) => { let u_email = msg.email; let r_email = msg.r_email; let order_status = "Order Placed"; let order_type = msg.order_type; let address = msg.address; let bill = msg.bill; let item = msg.item; const order = new Order({ u_email, r_email, order_status, order_type, address, bill, item }); }); //Profile Page app.get('/user/profile', (req, res) => { console.log('Inside user profile API | Request body email is: ', req.query.email); User.findOne({ email: req.query.email }) .then((result) => { if (result) { console.log('DB Result: ', result); } else { console.log('No data'); } res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(JSON.stringify(result)); }) .catch((err) => { console.log(err); }) }) // KAFKA //Profile Page Update app.post('/user/profile/update', (req, res) => { console.log(req.body); kafka.make_request("updateUser", req.body, function (err, results) { if (err) { console.log("Inside err"); res.json({ status: "error", msg: "System Error, Try Again.", }); } else { console.log("Inside router post"); console.log(results); res.status(200).send(results); } }); // console.log("trying to update " + req.body.city); // const filter = { email: req.body.email }; // const update = { // $set: { // email: req.body.email, // name: req.body.name, // phone: req.body.phone, // address: req.body.address, // city: req.body.city, // } // }; // User.findOneAndUpdate(filter, update, { new: true }, (err, result) => { // if (err) { // console.log("error"); // res.status(500).send(err); // //callback(null, "error"); // } else { // console.log(result); // res.status(200).send(result); // //callback(null, "error"); // } // }); }); //Receipt //-----------------------------------------------------------------------------// //User Favourite Restaurant Page app.get('/user/favourite', (req, res) => { User.find({ email: req.body.email }, (error, favourite) => { if (error) { res.writeHead(500, { 'Content-Type': 'text/plain' }) res.end(); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }) console.log(JSON.stringify("Favourite Data got", favourite)); res.end(JSON.stringify("Favourite Data got", favourite)); } }); }); //-----------------------------------------------------------------------------// //---------------------------------------------------------------- USER's APIS Ends --------------------------------------------------// //---------------------------------------------------------------- Restaurant's APIS Starts ------------------------------------------// //Restaurant Login app.post('/restaurant/login', (req, res) => { // console.log(req.body); RestaurantModel.findOne({ email: req.body.email, password: req.body.password }, (error, user) => { if (error) { res.writeHead(500, { 'Content-Type': 'text/plain' }) res.end("Error Occured"); } if (user) { res.writeHead(200, { 'Content-Type': 'text/plain' }) console.log("Restaurant login api 200 status") res.end("Restaurant login api 200 status"); } else { // console.log(user); res.writeHead(401, { 'Content-Type': 'text/plain' }) res.end("Invalid Credentials"); } }); }); //Restaurant Signup app.post('/restaurant/signup', (req, res) => { var NewRestaurant = RestaurantModel({ // restaurant_id: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true }, name: { type: String }, address: { type: String }, city: { type: String }, state: { type: String }, zip_code: { type: String } }); // RestaurantModel.find({ email: msg.email }, (err, result) => { // if (result) { // console.log(result); // //res.end(201, "You already have an account with Uber Eats") // callback(null, "You already have an account with Uber Eats"); // } // else { // RestaurantModel.save((err, result) => { // if (err) { // console.log("error is: " + err); // callback(null, "Something went wrong. Please try again later"); // //res.status(500).send(); // } // else { // console.log("result=" + result); // const payload = { // id: result._id, // username: msg.name, // email: msg.email // }; // const token = jwt.sign(payload, secret); // callback(null, "JWT " + token); // } // }); // } RestaurantModel.findOne({ email: req.body.email }, (error, email) => { console.log("email:", req.body.email); if (error) { res.writeHead(500, { 'Content-Type': 'text/plain' }) res.end("Error in 500", error); } if (email) { res.writeHead(400, { 'Content-Type': 'text/plain' }) res.end("E-mail id already exsists"); } else { NewRestaurant.save((error, data) => { if (error) { res.writeHead(500, { 'Content-Type': 'text/plain' }) console.log("Error code 500"); res.end(); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }) res.end("User Added Successfully") } }) } }); }) //Restaurant Home app.post('/restaurant/home', (req, res) => { RestaurantModel.find({ 'email': req.body.email }, { menu: 1 }) .then((result) => { if (result) { console.log('Results: ', result); } else { console.log('NO DATA'); } res.send(result); }) .catch((err) => { console.log(err); }) }) //Restaurant Add Menu app.post('/restaurant/addmenu', (req, res) => { RestaurantModel.findOneAndUpdate({ email: req.body.email }, { $push: { category_items: [ new Schema({ // item_id: {type: Number}, item_name: { type: String }, description: { type: String }, price: { type: Number }, dish_type: { type: String } //Veg || Non Veg }) ] } }, (err, result) => { if (err) { console.log(err); callback(null, "Error"); // console.log(err); } else { // console.log(result); callback(null, result); } } ); }) app.post('/restaurant/order/cancelorder', (req, res) => { OrderModel.findOneAndUpdate({ _id: req.body.order_id }, { $set: { order_status: "Cancelled" } }, { new: true }, (err, result) => { if (err) { console.log("error is " + err); res.status(500).send("Something went wrong"); } else { res.status(200).send("Order cancelled"); } }); }); app.post('/user/order/cancelorder', (req, res) => { OrderModel.findOneAndUpdate({ _id: req.body.order_id }, { $set: { order_status: "Cancelled" } }, { new: true }, (err, result) => { if (err) { console.log("error is " + err); res.status(500).send("Something went wrong"); } else { res.status(200).send("Order cancelled"); } }); }); // app.post('/restaurant/orders/updatestatus', (req, res) => { // OrderModel.findOneAndUpdate({_id: req.body.order_id}, { // $set: {order_status: req.body.order_status}}, { new: true }, (err,result)=>{ // if(err){ // console.log("error is " + err); // res.status(500).send("Something went wrong"); // }else{ // res.status(200).send("Order cancelled"); // } // }); // }); app.post('/user/order/cancelorder', (req, res) => { OrderModel.findOneAndUpdate({ _id: req.body.order_id }, { $set: { order_status: "Cancelled" } }, { new: true }, (err, result) => { if (err) { console.log("error is " + err); res.status(500).send("Something went wrong"); } else { res.status(200).send("Order cancelled"); } }); }); //----------------------------------------------------------------------------- //Restaurant Update Menu Price app.post('/restaurant/menu/update', (req, res) => { RestaurantModel.findOneAndUpdate({ 'email': req.body.email, 'item_name': req.body.item_name }, { 'price': req.body.price }, { new: true }) .then((result) => { if (result) { console.log('Results: ', result); } else { console.log('NO DATA'); } res.send(result); }) .catch((err) => { console.log(err); }) }) //----------------------------------------------------------------------------- //DONE //Restaurant Orders app.post('/restaurant/order', (req, res) => { OrderModel.find({ 'r_email': req.body.email }) .then((result) => { if (result) { console.log('Results: ', result); } else { console.log('NO DATA'); } res.send(result); }) .catch((err) => { console.log(err); }) }) //User orders app.post('/user/order', (req, res) => { OrderModel.find({ 'u_email': req.body.email }) .then((result) => { if (result) { console.log('Results: ', result); } else { console.log('NO DATA'); } res.send(JSON.stringify(result)); }) .catch((err) => { console.log(err); }) }) //DONE //Restaurant Order Status Update app.post('/restaurant/order/update', (req, res) => { OrderModel.findOneAndUpdate({ _id: req.body.order_id}, { order_status: req.body.order_status }, { new: true }) .then((result) => { if (result) { console.log('Results: ', result); } else { console.log('NO DATA'); } res.send(result); }) .catch((err) => { console.log(err); }) }) //---------------------------------------------------------------- Restaurant's APIS Ends ------------------------------------------// //---------------------------------------------------------------- Test API's starts -----------------------------------------------// app.post('/test', (req, res) => { OrderModel.create({ u_email: req.body.u_email, r_email: req.body.r_email, order_status: req.body.order_status, order_type: req.body.order_type, delivery_address: req.body.delivery_address, bill: req.body.bill, // item: [ // new Schema({ // item_name: req.body.item_name, // item_price: req.body.item_price, // item_qty: req.body.item_qty // }) // ] }) .then((result) => { if (result) { console.log('Results: ', result); } else { console.log('NO DATA'); } res.send(result); }) .catch((err) => { console.log(err); }); }) //---------------------------------------------------------------- Test API's ENDS -------------------------------------------------// app.listen(3001, () => console.log("Server Listening on port 3001"));
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="author" content="Goodness Arinzechukwu Okafor" /> <meta name="description" content="course assignment portal" /> <meta property="og:title" content="Goodness Arinzechukwu Okafor - WDD 230 - Web Frontend Development" /> <meta property="og:type" content="website" /> <meta property="og:image" content="https://t3.ftcdn.net/jpg/03/59/31/68/360_F_359316888_QL4VKw3ZLdZWeHGZaajVrt6jbWQG5NsM.jpg" /> <meta property="og:url" content="https://heavenlyaura.github.io/wdd230/" /> <link rel="icon" href="favicon.ico" /> <link rel="stylesheet" href="styles/normalize.css" /> <link rel="stylesheet" href="styles/base.css" /> <link rel="stylesheet" href="styles/larger.css" /> <title> Goodness Arinzechukwu Okafor - WDD 230 - Web Frontend Development </title> </head> <body> <header> <div class="profile-picture"> <img class="my-image" src="images/my-picture.jpg" alt="my picture" /> </div> <h1>Goodness Arinzechukwu Okafor</h1> </header> <nav> <button id="menu"></button> <ul class="navigation"> <li><a href="index.html">Home</a></li> <li><a href="lesson03/chamber-site-plan.html">Site Plan</a></li> <li><a href="chamber/index.html">Chamber</a></li> <li><a href="https://www.byui.edu/" target="_blank">BYU-Idaho</a></li> <li><a href="final-project/index.html" target="_blank">BYU-Idaho</a></li> <li> <a href="https://www.churchofjesuschrist.org/study/scriptures/bofm/1-ne/3?lang=eng" target="_blank" >Scripture</a > </li> </ul> </nav> <div class="hero"> <picture> <source srcset="images/aba-nigeria-temple.webp" media="(max-width: 500px)" /> <source media="(max-width: 980px)" srcset="images/aba-nigeria-temple-large.webp" /> <img src="images/aba-nigeria-temple-large.webp" alt="aba nigeria temple" /> </picture> <div class="label"> <h4>Aba Nigeria Temple</h4> </div> </div> <main> <h2>WDD 230: Web Frontend Development</h2> <hr /> <section class="card"> <h3>Learning Activities</h3> <ol class="activities"> </ol> </section> <section class="card"> <h3>Information</h3> <p class="visit"></p> <p class="city"></p> <p class="temperature"></p> <p class="description"></p> <p class="emoji"></p> </section> <div class="iframe"> <iframe title="Area map" src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d84371.59729517039!2d7.282171261253809!3d9.148857368994495!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2sng!4v1706021749332!5m2!1sen!2sng" style="border: 0" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade" ></iframe> </div> </main> <footer> <p id="copyright">Goodness Arinze Okafor, Abuja Nigeria</p> <p id="last-modified"></p> </footer> <script src="scripts/links.js"></script> <script src="scripts/getdates.js"></script> <script src="scripts/hambuger.js"></script> <!-- <script src="chamber/scripts/windchill.js"></script> --> <script src="scripts/getweather.js"></script> </body> </html>
<!DOCTYPE html> <html lang="es"> <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>Pagina Responsiva Donalson Javier</title> <!-- BootStrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <!-- BootStrap JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script> </head> <style> body{ background: #0f0c29; /* fallback for old browsers */ background: -webkit-linear-gradient(to right, #24243e, #302b63, #0f0c29); /* Chrome 10-25, Safari 5.1-6 */ background: linear-gradient(to right, #24243e, #302b63, #0f0c29); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */ } body::-webkit-scrollbar{ width: 7px; } .ND{ text-decoration: none; } .DescriPC{ display: inline-block; vertical-align: top; color:white; font-size:12px; font-weight: bold } </style> <body> <nav class="navbar fixed-top navbar-expand-lg bg-dark navbar-dark"> <div class="container-fluid"> <a class="navbar-brand" href="{{ url_for('Inicio') }}"> <img src="{{ url_for('static', filename='imagenes/Logo.PNG') }}" alt="" width="30" height="24"> DJ's HardWare</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link" href="{{ url_for('Productos') }}">Productos</a> </li> <li class="nav-item"> <a class="nav-link" href="https://wa.me/50230599403">Contactanos</a> </li> </ul> <form class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Buscar" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Buscar</button> </form> </div> </div> </nav> {% block content %} {% endblock %} </body> </html>
# Copyright 2018-2022 Carsten Blank # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import logging import numpy as np from dc_qiskit_stochastics.qiskit_util import ibmq_ourense, ibmqx2 from dc_qiskit_stochastics.discrete_stochastic_process import DiscreteStochasticProcess from dc_qiskit_stochastics.error_mitigation import create_error_mitigation_experiment import dc_quantum_scheduling as scheduling from dc_quantum_scheduling.qiskit.qiskit_provider import set_provider_config from dc_quantum_scheduling import client from gBm_delta_data import S_0, r, time_to_maturity, mu, sigma logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO') [logging.getLogger(name).setLevel('WARN') for name in logging.root.manager.loggerDict if name.startswith('qiskit')] logging.getLogger(__name__).setLevel('INFO') LOG = logging.getLogger(__name__) set_provider_config(hub='ibm-q', group='open', project='main') client.set_url('http://localhost:8080') if __name__ == "__main__": version = 'v001' n = 4 shots = 8192 * 1 P = 100 L = 100 backend = ibmqx2 backend_name = "sim" if backend is None else backend().name() l_array = np.arange(-L, L + 1) fourier_coefficients = np.asarray( [-1.0j / (2 * np.pi * l) * np.exp(-2 * np.pi ** 2 * l ** 2 / P ** 2) if l != 0 else 1 / 2 for l in l_array]) char_func_input = 2 * np.pi / P * l_array strike_prices = np.asarray([25, 55, 85, 105, 110, 115, 120, 125, 130, 160, 190, 220]) prepared_experiments = [] for strike_price in strike_prices: initial_value = (np.log(S_0) - np.log(strike_price) + (r + sigma**2 / 2) * time_to_maturity) \ / (sigma * np.sqrt(time_to_maturity)) x_1 = (mu - sigma**2/2) / (n * sigma * np.sqrt(time_to_maturity)) \ - 1 / (np.sqrt(n) * np.sqrt(time_to_maturity)) x_2 = (mu - sigma**2/2) / (n * sigma * np.sqrt(time_to_maturity)) \ + 1 / (np.sqrt(n) * np.sqrt(time_to_maturity)) probabilities = np.asarray(n * [[.5, .5]]) realizations = np.asarray(n * [[x_1, x_2]]) dsp: DiscreteStochasticProcess = DiscreteStochasticProcess( initial_value=initial_value, probabilities=probabilities, realizations=realizations ) configuration = { 'shots': shots, 'tags': ['gBm_delta_donsker_qc_fourier', f'{datetime.datetime.now().date().isoformat()}', f'version={version}', f'P={P}', f'L={L}', f'shots={shots}', f'K={strike_price}', f'trans_backend={backend_name}'], 'no_noise': False, 'strike_price': strike_price } exp: scheduling.PreparedExperiment = dsp.characteristic_function( evaluations=char_func_input, other_arguments=configuration, transpiler_target_backend=backend ) prepared_mitigation = create_error_mitigation_experiment(exp) exp.tags += ['main experiment'] key_experiment = client.save_prepared_experiment(exp) key_mitigation = client.save_prepared_experiment(prepared_mitigation) prepared_experiments.append((key_experiment, key_mitigation)) LOG.info(f'======> STRIKE_PRICE={strike_price} / Experiment key={key_experiment}') LOG.info(f'======> STRIKE_PRICE={strike_price} / Mitigation key={key_mitigation}') # for strike_price, (key_experiment, key_mitigation) in zip(strike_prices, prepared_experiments): # LOG.info(f'======> STRIKE_PRICE={strike_price} / Experiment key={key_experiment}') # LOG.info(f'======> STRIKE_PRICE={strike_price} / Mitigation key={key_mitigation}') # client.run_experiment(key_experiment, backend=backend()) # client.run_experiment(key_mitigation, backend=backend())
cbuffer TransformationBuffer : register(b0) { matrix ModelToWorldMatrix; matrix WorldToViewMatrix; matrix ProjectionMatrix; }; struct VSIn { float3 Pos : POSITION; float3 Normal : NORMAL; float3 Tangent : TANGENT; float3 Binormal : BINORMAL; float2 TexCoord : TEX; }; struct PSIn { float4 Pos : SV_Position; float3 Normal : NORMAL; float2 TexCoord : TEX; float4 WorldPos : POSITION1; }; //----------------------------------------------------------------------------------------- // Vertex Shader //----------------------------------------------------------------------------------------- PSIn VS_main(VSIn input) { //PSIn output = (PSIn)0; // //// Model->View transformation //matrix MV = mul(WorldToViewMatrix, ModelToWorldMatrix); //// Model->View->Projection (clip space) transformation //// SV_Position expects the output position to be in clip space //matrix MVP = mul(ProjectionMatrix, MV); // //// Perform transformations and send to output //output.Pos = mul(MVP, float4(input.Pos, 1)); //output.Normal = normalize( mul(ModelToWorldMatrix, float4(input.Normal,0)).xyz ); //output.TexCoord = input.TexCoord; // //return output; PSIn output; // Model->View transformation matrix MV = mul(WorldToViewMatrix, ModelToWorldMatrix); // Model->View->Projection (clip space) transformation matrix MVP = mul(ProjectionMatrix, MV); // Perform transformations and send to output output.Pos = mul(MVP, float4(input.Pos, 1.0f)); output.Normal = normalize(mul(ModelToWorldMatrix, float4(input.Normal, 0.0f)).xyz); output.TexCoord = input.TexCoord; output.WorldPos = mul(ModelToWorldMatrix, float4(input.Pos, 1.0f)); // Optionally output world position return output; }
<!DOCTYPE html> <html lang=""> <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>美夢成真</title> <link rel="stylesheet" href="style/all.css" /> <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=Kalam:wght@700&family=Noto+Sans+TC:wght@400;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css"> <style> .font{ font-family: 'Kalam', cursive; /* font-family: 'Noto Sans TC', sans-serif; */ } </style> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand d-block" href="./index.html" ><i class="bi bi-flower1"></i> 美夢成真</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ms-auto mb-2 mb-lg-0 align-items-center"> <li class="nav-item"> <a class="nav-link fs-5 fw-bold" aria-current="page" href="./index.html" >Home</a > </li> <li class="nav-item px-5"> <a class="nav-link fs-5 fw-bold" aria-current="page" href="./server.html" >服務介紹</a > </li> <li class="nav-item"> <a class="nav-link fs-5 fw-bold text-primary" aria-current="page" href="./work.html" >設計作品</a > </li> <li class="nav-item px-5"> <a class="nav-link fs-5 fw-bold" aria-current="page" href="./list.html" >飾品專區</a > </li> <li class="nav-item"> <a class="nav-link fs-5 fw-bold d-block py-2 px-5 rounded-pill bg-primary text-dark" aria-current="page" href="./custom.html" >客製古風飾品</a > </li> </ul> </div> </div> </nav> <div class="pt-5"style="background-image: url(./style/img/lightpaperfibers.png);"> <h2 class="text-center font mt-5 mb-3">近期作品</h2> <div class="container"> <div class="row g-4"> <div class="col-12 col-lg-2 font"> <p class="text-center text-lg-start">Designer</p> <ul class="d-flex flex-row flex-lg-column list-unstyled justify-content-around"> <li class="work-li mt-2 ms-4 text-primary">All</li> <li class="work-li mt-2 ms-4">Jenny</li> <li class="work-li mt-2 ms-4">Zoe</li> <li class="work-li mt-2 ms-4">Michael</li> <li class="work-li mt-2 ms-4">Birdy</li> </ul> </div> <div class="col-12 col-lg-10"> <div class="row g-3"> <div class="col-6 col-lg-4"> <!-- <img src="./style/img/04.png" alt="" class="img-fluid rounded index-img" > --> <div class="card border-0 position-relative"> <a href="#"> <img src="./style/img/04.png" class="rounded-4 card-img" alt="dog07"> <div class="designer-name-card font-family-second d-flex ps-lg-6 ps-2 pb-2 pb-lg-3 align-items-end card-img-overlay"> <p class="mb-0 font text-white">designer<br><span class="fw-bold fs-4">Jenny</span></p> </div> </a> </div> </div> <div class="col-6 col-lg-4"> <!-- <img src="./style/img/05.png" alt="" class="img-fluid rounded index-img" > --> <div class="card border-0 position-relative"> <a href="#"> <img src="./style/img/05.png" class="rounded-4 card-img" alt="dog07"> <div class="designer-name-card font-family-second d-flex ps-lg-6 ps-2 pb-2 pb-lg-3 align-items-end card-img-overlay"> <p class="mb-0 font text-white">designer<br><span class="fw-bold fs-4">Jenny</span></p> </div> </a> </div> </div> <div class="col-6 col-lg-4"> <!-- <img src="./style/img/06.png" alt="" class="img-fluid rounded index-img" > --> <div class="card border-0 position-relative"> <a href="#"> <img src="./style/img/06.png" class="rounded-4 card-img" alt="dog07"> <div class="designer-name-card font-family-second d-flex ps-lg-6 ps-2 pb-2 pb-lg-3 align-items-end card-img-overlay"> <p class="mb-0 font text-white">designer<br><span class="fw-bold fs-4">Jenny</span></p> </div> </a> </div> </div> <div class="col-6 col-lg-4 mb-5"> <!-- <img src="./style/img/07.png" alt="" class="img-fluid rounded index-img" > --> <div class="card border-0 position-relative"> <a href="#"> <img src="./style/img/07.png" class="rounded-4 card-img" alt="dog07"> <div class="designer-name-card font-family-second d-flex ps-lg-6 ps-2 pb-2 pb-lg-3 align-items-end card-img-overlay"> <p class="mb-0 font text-black">designer<br><span class="fw-bold fs-4">Jenny</span></p> </div> </a> </div> </div> </div> </div> </div> </div> </div> <!-- <img src="./style/img/logo.png" alt="www"> --> <footer class=""> <div class="container"> <div class="row justify-content-center my-5"> <div class="col-lg-5"> <div class="row justify-content-center"> <div class="col-sm-5 text-center"> <img src="./style/img/link01.png" alt="www" class="img-fluid" /> </div> <div class="col-sm-5 text-center pt-3 pt-lg-0"> <h4>加入美夢團隊</h4> <p>我也對古風飾品有興趣,想加入設計行列</p> <button type="button" class="btn btn-outline-dark rounded-pill px-5 py-2 text-nowrap" > 聯絡我們 </button> </div> </div> </div> <div class="col-lg-5"> <div class="row justify-content-center pt-3 pt-lg-0"> <div class="col-sm-5 text-center"> <img src="./style/img/link02.png" alt="www" class="img-fluid" /> </div> <div class="col-sm-5 text-center pt-3 pt-lg-0"> <h4>加入美夢團隊</h4> <p>我也對古風飾品有興趣,想加入設計行列</p> <button type="button" class="btn btn-outline-dark rounded-pill px-5 py-2 text-nowrap" > 聯絡我們 </button> </div> </div> </div> </div> </div> </footer> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script> </body> </html>
import { RouterProvider, createBrowserRouter } from "react-router-dom"; import { HomePage, AboutPage, MenuPage } from "./pages"; import { Layout } from "./components/Layout"; const router = createBrowserRouter([ { element: <Layout />, children: [ { path: "/", element: <HomePage />, }, { path: "/about", element: <AboutPage />, }, { path: "menu", element: <MenuPage />, }, ], }, ]); function App() { return <RouterProvider router={router} />; } export default App;
import '../../../../core/typedefs/typedef.dart'; import '../base_success_response_mapper/data_json_array_response_mapper.dart'; import '../base_success_response_mapper/data_json_object_response_mapper.dart'; import '../base_success_response_mapper/json_array_response_mapper.dart'; import '../base_success_response_mapper/json_object_response_mapper.dart'; import '../base_success_response_mapper/result_json_array_response_mapper.dart'; import '../base_success_response_mapper/result_json_object_response_mapper.dart'; abstract class BaseSuccessResponseMapper<I, O> { const BaseSuccessResponseMapper(); factory BaseSuccessResponseMapper.fromType(SuccessResponseMapperType type) { switch (type) { case SuccessResponseMapperType.dataJsonObject: return DataJsonObjectResponseMapper<I>() as BaseSuccessResponseMapper<I, O>; case SuccessResponseMapperType.dataJsonArray: return DataJsonArrayResponseMapper<I>() as BaseSuccessResponseMapper<I, O>; case SuccessResponseMapperType.jsonObject: return JsonObjectResponseMapper<I>() as BaseSuccessResponseMapper<I, O>; case SuccessResponseMapperType.jsonArray: return JsonArrayResponseMapper<I>() as BaseSuccessResponseMapper<I, O>; case SuccessResponseMapperType.resultJsonObject: return ResultJsonObjectResponseMapper<I>() as BaseSuccessResponseMapper<I, O>; case SuccessResponseMapperType.resultJsonArray: return ResultJsonArrayResponseMapper<I>() as BaseSuccessResponseMapper<I, O>; } } // ignore: avoid-dynamic O map(dynamic response, Decoder<I>? decoder); // ignore: avoid-dynamic } enum SuccessResponseMapperType { dataJsonObject, dataJsonArray, resultJsonObject, resultJsonArray, jsonObject, jsonArray, }
import { Component, OnInit, ViewChild } from '@angular/core'; import { exportDataGrid } from 'devextreme/excel_exporter'; import { Workbook } from 'exceljs'; import { ModalDirective } from 'ngx-bootstrap/modal'; import { Predmeti } from 'src/app/models/predmeti.model'; import { StayStudentService } from 'src/app/service/stay-student.service'; import saveAs from 'file-saver'; import { Moduli } from 'src/app/models/moduli.model'; import { Sifrarnik } from 'src/app/models/sifrarnik.model'; @Component({ selector: 'app-predmeti', templateUrl: './predmeti.component.html', styleUrls: ['./predmeti.component.css'] }) export class PredmetiComponent implements OnInit { @ViewChild('subjectModal', { static: false }) subjectModal: ModalDirective; @ViewChild('confirmModal', { static: false }) confirmModal: ModalDirective; blukId: string = ""; predmeti: Predmeti[] = []; isValid: boolean = false; moduli: Moduli[] = []; sifrarnik: Sifrarnik[] = []; predmet: Predmeti = new Predmeti; selectedSubject: Predmeti = new Predmeti; semestri: any[] = [{isWinter:true, name: 'Zimski'}, {isWinter:false, name: 'Ljetni'}] constructor( private service: StayStudentService ) {} ngOnInit(): void { this.getSubjects(); } getSubjects(){ this.service.getPredmetsList().then(data => { this.predmeti = data; }); this.service.getModulsList().then(data => { this.moduli = data; }); this.service.getSifrarnikList().then(data => { this.sifrarnik = data; }); } openSubjectModal(data: any){ this.predmet = data; this.subjectModal.show(); } openConfirmModal(data: any){ this.selectedSubject = data; this.confirmModal.show(); } removeSubject(data: any){ var index = this.predmeti.findIndex(value=>{ if(value && value.id == data.id){ return true; } return false; }); this.predmeti.splice(index,1); this.service.deleteSubject(data.id); } resetPredmet(){ this.predmet = new Predmeti; } saveSubject(){ if(!this.predmet.id || this.predmet.id == 0){ this.service.addSubject(this.predmet).then(data => { this.subjectModal.hide(); this.getSubjects(); }); }else{ this.service.updateSubject(this.predmet).then(data => { this.subjectModal.hide(); this.getSubjects(); }); } } onExporting(e) { const workbook = new Workbook(); const worksheet = workbook.addWorksheet('Main sheet'); exportDataGrid({ component: e.component, worksheet: worksheet }).then(function() { workbook.xlsx.writeBuffer() .then(function(buffer: BlobPart) { saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'Predmeti.xlsx'); }); }); e.cancel = true; } isDisabled(){ if(!this.predmet.naziv || !this.predmet.idSifrarnik || !this.isValid){ return true; } return false; } isValidCheck(){ if(this.predmet){ let sif = this.sifrarnik.find(t => t.id == this.predmet.idSifrarnik); if(sif.zahtijevaModul && !this.predmet.idModul){ this.isValid = false; }else{ this.isValid = true; } } } }
# 1장 SQL 처리 과정과 I/O ## 1.1 SQL 파싱과 최적화 ### 1.1.1 구조적, 집합적, 선언적 질의 언어 - SQL은 기본적으로 구조적이고 집합적이고 선언적인 질의 언어다 - 원하는 결과집합을 구조적, 집합적으로 선언하지만, 그 결과집합을 만드는 과정은 절차적일 수 밖에 없다 = 프로시저가 필요하다! - DBMS 내부의 엔진인 옵티마이저가 프로시저를 생성한다 = 프로시저가 대신 프로그래밍 해주는 셈 - 프로시저를 작성하고 컴파일 해서 실행 가능한 상태로 만드는 전 과정을 `SQL 최적화` ### 1.1.2 SQL 최적화 1. SQL 파싱 - 파싱 트리 생성 - Syntax 체크 - Semantic 체크 2. SQL 최적화 3. 로우 소스 생성(실행 가능한 코드 또는 프로시저 형태로 포맷팅하는 단계) ### 1.1.3 SQL 옵티마이저 - 쿼리를 수행하기 위한 실행계획들을 찾아냄 - 데이터 딕셔너리에 미리 수집해둔 오브젝트에 통계 및 시스템 통계 정보를 이용해 각 실행계획의 예상 비용 산정 - 최저 비용을 나타내는 실행계획 선택 ### 1.1.4 실행계획과 비용 - MySQL에서 실행 계획을 확인하기 위한 키워드 `EXPLAIN` - 실행하는 실행계획은 옵티마이저가 비용을 근거로 선택한 것 - 비용은 쿼리를 실행하는 동안 발생할 것으로 `예상되는` `I/O 횟수, 예상 소요 시간`을 표현한 것 **옵티마이저가 실행계획을 세우기 위해 고려하는 수많은 정보들** - 테이블, 컬럼, 인덱스 구조에 관한 기본 정보 - 오브젝트 통계: 테이블 통계, 인덱스 통계, (히스토그램을 포함한) 컬럼 통계 - 시스템 통계: CPU 속도, Single Block I/O 속도, Mutliblock I/O 속도 등 - 옵티마이저 관련 파라미터 ### 1.1.5 옵티마이저 힌트 - 상황에 따라 사용하거나 사용하지 않을 수 있음 - MySQL에서 힌트를 사용하기 위해서 주석 기호에 +를 붙여 작성한다 예시: `SELECT /*+ ... 8/` ## 1.2 SQL 공유 및 재사용 ### 1.2.1 소프트 파싱 vs 하드 파싱성 ![SGA 구조](/img/pic_1-4.png) - SGA: 서버 프로세스와 백그라운드 프로세스가 공통으로 액세스하는 데이터와 제어 구조를 캐싱하는 메모리 공간 - 라이브러리 캐시(쿼리 캐시): SQL파싱, 최적화, 로우 소스 생성 과정을 거친 내부 프로시저는 라이브러리 캐시에 저장되어 재사용된다 - 소프트 파싱: 파싱한 SQL이 라이브러리 캐시에 존재하면 바로 실행 - 하드 파싱: 파싱한 SQL이 라이브러리 캐시에 존재하지 않아서 최적화, 로우 소스 생성과정을 모두 거치는 것 - 재사용 이유? 최적화 과정에 딕셔너리, 통걔 정보를 읽어 효율성을 판단하는 과정은 CPU를 많이 사용하는 과정 ### 1.2.2 바인드 변수의 중요 - 라이브러리 캐시에 저장되는 SQL에는 이름이 없다 - SQL자체가 검색을 위한 key -> 대, 소문자, 뛰어쓰기 등 아주 조금만 달라도 매번 하드 파싱하고 캐시에 저장한다 - (중요)!바인드 변수를 사용할 것(자바 PreparedStatement)! **바인드 변수** - PL/SQL 또는 SQL 쿼리문에서 WHERE 절에 value 값을 (?) 로 사용하는 변수 - 아래와 같이 파라이터 Driven 방식으로 내부 프로시저를 생성한다 `create procedure LOGIN (login_id varchar2) { ... }` ## 1.3 데이터 저장 구조 및 I/O 메커니즘 ### 1.3.1 SQL이 느린 이유 - SQL이 느린 이유는 디스크 I/O 때문. 디스크 I/O가 SQL 성능을 좌우 - I/O를 진행하는 동안 프로세스는 대기 상태에 빠진다 - 스토리지 성능이 빨라지고 있지만 여전히 시간이 가장 많이 소요되는 작업 ### 1.3.2 데이터베이스 저장 구조 - 데이터파일: 디스크 상의 물리적인 OS 파일 - 테이블 스페이스: 세그먼트를 담는 컨테이너, 여러 개의 데이터파일로 구성됨 - 세그먼트: 테이블, 인덱스, LOB컬럼 등과 같이 데이터 저장공간이 필요한 오브젝트, 파니셔닝 되지 않았다면 한 오브젝트는 하나의 세그먼트에 저장됨 - 테이블 세그먼트 헤더에 익스텐트 맵(각 익스텐트의 첫 번째 블록 DBA 저장)이 있음 - 익스텐트: 공간을 확장하는 단위. 세그먼트 구성요소. 연속된 블록 집합. 세그먼트 공간이 부족하면 테이블스페이스로부터 익스텐트를 추가 할당 받음 - 한 세그먼트의 익스텐트끼리는 연속된 공간이 아닐 수 있음 - 블록(or 페이지): 실제 데이터가 저장되는 공간. 익스텐트의 구성요소. 한 블록에 저장된 레코드는 모두 같은 테이블 레코드 - 익스텐트 내의 블록은 서로 인접한 연속된 공간 - DBA(Data Block Address): 데이터 블록이 디스크 상에서 몇 번 데이터파일의 몇 번째 블록인지 나타내는 고유 주소값 ![그림 1-12](/img/pic_1-12.png) ### 1.3.3 블록 단위 I/O 데이터 I/O 단위는 블록이다. 한 레코드만 읽고 싶어도 그 레코드가 포함된 해당 블록을 통째로 읽음(테이블, 인덱스 모두 해당) ### 1.3.4 시퀀셜 액세스 vs 랜덤 액세스 테이블 또는 인덱스 블록을 액세스하는 방법 - 시퀀셜 액세스: 논리적 혹은 물리적으로 연결된 순서에 따라 차례로 블록을 읽는 방식 - 인덱스 리프 노드로 범위 검색 - 테이블 세그먼트 헤더 맵으로 풀 테이블 스캔 - 랜덤 엑세스: 레코드 하나를 읽기 위해 한 블록씩 접근하는 방식 ### 1.3.5 논리적 I/O vs 물리적 I/O - 자주 읽는 블록을 매번 디스크에서 읽는 것은 비효율적! -> 캐싱! - DB Buffer Cache: 디스크에서 읽은 데이터 블록을 캐시, 공유메모리 영역 - 데이터 블록을 읽을 땐 항상 버퍼 캐시부터 탐색 - 논리적 I/O: SQL을 처리하는 과정에서 메모리 버퍼 캐시에서 발생한 총 블록 I/O - 논리적 I.O (유사) 메모리 I/O - 물리적 I/O: 디스크에서 발생한 총 블록 I/O - 메모리 I/O(전기적 신호) <<<<< 디스크 I/O(액세스 암을 통해 물리적 작용) 대략 10,000배 느림 - 버퍼캐시 히트율(Buffer Cache Hit Ratio, BCHR) = (논리적 I/O - 물리적 I/O) / 논리적 I/O * 100 - OLTP 애플리케이션은 시스템 레벨에서 평균 99% 히트율을 달성해야 한다 - BCHR은 시스템 상황에 따라 달라지므로 물리적 I/O는 결국 통제 불가능한 외생변수 - 논리적 I/O는 내생변수 => SQL 튜닝을 통해 논리적 I/O를 줄이고, 그로 인해 물리적 I/O도 줄어들어 성능을 향상시키는 것! ### 1.3.6 Single Block I/O vs Multiblock I/O - Single block I/O: 한 번에 한 블록씩 요청해서 메모리에 적재하는 방식 - 인덱스를 사용하는 방식 - Multiblock I/O: 한 번에 여러 블록씩 요청해서 메모리에 적재하는 방식 - 테이블 전체 스캔 - 많은 데이터를 가져올 때 multiblcok I/O 단위가 클수록 유리 - multiblock I/O를 이용해도 인접 블록만 가져올 수 있다(같은 익스텐트 내에서면 여러 블록씩 가져올 수 있다는 이야기!) ### 1.3.7 Table Full Scan vs Index Range Scan - Table Full Scan이라고 항상 느리고, Index Range Scan이라고 항상 빠른 것이 아니다 - 많은 데이터를 처리하는 집계용 SQL, 배치 프로그램 등은 Table Full Scan을 사용해서 자주 성능이 향상된다 ### 1.3.8 캐시 탐색 메커니즘 - Direct Path I/O를 제외한 모든 블록 I/O는 메모리 버퍼캐시를 경유한다 - 버퍼캐시는 해시 구조로 관리한다(같은 입력값은 동일한 해시 체인=버킷에 연결) - 해시 체인에 버퍼 헤더를 담고 있다, 거기서 얻은 포인터로 버퍼 블록을 액세스 한다 ![그림 1-27](/img/pic_1-27.png) - 버퍼캐시, 버퍼캐시 체인은 공유자원이므로 직렬화 메커니즘이 필요하다 - 캐시버퍼 체인 레치, Lock => 직렬화 메커니즘으로 경합을 줄이기 위해 SQL 튜닝을 통해 논리적 I/O를 줄여야한다 ### 기타 - OLTP: online transaction processing - DW: data warehouse ### 참고 링크 https://myinfrabox.tistory.com/92 https://velog.io/@sezzzini/%EA%B8%88%EC%9C%B5-IT-ETL-%EA%B3%BC-DW#dw ### 질문 1. 1.1장 질문 - 데이터 딕셔너리가 뭔가요? - SQL plus의 Auto trace 기능? 2. 1.2장 질문 3. 1.3 장 질문 - 59p Full Scan 중에 Chian이 발생한 로우를 읽을 때도 Single Block I/O 방식으로 발생. Chian이 뭐지,,? - 인덱스를 이용한 접근은 Single Block I/O를 사용한다고 했는데, 인덱스의 리프 노드로 시퀀셜 액세스 해도 Single Block I/O로 동작할까? Mutliblock I/O로 동작할까?
package com.example.myapplication; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import android.app.NotificationChannel; import android.app.NotificationManager; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; @RequiresApi(api = Build.VERSION_CODES.O) public class Notifications extends AppCompatActivity { Button notifyBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notifications); notifyBtn = findViewById(R.id.notify_btn); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ NotificationChannel channel = new NotificationChannel("My notification", "My Notification", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } notifyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NotificationCompat.Builder builder = new NotificationCompat.Builder(Notifications.this, "My notification"); builder.setContentTitle("My Title"); builder.setContentText("Hello from I2GIS, this is a simple notification"); builder.setSmallIcon(R.drawable.ic_sms); builder.setAutoCancel(true); NotificationManagerCompat managerCompat = NotificationManagerCompat.from(Notifications.this); managerCompat.notify(1, builder.build()); } }); } }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:p="http://primefaces.org/ui"> <ui:composition> <p:dialog id="EmpresaEditDlg" widgetVar="EmpresaEditDialog" modal="true" resizable="false" appendTo="@(body)" header="#{bundle.EditEmpresaTitle}"> <h:form id="EmpresaEditForm"> <h:panelGroup id="display"> <p:panelGrid columns="2" rendered="#{empresaController.selected != null}"> <p:outputLabel value="#{bundle.EditEmpresaLabel_IDEmpresa}" for="IDEmpresa" /> <p:inputText id="IDEmpresa" value="#{empresaController.selected.IDEmpresa}" title="#{bundle.EditEmpresaTitle_IDEmpresa}" required="true" requiredMessage="#{bundle.EditEmpresaRequiredMessage_IDEmpresa}"/> <p:outputLabel value="#{bundle.EditEmpresaLabel_nombreEmpresa}" for="nombreEmpresa" /> <p:inputText id="nombreEmpresa" value="#{empresaController.selected.nombreEmpresa}" title="#{bundle.EditEmpresaTitle_nombreEmpresa}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_tipoEmpresa}" for="tipoEmpresa" /> <p:inputText id="tipoEmpresa" value="#{empresaController.selected.tipoEmpresa}" title="#{bundle.EditEmpresaTitle_tipoEmpresa}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_numRuc}" for="numRuc" /> <p:inputText id="numRuc" value="#{empresaController.selected.numRuc}" title="#{bundle.EditEmpresaTitle_numRuc}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_actividadEconomica}" for="actividadEconomica" /> <p:inputText id="actividadEconomica" value="#{empresaController.selected.actividadEconomica}" title="#{bundle.EditEmpresaTitle_actividadEconomica}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_numeroEstudiantes}" for="numeroEstudiantes" /> <p:inputText id="numeroEstudiantes" value="#{empresaController.selected.numeroEstudiantes}" title="#{bundle.EditEmpresaTitle_numeroEstudiantes}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_emailEmpresa}" for="emailEmpresa" /> <p:inputText id="emailEmpresa" value="#{empresaController.selected.emailEmpresa}" title="#{bundle.EditEmpresaTitle_emailEmpresa}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_numContacto}" for="numContacto" /> <p:inputText id="numContacto" value="#{empresaController.selected.numContacto}" title="#{bundle.EditEmpresaTitle_numContacto}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_docAdjuntos}" for="docAdjuntos" /> <p:inputText id="docAdjuntos" value="#{empresaController.selected.docAdjuntos}" title="#{bundle.EditEmpresaTitle_docAdjuntos}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_numConvenio}" for="numConvenio" /> <p:inputText id="numConvenio" value="#{empresaController.selected.numConvenio}" title="#{bundle.EditEmpresaTitle_numConvenio}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_numInforme}" for="numInforme" /> <p:inputText id="numInforme" value="#{empresaController.selected.numInforme}" title="#{bundle.EditEmpresaTitle_numInforme}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_horarioAtencion}" for="horarioAtencion" /> <p:calendar id="horarioAtencion" pattern="HH:mm:ss" value="#{empresaController.selected.horarioAtencion}" title="#{bundle.EditEmpresaTitle_horarioAtencion}" showOn="button"/> <p:outputLabel value="#{bundle.EditEmpresaLabel_firmaConvenio}" for="firmaConvenio" /> <p:inputText id="firmaConvenio" value="#{empresaController.selected.firmaConvenio}" title="#{bundle.EditEmpresaTitle_firmaConvenio}" /> <p:outputLabel value="#{bundle.EditEmpresaLabel_IDPersona}" for="IDPersona" /> <p:selectOneMenu id="IDPersona" value="#{empresaController.selected.IDPersona}" > <f:selectItem itemLabel="#{bundle.SelectOneMessage}"/> <f:selectItems value="#{personaController.itemsAvailableSelectOne}" var="IDPersonaItem" itemValue="#{IDPersonaItem}"/> </p:selectOneMenu> </p:panelGrid> <p:commandButton actionListener="#{empresaController.update}" value="#{bundle.Save}" update="display,:EmpresaListForm:datalist,:growl" oncomplete="handleSubmit(args, 'EmpresaEditDialog');"/> <p:commandButton value="#{bundle.Cancel}" onclick="EmpresaEditDialog.hide()"/> </h:panelGroup> </h:form> </p:dialog> </ui:composition> </html>
using Invasion.Engine.Collisions; using Invasion.Engine.Interfaces; using Invasion.Models.Collisions; using System.Numerics; namespace Invasion.Engine.Components.Colliders { /// <summary> /// Represents base collider component /// </summary> public abstract class ColliderBase : IComponent { /// <summary> /// Collider gameobject /// </summary> public GameObject ColliderObject { get; private set; } /// <summary> /// Collisions controller /// </summary> public CollisionController Collisions { get; private set; } /// <summary> /// Collider base constructor /// </summary> /// <param name="collisions">Collisions controller</param> /// <param name="colliderObject">Collider object</param> public ColliderBase(CollisionController collisions, GameObject colliderObject) { ColliderObject = colliderObject; Collisions = collisions; } /// <summary> /// Checks if one collider inside another /// </summary> /// <param name="other">Other collider</param> /// <returns>True if colliders inside each another</returns> public abstract bool IsInside(ColliderBase other); /// <summary> /// Checks if point is inside collider /// </summary> /// <param name="point">Point to check</param> /// <returns>True if point inside collider, other returns false</returns> public abstract bool IsPointInsideCollider(Vector2 point); /// <summary> /// Try to collide with other collider /// </summary> /// <param name="other">Other collider</param> public void TryCollide(ColliderBase other) { if (IsInside(other)) { if (CollisionMatrix.IsCollided(ColliderObject.Layer, other.ColliderObject.Layer)) { if (ColliderObject.TryTakeComponent(out Transform g1transform) && ColliderObject.TryTakeComponent(out RigidBody2D rigidBody)) { int x = 0, y = 0; if (rigidBody.Speed.X < 0) x = 1; else if (rigidBody.Speed.X > 0) x = -1; if (rigidBody.Speed.Y < 0) y = 1; else if (rigidBody.Speed.Y > 0) y = -1; g1transform.Position = new Vector3(g1transform.Position.X + x * 0.1f, g1transform.Position.Y + 0.1f * y, g1transform.Position.Z); } } else { Collisions.TryCollide((ColliderObject, other.ColliderObject)); } } } } }
@using Data.Models.Data.ProviderData @using ISNAPOO.Common.Framework @using ISNAPOO.Core.Contracts.Common @using ISNAPOO.Core.ViewModels.Common @inject ISettingService SettingService @inject IDataSourceService DataSourceService @inject UserManager<ApplicationUser> userManager @inherits BlazorBaseComponent <SfDialog @ref="@sfDialog" Target="#target" Width="60%" EnableResize=true AllowDragging="true" IsModal="true" ShowCloseIcon="true" AllowPrerender="true" @bind-Visible="@IsVisibleAddModal" CssClass="@dialogClass"> <DialogTemplates> <Header> Данни за настройка </Header> <Content> <EditForm Model="model" OnSubmit="@Save"> <ValidationSummary /> <DataAnnotationsValidator /> <div class="modal-body"> <div class="row"> <div class="col-sm-4"> <!-- text input --> <div class="form-group required"> <label class="control-label"> Име: </label> <InputText class="form-control" @bind-Value="model.SettingName" /> </div> </div> <div class="col-sm-4"> <!-- text input --> <div class="form-group required"> <label class="control-label"> Код: </label> <InputText Readonly="true" class="form-control" @bind-Value="model.SettingIntCode" /> </div> </div> <div class="col-sm-4"> <!-- text input --> <div class="form-group required"> <label class="control-label"> Стойност: </label> <InputText class="form-control" @bind-Value="model.SettingValue" /> </div> </div> </div> <div class="row"> <div class="col"> <!-- text input --> <div class="form-group"> <label class="control-label"> Описание: </label> <InputTextArea class="form-control" @bind-Value="model.SettingDescription" /> </div> </div> <br /> </div> </div> <div class="row"> <div class="col-sm-12"> <div class="form-group"> <div class="text-right"> <button class="btn btn-info" type="submit">Запиши</button> <button type="button" class="btn btn-outline-secondary" @onclick="@Cancel">Отказ</button> </div> </div> </div> </div> </EditForm> </Content> </DialogTemplates> </SfDialog> <ToastMsg @ref="toast"></ToastMsg> <ConfirmDialog CallbackCancel="ConfirmDialogCallback" @ref="ConfirmDialog"></ConfirmDialog> @code { private bool IsVisibleAddModal { get; set; } = false; SfDialog sfDialog; ToastMsg toast; private string dialogClass = ""; SettingVM model = new SettingVM(); [Parameter] public EventCallback<SettingVM> CallbackAfterSave { get; set; } private string prevSettingIntCode = string.Empty; private string prevSettingName = string.Empty; public void OpenModal(SettingVM _model) { this.IsVisibleAddModal = true; this.model = _model; prevSettingIntCode = model.SettingIntCode; prevSettingName = model.SettingName; this.StateHasChanged(); } public async Task<SettingVM> SaveFromParent() { return this.model; } private async Task Save() { bool hasPermission = await CheckUserActionPermission("ManageSettingsData", false); if (!hasPermission) { return; } this.SpinnerShow(); if (model.SettingClass.Equals("int")) { int number; bool IsInt = int.TryParse(model.SettingValue, out number); if (!IsInt) { await this.ShowErrorAsync("Стойноста трябва да е само числа!"); return; } } else if (model.SettingClass.Equals("bool")) { bool boolean; bool IsBool = bool.TryParse(model.SettingValue, out boolean); if (!IsBool) { await this.ShowErrorAsync("Стойноста трябва да е true или false!"); return; } } ResultContext<SettingVM> resultContext = new ResultContext<SettingVM>(); resultContext.ResultContextObject = this.model; resultContext = await this.SettingService.UpdateSettingeAsync(resultContext); if (resultContext.HasErrorMessages) { await this.ShowErrorAsync(string.Join(Environment.NewLine, resultContext.ListErrorMessages)); } else { if (resultContext.ResultContextObject.SettingIntCode == "MaxFailedAccessAttempts") { userManager.Options.Lockout.MaxFailedAccessAttempts = Int32.Parse(resultContext.ResultContextObject.SettingValue); } if (resultContext.ResultContextObject.SettingIntCode == "DefaultLockoutTimeSpan") { userManager.Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(Int32.Parse(resultContext.ResultContextObject.SettingValue)); } await DataSourceService.ReloadSettings(); await SettingService.ReloadSettings(); await this.ShowSuccessAsync("Записът е успешен!"); } this.SpinnerHide(); await CallbackAfterSave.InvokeAsync(this.model); } private void Cancel() { this.IsVisibleAddModal = false; } }
import { useEffect, useState } from 'react'; /** * Custom hook to track the active element in the viewport based on scroll position. * * @param {string[]} targetIds - Array of target element IDs to track. * @param {(activeId: string) => void} callback - Callback function to be executed when active element changes. * @returns {string | null} - ID of the currently active element. */ export const useScrollspy = ( targetIds: string[], callback: (activeId: string) => void ): string | null => { const [activeId, setActiveId] = useState<string | null>(null); useEffect(() => { const handleScroll = () => { const targets = targetIds.map((id) => document.getElementById(id)); let activeTarget: HTMLElement | null = null; for (let i = targets.length - 1; i >= 0; i--) { const target = targets[i]; if (!target) continue; const rect = target.getBoundingClientRect(); const isVisible = rect.top >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight); const isPartiallyVisible = rect.top < window.innerHeight && rect.bottom >= 0; if ((isVisible || isPartiallyVisible) && !activeTarget) { activeTarget = target; break; } } if (activeTarget) { setActiveId(activeTarget.id); if (callback) { callback(activeTarget.id); } } }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, [targetIds, callback]); return activeId; }; export default useScrollspy;
import matplotlib.pyplot as plt from datetime import datetime, timedelta from .analysis import polyfit import numpy as np import matplotlib def plot_water_levels(station, dates, levels): plt.plot(dates, levels) plt.xlabel('date') plt.ylabel('water level (m)') plt.xticks(rotation=45) plt.title(station.name) plt.legend() plt.tight_layout() plt.show() def plot_water_level_with_fit(station, dates, levels, p): # Define plot plt.plot(dates, levels, label = "collected data") # Plot x and y-axis plt.xlabel('date') plt.ylabel('water level (m)') plt.ylabel('water level (m)') plt.xticks(rotation=45) plt.title(station.name) # Plot the line of best fit a_n, d0 = polyfit(dates, levels, p) x = matplotlib.dates.date2num(dates) x_axis = np.linspace(x[0], x[-1], 50) plt.plot(x_axis, a_n(x_axis - d0), label = "trend line of best fit") # Add the typical high and low ranges used for Task2F low = station.typical_range[0] high = station.typical_range[1] # Plots these values plt.axhline(low, color = "green", linestyle = "dotted", label = "typical low") plt.axhline(high, color = "red", linestyle = "dotted", label = "typical high") plt.legend() plt.tight_layout() plt.show()
import React from 'react'; import {Button, Form, Input, Switch, Tooltip} from "antd"; import {ModalForm,} from '@ant-design/pro-components'; import {EditOutlined, PlusOutlined} from "@ant-design/icons"; import {addRole, getRoleDetail, updateRole} from "../../../../../api/role.js"; function RoleEditModal({actionRef, update = false, roleId}) { const [form] = Form.useForm(); async function submit(v) { console.log(v); v.status = v.status ? 1 : 0; if (update) { v.id = roleId; await updateRole(v); } else { await addRole(v); } actionRef.current.reload(); return true; } async function getRole() { const data = await getRoleDetail(roleId); const {id, name, description, status} = data; return {id, name, description, status: status === 1}; } return ( <> <ModalForm request={async () => { if (update) { return await getRole(); } return {status: true}; }} width={500} title={update ? '修改角色' : "新增角色"} trigger={ <span> { update ? <Tooltip placement="bottom" title={'编辑'}> <Button size={"small"} icon={<EditOutlined/>}/> </Tooltip> : <Button type="primary"> <PlusOutlined/> 新增 </Button> } </span> } form={form} autoFocusFirstInput modalProps={{ destroyOnClose: true, // onCancel: () => console.log('run'), }} submitTimeout={2000} onFinish={submit} > <Form.Item label="角色名称" name="name" rules={[ { required: true, message: '请输入角色名称!', }, { min: 1, max: 20, message: '角色名称需大于1个字符并且小于20个字符!' } ]} > <Input/> </Form.Item> <Form.Item name="description" label="描述信息" rules={[ { required: true, message: '请输入描述信息!' } ]} > <Input.TextArea showCount maxLength={255}/> </Form.Item> <Form.Item name="status" label='状态' valuePropName="checked"> <Switch/> </Form.Item> </ModalForm> </> ); } export default RoleEditModal;
import { type } from "os"; import React, { useEffect, useState } from "react"; import { IUser } from "../../pages/NewsApp"; type Props = { data?:IUser setDataDetail : (data:IUser | null ) => void; } export function DetailNewItem(props:Props) { const [email , setEmail] = useState<string>(""); const [name , setName] = useState<string> (""); const [body , setBody] = useState<string>(""); useEffect(() => { if(!props.data) return; const {body,email,id,name} = props.data; try { const requestOptions = { method: 'GET', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email : email, name : name, body : body, }) }; fetch('https://jsonplaceholder.typicode.com/comments', requestOptions) .then(response => response.json()) .then(data => ( setEmail(data.email), setName(data.name), setBody(data.body) )); } catch (error) { console.log(error) } }, [[props.data]]); return ( <div id = "detailContainer"> <div className="detailInnerContainer"> <div className="detailForm"> <div className="img-fuild"> <img src="https://danviet.mediacdn.vn/zoom/480_300/296231569849192448/2021/9/14/464-16316288609712092007554-72-0-872-1280-crop-1631631008044111074198.jpg" alt="" /> </div> <div className="detailCotent "> <div> <h3 className="text-center"> Title: {props.data?.name}</h3> <p className="text-dark"> Content New Item : {props.data?.body}</p> <p className="text-secondary">Email Address : {props.data?.email}</p> </div> <a href="https://tuoitre.vn/cuoc-chien-nga-ukraine-ngan-tac-dong-tieu-cuc-toi-kinh-te-viet-nam-20220228081015907.htm" className="btn btn-outline-secondary text-dark p-2"> More .... </a> </div> </div> <hr/> <button onClick={()=>props.setDataDetail(null)} className="btn btn-danger m-2">Close</button> </div> </div> ) }
source("binning.R") source("simulation.R") source("plot.R") # Simulate some data set.seed(123) n <- 10000 labels <- c("default", "repay") s <- sim_mixture_normal( 0.25*n, weights = c(0.5, 0.5), mean = c(450, 580), sd = c(100, 125), labels = labels ) head(s) # Shiny App --------------------------------------------------------------- library(shiny) library(animate) library(htmltools) # UI ---- ui <- fluidPage( titlePanel("Fairness in Machine Learning"), h4("This app replicates the visualisation as it is seen in the article", a(href='https://bair.berkeley.edu/blog/2018/05/17/delayed-impact/', '"Delayed impact of fair machine learning"'), "."), mainPanel( sliderInput( "threshold", "Credit score threshold:", min = 300, max = 800, value = 450, width = "500px", ), animateOutput( outputId = "animateOutput", width = "100%", height = "400px" ) ), # Use "oninput" listener for better reactivity # This observes the slider named "threshold" (set above in `ui`), then # trigger an event called "threshold_oninput" with the slider value # to be used in `server` below. tags$script(' window.onload = function() { document.querySelector("#threshold").oninput = function() { Shiny.onInputChange("threshold_oninput", this.value); }; } ') ) # Server ---- server <- function(input, output, session) { # Set up the device device <- animate$new(600, 600, session = session, id = "svg_1") attach(device) # Add a second svg element svg(500, 500, id = "svg-text-panel", root = "#animateOutput", style = list(width="500px", height="500px")) # Update plot when the slider value changes observeEvent(input$threshold_oninput, { threshold <- as.numeric(input$threshold_oninput) plot_distribution(threshold) }, ignoreNULL = FALSE) } # Definition of the plotting function ---- # It is cleaner to separate the key logic from `ui` and `server`. plot_distribution <- function(threshold = 450) { # Handle initial empty input from shiny if (length(threshold) == 0 || is.null(threshold)) { threshold <- 450 } p <- sim_data_to_plot_data(s, threshold) draw_first_panel(p, threshold) stat <- p |> dplyr::group_by(granted, default) |> dplyr::summarise(count = dplyr::n(), .groups = "drop_last") |> dplyr::ungroup() total <- sum(stat$count) n_payback <- sum(stat[stat$granted & !stat$default, "count"]) n_default <- sum(stat[stat$granted & stat$default, "count"]) # For simplicity, we assume each ball represents 5 loans (rounded up) multiplier <- 5 param <- list( n_loan = total * multiplier, accepted = (n_payback + n_default) / total, payback = n_payback / total, default = n_default / total, profit = n_payback * multiplier, loss = n_default * multiplier * -3, PL_net = multiplier * (n_payback + n_default * -3), score_gain = n_payback * multiplier * 50, score_loss = n_default * multiplier * -80, score_net = (n_payback * 50 + n_default * -80) / total ) draw_second_panel(param) } shinyApp(ui = ui, server = server)
import './App.css'; import React from 'react'; import {BrowserRouter as Router,Link,Route,Routes} from 'react-router-dom' import User from './Components/User'; import { useEffect,useState } from 'react'; import Child from './Components/Child'; // function App() { // let users=[ // {id:1,name:'Saurav',email:'saurav@gmail.com'}, // {id:2,name:'jatin',email:'jatin@gmail.com'}, // {id:3,name:'sachin',email:'sachin@gmail.com'}, // {id:4,name:'Shubham',email:'shubham@gmail.com'}, // {id:5,name:'Anil',email:'Anil@gmail.com'} // ] // return ( // <div className="App"> // <Router> // { // users.map((item)=> // <div><Link to={"/user/"+item.id+"/"+item.name}><h3>{item.name}</h3></Link> // </div> // )} // <Route path="/user/:id/:name"><User/></Route> // </Router> // </div> // ); // } // function Home(){ // return( // <> // <h1>This is Home Page</h1> // <p>Website of home PAge</p> // </> // ) // } // function About(){ // return( // <> // <h1>This is About Page</h1> // <p>Website of About PAge</p> // </> // ) // } // export default App; // //--starting with api // function App(){ // const [data,setdata]=useState([]) // useEffect(()=>{ // fetch("http://localhost:3000/users").then((result)=>{ // result.json().then((resp)=>{ // //console.warn("response",resp) // setdata(resp) // }) // }) // },[]) // console.warn(data) // return( // <div className='App'> // <h1>This is API tutorial</h1> // <table border="1"> // <tr> // <td>ID</td> // <td>Name</td> // <td>Email</td> // <td>Contact</td> // </tr> // { // data.map((item)=> // <tr> // <td>{item.id}</td> // <td>{item.name}</td> // <td>{item.email}</td> // <td>{item.address}</td> // </tr> // ) // } // </table> // </div> // ) // } // export default App; // //---Post method with rest API---- // function App(){ // const [name,setname]=useState(""); // const [email,setemail]=useState(""); // const [address,setaddress]=useState(""); // function saveuser(){ // console.warn(name,email,address); // let data={name,email,address} // fetch("http://localhost:3000/users", { // method: "POST", // headers: { // 'Accept': 'application/json', // 'Content-Type': 'application/json', // }, // body:JSON.stringify(data) // }).then((resp)=>{ // // console.warn("resp",resp);; // resp.json().then((result)=>{ // console.warn("response",result) // }) // }) // } // return( // <div className='App'> // <h1>Post API Method</h1> // <input type='text' value={name} onChange={(e)=>setname(e.target.value)} name='name' /><br/><br/> // <input type='text' value={email} onChange={(e)=>setemail(e.target.value)} name='email' /><br/><br/> // <input type='text' value={address} onChange={(e)=>setaddress(e.target.value)} name='address' /><br/><br/> // <button type='button' onClick={saveuser}>Save new user</button> // </div> // ); // } // export default App; // //----Delete method,prefilled,update method using PUT request---- // function App(){ // const [data,setdata]=useState([]) // const [name,setname]=useState("") // const [email,setemail]=useState("") // const [address,setaddress]=useState("") // const [userid,setuserid]=useState(null) // useEffect(()=>{ // getlist() // },[]) // function getlist(){ // fetch("http://localhost:3000/users").then((result)=>{ // result.json().then((resp)=>{ // //console.warn("response",resp) // setdata(resp) // setname(resp[0].name) // setemail(resp[0].email) // setaddress(resp[0].address) // setaddress(resp[0].userid) // }) // }) // } // function deleteuser(id){ // fetch(`http://localhost:3000/users${id}`,{ // method:'DELETE' // }).then((result)=>{ // result.json().then((resp)=>{ // console.warn(resp) // getlist() // }) // }) // } // function selectuser(id){ // console.warn(data[id-1]) // setname(data[id-1].name) // setemail(data[id-1].email) // setaddress(data[id-1].address) // setuserid(data[id-1].userid) // } // function updateuser(){ // let item={name,email,address,userid} // fetch(`http://localhost:3000/users${userid}`,{ // method:'PUT', // headers:{ // 'Accept': 'application/json', // 'Content-Type': 'application/json' // }, // body:JSON.stringify(item) // }).then((result)=>{ // result.json().then((resp)=>{ // console.warn(resp) // getlist() // }) // }) // } // return( // <div className='App'> // <h1>This is API tutorial</h1> // <table border="1"> // <tr> // <td>ID</td> // <td>Name</td> // <td>Email</td> // <td>Contact</td> // </tr> // { // data.map((item)=> // <tr> // <td>{item.id}</td> // <td>{item.name}</td> // <td>{item.email}</td> // <td>{item.address}</td> // <td><button onClick={()=>deleteuser(item.id)}>Delete</button></td> // <td><button onClick={()=>selectuser(item.id)}>Update</button></td> // </tr> // ) // } // </table> // <div> // <input type='text' value={name} onChange={(e)=>setname(e.target.value)} /> <br/><br/> // <input type='text' value={email} onChange={(e)=>setemail(e.target.value)} /> <br/><br/> // <input type='text' value={address} onChange={(e)=>setaddress(e.target.value)} /> <br/><br/> // <button onClick={updateuser}>Uppdate</button> // </div> // </div> // ) // } // export default App; // //---Previous State--- // export default function App(){ // const [count,setcount]=useState(1) // function updatestate(){ // // let rand=Math.floor(Math.random()*10) // // //setcount(rand) // // setcount((pre)=>{ // // console.warn(pre) // // if(pre<5) // // alert("low value") // // return rand // // }) // //for loop wala method // for(let i=0;i<5;i++){ // setcount(count+5) // } // } // return( // <div className='App'> // <h1>{count}</h1> // <button onClick={updatestate}>Update kr</button> // </div> // ) // } //---previous props with hooks // export default function App(){ // const [count,setcount]=useState(1) // return ( // <div className='App'> // <h1>{count}</h1> // <Child count={count}/> // <button onClick={()=>setcount(Math.floor(Math.random()*10))}>Update Me</button> // </div> // ) // } //--state with object--- export default function App(){ const [data,setdata]=useState({name:'Saurav',age:21}) return ( <div className='App'> <h1>{data.name}</h1> <h1>{data.age}</h1> <input type='text' placeholder='Enter name' value={data.name} onChange={(e)=>{setdata({...data,name:e.target.value})}}/> <input type='text' placeholder='Enter age' value={data.age} onChange={(e)=>{setdata({...data,age:e.target.value})}}/> </div> ) }
# Cadastro Jogador de futebol : Versão 01 # Crie um programa que gerencie o aproveitamento de um jogador de futebol. # O programa vai ler o nome do jogador e quantas partidas ele jogou. # Depois vai ler a quantidade de gols feitos em cada partida. # No final, tudo isso será guardado em um dicionário, # incluindo o total de gols feitos durante o campeonato. # Versão 03: from time import sleep # Declarações das variáveis: jogador=dict() # Variável 'jogador' recebe um dicionário gol=[] # Variável gol recebe lista partidas=0 # Contagem de partidas total_gols = 0 # Contagem de gols # Inserindo dados pelo usuário: print(f'{'+'*50}\n{'Rendimento do jogador':^48}\n{'+'*50}\nInsira os dados abaixo...') sleep(0.5) jogador['Nome']=input('Nome do jogador: ').capitalize() sleep(0.3) partidas=int(input(f'Quantas partidas {jogador["Nome"]} jogou? ')) # Inserir um laço para cada partida: for p in range(partidas): gol.append(int(input(f'Quantos gols da {p+1}º partida? '))) # Para cada partida,a lista 'gol' recebe os dados total_gols += gol[p] # Variável contagem 'total_gols' recebe os gols # Fora do laço, cria-se uma chave 'Gols' de jogador para receber uma cópia da lista 'gol' jogador['Gols']=gol.copy() jogador['Total']=total_gols # Dicionário jogador com chave 'total' recebe contagem de gols 'total_gols' # Mostrar valores na tela: sleep(0.8) print(f'{'+'*50}\n{"Percorrendo o dicionário JOGADOR":^48}\n{'+'*50}') sleep(1) print(jogador) sleep(1) print() for k,v in jogador.items(): sleep(1) print(f'O campo {k} tem o valor {v}.') print() # Mostrar o total de partidas e o total de gols: print(f'O jogador {jogador["Nome"]} tem {partidas} partidas.') for c in range(0,partidas): print(f'Na partida {c+1} fez {jogador["Gols"][c]}') print(f'Fez um total de {jogador["Total"]} gols.')
<div align="center"> <h1 align="center">Welcome to web-scraper 🕸️</h1> A simple web scraping with Puppeteer in TypeScript <p> <a> <img src="https://img.shields.io/github/package-json/v/lkcozy/web-scraper" alt="Current version." /> </a> <a href="#" target="_blank"> <img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-green.svg" /> </a> <img src="https://github.com/lkcozy/web-scraper/actions/workflows/pullRequestlog.yml/badge.svg?branch=main" alt="📝 Update Pull Requests Log" /> <img src="https://github.com/lkcozy/web-scraper/actions/workflows/checkUpdats.yml/badge.svg?branch=main" alt="🔎 Check Updates" /> <img src="https://github.com/lkcozy/web-scraper/actions/workflows/airQuality.yml/badge.svg" alt="🔎 Check Air Quality" /> <a href="https://github.dev/lkcozy/web-scraper" target="_blank"> <img src="https://img.shields.io/badge/GitHub_Dev-open-blue" alt="Open Code Notes with GitHub Dev" /> </a> </a> </p> </div> ## Getting Started ### Install github cli ```zsh brew install gh ``` ### Set github secrets ```zsh gh secret set EMAIL_USERNAME -b"" gh secret set EMAIL_PASSWORD -b"" # Your private API token (see aqicn.org/data-platform/token/) gh secret set AIR_QUALITY_API_TOKEN -b"" gh secret set AIR_QUALITY_CITY_LIST -b"" # a,b,c # https://github.com/KanHarI/gpt-commit-summarizer gh secret set OPENAI_API_KEY -b"" # https://pirate-weather.apiable.io/products/weather-data gh secret set PIRATE_WEATHER_API_KEY -b"" ``` ### Add/Update secrets in workflows accordingly ## Usage ```zsh yarn install yarn build yarn watch ``` ## [Test GitHub Actions locally](https://lkcozy.github.io/code-notes/git/github-actions#test-github-actions-locally) ```zsh brew install act ``` ```zsh act --secret-file act.secrets ``` ## Reference - [gh-action-data-scraping](https://github.com/sw-yx/gh-action-data-scraping): This repo shows how to use github actions to do automated data scraping, with storage in git itself! free git storage and scheduled updates!!! - [Puppeteer](https://github.com/puppeteer/puppeteer): Puppeteer is a tool to manipulate web page by using headless Chrome. - [Setting up a typescript project in 2021](https://dev.to/avalon-lab/setting-up-a-typescript-project-in-2021-4cfg): This post will describe how to create a project in typescript from scratch. The final project include some basic code, tests, commit hooks to enforce code formatting, automatic tests on push and more. [Source Code](https://github.com/xiorcal/ts-demo) - [Automatic Commit Summaries Using OpenAI’s Language Model](https://betterprogramming.pub/leverage-openais-language-model-for-automated-commit-summaries-8181cef30375) test
import React, { useState } from 'react'; import { TextField, Button, Typography, Container, Tab, Tabs } from '@mui/material'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; const Registration = () => { const navigate = useNavigate(); const [userData, setUserData] = useState({ name: '', email: '', password: '', birthDate: '', gender: '', profilePhoto: null }); const [loginData, setLoginData] = useState({ email: '', password: '' }); const [tabValue, setTabValue] = useState(0); const handleChange = (e) => { const { name, value } = e.target; if (tabValue === 0) { setUserData({ ...userData, [name]: value }); } else { setLoginData({ ...loginData, [name]: value }); } }; const handleSubmit = async (e) => { if (tabValue === 0) { // Registration tab const formData = new FormData(); formData.append('name', userData.name); formData.append('email', userData.email); formData.append('password', userData.password); formData.append('birthDate', userData.birthDate); formData.append('gender', userData.gender); if (userData.profilePhoto) { formData.append('profilePhoto', userData.profilePhoto); } try { const response = await axios.post('http://localhost:5000/register', formData, { headers: { 'Content-Type': 'multipart/form-data', }, }); console.log(response.data); // alert('User registered successfully!'); } catch (error) { console.error('Registration failed:', error); alert('Registration failed!'); } } else { e.preventDefault(); // Handle login submission here try { const response = await axios.post('http://localhost:5000/login', loginData, { headers: { 'Content-Type': 'application/json', }, }); console.log(response.data); navigate('/account'); localStorage.setItem('user', JSON.stringify(response.data.user)); // alert('Logged in successfully!'); } catch (error) { console.error('Login failed:', error); alert('Login failed!'); } } }; const handleTabChange = (event, newValue) => { setTabValue(newValue); }; return ( <Container component="main" maxWidth="xs"> <Tabs value={tabValue} onChange={handleTabChange} centered> <Tab label="Регистрация" /> <Tab label="Вход" /> </Tabs> {tabValue === 0 && ( <div> <Typography component="h1" variant="h5">Регистрация</Typography> <form onSubmit={handleSubmit} encType="multipart/form-data"> <TextField variant="outlined" margin="normal" required fullWidth label="Имя" name="name" autoFocus onChange={handleChange} /> <TextField variant="outlined" margin="normal" required fullWidth label="Email" name="email" onChange={handleChange} /> <TextField variant="outlined" margin="normal" required fullWidth label="Пароль" name="password" type="password" onChange={handleChange} /> <TextField variant="outlined" margin="normal" fullWidth label="Дата рождения" name="birthDate" type="date" InputLabelProps={{ shrink: true }} onChange={handleChange} /> <TextField variant="outlined" margin="normal" fullWidth label="Пол" name="gender" onChange={handleChange} /> <input accept="image/*" type="file" onChange={(e) => setUserData({ ...userData, profilePhoto: e.target.files[0] })} /> <Button type="submit" fullWidth variant="contained" color="primary" > Зарегистрироваться </Button> </form> </div> )} {tabValue === 1 && ( <div> <Typography component="h1" variant="h5">Вход</Typography> <form onSubmit={handleSubmit}> <TextField variant="outlined" margin="normal" required fullWidth label="Email" name="email" autoFocus onChange={handleChange} /> <TextField variant="outlined" margin="normal" required fullWidth label="Пароль" name="password" type="password" onChange={handleChange} /> <Button type="submit" fullWidth variant="contained" color="primary" > Войти </Button> </form> </div> )} </Container> ) } export default Registration
import Layout from './../Components/Layout'; import Breadcrumb from './../Components/Breadcrumb'; import { useEffect, useState } from 'react'; import { useParams } from 'react-router'; import OwlCarousel from 'react-owl-carousel'; import { Link } from 'react-router-dom'; import { categoryProducts, getProductDetails } from '../Api'; import ReactMarkdown from 'react-markdown' import remarkGfm from 'remark-gfm' import InquiryModal from '../Components/InquiryModal'; const Product = () => { const [pageTitle, setPageTitle] = useState('') const [productCategory, setProductCategory] = useState('') const [currentImage, setCurrentImage] = useState(''); const { product, category } = useParams(); const [productDetails, setProductDetails] = useState({}); const [images, setImages] = useState([]); const [relatedProducts, setRelatedProducts] = useState([]); const [showModal, setShowModal] = useState(false); const [popUpData, setPopUpData] = useState({}); useEffect(() => { const getAPIdata = async () => { const { data: productDetailsData } = await getProductDetails(product); const { data: relatedProductsData } = await categoryProducts(category); setRelatedProducts(relatedProductsData[0].attributes.products.data); setProductDetails(productDetailsData[0].attributes); setCurrentImage(productDetailsData[0].attributes.images.data[0].attributes.url); setImages(productDetailsData[0].attributes.images.data); } getAPIdata(); }, [product, category]); let carousel3 = { margin: 15, autoplay: true, autoplayTimeout: 3000, autoplayHoverPause: true, dots: false, animateOut: 'animate__backOutLeft', animateIn: 'animate__zoomIn', responsive: { 0: { items: 1, loop: true, }, 600: { items: 2, margin: 50, loop: true, }, 1024: { items: 3, loop: true }, 1280: { items: 4, loop: true }, 1300: { items: 4, loop: true }, 1600: { items: 6, loop: true } } } return ( <Layout> <Breadcrumb title={product} cateogry={category} setProductCategory={setProductCategory} setPageTitle={setPageTitle} /> <InquiryModal setShowModal={setShowModal} showModal={showModal} popUpData={popUpData} /> <section className="my-10"> <div className="container mx-auto"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-4"> <div className="flex flex-col lg:flex-row-reverse"> <div className="product-img border flex justify-center items-center rounded-xl"> {productDetails?.images?.data ? <img className="h-auto w-auto" src={currentImage} alt="Violet.png" /> : <div className="h-full w-full bg-gray-300 animate-pulse" /> } </div> <div className="flex flex-row lg:flex-col thumb-area"> {images.length ? <> { images.map((image) => ( <img key={image.attributes.name} onClick={() => setCurrentImage(image.attributes.url)} className="h-20 w-auto mx-2 my-1 hover:border-blue-400 hover:shadow-xl shadow transition duration-300 ease-in-out cursor-pointer rounded border" src={image.attributes.formats.thumbnail.url} alt={image.attributes.name} /> )) } </> : <> {[...Array(5)].map((_, index) => ( <div key={'item' + index} className="p-20 animate-pulse mx-2 my-1 h-20 w-14 bg-gray-500 text-transparent" /> ))} </> } </div> </div> <div className="lg:mx-4"> <h1 className="text-gray-600 text-xl lg:text-3xl font-semibold text-left pb-10"> {productCategory} {pageTitle} </h1> {productDetails?.description ? <p className="text-base lg:text-lg text-gray-600"> {productDetails?.description} </p> : <div className="h-40 w-full bg-gray-300 animate-pulse rounded-xl" /> } <div className="mt-20"> <h1 className="text-gray-600 text-xl lg:text-3xl font-semibold text-left pb-5"> Specificaiton </h1> {productDetails?.specification ? <ReactMarkdown remarkPlugins={[remarkGfm]}>{productDetails.specification}</ReactMarkdown> : <div className="h-40 w-full bg-gray-300 animate-pulse rounded-xl" /> } </div> <div className='mt-10'> <button onClick={() => { setShowModal(true); setPopUpData(productDetails && productDetails) }} className='px-4 py-4 bg-[#66c6dc] text-white rounded-lg hover:shadow-xl transition duration-200 ease-in'> Inquiry about this product </button> </div> </div> </div> </div> </section> {/* related product section */} <section className="mt-20 bg-light-blue py-20"> <div className="container mx-auto"> <h1 className="text-2xl text-gray-600 lg:text-3xl font-bold text-left">Related Products</h1> {relatedProducts.length ? <> <OwlCarousel {...carousel3} className="owl-theme w-full my-10"> {relatedProducts.map((product) => ( <div key={product.attributes.name} className="item h-82 w-63 carousel-img border rounded-2xl shadow-2xl overflow-hidden mx-auto flex flex-col justify-center items-center lg:block lg:w-auto relative group animate__animated animate__fadeIn wow"> {product.attributes.images.data ? <img className="transform scale-100 h-80 group-hover:scale-110 transition duration-150 ease-in-out" src={product.attributes.images.data[0].attributes.url} alt={product.attributes.name} /> : <img className="transform scale-100 h-80 group-hover:scale-110 transition duration-150 ease-in-out" src='/images/image-error.png' alt='error' /> } <h1 className="flex px-4 py-4 custom-line-clamp-2 absolute bottom-0 text-white w-full bg-primary text-sm justify-center items-center"> {product.attributes.name} </h1> <div className="absolute inset-0 rounded-lg bg-blurBg opacity-0 group-hover:opacity-100 flex justify-center items-center transition duration-200 ease-in-out"> <Link to={`/products/${category}/${product.attributes.code}`} className="flex items-center rounded-lg shadow-lg hover:text-white px-3 py-2 bg-primary text-white"> <i className="bi bi-eye-fill text-xl px-3"></i> </Link> </div> </div> ))} </OwlCarousel> </> : <OwlCarousel {...carousel3} className="owl-theme w-full my-10"> {[...Array(10)].map((_, i) => ( <div key={'demo' + i} className="item h-82 w-63 carousel-img border rounded-2xl shadow-2xl overflow-hidden mx-auto flex flex-col justify-center items-center lg:block lg:w-auto relative group animate__animated animate__fadeIn wow animate__delay-1s"> <div className="transform h-72 bg-gray-300 scale-100 group-hover:scale-110 transition duration-150 ease-in-out" /> <div className="p-10 animate-pulse w-full lg:w-96 bg-gray-500 text-transparent block h-full" /> </div> ))} </OwlCarousel>} </div> </section> </Layout> ) } export default Product
/* * This file contains public type interfaces. * If changing these, consider whether it might be a breaking change. */ export type ButtonStates = Map<number, boolean> export interface ShuttleEvents { // Note: This interface defines strong typings for any events that are emitted by the Shuttle class. disconnected: () => void error: (err: any) => void shuttle: ( /** Shuttle value. Range: -1 - 7 */ shuttle: number ) => void jog: ( /** Value difference from last emitted event */ delta: number, /** Jog value, range: 0-255 */ jogValue: number ) => void down: (buttonIndex: number) => void up: (buttonIndex: number) => void } export interface ShuttleInfo { /** Name of the device */ name: string /** Vendor id of the HID device */ vendorId: number /** Product id of the HID device */ productId: number /** Interface number of the HID device */ interface: number }
use plotters::{ prelude::{BitMapBackend, ChartBuilder, IntoDrawingArea, PathElement}, series::LineSeries, style::*, }; use crate::MAX_MONEY; const BALANCE_PLOT_PATH: &str = "plots/zsf_balance.png"; const BLOCK_SUBSIDY_PLOT_PATH: &str = "plots/zsf_block_subsidy.png"; const PLOT_ZOOM: usize = 5; pub const PLOT_SAMPLING: u32 = 1000; pub fn generate_plots( balance_points: Vec<(f64, f64)>, zsf_reward_points: Vec<(f64, f64)>, legacy_reward_points: Vec<(f64, f64)>, years: f64, ) { balance_plot( &balance_points[0..(balance_points.len() / PLOT_ZOOM)], years / PLOT_ZOOM as f64, ); block_subsidy_plot( &zsf_reward_points[0..(balance_points.len() / PLOT_ZOOM)], &legacy_reward_points[0..(balance_points.len() / PLOT_ZOOM)], years / PLOT_ZOOM as f64, ); } fn balance_plot(points: &[(f64, f64)], years: f64) { let root = BitMapBackend::new(BALANCE_PLOT_PATH, (1024, 768)).into_drawing_area(); root.fill(&WHITE).unwrap(); let mut chart = ChartBuilder::on(&root) .caption("ZSF balance", ("sans-serif", 50).into_font()) .margin(50) .x_label_area_size(50) .y_label_area_size(50) .build_cartesian_2d(0f64..years, 0f64..(MAX_MONEY as f64)) .unwrap(); chart .configure_mesh() .bold_line_style(WHITE.mix(0.3)) .y_desc("ZSF balance in ZEC") .x_desc("Years from activation") .axis_desc_style(("sans-serif", 15)) .y_label_formatter(&|x| format!("{}M", x / 1_000_000_f64)) .draw() .unwrap(); let series = LineSeries::new(points.to_owned(), &RED); chart.draw_series(series).unwrap(); root.present().unwrap(); println!("Plot saved to {}", BALANCE_PLOT_PATH); } fn block_subsidy_plot( zsf_reward_points: &[(f64, f64)], legacy_reward_points: &[(f64, f64)], years: f64, ) { let root = BitMapBackend::new(BLOCK_SUBSIDY_PLOT_PATH, (1024, 768)).into_drawing_area(); root.fill(&WHITE).unwrap(); let mut chart = ChartBuilder::on(&root) .caption( "Block subsidies - ZSF vs current", ("sans-serif", 50).into_font(), ) .margin(50) .x_label_area_size(50) .y_label_area_size(50) .build_cartesian_2d(0f64..years, 0f64..5f64) .unwrap(); chart .configure_mesh() .bold_line_style(WHITE.mix(0.3)) .y_desc("Block subsidy in ZEC") .x_desc("Years from activation") .axis_desc_style(("sans-serif", 15)) .draw() .unwrap(); let zsf_series = LineSeries::new(zsf_reward_points.to_owned(), &RED); let legacy_series = LineSeries::new(legacy_reward_points.to_owned(), &BLUE); chart .draw_series(zsf_series) .unwrap() .label("ZSF Smooth Issuance") .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], RED)); chart .draw_series(legacy_series) .unwrap() .label("Current issuance") .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], BLUE)); chart .configure_series_labels() .background_style(WHITE.mix(0.8)) .border_style(BLACK) .draw() .unwrap(); root.present().unwrap(); println!("Plot saved to {}", BLOCK_SUBSIDY_PLOT_PATH); }
package com.example.bootcalculatorproject.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.example.bootcalculatorproject.dto.Response; import com.example.bootcalculatorproject.jpa.ResponseEntity; import com.example.bootcalculatorproject.service.CalculatorService; import com.example.bootcalculatorproject.service.CalculatorServiceForData; import lombok.extern.slf4j.Slf4j; @RestController @Slf4j @RequestMapping("/calculatorapi/v1/") public class CalculatorController { @Autowired private CalculatorService calculatorService; @Autowired private CalculatorServiceForData calculatorServiceForData; public enum Operation { ADDITION("addition"), SUBTRACTION("subtraction"), MULTIPLICATION("multiplication"), DIVISION("division"),SQUARE("square"), SQUARE_ROOT("squareroot"), FACTORIAL("factorial"), MIN_MAX("min-max"); private String name; Operation(String name) { this.name = name; } public String getName() { return name; } } @Cacheable(value = "requestResponseEntity", cacheManager = "requestResponseEntityManager") @GetMapping("/Addition") public Response getAddition(@RequestParam(name = "number1") Double num1, @RequestParam(name = "number2") Double num2) { Response response = new Response(); ResponseEntity responseEntity = new ResponseEntity(); responseEntity= calculatorServiceForData.findByRequest((num1.toString()) + " + " + (num2.toString())); Double result = calculatorService.getAddition(num1, num2); Long t = System.currentTimeMillis(); Double add = 0.0; response.setAnswer(result); response.setDetail(num1.toString() + " + " + (num2.toString()) + " = " + (add.toString())); responseEntity = setDataInRepo((num1.toString()) + " + " + (num2.toString()), (add.toString()), Operation.ADDITION.getName(), t); calculatorServiceForData.saveRequstResponse(responseEntity); log.error("<< logs of getAddition method >>" + response.toString()); return response; } @Cacheable(value = "requestResponseEntity", cacheManager = "requestResponseEntityManager") @GetMapping("/Substraction") public Response getSubstraction(@RequestParam double number1, @RequestParam double number2) { Response response = new Response(); ResponseEntity responseEntity = new ResponseEntity(); Double result = calculatorService.getSubstraction(number1, number2); Long t = System.currentTimeMillis(); Double subtract = 0.0; response.setAnswer(result); response.setDetail(number1 + "-" + number2 + "=" + result); responseEntity = setDataInRepo((number1 + " - " + number2 ), (subtract.toString()), Operation.SUBTRACTION.getName(), t); calculatorServiceForData.saveRequstResponse(responseEntity); log.error("<< logs of getSubstraction method >>" + response.toString()); return response; } @Cacheable(value = "requestResponseEntity", cacheManager = "requestResponseEntityManager") @GetMapping("/Multiplication") public Response getMultiplication(@RequestParam double number1, @RequestParam double number2) { Response response = new Response(); ResponseEntity responseEntity = new ResponseEntity(); Double result = calculatorService.getMultiplication(number1, number2); Long t = System.currentTimeMillis(); Double multiplication = 0.0; response.setAnswer(result); response.setDetail(number1 + "*" + number2 + "=" + result); responseEntity = setDataInRepo((number1 + " * " + number2 ), (multiplication.toString()), Operation.MULTIPLICATION.getName(), t); calculatorServiceForData.saveRequstResponse(responseEntity); log.error("<< logs of getMultiplication method >>" + response.toString()); return response; } @Cacheable(value = "requestResponseEntity", cacheManager = "requestResponseEntityManager") @GetMapping("/Division") public Response getdivision(@RequestParam double number1, @RequestParam double number2) { Response response = new Response(); ResponseEntity responseEntity = new ResponseEntity(); Double result = calculatorService.getdivision(number1, number2); Long t = System.currentTimeMillis(); Double division = 0.0; response.setAnswer(result); response.setDetail(number1 + "/" + number2 + "=" + result); responseEntity = setDataInRepo((number1 + " / " + number2 ), (division.toString()), Operation.DIVISION.getName(), t); calculatorServiceForData.saveRequstResponse(responseEntity); log.error("<< logs of getdivision method >>" + response.toString()); return response; } @Cacheable(value = "requestResponseEntity", cacheManager = "requestResponseEntityManager") @GetMapping("/square/{number}") public Response square(@PathVariable double number) { Response response = new Response(); ResponseEntity responseEntity = new ResponseEntity(); Long t = System.currentTimeMillis(); Double square = 0.0; Double result = calculatorService.square(number); responseEntity = setDataInRepo((number + " Square of " ), (square.toString()), Operation.SQUARE.getName(), t); response.setAnswer(result); calculatorServiceForData.saveRequstResponse(responseEntity); log.error("<< logs of square method >>" + response.toString()); return response; } @Cacheable(value = "requestResponseEntity", cacheManager = "requestResponseEntityManager") @GetMapping("/squareroot/{number}") public Response squareRoot(@PathVariable double number) { Response response = new Response(); ResponseEntity responseEntity = new ResponseEntity(); Long t = System.currentTimeMillis(); Double squareroot = 0.0; Double result = calculatorService.squareRoot(number); response.setAnswer(result); responseEntity = setDataInRepo((number + " Square root of " ), (squareroot.toString()), Operation.SQUARE_ROOT.getName(), t); calculatorServiceForData.saveRequstResponse(responseEntity); log.error("<< logs of squareRoot method >>" + response.toString()); return response; } @Cacheable(value = "requestResponseEntity", cacheManager = "requestResponseEntityManager") @GetMapping("/factorial/{number}") public Response factorial(@PathVariable int number) { Response response = new Response(); ResponseEntity responseEntity = new ResponseEntity(); Long t = System.currentTimeMillis(); Double resul = 0.0; Double result = calculatorService.factorial(number); responseEntity = setDataInRepo((number + " ! " ), (resul.toString()), Operation.FACTORIAL.getName(), t); response.setAnswer(result); calculatorServiceForData.saveRequstResponse(responseEntity); log.error("<< logs of factorial method >>" + response.toString()); return response; } @Cacheable(value = "requestResponseEntity", cacheManager = "requestResponseEntityManager") @PostMapping("/min-max") public String minmax(@RequestBody List<Integer> numbers){ ResponseEntity responseEntity = new ResponseEntity(); Long t = System.currentTimeMillis(); Double minmax = 0.0; String result = calculatorService.minmax(numbers); responseEntity = setDataInRepo((numbers + " minmax " ), (minmax.toString()), Operation.MIN_MAX.getName(), t); calculatorServiceForData.saveRequstResponse(responseEntity); log.error("<< logs of minmax method >>" + result.toString()); return result; } private ResponseEntity setDataInRepo(String request, String response, String operation, Long sqlTimestamp) { ResponseEntity ResponseEntity = new ResponseEntity(); ResponseEntity.setRequest(request); ResponseEntity.setResponse(response); ResponseEntity.setOperation(operation); ResponseEntity.setSqlTimestamp(sqlTimestamp); return ResponseEntity; } }
/* * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j 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/>. */ package org.neo4j.gds.wcc; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.neo4j.gds.AlgoBaseProc; import org.neo4j.gds.GdsCypher; import org.neo4j.gds.MutateNodePropertyTest; import org.neo4j.gds.StoreLoaderBuilder; import org.neo4j.gds.api.DefaultValue; import org.neo4j.gds.api.nodeproperties.ValueType; import org.neo4j.gds.core.Aggregation; import org.neo4j.gds.core.CypherMapWrapper; import org.neo4j.gds.core.loading.GraphStoreCatalog; import org.neo4j.gds.core.utils.paged.dss.DisjointSetStruct; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.InstanceOfAssertFactories.LONG; import static org.assertj.core.api.InstanceOfAssertFactories.MAP; import static org.neo4j.gds.TestSupport.assertGraphEquals; import static org.neo4j.gds.TestSupport.fromGdl; class WccMutateProcTest extends WccProcTest<WccMutateConfig> implements MutateNodePropertyTest<Wcc, WccMutateConfig, DisjointSetStruct> { @Override public String mutateProperty() { return "componentId"; } @Override public ValueType mutatePropertyType() { return ValueType.LONG; } @Override public Class<? extends AlgoBaseProc<Wcc, DisjointSetStruct, WccMutateConfig, ?>> getProcedureClazz() { return WccMutateProc.class; } @Override public WccMutateConfig createConfig(CypherMapWrapper mapWrapper) { return WccMutateConfig.of(mapWrapper); } @Override public String expectedMutatedGraph() { return " (a {componentId: 0})" + ", (b {componentId: 0})" + ", (c {componentId: 0})" + ", (d {componentId: 0})" + ", (e {componentId: 0})" + ", (f {componentId: 0})" + ", (g {componentId: 0})" + ", (h {componentId: 7})" + ", (i {componentId: 7})" + ", (j {componentId: 9})" + // {A, B, C, D} ", (a)-[{w: 1.0d}]->(b)" + ", (b)-[{w: 1.0d}]->(c)" + ", (c)-[{w: 1.0d}]->(d)" + ", (d)-[{w: 1.0d}]->(e)" + // {E, F, G} ", (e)-[{w: 1.0d}]->(f)" + ", (f)-[{w: 1.0d}]->(g)" + // {H, I} ", (h)-[{w: 1.0d}]->(i)"; } @Test void testMutateAndWriteWithSeeding() throws Exception { registerProcedures(WccWriteProc.class); var testGraphName = "wccGraph"; var initialGraphStore = new StoreLoaderBuilder().databaseService(db) .build() .graphStore(); GraphStoreCatalog.set(emptyWithNameNative(getUsername(), testGraphName, nodeProperties()), initialGraphStore); var mutateQuery = GdsCypher .call(testGraphName) .algo("wcc") .mutateMode() .addParameter("mutateProperty", mutateProperty()) .yields(); runQuery(mutateQuery); var writeQuery = GdsCypher .call(testGraphName) .algo("wcc") .writeMode() .addParameter("seedProperty", mutateProperty()) .addParameter("writeProperty", mutateProperty()) .yields(); runQuery(writeQuery); var updatedGraph = new StoreLoaderBuilder().databaseService(db) .addNodeProperty(mutateProperty(), mutateProperty(), DefaultValue.of(42.0), Aggregation.NONE) .build() .graph(); assertGraphEquals(fromGdl(expectedMutatedGraph()), updatedGraph); } @Test void testMutateYields() { var testGraphName = "wccGraph"; var initialGraphStore = new StoreLoaderBuilder().databaseService(db) .build() .graphStore(); GraphStoreCatalog.set(emptyWithNameNative(getUsername(), testGraphName, nodeProperties()), initialGraphStore); String query = GdsCypher .call(testGraphName) .algo("wcc") .mutateMode() .addParameter("mutateProperty", mutateProperty()) .yields( "nodePropertiesWritten", "preProcessingMillis", "computeMillis", "mutateMillis", "postProcessingMillis", "componentCount", "componentDistribution", "configuration" ); runQueryWithRowConsumer( query, row -> { Assertions.assertThat(row.getNumber("nodePropertiesWritten")) .asInstanceOf(LONG) .isEqualTo(10L); Assertions.assertThat(row.getNumber("preProcessingMillis")) .asInstanceOf(LONG) .isGreaterThan(-1L); Assertions.assertThat(row.getNumber("computeMillis")) .asInstanceOf(LONG) .isGreaterThan(-1L); Assertions.assertThat(row.getNumber("postProcessingMillis")) .asInstanceOf(LONG) .isGreaterThan(-1L); Assertions.assertThat(row.getNumber("mutateMillis")) .asInstanceOf(LONG) .isGreaterThan(-1L); Assertions.assertThat(row.getNumber("componentCount")) .asInstanceOf(LONG) .as("wrong component count") .isEqualTo(3L); assertUserInput(row, "threshold", 0D); assertUserInput(row, "consecutiveIds", false); assertThat(row.get("componentDistribution")) .isInstanceOf(Map.class) .asInstanceOf(MAP) .containsExactlyInAnyOrderEntriesOf( Map.of( "p99", 7L, "min", 1L, "max", 7L, "mean", 3.3333333333333335D, "p999", 7L, "p95", 7L, "p90", 7L, "p75", 7L, "p50", 2L ) ); } ); } @Test void zeroCommunitiesInEmptyGraph() { runQuery("CALL db.createLabel('VeryTemp')"); runQuery("CALL db.createRelationshipType('VERY_TEMP')"); String graphName = "emptyGraph"; var loadQuery = GdsCypher.call(graphName) .graphProject() .withNodeLabel("VeryTemp") .withRelationshipType("VERY_TEMP") .yields(); runQuery(loadQuery); String query = GdsCypher .call(graphName) .algo("wcc") .mutateMode() .addParameter("mutateProperty", "foo") .yields("componentCount"); runQueryWithRowConsumer(query, row -> { assertThat(row.getNumber("componentCount")) .asInstanceOf(LONG) .isEqualTo(0); }); } @Test @Disabled("This procedure for now does no longer extend MutateProc") @Override public void testExceptionLogging() {} }
<button type="button" [mat-dialog-close]="true" mat-icon-button> <mat-icon>close-icon</mat-icon> </button> <mat-dialog-content> <form [formGroup]="form"> <mat-form-field appearance="outline"> <mat-label>Airline Name</mat-label> <input type="text" matInput formControlName="airlineName" readonly> </mat-form-field> &nbsp;&nbsp; <mat-form-field appearance="outline"> <mat-label>Source</mat-label> <input type="text" readonly formControlName="source" matInput> </mat-form-field> &nbsp;&nbsp; <mat-form-field appearance="outline"> <mat-label>Destination</mat-label> <input type="text" readonly matInput formControlName="destination"> </mat-form-field> &nbsp;&nbsp; <mat-form-field appearence="outline"> <mat-label>Date</mat-label> <input type="text" readonly matInput formControlName="date"> </mat-form-field> &nbsp;&nbsp; <mat-form-field appearance="outline"> <mat-label>Boarding Time</mat-label> <input type="text" matInput readonly formControlName="boardingTime"> </mat-form-field> &nbsp;&nbsp; <mat-form-field appearance="outline"> <mat-label>Flight Id</mat-label> <input type="text" matInput formControlName="flightId" readonly> </mat-form-field> &nbsp;&nbsp; <mat-form-field appearance="outline"> <mat-label>Customer Email</mat-label> <input type="text" matInput readonly [value]="user_id"> </mat-form-field> &nbsp;&nbsp; <mat-form-field appearance="outline"> <mat-label>Choose Seat</mat-label> <mat-select formControlName="seatNo" multiple> <mat-option *ngFor="let seat of this.data.seats" [value]="seat">{{seat}}</mat-option> </mat-select> <mat-error *ngIf="this.form.get('seatNo').errors?.['required']">This fileld can't be empty</mat-error> </mat-form-field> </form> </mat-dialog-content> <mat-dialog-actions> <button type="submit" mat-raised-button color="primary" [disabled]="this.form.invalid" (click)="bookFlight(this.form.value)">Confirm Booking</button> <button type="reset" mat-raised-button color="warn" mat-dialog-close>Cancel</button> </mat-dialog-actions>
import 'package:flutter/material.dart'; import 'package:news_app/screens/discover_screen.dart'; import 'package:news_app/screens/home_screen.dart'; class BottomNavBar extends StatelessWidget { const BottomNavBar({ Key? key, required this.index, }): super(key: key); final int index; @override Widget build(BuildContext context) { return BottomNavigationBar( currentIndex: 0, showSelectedLabels: false, showUnselectedLabels: false, selectedItemColor: Colors.black, unselectedItemColor: Colors.black.withAlpha(100), items: [ BottomNavigationBarItem (icon: Container( margin: const EdgeInsets.only(left: 50), child: IconButton( onPressed: (){ Navigator.pushNamed(context, HomeScreen.routeName); }, icon: const Icon(Icons.home)), ), label: "Домой" ), BottomNavigationBarItem (icon: IconButton( onPressed: (){ Navigator.pushNamed(context, DiscoverScreen.routeName); }, icon: const Icon(Icons.search)), label: "Поиск" ), BottomNavigationBarItem (icon: Container( padding: const EdgeInsets.only(right: 50), child: IconButton( onPressed: (){ print("Экран профился пока нет"); // Navigator.pushNamed(context, ArticleScreen.routeName); }, icon: const Icon(Icons.person)), ), label: "Профиль" ), ]); } }
package com.mzulsept.zulrestapi import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.mzulsept.zulrestapi.api.ApiConfig class PostAdapter ( val dataPost: List<DataPosts?>?, param:(Any)-> Unit ): RecyclerView.Adapter<PostAdapter.MyViewHolder>(){ class MyViewHolder (view: View) : RecyclerView.ViewHolder(view){ val imgPost = view.findViewById<ImageView>(R.id.item_image_post) val titlePost = view.findViewById<TextView>(R.id.title) val contentPost = view.findViewById<TextView>(R.id.content) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_post,parent, false) return MyViewHolder(view) } override fun getItemCount(): Int { if (dataPost != null){ return dataPost.size } return 0 } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val currentItem = dataPost?.get(position) holder.titlePost.text = currentItem?.title holder.contentPost.text = currentItem?.content Glide.with(holder.itemView.context) .load(currentItem?.image) .into(holder.imgPost) holder.itemView.setOnClickListener{ val title = dataPost?.get(position)?.title Toast.makeText(holder.itemView.context, "${title}", Toast.LENGTH_SHORT).show() } } }
<!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>Limiting a Select List</title> </head> <body> <main> <header> <h1>Limiting a Select List</h1> </header> <p>Limiting the number of items to be selected in a select list</p> <section style="display: flex"> <div> <select name="select-list" id="select-list" size="10" multiple> <option value="item-1">Item 1</option> <option value="item-2">Item 2</option> <option value="item-3">Item 3</option> <option value="item-4">Item 4</option> <option value="item-5">Item 5</option> <option value="item-6">Item 6</option> <option value="item-7">Item 7</option> <option value="item-8">Item 8</option> <option value="item-9">Item 9</option> <option value="item-10">Item 10</option> </select> </div> <div id="messages"></div> </section> </main> <script> let selectList = document.querySelector('#select-list'); selectList.addEventListener('change', (event) => { let selectedOptions = event.target.selectedOptions; let maxSelected = 3; console.log(`[change] selectedOptions.length ${selectedOptions.length}`); if (selectedOptions.length > maxSelected) { logMessage('[change] Cannot select more than three elements'); while (selectedOptions.length > maxSelected) { selectedOptions[selectedOptions.length - 1].selected = false; } } }); function logMessage(message, replace = false) { let target = document.querySelector('#messages'); if (replace) target.replaceChildren(); target.insertAdjacentHTML('beforeend', `<p>${message}</p>`); } </script> </body> </html>
import 'package:flutter/material.dart'; import 'package:surge_media/Users.dart'; import 'package:surge_media/Posts.dart'; import 'package:surge_media/Events.dart'; import 'package:surge_media/Hashtags.dart'; class Explore extends StatefulWidget { @override _ExploreState createState() => _ExploreState(); } class _ExploreState extends State<Explore> { String selectedButton = 'Explore'; List<String> items = List.generate(10, (index) => "Item $index"); ScrollController _scrollController = ScrollController(); bool isLoading = false; @override void initState() { super.initState(); _scrollController.addListener(() { if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) { _loadMoreItems(); } }); } Future<void> _loadMoreItems() async { if (!isLoading) { setState(() { isLoading = true; }); // Simulate a network call await Future.delayed(Duration(seconds: 2)); List<String> newItems = List.generate(10, (index) => "Item ${items.length + index}"); setState(() { items.addAll(newItems); isLoading = false; }); } } @override void dispose() { _scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Explore"), ), body: ListView.builder( controller: _scrollController, itemCount: items.length + 1, // +1 for the loading indicator itemBuilder: (context, index) { if (index == items.length) { return isLoading ? Center(child: CircularProgressIndicator()) : SizedBox.shrink(); } return Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Search Box if (index == 0) ...[ _buildSearchBox(), SizedBox(height: 12), // Buttons Row Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ _buildButton(context, 'Explore'), _buildButton(context, 'Users'), _buildButton(context, 'Hashtags'), _buildButton(context, 'Posts'), _buildButton(context, 'Events'), ], ), SizedBox(height: 12), // Horizontal Line Divider(color: Colors.grey), SizedBox(height: 12), ], // Items _buildImageRow(index), SizedBox(height: 12), _buildWideRectangle(index), ], ), ); }, ), ); } Widget _buildSearchBox() { return Container( padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0), decoration: BoxDecoration( color: Color(0xFFF6F6F6), borderRadius: BorderRadius.circular(8), ), child: Row( children: [ Icon(Icons.search, size: 16), SizedBox(width: 8), Text( "Search Anything", style: TextStyle( fontSize: 14, color: Colors.grey, ), ), ], ), ); } Widget _buildButton(BuildContext context, String title) { bool isSelected = selectedButton == title; return GestureDetector( onTap: () { setState(() { selectedButton = title; }); // Navigate to respective pages switch (title) { case 'Explore': Navigator.push( context, MaterialPageRoute(builder: (context) => Explore()), ); break; case 'Users': Navigator.push( context, MaterialPageRoute(builder: (context) => Users()), ); break; case 'Hashtags': Navigator.push( context, MaterialPageRoute(builder: (context) => Hashtags()), ); break; case 'Posts': Navigator.push( context, MaterialPageRoute(builder: (context) => Posts()), ); break; case 'Events': Navigator.push( context, MaterialPageRoute(builder: (context) => Events()), ); break; } }, child: Column( children: [ Text( title, style: TextStyle( fontSize: 14, color: isSelected ? Colors.blue : Colors.black, fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, ), ), SizedBox(height: 4), if (isSelected) Container( height: 2, width: 20, color: Colors.blue, ), ], ), ); } Widget _buildImageRow(int index) { String image1 = index % 2 == 0 ? 'assets/RockBand.jpg' : 'assets/MoonStuffs.jpg'; String image2 = index % 2 == 0 ? 'assets/CrowdMusicParty.jpg' : 'assets/SkyGraffiti.jpg'; return Row( children: [ Expanded( child: Container( margin: EdgeInsets.only(right: 4), child: ClipRRect( borderRadius: BorderRadius.circular(8), child: Image.asset(image1, fit: BoxFit.cover), ), ), ), Expanded( child: Container( margin: EdgeInsets.only(left: 4), child: ClipRRect( borderRadius: BorderRadius.circular(8), child: Image.asset(image2, fit: BoxFit.cover), ), ), ), ], ); } Widget _buildWideRectangle(int index) { String username = index % 2 == 0 ? "suffering.eternal223" : "RandomMan123"; String imagePath = index % 2 == 0 ? 'assets/Refined.jpg' : 'assets/ManPic1.jpg'; String quote = index % 2 == 0 ? "“When a life gives you lemonade, don’t make lemonade.”" : "“When a life gives you lemonade, don’t make lemonade. Make strawberries instead because it is sweet”"; return Container( padding: EdgeInsets.all(12), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.1), blurRadius: 2, spreadRadius: 1, offset: Offset(0, 2), ), ], ), child: Row( children: [ ClipOval( child: Image.asset(imagePath, height: 40, width: 40, fit: BoxFit.cover), ), SizedBox(width: 8), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( username, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), SizedBox(height: 4), Text( quote, style: TextStyle( fontSize: 12, color: Colors.grey, overflow: TextOverflow.ellipsis, ), maxLines: 2, ), ], ), ), ], ), ); } }
import QtQuick 2.6 import QtQuick.Window 2.2 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.2 Window { visible: true width: 720 height: 480 title: qsTr("Каталог кафе") // объявляется системная палитра SystemPalette { id: palette; colorGroup: SystemPalette.Active } Rectangle{ anchors.left: parent.left anchors.top: parent.top anchors.right: parent.right anchors.bottom: btnAdd.top anchors.bottomMargin: 8 border.color: "gray" ScrollView { anchors.fill: parent ScrollBar.horizontal.policy: ScrollBar.AlwaysOff ScrollBar.vertical.policy: ScrollBar.AlwaysOn Text { anchors.fill: parent text: "Could not connect to SQL" color: "red" font.pointSize: 20 font.bold: true visible: IsConnectionOpen === false } ListView { id: cafeList anchors.fill: parent model: cafeModel // назначение модели, данные которой отображаются списком delegate: DelegateForCafe{} clip: true // activeFocusOnTab: true // реагирование на перемещение между элементами ввода с помощью Tab focus: true // элемент может получить фокус opacity: {if (IsConnectionOpen === true) {100} else {0}} } } } Button { id: btnAdd anchors.bottom: parent.bottom anchors.bottomMargin: 8 anchors.rightMargin: 8 anchors.right:btnEdit.left text: "Добавить" width: 100 onClicked: { windowAddEdit.currentIndex = -1 windowAddEdit.show() } } Button { id: btnEdit anchors.bottom: parent.bottom anchors.bottomMargin: 8 anchors.right: btnDel.left anchors.rightMargin: 8 text: "Редактировать" width: 100 onClicked: { var nameCafe = cafeList.currentItem.cafeData.nameOfCafe var kitchenTypeCafe = cafeList.currentItem.cafeData.kitchenTypeOfCafe var addressCafe = cafeList.currentItem.cafeData.addressOfCafe var timeCafe = cafeList.currentItem.cafeData.timeOfCafe var index = cafeList.currentItem.cafeData.idOfCafe windowAddEdit.execute(nameCafe, addressCafe, kitchenTypeCafe, timeCafe, index) } } ComboBox { id: comboBoxKitchenType anchors.bottom: parent.bottom anchors.bottomMargin: 3 anchors.left:parent.left width: 120 model: ["Японская", "Русская", "Итальянская", "Американская"] } Button { id: butCount // Устанавливаем расположение кнопки anchors.bottom: parent.bottom anchors.bottomMargin: 8 anchors.left: comboBoxKitchenType.right anchors.leftMargin: 8 text: "Подсчитать" width: 100 onClicked: { windowAnswer.countCafes(comboBoxKitchenType.currentValue.toString()) } } DialogCount { id: windowAnswer } Button { id: btnDel anchors.bottom: parent.bottom anchors.bottomMargin: 8 anchors.right:parent.right anchors.rightMargin: 8 text: "Удалить" width: 100 enabled: { if (cafeList.currentItem == null || cafeList.currentItem.cafeData == null) { false } else { cafeList.currentItem.cafeData.idOfCafe >= 0 } } onClicked: del(cafeList.currentItem.cafeData.idOfCafe) } DialogForAddorEdit { id: windowAddEdit } }
## Project: DaMN project ## Title: Nanoplastics modulate the outcome of a zooplankton-microparasite ## interaction. ## Script purpose: Performs Survival analysis of the data. ## Date: 15-Oct-2022 ## Authors: Stylianos Mavrianos, ## Florent Manzi, ## Ramsy Agha, ## Noemi Azoubib, ## Charlotte Schampera, ## Justyna Wolinska1 ## Corresponding author: florent.vmanzi@gmail.com #_______________________________________________________________________________ getwd() # Set working dir setwd('/Volumes/NO NAME/Erasmus/Erasmus_Placement/Project_DaMN/Analysis/R_analysis') # Importing Libraries library(ggplot2) library(dplyr) library(survival) # Importing Dependencies source("Final_Scripts/Utils.R") # Required functions source("Final_Scripts/Preprocessing.R") # Data Daily_suv <- Data_1%>% group_by(Treatment)%>% arrange(Age_death) %>% mutate(cumsuv = array(length(Age_death):1)) %>% mutate(cumsuv = cumsuv -1 ) %>% mutate(cumsuv = (cumsuv / 25 )) %>% select(cumsuv, NP_treatment, Inf_treatment, Treatment, Age_death) %>% ungroup() Daily_suv$Inf_treatment <- factor(Daily_suv$Inf_treatment, levels = c("Control","Infected"), labels = c("Control", "Parasite-inoculated")) Daily_suv$status <- (Daily_suv$Age_death != 29) Daily_suv$status <- as.numeric(Daily_suv$status, levels = c('FALSE', 'TRUE'), labels = c(1, 0)) Daily_suv$Infection_status <- as.numeric(Daily_suv$Inf_treatment, levels = c('Control', 'Parasite-inoculated'), labels = c(0, 1)) Daily_suv$NP_status <- as.numeric(Daily_suv$NP_treatment, levels = c('Zero', 'Low', 'High'), labels = c('0', '1', '2')) # Survival analysis ---- coxph(Surv(Age_death, status) ~ Infection_status , data = Daily_suv) coxph(Surv(Age_death, status) ~ NP_status , data = Daily_suv) coxph(Surv(Age_death, status) ~ NP_status+Infection_status , data = Daily_suv) s1 <- survfit(Surv(Daily_suv$Age_death, Daily_suv$status) ~ Daily_suv$NP_status + Daily_suv$Infection_status) # Summarize res <- surv_summary(s1, Daily_suv) # Daily survival ---- ggplot(Daily_suv, aes( x = Age_death, y = cumsuv , group = Treatment, color = Inf_treatment )) + scale_y_continuous(breaks=seq( 0, 2, 0.1)) + scale_x_continuous(breaks=seq( 1, 30, 2)) + labs( x = "\nDays", y = "\nCumulative Survival", title = "\nDaily survival") + facet_wrap(~ NP_treatment) + geom_vline(xintercept = 11, linetype="dashed", color = "red") + geom_vline(xintercept = 3, linetype="dashed", color = "red") + geom_step() + scale_colour_manual(values = c("blue", "red")) + guides(col=guide_legend("Infection treatment"), shape =guide_legend("Exposed")) + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_line(), plot.title = element_text(hjust = 0.5, size = 15)) # Survival probability ---- ggplot(res, aes( x = time, y = surv ,group =Infection_status, fill = Infection_status )) + facet_wrap(~NP_status ) + scale_y_continuous(breaks=seq( 0, 1, 0.15)) + scale_x_continuous(breaks=seq( 1, 30, 5)) + labs( x = "\nDays", y = "\nsurvival probability", title = "\nSurvival") + geom_ribbon(aes(ymin= lower, ymax = upper), alpha= 0.3, ) + geom_line() + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_line(), plot.title = element_text(hjust = 0.5, size = 15))
package be.motormouth.allocation.entities; import be.motormouth.member.entities.Member; import be.motormouth.parkinglot.entities.ParkingLot; import jakarta.persistence.*; import java.time.Duration; import java.time.LocalDateTime; import java.util.Objects; import java.util.concurrent.TimeUnit; @Entity @Table(name = "ALLOCATION") public class Allocation { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "allocation_seq") @SequenceGenerator(name = "allocation_seq", sequenceName = "allocation_seq", allocationSize = 1) private Long id; @ManyToOne @JoinColumn(name = "FK_PARKING_LOT_ID") private ParkingLot parkingLot; @ManyToOne @JoinColumn(name = "FK_MEMBER_ID") private Member member; private String licensePlate; private LocalDateTime startTime; private LocalDateTime endTime; @Enumerated(EnumType.STRING) @Column(name = "STATUS") private AllocationStatus allocationStatus; public Allocation(ParkingLot parkingLot, Member member, String licensePlate) { this.parkingLot = parkingLot; this.member = member; this.licensePlate = licensePlate; this.startTime = LocalDateTime.now(); this.allocationStatus = AllocationStatus.NOT_YET_INVOICED; } protected Allocation() { // for JPA } public Long getId() { return id; } public ParkingLot getParkingLot() { return parkingLot; } public Member getMember() { return member; } public String getLicensePlate() { return licensePlate; } public LocalDateTime getStartTime() { return startTime; } public LocalDateTime getEndTime() { return endTime; } public void setEndTime(LocalDateTime endTime) { this.endTime = endTime; } public AllocationStatus getAllocationStatus() { return allocationStatus; } public Duration calculateDuration() { Duration duration; if (endTime == null ) { return duration = Duration.between(startTime, LocalDateTime.now()); } else { return duration = Duration.between(startTime, endTime); } // long millis = duration.toMillis(); // return String.format("%02d:%02d:%02d", // TimeUnit.MILLISECONDS.toHours(millis), // TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); } public boolean isActive() { return endTime == null; } public void setAllocationStatus(AllocationStatus allocationStatus) { this.allocationStatus = allocationStatus; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Allocation that = (Allocation) o; return Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(id); } }
import { ApiProperty } from '@nestjs/swagger'; import { IsInt, IsString } from 'class-validator'; import { IsExist } from 'src/validators/unique.validator'; export class CreateAnswerDto { @ApiProperty({ example: 1, description: 'The user ID' }) @IsInt() @IsExist('user', 'id') user_id: number; @ApiProperty({ example: 1, description: 'The city ID' }) @IsInt() @IsExist('city', 'id') city_id: number; @ApiProperty({ example: 'Some answer', description: 'The user\'s answer' }) @IsString({ message: 'Answer must be a string' }) answer: string; @ApiProperty({ example: 'Some answer', description: 'The user\'s answer' }) @IsString({ message: 'Profile must be a string' }) profile: string; @ApiProperty({ example: 1, description: 'total of answer' }) @IsInt() total: number; }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Extensions.Options; using SettingsAPI.Common; using SettingsAPI.Error; using SettingsAPI.Model.Enum; namespace SettingsAPI.Service { public class ValidationService : IValidationService { private readonly IMobileOptService _mobileOptService; private readonly IAwsService _awsService; private readonly IOptions<Settings> _options; private readonly ITimeService _timeService; public ValidationService(IMobileOptService mobileOptService, IAwsService awsService, IOptions<Settings> options, ITimeService timeService) { _mobileOptService = mobileOptService; _awsService = awsService; _options = options; _timeService = timeService; } public void ValidateQueryConditions(int limit, int offset, string dateFromStr, string dateToStr, string orderBy, string sortDirection, ApiUsed apiUsed) { if (limit <= 0) throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.Limit)); if (offset < 0) throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.Offset)); DateTime? dateFrom = null; if (dateFromStr != null) { try { dateFrom = DateTime.ParseExact(dateFromStr, Constant.DateQueryParameterFormat, CultureInfo.InvariantCulture); } catch { throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.DateFrom)); } } DateTime? dateTo = null; if (dateToStr != null) { try { dateTo = DateTime.ParseExact(dateToStr, Constant.DateQueryParameterFormat, CultureInfo.InvariantCulture); } catch { throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.DateTo)); } } if (dateFrom != null && dateTo != null && (dateFrom > dateTo)) { throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.DateFrom)); } switch (apiUsed) { case ApiUsed.Transaction: { if (!Enum.TryParse(orderBy, out TransactionOrderByField _)) throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.OrderBy)); break; } case ApiUsed.MemberClickHistory: { if (!Enum.TryParse(orderBy, out MemberClickHistoryOrderByField _)) throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.OrderBy)); break; } default: throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.OrderBy)); } if (!Enum.TryParse(sortDirection, out SortDirection _)) throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.SorDirection)); } public void ValidateQueryConditionsForTotalCount(string dateFromStr, string dateToStr) { DateTime? dateFrom = null; if (dateFromStr != null) { try { dateFrom = DateTime.ParseExact(dateFromStr, Constant.DateQueryParameterFormat, CultureInfo.InvariantCulture); } catch { throw new InvalidQueryConditionException( Util.GetDescriptionFromEnum(QueryConditionFields.DateFrom)); } } DateTime? dateTo = null; if (dateToStr != null) { try { dateTo = DateTime.ParseExact(dateToStr, Constant.DateQueryParameterFormat, CultureInfo.InvariantCulture); } catch { throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.DateTo)); } } if (dateFrom != null && dateTo != null && (dateFrom > dateTo)) { throw new InvalidQueryConditionException(Util.GetDescriptionFromEnum(QueryConditionFields.DateFrom)); } } public void ValidateEmail(string email) { var isValidate = Util.IsValidEmail(email); if (!isValidate || email.Length > Constant.EmailMaxLength) throw new InvalidEmailException(); } public bool IsEnumDescriptionValid<T>(string description) { var descriptions = new DescriptionAttributes<T>().Descriptions.ToList(); return descriptions.Contains(description); } public void ValidateGender(string gender) { var descriptions = new DescriptionAttributes<Gender>().Descriptions.ToList(); if (!descriptions.Contains(gender)) throw new InvalidGenderException(); } public DateTime ValidateAndParseDateOfBirth(string dateOfBirthStr) { try { var dateOfBirth = DateTime.ParseExact(dateOfBirthStr, Constant.DateOfBirthFormat, CultureInfo.InvariantCulture); //Check date of birth must early than and greater than 14 ages from current date CheckDateOfBirth(dateOfBirth); return dateOfBirth; } catch (Exception ex) { if (ex.GetType() == typeof(InvalidDateOfBirthException)) throw; throw new InvalidDateOfBirthException(string.Format(AppMessage.FieldInvalid, "Date of birth")); } } public void ValidatePhone(string phone) { if (string.IsNullOrWhiteSpace(phone) || phone.StartsWith("(")) throw new InvalidMobileNumberException(); //Try match with australia phone var regex = new Regex(Constant.AustraliaPhoneRegex); if (regex.IsMatch(phone)) return; //If false, try match with newzealand phone regex = new Regex(Constant.NewzealandPhoneRegex); if (!regex.IsMatch(phone)) throw new InvalidMobileNumberException(); } public void ValidateOtp(string phone, string mobileOtp, string email) { if (!_mobileOptService.VerifyMobileOtp(phone, mobileOtp, email)) throw new InvalidMobileOtpException(); } public void ValidateAccountNumber(string accountNumber) { if (string.IsNullOrWhiteSpace(accountNumber) || accountNumber.Length < 6 || accountNumber.Length > 10) throw new BankAccountValidationException( Util.GetDescriptionFromEnum(BankAccountValidationFields.AccountNumber)); if (!Regex.IsMatch(accountNumber, Constant.AccountNumberRegex)) throw new BankAccountValidationException(Util.GetDescriptionFromEnum(BankAccountValidationFields.AccountNumber)); } public async Task ValidateBsb(string bsb) { var bsbList = await _awsService.FetchBsbData(); var enumerable = bsbList as string[] ?? bsbList.ToArray(); if (!enumerable.Contains(bsb)) throw new BankAccountValidationException(Util.GetDescriptionFromEnum(BankAccountValidationFields.Bsb)); } public void ValidateAccountName(string accountName) { if (string.IsNullOrWhiteSpace(accountName) || (!Regex.IsMatch(accountName, Constant.AccountNameRegex))) throw new BankAccountValidationException( Util.GetDescriptionFromEnum(BankAccountValidationFields.AccountName)); } public void ValidatePostCode(string postCode) { if (string.IsNullOrWhiteSpace(postCode) || (!Regex.IsMatch(postCode, Constant.PostCodeRegex))) throw new InvalidPostCodeException(); } public void ValidateAmount(decimal amount, decimal balance) { if (amount < 0) throw new InvalidAmountException(string.Format(AppMessage.FieldInvalid, "Amount")); if (amount < Convert.ToDecimal(_options.Value.MinRedemptionAmount)) throw new InvalidAmountException(string.Format(AppMessage.MinimumAmountRequired, _options.Value.MinRedemptionAmount)); if (Math.Round(balance, 2) < amount) throw new InvalidAmountException(AppMessage.AmountGreaterThanAvailableRewards); if (amount >= Convert.ToInt32(_options.Value.MaxRedemptionAmount)) throw new InvalidAmountException(AppMessage.AmountGreaterThanMaximumLimit); } public void ValidatePaymentMethod(string paymentMethod) { if (!Enum.IsDefined(typeof(PaymentMethod), paymentMethod)) throw new InvalidPaymentMethodException(); } public void ValidatePassword(string password) { if (string.IsNullOrWhiteSpace(password) || password.Trim().Length < Constant.PasswordMinLength) { throw new InvalidPasswordException("Your password"); } } public void ValidateUri(string uri) { if (!Regex.IsMatch(uri, Constant.UriRegex)) { throw new InvalidUriException(); } } public void ValidateEmailVerificationCode(string code, out string memberIdStr, out string hashedEmail) { if (string.IsNullOrWhiteSpace(code)) throw new InvalidEmailVerificationCodeException(); string[] decodeDataArr; try { decodeDataArr = code.Split("$"); } catch { throw new InvalidEmailVerificationCodeException(); } if (decodeDataArr.Length < 2) throw new InvalidEmailVerificationCodeException(); memberIdStr = decodeDataArr[0]; hashedEmail = string.Join("$", decodeDataArr.Skip(1).ToArray()); if (string.IsNullOrWhiteSpace(memberIdStr) || string.IsNullOrWhiteSpace(hashedEmail)) throw new InvalidEmailVerificationCodeException(); } public void ValidateCheckMobileLinkCode(string code) { if (string.IsNullOrWhiteSpace(code)) throw new BadRequestException("Bad paramers"); if (!Regex.IsMatch(code, Constant.MobileLinkCode)) { throw new BadRequestException("Bad paramers"); } } public void ValidateName(string firstName, string lastName) { if (string.IsNullOrWhiteSpace(firstName) || (firstName.Length <= 1) || (firstName.Length > 50)) throw new InvalidNameException("First name"); if (string.IsNullOrWhiteSpace(lastName) || (lastName.Length <= 1) || (lastName.Length > 50)) throw new InvalidNameException("Last name"); } public void ValidateFeedback(string feedback) { if (string.IsNullOrWhiteSpace(feedback)) throw new InvalidFeedbackException(); } public void ValidateAppVersion(string appVersion) { if (string.IsNullOrWhiteSpace(appVersion)) throw new InvalidAppVersionException(); } public void ValidateDeviceModel(string deviceModel) { if (string.IsNullOrWhiteSpace(deviceModel)) throw new InvalidDeviceModelException(); } public void ValidateOperatingSystem(string operatingSystem) { if (string.IsNullOrWhiteSpace(operatingSystem)) throw new InvalidOperationException(); } public void ValidateBuildNumber(string buildNumber) { if (string.IsNullOrWhiteSpace(buildNumber)) throw new InvalidBuildNumberException(); } private class DescriptionAttributes<T> { private List<DescriptionAttribute> Attributes = new List<DescriptionAttribute>(); internal List<string> Descriptions { get; set; } public DescriptionAttributes() { RetrieveAttributes(); Descriptions = Attributes.Select(x => x.Description).ToList(); } private void RetrieveAttributes() { foreach (var attribute in typeof(T).GetMembers().SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())) Attributes.Add(attribute); } } private void CheckDateOfBirth(DateTime dateOfBirth) { var dateNow = _timeService.GetCurrentDateTimeToday(); if ((dateNow.Year - dateOfBirth.Year) > 0 || (((dateNow.Year - dateOfBirth.Year) == 0) && ((dateOfBirth.Month < dateNow.Month) || ((dateOfBirth.Month == dateNow.Month) && (dateOfBirth.Day <= dateNow.Day))))) { int age; if (dateNow.Month > dateOfBirth.Month) age = dateNow.Year - dateOfBirth.Year; else if (dateNow.Month == dateOfBirth.Month) { if (dateNow.Day >= dateOfBirth.Day) age = dateNow.Year - dateOfBirth.Year; else age = (dateNow.Year - 1) - dateOfBirth.Year; } else age = (dateNow.Year - 1) - dateOfBirth.Year; if (age < Constant.MinUserAgeAllow) throw new InvalidDateOfBirthException(AppMessage.DateOfBirthNotAllow); } else throw new InvalidDateOfBirthException(AppMessage.DateOfBirthWrong); } } }
/** * Create the store with dynamic reducers */ import { createStore, applyMiddleware, compose } from 'redux'; import { fromJS } from 'immutable'; import createReducer from './reducers'; export default function configureStore(initialState = {}) { const middlewares = [ ]; const enhancers = [ applyMiddleware(...middlewares), ]; // If Redux DevTools Extension is installed use it, otherwise use Redux compose /* eslint-disable no-underscore-dangle */ const composeEnhancers = process.env.NODE_ENV !== 'production' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ // TODO Try to remove when `react-router-redux` is out of beta, LOCATION_CHANGE should not be fired more than once after hot reloading // Prevent recomputing reducers for `replaceReducer` shouldHotReload: false, }) : compose; /* eslint-enable */ const store = createStore( createReducer(), fromJS(initialState), composeEnhancers(...enhancers) ); // Extensions store.injectedReducers = {}; // Reducer registry // // Make reducers hot reloadable, see http://mxs.is/googmo // /* istanbul ignore next */ // if (module.hot) { // module.hot.accept('./reducers', () => { // store.replaceReducer(createReducer(store.injectedReducers)); // store.dispatch({ type: '@@REDUCER_INJECTED' }); // }); // } return store; }
package com.jhw.springboot.web; import com.jhw.springboot.config.auth.SecurityConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) // 스프링 부트 테스트와 JUnit 사이에 연결자 역활 @WebMvcTest(controllers = HelloController.class, excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class)}) // Web에 집중할 수 있는 어노테이션 public class HelloControllerTest { @Autowired private MockMvc mvc; // 웹 API를 테스트. @Test @WithMockUser(roles = "USER") public void hello_return() throws Exception { String hello = "hello"; mvc.perform(get("/hello")) // HTTP GET 요청 .andExpect(status().isOk()) // Status 검증 .andExpect(content().string(hello)); // 응답 본문의 내용을 검증 } @Test @WithMockUser(roles = "USER") public void helloDto_return() throws Exception { String name = "hello"; int amount = 1000; mvc.perform(get("/hello/dto").param("name", name).param("amount", String.valueOf(amount))) // 요청 파라미터 설정. String만 허용. .andExpect(status().isOk()) .andExpect(jsonPath("$.name", is(name))) // $를 기준으로 필드명을 명시. .andExpect(jsonPath("$.amount", is(amount))); } }
#!/usr/bin/python3 """Adds two int values""" def add_integer(a, b=98): """ Returns: Int and b Typecast and converts float int int before addition Raise TypeError if not int or float """ if ((not isinstance(a, int) and not isinstance(a, float))): raise TypeError("a must be an integer") if ((not isinstance(b, float) and not isinstance(b, int))): raise TypeError("b must be an integer") return int(a) + int(b)
@extends('layouts.adminmaster') @section('content') <div class="dashboard-content-one"> <!-- Breadcubs Area Start Here --> <div class="breadcrumbs-area"> <h3>Creation Soft Nepal</h3> <ul> <li> <a href="{{url('admin/dashboard')}}">Home</a> </li> <li>Product section</li> </ul> </div> <!-- Add New product Area Start Here --> <div class="card height-auto"> <div class="card-body"> <div class="d-flex justify-content-between align-items-center mb-3"> <h3>All Product</h3> @can('create portfolio') <a class="btn btn-primary btn-lg" href="{{ route('products.create') }}">add product</a> @endcan </div> @if(session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif <!--Product table data --> <div class="table-responsive mt-5"> <table class="table display data-table text-nowrap"> <thead> <tr> <th> <div class="form-check"> <input type="checkbox" class="form-check-input checkAll"> <label class="form-check-label">ID</label> </div> </th> <th>Title</th> <th>Actions</th> </tr> </thead> <tbody id="productId" class=""> @foreach ($products as $key=>$product) <tr> <td>{{ ++$key }}</td> <td>{{ $product->title }}</td> <td class="d-flex flex-row"> <div class="mx-2"> @can('view product') <a href="{{ url('/admin/products' , $product->id)}}" class="fw-btn-fill btn-info "> view </a> @endcan </div> <div class="mx-2"> @can('update product') <a href="{{ url('admin/products/edit/' . $product->id)}}" class="fw-btn-fill btn-primary "> update </a> @endcan </div> <div class="mx-2"> @can('delete product') <button data-toggle="modal" data-target="#destroyModal" onclick="destroy('{{ $product->id}}')" class="btn fw-btn-fill btn-danger">Delete</button> @endcan </div> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> <!-- Add New product Area End Here --> <!-- Delete Modal --> <div class="modal fade" id="destroyModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title fs-5" id="exampleModalLabel">Delete Product</h3> </div> <div class="modal-body"> <form class="new-added-form" method="POST" id="deleteform" enctype="multipart/form-data"> @csrf @method('DELETE') <div class="form-group"> <input type="hidden" id="product_id" name="product_id"> <div class=""> Are you Sure? You want to delete this Product. </div> <div class="form-group mt-3"> <button type="submit" class="btn-fill-lg btn-gradient-yellow btn-hover-bluedark">Delete</button> <button type="button" class="btn bg-danger btn-fill-lg" data-dismiss="modal">Cancel</button> </div> </div> </form> </div> </div> </div> </div> <!-- End Delete Modal --> <footer class="footer-wrap-layout1"> <div class="copyright">© Copyrights <a href="#">Creation Soft Nepal</a> 2019. All rights reserved. Designed by <a href="#">PsdBosS</a></div> </footer> </div> @endsection @section('scripts') <script> function destroy(id) { console.log(id); var form = $('#deleteform'); var address = "{{url('admin/products/delete/')}}" + '/' + id; form.prop('action', address); } // Delete form submission $('#deleteform').submit(function(e) { e.preventDefault(); var form = $(this); $.ajax({ url: form.attr('action'), type: form.prop('method'), data: form.serialize(), success: function(response) { // Handle success response console.log(response); $.get(window.location.href, function(data) { var newTbody = $(data).find('.table-responsive #productId').html(); $('.table-responsive #productId').html(newTbody); }); $('#destroyModal').modal('hide'); // You can perform actions like hiding modal, refreshing the product list, etc. }, error: function(xhr, status, error) { // Handle error response console.error(error); } }); }); </script> @endsection
import {Injectable} from '@angular/core'; import {BehaviorSubject, Observable} from "rxjs"; @Injectable({ providedIn: 'root' }) export class TrackService { private tracksSubject: BehaviorSubject<string[]>; constructor() { this.tracksSubject = new BehaviorSubject<string[]>([]); } setTracks(tracks: string[]): void { this.tracksSubject.next(tracks); } get tracksObservable(): Observable<string[]> { return this.tracksSubject.asObservable(); } get tracks(): string[] { return this.tracksSubject.value; } }
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:p="http://primefaces.org/ui" xmlns:jsf="http://xmlns.jcp.org/jsf" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:o="http://omnifaces.org/ui" xmlns:of="http://omnifaces.org/functions" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core" xmlns:pm="http://primefaces.org/mobile"> <h:head> <link rel="preconnect" href="https://rsms.me/"/> <link rel="stylesheet" href="https://rsms.me/inter/inter.css"/> <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <title>INICIO</title> </h:head> <h:body> <f:event type="preRenderView" listener="#{maestroUI.consultarMaestro()}"/> <h:form id="form"> <p:growl id="msgs" showDetail="true"/> <div style="text-align: center; margin: 5px"> <div class="panel-body"> <!--<p:outputLabel value="Tipo Maestro"/> --> <h:selectOneMenu class ="form-control" value="#{maestroUI.filtrarTipoEmpleado}" converter="omnifaces.SelectItemsConverter"> <f:selectItem itemLabel="Elige una opción" itemValue="#{-1}" /> <f:selectItem itemLabel="Maestro Tiempo Completo" itemValue="#{0}" /> <f:selectItem itemLabel="Maestro Asignatura" itemValue="#{1}" /> <f:selectItem itemLabel="Maestro Técnico" itemValue="#{2}" /> <p:ajax event="change" update="searchResults" listener="#{maestroUI.busquedaDinamica()}" /> </h:selectOneMenu> </div> <p:inputText class ="form-control" placeholder="Busqueda por nombre o clave" id="searchInput" value="#{maestroUI.palabraBuscada}"> <p:ajax event="keyup" update="searchResults" listener="#{maestroUI.busquedaDinamica()}" /> </p:inputText> </div> <!--PAGINACION DE TABLA--> <!--<p:dataTable paginator="true" rows="10" rowsPerPageTemplate="5,10,15" id="searchResults" var="carre" value="" class="custom-table" emptyMessage="No se encontraron registros"> --> <p:dataTable id="searchResults" var="mae" value="#{maestroUI.resultados}" class="custom-table" emptyMessage="No se encontraron registros"> <p:column> <f:facet name="header"> <h:outputText value="No.Empleado"/> </f:facet> <h:outputText id="clave" value="#{mae.getNEmpleado()}"/> </p:column> <p:column> <f:facet name="header"> <h:outputText value="Nombre"/> </f:facet> <h:outputText value="#{mae.getNombreMaestro()}"/> </p:column> <p:column> <f:facet name="header"> <h:outputText value="Tipo Empleado"/> </f:facet> <h:outputText value="#{mae.getTipo() == 0 ? 'Tiempo Completo' : (mae.getTipo() == 1 ? 'Asignatura' : (mae.getTipo() == 2 ? 'Técnico' : ''))}"/><!--mae.getTipo()--> </p:column> <p:column> <f:facet name="header"> <h:outputText value="Horas Investigación"/> </f:facet> <h:outputText value="#{mae.getHrsIE()}"/> </p:column> <p:column> <f:facet name="header"> <h:outputText value="Horas Adicionales"/> </f:facet> <h:outputText value="#{mae.getHrsad()}"/> </p:column> <p:column> <f:facet name="header"> <h:outputText value="Horas Maximas"/> </f:facet> <h:outputText value="#{mae.getHmax()}"/> </p:column> <p:column> <f:facet name="header"> <h:outputText value="Acciones"/> </f:facet> <p:button value="M" outcome='modMaestro.xhtml'> <f:param name="paramName" value="#{mae.getIdMaestro()}"/> </p:button> <!--<p:commandButton value="E"/>--> </p:column> </p:dataTable> </h:form> </h:body> <style> /*body{ font-size: 1.75vw; }*/ /* Estilo para la última celda de la tabla */ .custom-table tr{ border-right: transparent !important; border-left: transparent !important; } /* Estilo para las líneas horizontales de la tabla */ .custom-table tr{ border-bottom: 1px solid gray; /* Líneas horizontales grises */ background-color: transparent !important; border-right: 1px solid green; } /* Estilo para la primera celda de la tabla */ .custom-table tr:last-child { border-right: transparent !important; } /* Estilo para el header de la tabla */ .custom-table th { background-color: transparent !important; /* Header transparente */ color: black; /* Texto negro */ border-left: transparent !important; border-right: transparent !important; border-top: transparent !important; border-bottom: 1px solid green; /* Borde verde */ } </style> </html>
import { useCallback, useEffect, useRef } from 'react'; import { NativeEventEmitter, NativeModules, Platform } from 'react-native'; const LINKING_ERROR = `The package 'expo-moquette' doesn't seem to be linked. Make sure: \n\n` + Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo managed workflow\n'; const ExpoMoquette = NativeModules.ExpoMoquette ? NativeModules.ExpoMoquette : new Proxy( {}, { get() { throw new Error(LINKING_ERROR); }, } ); export type Client = { id: string; address: string; port: number; }; export type ServerConfig = Partial<{ host: string; port: number; wssPort: number; password: string; username: string; nettyMaxBytes: number; }>; export type ServerStatus = { port: number; sslPort: number; }; export function startServerAsync(config: ServerConfig): Promise<string> { return ExpoMoquette.startServerAsync(config); } export function getConnectedList(): Promise<Client[]> { return ExpoMoquette.getConnectedClientsAsync(); } export function restartServerAsync(): Promise<ServerStatus> { return ExpoMoquette.restartServerAsync(); } export function stopServerAsync(): Promise<ServerStatus> { return ExpoMoquette.stopServerAsync(); } export function getServerStatusAsync(): Promise<ServerStatus> { return ExpoMoquette.getServerStatusAsync(); } export function isAvailable() { return Platform.OS === 'android'; } const emitter = new NativeEventEmitter(); const ON_CONNECT = 'ON_CONNECT'; const ON_CONNECTION_LOST = 'ON_CONNECTION_LOST'; const ON_DISCONNECT = 'ON_DISCONNECT'; const ON_MESSAGE = 'ON_MESSAGE'; export function subscribeTopic(topic: string, callback: (event: any) => void) { return emitter.addListener(ON_MESSAGE, (event: any) => { if (event.topic === topic || event.topic.startsWith(topic)) { callback(event); } }); } type EventData = { eventName: 'ON_CONNECT' | 'ON_DISCONNECT' | 'ON_CONNECTION_LOST'; event: { clientID: string; totalClients: number; username: string; }; }; export function useClientEvent(handler: (event: EventData) => void) { const refHandler = useRef(handler); refHandler.current = handler; const createEventHandler = useCallback( (eventName: EventData['eventName']) => { return (event: any) => { refHandler.current({ event, eventName }); }; }, [] ); useEffect(() => { const subs = [ emitter.addListener(ON_CONNECT, createEventHandler(ON_CONNECT)), emitter.addListener(ON_DISCONNECT, createEventHandler(ON_DISCONNECT)), emitter.addListener( ON_CONNECTION_LOST, createEventHandler(ON_CONNECTION_LOST) ), ]; return () => { subs.forEach((sub) => sub.remove()); }; }, [createEventHandler]); }
## Search Problem in CSPs - **Initial State**: Empty assignment - **Successor Function**: Assign a value to an unassigned variable - **Goal Test**: Assignment is complete and satisfies all constraints - **Variable**: Items that can be assigned values - **Domains**: The set of values that can be assigned to variables - **Constraints**: Rules that limit the domain values for variables ## Types of CSPs ### Discrete Variables - **Finite Domains**: Boolean CSPs, map coloring - **Infinite Domains**: Job scheduling; requires a constraint language ### Continuous Variables - Relevant in time-series data analysis - Polynomial-time solvable with linear constraints ## Constraints ### Unary Constraints - Restricts values of a single variable. - **Example**: A country must be colored red. ### Binary Constraints - Restricts combinations of values between two variables. - **Example**: Neighboring countries must have different colors. ### N-ary Constraints (Higher Order) - Restricts combinations of values between three or more variables. - **Example**: Multiple tasks must be completed within a specific time frame. ## Solving CSPs ### Backtracking - **Example**: Sudoku; assign numbers one at a time and backtrack if needed. ### Most Constrained Variable (MCV) - Select the variable with the fewest legal moves. - **Example**: Choose the country with the most neighbors to color first. ### Least Constraining Value - Pick the value that imposes the fewest constraints on other variables. - **Example**: Choose a meeting time that leaves the most free slots for other meetings. ### Forward Checking - Eliminate future domain values that conflict with current assignments. - **Example**: In Eight Queens Puzzle, place a queen and remove invalid cells for future queens. ### Arc Consistency - Each value in the domain of one variable has a compatible value in the domain of another variable. - **Example**: In SEND + MORE = MONEY, assigning 'S' to 9 removes 9 from the domain of other letters. ### Iterative Min-conflicts - Start with an initial assignment and iteratively correct variables causing conflicts. - **Example**: Timetable Scheduling; move conflicting classes to minimize conflicts. --- CSPs are search problems where states are defined by the values of variables, and the goal is determined by constraints. Variable ordering and value selection heuristics can optimize the search process. Techniques like forward checking and arc consistency can prevent assignments that will lead to failure and can help in detecting inconsistencies more efficiently.
package hotel; import hotel.roomsfactory.RoomFactory; import hotel.roomsfactory.rooms.Room; import personas.Administrador; import personas.Cliente; import java.util.Vector; public class Hotel { private static Hotel instance; private String nombre; private Administrador admin; private Vector<Cliente> clientes; private Vector<Vector<Room>> cuartos; private Hotel(String nombre, Administrador admin, Vector<Cliente> clientes, int N) { this.nombre = nombre; this.admin = admin; this.clientes = clientes; // N es el tamaño de la matriz // Inicializamos el terreno this.cuartos = new Vector<>(); for(int i = 0; i < N; i++) { this.cuartos.add(new Vector<>()); } for(Vector<Room> vector: cuartos){ for(int i = 0; i < N; i++) { vector.add(null); } } } public static Hotel getInstancia(){ if(instance == null){ Administrador administrador = new Administrador("Juan Pérez", 34, "Montreal", "jperese", "1234", 101, "Gerente"); Vector<Cliente> vectorCliente = new Vector<Cliente>(); vectorCliente.add(new Cliente("Diego Monterrosa", 22, "San Vicente", "dmonterrosa", "password", 1200.00, "good", 2, "", "")); instance = new Hotel("Skyloft", administrador, vectorCliente, 5); } return instance; } public String getNombre() {return nombre;} public void setNombre(String nombre) {this.nombre = nombre;} public Administrador getAdmin() {return admin;} public void setAdmin(Administrador admin) {this.admin = admin;} public Vector<Cliente> getClientes() {return clientes;} public void setClientes(Vector<Cliente> clientes) {this.clientes = clientes;} public Vector<Vector<Room>> getCuartos() {return cuartos;} public void setCuartos(Vector<Vector<Room>> cuartos) {this.cuartos = cuartos;} }
import { Component, HostListener, OnInit, ViewChild } from '@angular/core'; import { Capacitor } from '@capacitor/core'; import { SplashScreen } from '@capacitor/splash-screen'; import { StatusBar, Style } from '@capacitor/status-bar'; import { IonMenu, Platform } from '@ionic/angular'; import { TranslateService } from '@ngx-translate/core'; import {MatSidenavModule} from '@angular/material/sidenav'; import { NavController } from '@ionic/angular'; @Component({ selector: 'app-root', templateUrl: 'app.component.html', }) export class AppComponent implements OnInit { // showFiller = false; @ViewChild('mainMenu') mainMenu: IonMenu; // @ViewChild('mainMenu', { static: false }) set menuSetter(mainMenu: IonMenu) { // if (mainMenu) { // this.mainMenu = mainMenu; // this.openMenu(); // } // } // mainMenu: IonMenu; constructor(public navController: NavController,private platform: Platform, private translate: TranslateService) { this.initializeApp(); } desktop : boolean=false; ionViewWillEnter() { // await this.loadAll(); // Open the menu after the view has been initialized this.openMenu(); } ngOnInit() { this.detectDeviceType(); // this.openMenu(); } @HostListener('window:resize', ['$event']) onResize(event: any) { this.detectDeviceType(); } openMenu() { // Open the menu programmatically if (this.desktop) { this.mainMenu.open(); } } detectDeviceType() { if (window.innerWidth > 768) { this.desktop = true } else { this.desktop = false } console.log(this.desktop) } initializeApp() { this.platform.ready().then(async () => { if (Capacitor.isPluginAvailable('StatusBar')) { await StatusBar.setStyle({ style: Style.Default }); } if (Capacitor.isPluginAvailable('SplashScreen')) { await SplashScreen.hide(); } }); this.initTranslate(); } initTranslate() { const enLang = 'en'; // Set the default language for translation strings, and the current language. this.translate.setDefaultLang(enLang); if (this.translate.getBrowserLang() !== undefined) { this.translate.use(this.translate.getBrowserLang()); } else { this.translate.use(enLang); // Set your language here } } m1(){ this.navController.navigateForward('/tabs/home') } m2(){ this.navController.navigateForward('/tabs/entities') } m3(){ this.navController.navigateForward('/tabs/account') } }
import React, { useEffect, useState } from 'react'; import { Skeleton, Box, Heading, Text } from "@chakra-ui/core"; import { Card } from 'components/ui/ui'; import { createElement } from 'components/dynamicElements'; import { PostContext } from 'contexts/post'; import data from "./demo"; const testpost = { title: 'Test Context', tags: [ '' ] } const createMarkup = htmlString => ({ __html: htmlString }); function Exercise( props ) { const [ context, setContext ] = useState( testpost ); const [ exercise, setExercise ] = useState( data ); const [ isLoading, setIsLoading ] = useState( true ); /** * If there is an exercise name defined, load the exercise data. * Return an error if the exercise can't be found and show sample data instead. * Finally, hold off on rendering until we know for sure what's going on. */ useEffect( () => { async function fetchExercise() { const exerciseName = props.name; if ( exerciseName ) { setIsLoading( true ); await import(`../../data/exercises/${exerciseName}.json`).then( value => { setExercise( value.default ) setIsLoading( false ); }, reason => { setIsLoading( false ); console.error( "The requested exercise couldn't be found. Rendering the demo exercise." ); }); } } fetchExercise(); }, [ props.name ]); return ( <Skeleton isLoaded={ !isLoading }> <PostContext.Provider value={ [ context, setContext ] }> <Card textAlign="right"> <Heading as="h3" size="lg" textAlign="left">{ exercise.title }</Heading> <Text fontSize="lg" textAlign="left" dangerouslySetInnerHTML={ createMarkup( exercise.directions ) } /> { exercise.components.map( ( component, index ) => <Box mb={10} key={ index.toString() }> { createElement( component ) } </Box> ) } </Card> </PostContext.Provider> </Skeleton> ); } export default Exercise;
import type { Session } from 'next-auth' import { signIn } from 'next-auth/react' import { useForm } from 'react-hook-form' import { toast } from 'react-hot-toast' import { FcGoogle } from 'react-icons/fc' import { Button, Center, Stack, Text, Icon, Input, FormControl, FormErrorMessage, } from '@chakra-ui/react' import { useCreateUsernameMutation } from '../graphql/generated' type UsernameFormFields = { username: string } type UsernameFormProps = { onSuccess: () => void } function UsernameForm({ onSuccess }: UsernameFormProps) { const { register, handleSubmit, formState: { errors }, } = useForm<UsernameFormFields>() const [createUsername, { loading }] = useCreateUsernameMutation() const onFormSubmit = async ({ username }: UsernameFormFields) => { try { const result = await createUsername({ variables: { username, }, }) if (result.data?.createUsername.success) { toast.success('Username successfully created! 🚀') onSuccess() return } toast.error(result.data?.createUsername.error || 'Unknown error') } catch (error) { toast.error('Create user error') } } return ( <Stack align="center" spacing={6} as="form" onSubmit={handleSubmit(onFormSubmit)} > <Text fontSize="3xl">Create a Username</Text> <FormControl isDisabled={loading} isInvalid={!!errors?.username}> <Input type="text" placeholder="Enter a username" {...register('username', { required: { message: 'Username is required', value: true, }, minLength: 1, maxLength: 50, })} /> {errors?.username && ( <FormErrorMessage>{errors.username.message}</FormErrorMessage> )} </FormControl> <Button isLoading={loading} w="100%" type="submit"> Save </Button> </Stack> ) } type AuthProps = { session: Session | null reloadSession: () => void } export function Auth({ reloadSession, session }: AuthProps) { return ( <Center h="100vh"> {session ? ( <UsernameForm onSuccess={reloadSession} /> ) : ( <Stack align="center" spacing={8}> <Text fontSize="3xl">MessengerQL</Text> <Button type="button" leftIcon={<Icon boxSize={6} as={FcGoogle} />} onClick={() => signIn('google')} > Continue with Google </Button> </Stack> )} </Center> ) }
# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ split_data """ import numpy as np import scipy.sparse as sp def split_data(x, val_ratio=0.05, test_ratio=0.1, graph_type='undirected'): r""" Cut the training set into training set, validation set and test set according to the proportion of user input, and perform graph reconstruction on the training set, and then return. Args: x (mindspore_gl.dataloader.Dataset): Graph Structured Dataset val_ratio(float, optional): Validation set proportion. Default: 0.05. test_ratio(float, optional): Test set proportion. Default: 0.1. graph_type(str, optional): The type of graph.'undirected': undirected graph, 'directed': directed graph. Default: 'undirected'. Returns: - **train** (numpy.ndarray) - Train set positive examples, shape :math:`(train\_len, 2)` . - **val** (numpy.ndarray) - Validation set positive example, shape :math:`(val\_len, 2)` . - **test** (numpy.ndarray) - Test set positive examples, shape :math:`(test\_len, 2)` . Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> from mindspore_gl.dataloader import split_data >>> from mindspore_gl.dataset import CoraV2 >>> ds = CoraV2('data_path') >>> adj_coo, (train, val, test) = split_data(ds) >>> print(train.shape, val.shape, test.shape) (11684, 2) (263, 2) (527, 2) """ col = x.adj_coo.col row = x.adj_coo.row # Construct an adjacency matrix adj = [] for i in range(len(col)): idx = [] idx.append(col[i]) idx.append(row[i]) adj.append(idx) # Take the upper triangular matrix adj_c = [i for i in adj if i[0] != i[1]] if graph_type == 'undirected': adj_cc = [] for i in adj_c: if [i[1], i[0]] not in adj_cc: adj_cc.append(i) else: adj_cc = adj_c # Shuffle the subscript order, split the validation set and the test set np.random.shuffle(adj_cc) s = len(adj_cc) val_l = int(s*val_ratio) test_l = int(s*test_ratio) idx = np.random.randint(val_l+test_l, s-val_l-test_l) val = adj_cc[idx:idx+val_l] test = adj_cc[idx+val_l:idx+val_l+test_l] # Remove the validation and test sets from the training set for i in val+test: if i in adj: adj.remove([i[1], i[0]]) adj.remove([i[0], i[1]]) train = adj adj, val, test, train = np.array(adj), np.array(val), np.array(test), np.array(train) # Refactored graph data = np.ones(train.shape[0]) adj_train = sp.csr_matrix((data, (train[:, 0], train[:, 1])), shape=x.adj_coo.shape).tocoo(copy=False) return adj_train, (train, val, test)
// Fill out your copyright notice in the Description page of Project Settings. #include "SaveGame/SSaveGameSubsystem.h" #include "EngineUtils.h" #include "SGameplayInterface.h" #include "SPlayerState.h" #include "ActionRoguelike/ActionRoguelike.h" #include "GameFramework/GameStateBase.h" #include "SaveGame/SSaveGameSettings.h" #include "Kismet/GameplayStatics.h" #include "Logging/StructuredLog.h" #include "SaveGame/SSaveGame.h" #include "Serialization/ObjectAndNameAsStringProxyArchive.h" void USSaveGameSubsystem::Initialize(FSubsystemCollectionBase& Collection) { Super::Initialize(Collection); const USSaveGameSettings* SaveGameSettings = GetDefault<USSaveGameSettings>(); CurrentSlotName = SaveGameSettings->SaveSlotName; if (SaveGameSettings->DummyDataTable) { // Force a synchronous load (further initialization of the game will likely assume this is initialized) UDataTable* DummyTable = SaveGameSettings->DummyDataTable.LoadSynchronous(); // Nothing to do with the table just yet, just here as an example for reference } } void USSaveGameSubsystem::HandleStartingNewPlayer(AController* NewPlayer) { ASPlayerState* PS = NewPlayer->GetPlayerState<ASPlayerState>(); if (ensure(PS)) { PS->LoadFromSavedGame(CurrentSaveGame); } } bool USSaveGameSubsystem::OverrideSpawnTransform(AController* NewPlayer) { if (!IsValid(NewPlayer)) { return false; } APlayerState* PlayerState = NewPlayer->GetPlayerState<APlayerState>(); if (PlayerState == nullptr) { return false; } if (APawn* MyPawn = PlayerState->GetPawn()) { FPlayerSaveData* FoundData = CurrentSaveGame->GetPlayerData(PlayerState); if (FoundData && FoundData->bUseSavedTransform) { MyPawn->SetActorLocationAndRotation(FoundData->Location, FoundData->Rotation); // Set control rotation to change camera direction, setting Pawn rotation is not enough NewPlayer->SetControlRotation(FoundData->Rotation); return true; } } return false; } void USSaveGameSubsystem::SetSlotName(FString NewSlotName) { if (NewSlotName.IsEmpty()) return; CurrentSlotName = NewSlotName; } void USSaveGameSubsystem::WriteSaveGame() { if (!ensureAlwaysMsgf(IsValid(CurrentSaveGame), TEXT("Always call \"LoadGame\" before \"SaveGame\" to create the object."))) return; CurrentSaveGame->SavedPlayers.Empty(); CurrentSaveGame->SavedActors.Empty(); AGameStateBase* GS = GetWorld()->GetGameState(); if (GS == nullptr) return; for (int32 i = 0; i < GS->PlayerArray.Num(); i++) { if (ASPlayerState* PlayerState = CastChecked<ASPlayerState>(GS->PlayerArray[i])) { PlayerState->WriteToSavedGame(CurrentSaveGame); break; // @todo: Update to support multiplayer } } for (FActorIterator It(GetWorld()); It; ++It) { AActor* Actor = *It; if (!IsValid(Actor) || !Actor->Implements<USGameplayInterface>()) continue; FActorSaveData ActorData; ActorData.ActorName = Actor->GetName(); ActorData.Transform = Actor->GetActorTransform(); FMemoryWriter MemoryWriter(ActorData.ByteData); FObjectAndNameAsStringProxyArchive Ar(MemoryWriter, true); // Find only properties with the SaveGame specifier Ar.ArIsSaveGame = true; Actor->Serialize(Ar); CurrentSaveGame->SavedActors.Add(ActorData); } UGameplayStatics::SaveGameToSlot(CurrentSaveGame, CurrentSlotName, 0); } void USSaveGameSubsystem::LoadSaveGame(FString InSlotName) { SetSlotName(InSlotName); if (UGameplayStatics::DoesSaveGameExist(CurrentSlotName, 0)) { CurrentSaveGame = Cast<USSaveGame>(UGameplayStatics::LoadGameFromSlot(CurrentSlotName, 0)); if (CurrentSaveGame == nullptr) { UE_LOGFMT(LogGame, Warning, "Failed to load SaveGame Data."); return; } UE_LOGFMT(LogGame, Log, "Loaded SaveGame Data."); for (FActorIterator It(GetWorld()); It; ++It) { AActor* Actor = *It; if (!Actor->Implements<USGameplayInterface>()) continue; for (FActorSaveData ActorData : CurrentSaveGame->SavedActors) { if (ActorData.ActorName == Actor->GetName()) { Actor->SetActorTransform(ActorData.Transform); FMemoryReader MemoryReader(ActorData.ByteData); FObjectAndNameAsStringProxyArchive Ar(MemoryReader, true); // Find only properties with the SaveGame specifier Ar.ArIsSaveGame = true; // Calling "serialize" with a FMemoryReader actually DE-serializes the data into the Actor's variables Actor->Serialize(Ar); ISGameplayInterface::Execute_OnActorLoaded(Actor); break; } } } OnSaveGameLoaded.Broadcast(CurrentSaveGame); } else { CurrentSaveGame = CastChecked<USSaveGame>(UGameplayStatics::CreateSaveGameObject(USSaveGame::StaticClass())); UE_LOGFMT(LogGame, Log, "Created New SaveGame Data."); } }
import React, { useState } from 'react'; import { SearchInquiry, Inquiry} from '../../components'; import { cancelAlert, payAlert } from '../../components/Atomic/Alert/Alert'; import { onFindInquiry, onPayInquiry, onCancelInquiry } from '../../redux/payment/action' import { connect } from 'react-redux'; import Swal from 'sweetalert2'; import './Virtual.css'; function Payment(props) { const [vaNumber, setVANumber] = useState(''); const [vaNumberFix, setVANumberFix] = useState(''); const [externalId, setExternalId] = useState(''); const [orderId, setOrderId] = useState(''); const [trxId, setTrxId] = useState(''); const [channel, setChannel] = useState(''); const [errSearch, setErrSearch] = useState(''); const [errPay, setErrPay] = useState(''); const [payAmount, setPayAmount] = useState(0); const [payAmountTxt, setPayAmountTxt] = useState(0); const [paidStatus, setPaidStatus] = useState(false); const [cancelStatus, setCancelStatus] = useState(false); const [mustTotalPay, setMustTotalPay] = useState(0); const [paymentMethod, setPaymentMethod] = useState(null); const [loading, setLoading] = useState(false); const [btnDisable, setBtnDisable] = useState(false) const [paymentType] = useState('va') const animationTimeout = Number(process.env.REACT_APP_ANIMATION_TIMEOUT) const minPayAmount = Number(process.env.REACT_APP_MIN_PAY_AMOUNT) const handleChange = (prop) => (e) => { var regex = /[^0-9]/g; if (prop === "va_number") { if (!e.target.value) { setErrSearch("VA Number is required"); setVANumber(''); } else { setErrSearch(null); setVANumber(e.target.value.replace(regex, '')); } } if (prop === "amount_val") { setPayAmount(e.target.value) setPayAmountTxt(e.target.value) setErrPay(null) } if (e.key === " ") { e.preventDefault(); setErrSearch('Whitespace is not allowed'); } if (e.key === 'Enter') { seaarchInquiryAct(); } } const clearInquiryAct = () => { setErrSearch('') setVANumber(''); setVANumberFix('') setOrderId('') setChannel('') setMustTotalPay(0) setExternalId(''); setPayAmount(0); setPayAmountTxt(''); } // ::SEARCH ACTION:: // const seaarchInquiryAct = () => { setLoading(true) const reqSearchInquiry = { "va_number": vaNumber, } if (vaNumber === '') { setErrSearch('VA Number is required'); setExternalId(''); setMustTotalPay(0); setPaymentMethod(null); setLoading(false) return } props.findInquiryProp( reqSearchInquiry, paymentType, e => { setErrPay('') setBtnDisable(true) if (e.status) { if ( e.status !== 200 && e.data.response_code) { Swal.fire({icon : "info", title : e.data.response_message}) setExternalId(''); setOrderId(''); setTrxId(''); setChannel(''); setVANumberFix(''); setLoading(false) setBtnDisable(false) return } } if (e.transaction_status === 'ACTIVE') { setExternalId(e.external_id); setOrderId(e.order_id); setTrxId(e.transaction_id); setChannel(e.payment_channel); setVANumberFix(e.payment_details.va_number); setMustTotalPay(e.payment_details.total_amount); setPaymentMethod(e.payment_method); setErrSearch(''); setPayAmountTxt(''); setLoading(false) setBtnDisable(false) } else { Swal.fire({icon : "info", title : "Transaction status is " + e.transaction_status.toLowerCase()}) setExternalId(''); setOrderId(''); setTrxId(''); setChannel(''); setVANumberFix(''); setMustTotalPay(0); setPaymentMethod(null); setLoading(false) setBtnDisable(false) return } }) } // ::PAY ACTION:: // const payInquiryAct = () => { const reqPayInquiry = { "external_id": externalId, "order_id": orderId, "transaction_id": trxId, "amount": Number(payAmount) } if (payAmount < minPayAmount || payAmount === 0) { setErrPay("Payment should not be less than " + minPayAmount); } else if (payAmount >= minPayAmount) { Swal.fire(payAlert).then((result) => { if (result.isConfirmed) { props.payInquiryProp(reqPayInquiry, paymentType, e => { if (e.status !== undefined && e.status !== 200) { if (e.data.response_code) { setPaidStatus(false); if (e.data.response_message) { Swal.fire({ icon : "info", title : e.data.response_message, confirmButtonColor : 'var(--blue)' }) } } } if (e.transaction_status === "PAID" || e.transaction_status === "ACTIVE") { setOrderId(''); setTrxId(''); setChannel(''); setExternalId('') setErrSearch(''); setPaidStatus(true); setVANumber(''); } setTimeout(() => { setPaidStatus(false) }, animationTimeout); }) } }); } } // ::CANCEL ACTION:: // const cancelInquiryAct = () => { setErrPay('') const reqCancelInquiry = { "external_id": externalId, "order_id": orderId, "transaction_id": trxId, "payment_method": paymentMethod, "payment_channel": channel } Swal.fire(cancelAlert).then((result) => { if (result.isConfirmed) { props.cancelInquiryProp( reqCancelInquiry, e => { if (undefined !== e.status && e.status !== 200) { if (e.data.response_code) { setCancelStatus(false); setErrPay(e.data.response_message); } } if (e.transaction_status === "CANCELED") { setExternalId(''); setOrderId(''); setTrxId(''); setChannel(''); setVANumberFix(''); setVANumber('') setErrSearch(''); setCancelStatus(true); setPaymentMethod(null); } setTimeout(() => { setCancelStatus(false) }, animationTimeout); }) } }); } return ( <> {/* <Header /> */} <SearchInquiry handleChange={handleChange} vaNumber={vaNumber} seaarchInquiryAct={seaarchInquiryAct} clearInquiryAct={clearInquiryAct} errSearch={errSearch} paidStatus={paidStatus} cancelStatus={cancelStatus} loading={loading} btnDisable={btnDisable} /> { externalId ? <Inquiry handleChange={handleChange} payInquiryAct={payInquiryAct} vaNumberFix={vaNumberFix} orderId={orderId} channel={channel} mustTotalPay={mustTotalPay} errPay={errPay} cancelInquiryAct={cancelInquiryAct} payAmountTxt={payAmountTxt} /> : "" } </> ) } const mapStateToProps = state => { return { dataPayment: state.payment.inquiry_data, } } const mapDispatchToProps = dispatch => { return { findInquiryProp: async (req, paymentType, callback) => { const res = await dispatch(onFindInquiry(req, paymentType)) callback(res); }, payInquiryProp: async (req, paymentType, callback) => { const res = await dispatch(onPayInquiry(req, paymentType)) callback(res); }, cancelInquiryProp: async (req, callback) => { const res = await dispatch(onCancelInquiry(req)) callback(res); } } } export default connect(mapStateToProps, mapDispatchToProps)(Payment)
from django.db import models from accounts.models import User from django.utils import timezone from extensions.utils import jalali_converter from django.contrib.contenttypes.fields import GenericRelation from comment.models import Comment class Category(models.Model): title = models.CharField(max_length=200,verbose_name="عنوان دسته بندی") slug = models.SlugField(max_length=100,unique=True,verbose_name="ادرس دسته بندی") status = models.BooleanField(default=True,verbose_name="آیا می خواید نمییش داداه شود؟") position = models.IntegerField(verbose_name="پوزیشن") class Meta: verbose_name="دسته بندی" verbose_name_plural = "دسته بندی ها" ordering = ['position'] def __str__(self): return self.title class IPAddress(models.Model): ip_address = models.GenericIPAddressField(verbose_name="آدرس ای پی") class Article(models.Model): post = models.TextField(max_length = 1000,unique=False,verbose_name='Post') pictures = models.ImageField(upload_to="images/",unique=False,verbose_name='Image',null=True,blank=True) category = models.ManyToManyField(Category,verbose_name='category',related_name='articles',null=True,blank=True,) author = models.ForeignKey(User, on_delete=models.CASCADE) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) private = models.BooleanField(default=False,verbose_name="Private") video = models.FileField(upload_to='video/',verbose_name="Video",null=True,blank=True) comments = GenericRelation(Comment) hits = models.ManyToManyField(IPAddress,through="ArticleHit",blank=True,related_name="hits",verbose_name="Views") def __str__(self): return self.post class Meta: verbose_name="پست" verbose_name_plural = "پست ها" ordering =['-publish'] def category_published(self): return self.category.filter(status=True) def jpublish(self): return jalali_converter(self.publish) jpublish.short_description = "زمان انتشار پست" def category_to_str(self): return " ".join([category.title for category in self.category.all()]) category_to_str.short_description = 'دسته بندی' class ArticleHit(models.Model): article = models.ForeignKey(Article,on_delete=models.CASCADE) ip_address = models.ForeignKey(IPAddress,on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True)
import 'package:dio/dio.dart'; import 'package:ms/core/base/base_response.dart'; import 'package:ms/core/network/api_helper.dart'; import 'package:ms/data/model/login_param.dart'; import 'package:ms/data/model/user.dart'; import 'package:retrofit/retrofit.dart'; part 'auth_service.g.dart'; @RestApi() abstract class AuthService { factory AuthService(Dio dio, {String baseUrl}) = _AuthService; static AuthService create() { final dio = ApiHelper().createDio() ..addOneAppLog() ..addAuthInterceptors(); final client = AuthService(dio); return client; } @POST('http://10.2.9.149:8081/api/users/register') Future<HttpResponse<BaseResponse<User>>> register( @Body() Map<String, dynamic> map); @POST('http://10.2.9.149:8081/api/auth/login') Future<HttpResponse<BaseResponse<User>>> login( @Body() LoginParam? loginParam); }
package fr.polytech.info4.service.mapper; import fr.polytech.info4.domain.*; import fr.polytech.info4.service.dto.ProduitDTO; import org.mapstruct.*; /** * Mapper for the entity {@link Produit} and its DTO {@link ProduitDTO}. */ @Mapper(componentModel = "spring", uses = {RestaurantMapper.class}) public interface ProduitMapper extends EntityMapper<ProduitDTO, Produit> { @Mapping(source = "restaurant.id", target = "restaurantId") ProduitDTO toDto(Produit produit); @Mapping(source = "restaurantId", target = "restaurant") @Mapping(target = "paniers", ignore = true) @Mapping(target = "removePanier", ignore = true) Produit toEntity(ProduitDTO produitDTO); default Produit fromId(Long id) { if (id == null) { return null; } Produit produit = new Produit(); produit.setId(id); return produit; } }
package com.oesia.apertura.demo.alcanceobra.controller; import com.oesia.apertura.demo.alcanceobra.model.AddAlcanceObraDTO; import com.oesia.apertura.demo.alcanceobra.service.interfaz.AddAlcanceObraInterface; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(path = "/alcanceobra") @Api(tags = "AlcanceObra") public class AddAlcanceObra { @Autowired private AddAlcanceObraInterface addAlcanceObraInterface; @PostMapping("/add") @ApiOperation(value = "AddAlcanceObra--Insert AlcanceObra") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 201, message = "CREATED"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 500, message = "Internal Server Error")}) public @ResponseBody ResponseEntity<String> addAlcanceObra(@RequestBody AddAlcanceObraDTO addAlcanceObraDTO) { addAlcanceObraInterface.add(addAlcanceObraDTO); return new ResponseEntity<>("Inserted in database correctly", HttpStatus.CREATED); } }
function fetchRandomNumbers() { return new Promise((resolve, reject) => { console.log("Fetching number..."); setTimeout(() => { let randomNum = Math.floor(Math.random() * (100 - 0 + 1)) + 0; console.log("Received random number:", randomNum); randomNum ? resolve(randomNum) : reject(new Error(`couldn't fetch random number`)); }, (Math.floor(Math.random() * 5) + 1) * 1000); }); } function fetchRandomString() { return new Promise((resolve, reject) => { console.log("Fetching string..."); setTimeout(() => { let result = ""; let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; let charactersLength = characters.length; for (let i = 0; i < 5; i++) { result += characters.charAt( Math.floor(Math.random() * charactersLength) ); } console.log("Received random string:", result); result ? resolve(result) : reject(new Error(`couldn't fetch the string`)); }, (Math.floor(Math.random() * 5) + 1) * 1000); }); } // **Task 1**: Right now, the function fetchRandomNumbers can be used by passing a callback, // Your task is to promisfy this function so that the following can be done: fetchRandomNumbers() .then((randomNum) => console.log(randomNum)) .catch((err) => console.error(err) ); //using async/await const fetchRandomNum = async () => { try { const randomNum = await fetchRandomNumbers(); console.log(randomNum) } catch(err) { console.log(err) } } fetchRandomNum(); fetchRandomString() .then((randomStr) => console.log(randomStr)) .catch((err) => console.error(err) ); //using async/await const fetchRandomStr = async () => { try { const randomStr = await fetchRandomString(); console.log(randomStr) } catch(err) { console.error(err) } } fetchRandomStr(); // **Task 2**: Fetch a random number -> add it to a sum variable and print sum-> fetch another random variable // -> add it to the same sum variable and print the sum variable. fetchRandomNumbers((randomNum) => randomNum) .then((randomNum) => { let sum = 5; console.log("Sum of first random number and sum", sum + randomNum); return sum; }) .then((sum) => { return fetchRandomNumbers((randomNum) => randomNum).then( (randomNum) => randomNum + sum ) .catch(error => console.error(error)); }) .then((sum) => console.log("Sum of 2nd random number and sum", sum)) .catch((err) => console.error(err)); // using async/await const sumOfTwoRandomNum = async () => { try { let sum = 5; sum += await fetchRandomNumbers(); console.log('sum of first random number and sum',sum); sum += await fetchRandomNumbers(); console.log('sum of second random number and sum',sum) } catch(err){ console.error(err) } } sumOfTwoRandomNum(); // **Task 3**: Fetch a random number and a random string simultaneously, concatenate their // and print the concatenated string Promise.all([fetchRandomNumbers(), fetchRandomString()]) .then((data) => console.log(data[0] + data[1])) .catch((err) => console.error(err)); // using asunc/await const concatRandomNumAndString = async () => { try { const number = await fetchRandomNumbers(); const string = await fetchRandomString(); console.log(number + string) } catch(err){ console.error(err); } } concatRandomNumAndString(); // **Task 4**: Fetch 10 random numbers simultaneously -> and print their sum. let promiseArray = []; for (let i = 0; i < 10; i++) { promiseArray.push(fetchRandomNumbers()); } let array = Promise.all(promiseArray); array .then((data) => { const sum = data.reduce((acc, curr) => acc + curr); return sum; }) .then((sum) => console.log(sum)) .catch(error => console.error(error)); // using async/await const sumOfTenRandomNum = async () => { try { let sum = 0; for(let i = 0; i < 10; i++){ sum += await fetchRandomNumbers(); } console.log(sum); } catch(err){ console.error(err) } } sumOfTenRandomNum();
import React from 'react'; import {HashRouter as Router, Redirect, Route, Switch} from "react-router-dom"; import Films from "../views/Films"; import Cinemas from "../views/Cinemas"; import Center from "../views/Center"; import NotFound from "../views/NotFound"; import Detail from "../views/Detail"; import Login from "../views/Login"; export default function IndexRouter(props) { return ( <div> {/*<BrowserRouter>*/} <Router> {props.children} <Switch> <Route path={"/films"} component={Films}/> <Route path={"/cinemas"} component={Cinemas}/> {/*<Route path={"/center"} component={Center}/>*/} <Route path={"/center"} render={(props) => localStorage.getItem("token") ? <Center {...props}/> : <Redirect to={"/login"}/>}/> <Route path={"/login"} component={Login}/> <Route path={"/detail/:filmId"} component={Detail}/> {/*<Route path={"/detail"} component={Detail}/>*/} {/*重定向*/} <Redirect from={"/"} to={"films"} exact/> <Route component={NotFound}/> </Switch> </Router> {/*</BrowserRouter>*/} </div> ); }
<!DOCTYPE html> <html lang="en"> <head> <title>MVC</title> <meta charset="utf-8" /> </head> <body> <section> <button id="create">Create</button> <div id="createEditTask"> <form id="createForm"> <input type="text" id="taskContentInput" /> <button id="save" type="submit">Save</button> <button id="cancel" type="reset">Cancel</button> </form> </div> <ul id="taskList"></ul> </section> <style> .task { padding: 15px; border: 1px solid #eee; } .select { background-color: #eee; } </style> <script> let apiTaskList = [ { id: `${Math.random()}`, content: 'Task One', }, { id: `${Math.random()}`, content: 'Task Two', }, { id: `${Math.random()}`, content: 'Task Three', }, ]; const api = { get: (url) => { const id = url.split('/')[2]; if (id) { return apiTaskList.find((task) => task.id === id); } else { return apiTaskList; } }, post: (url, task) => { apiTaskList.push(task); }, delete: (url) => { const id = url.split('/')[2]; apiTaskList = apiTaskList.filter((task) => task.id !== id); }, update: (url, newTask) => { apiTaskList = apiTaskList.map((task) => { if (task.id === newTask.id) { return newTask; } return task; }); }, }; // MODEL - BL responsibility class TaskModel { constructor(id, content, select) { this.id = id; this.content = content; this.select = select; } changeContent = (newContent) => { if (newContent.trim().length < 5) { alert('content should be longer than 5 symbols'); return; } this.content = newContent.trim(); }; changeSelect = () => { this.select = !this.select; }; fetch = () => { const task = api.get(`/tasks/${this.id}`); this.content = task.content; }; delete = () => { api.delete(`/tasks/${this.id}`); }; save = () => { api.update(`/tasks/${this.id}`, this); }; } // MODEL - BL responsibility class TaskListModel { list = []; subscribers = []; subscribe = (callback) => { this.subscribers.push(callback); }; publish = () => { this.subscribers.forEach((sub) => sub()); }; fetch = () => { const list = api.get('/tasks'); list.forEach((task) => { this.list.push(new TaskModel(task.id, task.content, false)); }); this.publish(); }; get = () => { return this.list; }; getById = (id) => { return this.list.find((task) => task.id === id); }; create = (content) => { const task = new TaskModel(`${Math.random()}`, content, false); api.post('/tasks', task); this.list.push(task); this.publish(); }; update = (id, content) => { const task = this.list.find((task) => task.id === id); task.changeContent(content); task.save(); this.publish(); }; delete = (id) => { const task = this.list.find((task) => task.id === id); task.delete(); this.list = this.list.filter((task) => task.id !== id); this.publish(); }; select = (id) => { this.list = this.list.map((task) => { if (task.id === id) { task.changeSelect(); } return task; }); this.publish(); }; } // VIEW // . super dumb. show ui, pass events to controller class TaskPanelView { constructor(taskList, handlers) { this.taskList = taskList; this.handlers = handlers; } $createEditForm = document.getElementById('createEditTask'); $createButton = document.getElementById('create'); $cancelButton = document.getElementById('cancel'); $createForm = document.getElementById('createForm'); $taskContentInput = document.getElementById('taskContentInput'); $taskList = document.getElementById('taskList'); showCreateEditForm = () => { this.$createEditForm.style.display = 'block'; }; hideCreateEditform = () => { this.$createEditForm.style.display = 'none'; }; init = () => { this.$createButton.addEventListener('click', () => { this.handlers.onCreate(); }); this.$cancelButton.addEventListener('click', () => { this.handlers.onCancel(); }); this.$createForm.addEventListener('submit', (e) => { e.preventDefault(); this.handlers.onSubmit(); }); this.taskList.subscribe(() => { const newList = this.taskList.get(); this.render(newList); }); }; render = (tasks) => { this.$taskList.innerHTML = ''; tasks.forEach((task) => { const editId = task.id + 'edit'; const deleteId = task.id + 'delete'; const selectId = task.id + 'select'; this.$taskList.insertAdjacentHTML( 'beforeend', ` <div class="task ${task.select ? 'select' : ''}"> <div>${task.content}</div> <button id="${editId}" type="button">Edit</button> <button id="${deleteId}" type="button">Delete</button> <button id="${selectId}" type="button">Select</button> </div> ` ); document.getElementById(selectId).addEventListener('click', () => { this.handlers.onSelect(task.id); }); document.getElementById(editId).addEventListener('click', () => { this.handlers.onEdit(task.id); }); document.getElementById(deleteId).addEventListener('click', () => { this.handlers.onDelete(task.id); }); }); }; } // CONTROLLER // . ui events logics, communicates with Model class TaskPanelController { editTaskId = ''; submit = () => { const content = this.taskPanelView.$taskContentInput.value; if (!!this.editTaskId) { this.taskList.update(this.editTaskId, content); this.editTaskId = ''; this.taskPanelView.hideCreateEditform(); } else { this.taskList.create(content); } this.taskPanelView.$taskContentInput.value = ''; }; init = () => { this.taskList = new TaskListModel(); this.taskPanelView = new TaskPanelView(this.taskList, { onCreate: () => { this.taskPanelView.showCreateEditForm(); }, onCancel: () => { this.taskPanelView.hideCreateEditform(); }, onSubmit: () => { this.submit(); }, onSelect: (id) => { this.taskList.select(id); }, onEdit: (id) => { this.editTaskId = id; const task = this.taskList.getById(id); this.taskPanelView.$taskContentInput.value = task.content; this.taskPanelView.showCreateEditForm(); }, onDelete: (id) => { this.taskList.delete(id); }, }); this.taskPanelView.init(); this.taskPanelView.hideCreateEditform(); this.taskList.fetch(); }; } // controller is the main entity, which inits other after const controller = new TaskPanelController(); controller.init(); </script> </body> </html>
@model IEnumerable<MVC_Demo.Models.Student> @{ ViewData["Title"] = "Students"; } <h1>Students</h1> <p> <a asp-action="Create">Create New</a> </p> <form asp-action="Index" method="get"> <div class="form-actions no-color"> <p> Find by <select asp-items="ViewBag.CurrentSelect" name="SelectedList"> <option value="0">Name</option> <option value="1">Class</option> <option value="2">Department</option> </select> <input type="text" name="SearchString" value="@ViewData["CurrentFilter"]" /> <input type="submit" value="Search" class="btn btn-default" /> | <a asp-action="Index">Back to Full List</a> </p> </div> </form> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Class) </th> <th> @Html.DisplayNameFor(model => model.Department) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Class) </td> <td> @Html.DisplayFor(modelItem => item.Department!.DeptName) </td> <td> <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> | <a asp-action="Details" asp-route-id="@item.ID">Details</a> | <a asp-action="Delete" asp-route-id="@item.ID">Delete</a> </td> </tr> } </tbody> </table>
import React, { useState , useEffect } from 'react'; import Navbar from '../components/Navbar/Navbar'; import SearchBar from '../components/SearchBar/SearchBar'; import PropertyCard from '../components/Property/PropertyCard'; import Footer from '../components/Footer/Footer'; import './Sales.css'; import Sort from '../components/Dropdown/Sort/Sort'; import DropdownMenu from '../components/Dropdown/DRopdown'; function Sales() { const [cardItems, setCardItems] = useState([]); const [selectedType, setSelectedType] = useState(''); const [selectedSort, setSelectedSort] = useState(''); const [searchQuery, setSearchQuery] = useState(''); const handleSearchChange = (event) => { setSearchQuery(event.target.value); }; const filteredCardItems = cardItems.filter((item) => item.title.toLowerCase().includes(searchQuery.toLowerCase()) ); const fetchData = async () => { try { let url = '/properties'; const queryParams = []; if (selectedType) { queryParams.push(`type=${selectedType}`); } if (selectedSort) { queryParams.push(`sort=${selectedSort.toLowerCase()}`); } if (queryParams.length > 0) { url += `?${queryParams.join('&')}`; } const response = await fetch(url); const data = await response.json(); setCardItems(data); } catch (error) { console.error('Error fetching data:', error); } }; useEffect(() => { fetchData(); }, [selectedType, selectedSort]); return ( <> <section className="h-screen"> <Navbar /> <div className="search-bar"> <SearchBar onSearchChange={handleSearchChange} /> </div> <div className='container'> <div className='h-text text-primary uppercase text-2xl leading-8 font-inter font-semibold'> <p className='mt-6'>Real Estates</p> </div> <div className='dropdown'> <DropdownMenu setSelectedType={setSelectedType} fetchData={fetchData} /> </div> <div className='sort'> <Sort setSelectedSort={setSelectedSort} fetchData={fetchData} /> </div> </div> <PropertyCard cardItems={filteredCardItems} /> <Footer /> </section> </> ); } export default Sales;
<template> <div id="detail"> <detail-nav-bar class="detail-nav" @titleClick="titleClick" ref="nav" /> <scroll class="content" ref="scroll" :probe-type="3" @scroll="contentScroll"> <detail-swiper :top-images="topImages"/> <detail-base-info :goods="goods"/> <detail-shop-info :shop="shop"/> <detail-goods-info :detail-info="detailInfo" @imageLoad="imageLoad"/> <detail-param-info ref="params" :param-info="paramInfo"/> <detail-comment-info ref="comment" :comment-info="commentInfo"/> <goods-list ref="recommend" :goods="recommends"/> </scroll> <detail-bottom-bar @addCart="addToCart"/> <back-top @click.native="backClick" v-show="isShowBackTop"/> </div> </template> <script> import DetailNavBar from './childComps/DetailNavBar' import DetailSwiper from './childComps/DetailSwiper' import DetailBaseInfo from './childComps/DetailBaseInfo' import DetailShopInfo from './childComps/DetailShopInfo' import DetailGoodsInfo from './childComps/DetailGoodsInfo' import DetailParamInfo from './childComps/DetailParamInfo' import DetailCommentInfo from './childComps/DetailCommentInfo' import DetailBottomBar from './childComps/DetailBottomBar' import Scroll from 'components/common/scroll/Scroll' import GoodsList from 'components/content/goods/GoodsList' import {getDetail, Goods, Shop, GoodsParam, getRecommend} from "network/detail"; import {debounce} from "@/common/utils"; import {backTopMixin} from "@/common/mixin"; import { mapActions } from 'vuex' export default { name: "Detail", components:{ DetailNavBar, DetailSwiper, DetailBaseInfo, DetailShopInfo, Scroll, DetailGoodsInfo, DetailParamInfo, DetailCommentInfo, DetailBottomBar, GoodsList, }, mixins: [backTopMixin], data(){ return{ iid:null, topImages: [], goods:{}, shop:{}, detailInfo:{}, paramInfo: {}, commentInfo: {}, recommends: [], themeTopYs: [], getThemeTopY: null, currentIndex: 0, } }, created(){ //1.保存传入的iid this.iid = this.$route.params.iid; //2.根据iid请求详情数据 getDetail(this.iid).then(res =>{ //1.获取顶部的图片轮播数据 // console.log(res); const data = res.result; this.topImages = data.itemInfo.topImages; //2.获取商品信息 this.goods = new Goods(data.itemInfo, data.columns, data.shopInfo.services); //3.创建店铺信息对象 this.shop = new Shop(data.shopInfo); //4.保存商品的详情数据 this.detailInfo = data.detailInfo; //5.获取参数的信息 this.paramInfo = new GoodsParam(data.itemParams.info, data.itemParams.rule); //6.获取评论信息 if(data.rate.cRate !== 0) { this.commentInfo = data.rate.list[0] } if(data.rate.Crate !==0) { this.commentInfo = data.rate.list[0] } // this.$nextTick(() => { //渲染完成之后回调一次 // this.themeTopYs = []; // //DOM渲染完成但是图片没有加载完 // this.themeTopYs.push(0); // this.themeTopYs.push(this.$refs.params.$el.offsetTop) // this.themeTopYs.push(this.$refs.comment.$el.offsetTop) // this.themeTopYs.push(this.$refs.recommend.$el.offsetTop) // }) }); getRecommend().then(res =>{ this.recommends = res.data.list }); this.getThemeTopY = debounce(() => { this.themeTopYs = []; this.themeTopYs.push(0); this.themeTopYs.push(this.$refs.params.$el.offsetTop - 44); this.themeTopYs.push(this.$refs.comment.$el.offsetTop - 44); this.themeTopYs.push(this.$refs.recommend.$el.offsetTop - 44); this.themeTopYs.push(Number.MAX_VALUE) },100) }, methods:{ ...mapActions(['addCart']), imageLoad(){ this.$refs.scroll.refresh(); this.getThemeTopY() }, titleClick(index) { this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 200) }, contentScroll(position) { const positionY = -position.y; // console.log(positionY) let length = this.themeTopYs.length; for(let i = 0; i < length-1; i++) { if (this.currentIndex !== i && (positionY >= this.themeTopYs[i] && positionY < this.themeTopYs[i+1])) { this.currentIndex = i; // console.log(this.currentIndex); this.$refs.nav.currentIndex = this.currentIndex } } //是否显示回到顶部 this.listenIsBackTop(position) }, addToCart() { //获取购物出需要显示的信息 const product = {} product.image = this.topImages[0]; product.title = this.goods.title; product.desc = this.goods.desc; product.price = this.goods.realPrice; product.iid = this.iid; //将商品添加到购物车里 // this.$store.commit('addCart', product) this.addCart(product).then(res => { this.$toast.show(res, 2000) // console.log(this.$toast) }) //引入mapActions // this.$store.dispatch('addCart',product).then(res => { //actions.js // console.log(res); // // }) } }, mounted() { // 1.图片加载完成的事件监听 // 防抖将一页的图片多次请求变为1次在图片请求完成之后刷新(不刷新无法滚动) //$bus实在main.js里面重新创建了一个Vue实例完成父孙组件之间的事件传递 const refresh = debounce(this.$refs.scroll.refresh, 50); this.$bus.$on('detailItemImgLoad', () => { refresh() }) } } </script> <style scoped> #detail{ position: relative; z-index: 9; background-color: #fff; height: 100vh; } .detail-nav{ position: relative; z-index: 9; background-color: #fff; } .content{ overflow: hidden; /*使顶部和底部导航栏无法拖动*/ /*等于*/ height: calc(100% - 44px - 59px); /*position: absolute; top: 44px; left: 0; right: 0; bottom: 49px;*/ } </style>
import React, { useEffect, useRef } from "react"; import girlImg from "../assets/img/webp/girl-img.webp"; import Slider from "react-slick"; import { Slider__Data } from "../pagejs/DataMap"; import { Container } from "react-bootstrap"; import { gsap } from "gsap"; import { ScrollTrigger } from "gsap/ScrollTrigger"; function Lights() { gsap.registerPlugin(ScrollTrigger); useEffect(() => { setTimeout(() => { gsap .timeline({ scrollTrigger: { trigger: ".serviceslider", start: "top 40%", end: "bottom top", scrub:true, // markers: true, }, }) .fromTo( ".Img_width_Light_Custom", { opacity: 0, x: "-50%", }, { x: "0%", opacity: 1, duration: 1, ease: "power3.out", }, "-=1" ) }); }, []); const lightSlider = useRef(); const settings = { dots: false, infinite: true, speed: 500, slidesToShow: 1, autoplay: true, pauseOnHover: false, autoplaySpeed: 4000, slidesToScroll: 1, arrows: false, fade: "fade", }; return ( <> <section className="position-relative serviceslider"> <Container> <h4 className="fs_3xl ff_futura text_dark_black text-center pb-4 pb-sm-5"> <i> These are just a few examples of how Nex can be utilized across <span className="d-xl-block"> different aspects of life :</span> </i> </h4> </Container> <div id="lights" className="position-relative" style={{ background: "#FFE4C7" }} > <div className="custom_container"> <div className="row flex-column-reverse flex-lg-row align-items-center"> <div className="col-xl-7 col-lg-6"> <div className="mt-4 mt-lg-0"> <img className="Img_width_Light_Custom" src={girlImg} alt="img" /> </div> </div> <div className="col-xl-5 col-lg-6"> <Slider ref={lightSlider} {...settings}> {Slider__Data.map((data) => { return ( <div className="d-flex align-items-center flex-column align-items-lg-start serviceslider"> <h2 className="ff_futura text-center text-lg-start fw-normal light_slider_para fs_4x4l text_dark_black text-capitalize mb-2 mt-4 pt-1"> {data.heading} </h2> <p className="light_slider_para text_dark_black mb-0 mb-sm-3 ff_futura text-center text-lg-start opacity_07"> {data.paragraph} </p> </div> ); })} </Slider> <div className="d-flex align-items-center light_arrows gap-5 justify-content-center"> <span onClick={() => lightSlider.current.slickPrev()}> <svg width="26" height="48" viewBox="0 0 26 48" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M1.29297 47.0984L24 24.3928L1.29297 1.68574" stroke="#0B0A0A" strokeWidth="2" /> </svg> </span> <span onClick={() => lightSlider.current.slickNext()}> <svg width="26" height="48" viewBox="0 0 26 48" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M1.29297 47.0984L24 24.3928L1.29297 1.68574" stroke="#0B0A0A" strokeWidth="2" /> </svg> </span> </div> </div> </div> </div> </div> </section> </> ); } export default Lights;