text
stringlengths
184
4.48M
/* * Copyright (C) 2021 The Android Open Source Project * * 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. * * File changed by cvzi (cuzi-android@openmail.cc). * */ package com.google.android.renderscript import android.graphics.Bitmap import kotlin.math.min // This string is used for error messages. private const val EXTERNAL_NAME = "RenderScript Toolkit" /** * A collection of high-performance graphic utility functions like blur and blend. * * This toolkit provides ten image manipulation functions: blend, blur, color matrix, convolve, * histogram, histogramDot, lut, lut3d, resize, and YUV to RGB. These functions execute * multithreaded on the CPU. * * Most of the functions have two variants: one that manipulates Bitmaps, the other ByteArrays. * For ByteArrays, you need to specify the width and height of the data to be processed, as * well as the number of bytes per pixel. For most use cases, this will be 4. * * The Toolkit creates a thread pool that's used for processing the functions. The threads live * for the duration of the application. They can be destroyed by calling the method shutdown(). * * This library is thread safe. You can call methods from different poolThreads. The functions will * execute sequentially. * * A native C++ version of this Toolkit is available. Check the RenderScriptToolkit.h file in the * cpp directory. * * This toolkit can be used as a replacement for most RenderScript Intrinsic functions. Compared * to RenderScript, it's simpler to use and more than twice as fast on the CPU. However RenderScript * Intrinsics allow more flexibility for the type of allocation supported. In particular, this * toolkit does not support allocations of floats. */ object Toolkit { /** * Blurs an image. * * Performs a Gaussian blur of a Bitmap and returns result as a Bitmap. A variant of * this method is available to blur ByteArrays. * * The radius determines which pixels are used to compute each blurred pixels. This Toolkit * accepts values between 1 and 25. Larger values create a more blurred effect but also * take longer to compute. When the radius extends past the edge, the edge pixel will * be used as replacement for the pixel that's out off boundary. * * This method supports input Bitmap of config ARGB_8888 and ALPHA_8. Bitmaps with a stride * different than width * vectorSize are not currently supported. The returned Bitmap has the * same config. * * An optional range parameter can be set to restrict the operation to a rectangular subset * of each buffer. If provided, the range must be wholly contained with the dimensions * described by sizeX and sizeY. NOTE: The output Bitmap will still be full size, with the * section that's not blurred all set to 0. This is to stay compatible with RenderScript. * * @param inputBitmap The buffer of the image to be blurred. * @param radius The radius of the pixels used to blur, a value from 1 to 25. Default is 5. * @param restriction When not null, restricts the operation to a 2D range of pixels. * @return The blurred Bitmap. */ @JvmOverloads fun blur(inputBitmap: Bitmap, radius: Int = 5, restriction: Range2d? = null): Bitmap { validateBitmap("blur", inputBitmap) require(radius in 1..25) { "$EXTERNAL_NAME blur. The radius should be between 1 and 25. $radius provided." } validateRestriction("blur", inputBitmap.width, inputBitmap.height, restriction) val outputBitmap = createCompatibleBitmap(inputBitmap) nativeBlurBitmap(nativeHandle, inputBitmap, outputBitmap, radius, restriction) return outputBitmap } /** * Blurs an image multiple times * * For radius > 25 blurs the image repeatably with radius 25 * * @param inputBitmap The buffer of the image to be blurred. * @param radius The radius of the pixels used to blur, a value above 0. Default is 5. * @param restriction When not null, restricts the operation to a 2D range of pixels. * @return The blurred Bitmap. */ @JvmOverloads fun blurMulti(inputBitmap: Bitmap, radius: Int = 5, restriction: Range2d? = null): Bitmap { if (radius <= 25) { return blur(inputBitmap, radius, restriction) } validateBitmap("blur", inputBitmap) require(radius > 0) { "$EXTERNAL_NAME blur. The radius should be greater than 0. $radius provided." } validateRestriction("blur", inputBitmap.width, inputBitmap.height, restriction) val outputBitmap = createCompatibleBitmap(inputBitmap) nativeBlurBitmap(nativeHandle, inputBitmap, outputBitmap, 25, restriction) for (r in radius - 25 downTo 1 step 25) { nativeBlurBitmap(nativeHandle, outputBitmap, outputBitmap, min(25, r), restriction) } return outputBitmap } private var nativeHandle: Long = 0 init { System.loadLibrary("renderscript-toolkit") nativeHandle = createNative() } private external fun createNative(): Long private external fun destroyNative(nativeHandle: Long) private external fun nativeBlurBitmap( nativeHandle: Long, inputBitmap: Bitmap, outputBitmap: Bitmap, radius: Int, restriction: Range2d? ) } /** * Define a range of data to process. * * This class is used to restrict a [Toolkit] operation to a rectangular subset of the input * tensor. * * @property startX The index of the first value to be included on the X axis. * @property endX The index after the last value to be included on the X axis. * @property startY The index of the first value to be included on the Y axis. * @property endY The index after the last value to be included on the Y axis. */ data class Range2d( val startX: Int, val endX: Int, val startY: Int, val endY: Int ) internal fun validateBitmap( function: String, inputBitmap: Bitmap, alphaAllowed: Boolean = true ) { if (alphaAllowed) { require( inputBitmap.config == Bitmap.Config.ARGB_8888 || inputBitmap.config == Bitmap.Config.ALPHA_8 ) { "$EXTERNAL_NAME. $function supports only ARGB_8888 and ALPHA_8 bitmaps. " + "${inputBitmap.config} provided." } } else { require(inputBitmap.config == Bitmap.Config.ARGB_8888) { "$EXTERNAL_NAME. $function supports only ARGB_8888. " + "${inputBitmap.config} provided." } } require(inputBitmap.width * vectorSize(inputBitmap) == inputBitmap.rowBytes) { "$EXTERNAL_NAME $function. Only bitmaps with rowSize equal to the width * vectorSize are " + "currently supported. Provided were rowBytes=${inputBitmap.rowBytes}, " + "width={${inputBitmap.width}, and vectorSize=${vectorSize(inputBitmap)}." } } internal fun createCompatibleBitmap(inputBitmap: Bitmap) = Bitmap.createBitmap(inputBitmap.width, inputBitmap.height, inputBitmap.config) internal fun validateRestriction( tag: String, sizeX: Int, sizeY: Int, restriction: Range2d? = null ) { if (restriction == null) return require(restriction.startX < sizeX && restriction.endX <= sizeX) { "$EXTERNAL_NAME $tag. sizeX should be greater than restriction.startX and greater " + "or equal to restriction.endX. $sizeX, ${restriction.startX}, " + "and ${restriction.endX} were provided respectively." } require(restriction.startY < sizeY && restriction.endY <= sizeY) { "$EXTERNAL_NAME $tag. sizeY should be greater than restriction.startY and greater " + "or equal to restriction.endY. $sizeY, ${restriction.startY}, " + "and ${restriction.endY} were provided respectively." } require(restriction.startX < restriction.endX) { "$EXTERNAL_NAME $tag. Restriction startX should be less than endX. " + "${restriction.startX} and ${restriction.endX} were provided respectively." } require(restriction.startY < restriction.endY) { "$EXTERNAL_NAME $tag. Restriction startY should be less than endY. " + "${restriction.startY} and ${restriction.endY} were provided respectively." } } internal fun vectorSize(bitmap: Bitmap): Int { return when (bitmap.config) { Bitmap.Config.ARGB_8888 -> 4 Bitmap.Config.ALPHA_8 -> 1 else -> throw IllegalArgumentException( "$EXTERNAL_NAME. Only ARGB_8888 and ALPHA_8 Bitmap are supported." ) } }
import _ from 'lodash'; import * as Yup from 'yup'; const requiredNumber = Yup .number() .required() ; const requiredInteger = requiredNumber.integer(); const workHours = requiredNumber; const advantage = Yup .string() .nullable() .oneOf(['advantage', 'disadvantage', 'normal']) ; export const validationSchema = Yup.object({ projectName: Yup .string() .label('Project Name') .default('') , workableHoursInADay: requiredNumber .positive() .label('Workable Hours in a Day') .default(16) , minimumWorksHoursPerDayBeforeExhaustionSaves: requiredNumber .min(0) .label('Minimum Hours Before Exhaustion Checks') .default(8) .when('workableHoursInADay', (value, schema) => schema.max( value, (v: any) => `${v.label} can't be more than Workable Hours in a Day ` + `(${value})` ) ) , conSTMod: requiredInteger .label('Constitution Saving Throw Mod') .default(0) , allowCriticalSavingThrows: Yup .bool() .default(true) .label('Allow Critical Saving Throws') , workTimeToFinishProject: workHours .positive() .default(1) .label('Work to Finish Project') , workHoursDone: workHours .min(0) .default(0) .label('Work Hours Done') .when('workTimeToFinishProject', (value, schema) => schema.max( value, (v: any) => `${v.label} can't be more than Work Hours to Finish Project ` + `(${value})` ) ) , currentLevelOfExhaustion: requiredInteger .min(0) .max(6) .default(0) .label('Current Level of Exhaustion') , dailyExhaustionCures: requiredInteger .min(0) .default(0) .label('Daily Exhaustion Cures') , daysPassed: requiredInteger .min(0) .default(0) .label('Days Passed') , workHoursLeftInTheDay: requiredNumber .min(0) .default(16) .label('Work Hours Left in the Day') .when('workableHoursInADay', (value, schema) => schema.max( value, (v: any) => `${v.label} can't be more than Workable Hours in a Day ` + `(${value})` ) ) , hoursWorkedToday: requiredNumber .min(0) .default(0) .label('Hours Worked Today') .when('workableHoursInADay', (value, schema) => schema.max( value, (v: any) => `${v.label} can't be more than Workable Hours in a Day ` + `(${value})` ) ) , conSTadvantage: advantage .default('normal') .label('Constitution Saving Throw Advantage') , autoRest: Yup .bool() .required() .default(true) .label('Auto rest when you have exhaustion') , }).required(); type FormValues = Yup.InferType<typeof validationSchema>; export default FormValues; function getLabels() { return _.mapValues(validationSchema.fields, v => v.spec.label); } export const labels = getLabels();
import React from "react"; import { Link } from "react-router-dom"; const Product = ({ product }) => { return ( <Link to={`/product/${product.id}`}> <div className="grad w-full h-{362px} rounded-md overflow-hidden relative group"> {/*badge*/} {product.attributes.isNew ? ( <div className="absolute bg-yellow-500 text-black text-[12px] font-extrabold uppercase top-4 right-4 px-1 rounded-full z-10"> New </div> ) : ( "" )} {/* image */} <div className="w-full h-[200px] flex justify-center relative"> <img className="group-hover:scale-90 transition-all w-[160px] h-[160px]" src={`http://localhost:1337${product.attributes.image.data.attributes.url}`} alt="" /> </div> {/*text*/} <div className="px-6 pb-8 flex flex-col"> {/*category tittle*/} <div className="text-sm text-yellow-500 capitalize mb-2"> {product.attributes.categories.data[0].attributes.title} </div> {/*tittle*/} <div className="text-[15px] mb-4 lg:mb-9"> {product.attributes.title.substring(0, 35)}... </div> {/*price*/} <div className="text-xl text-yellow-500"> Rp.{product.attributes.price} /Day </div> </div> </div> </Link> ); }; export default Product;
import { useState, useEffect } from "react"; import { Menu, Layout, theme, ConfigProvider, Typography } from "antd"; import { useLocation, useNavigate } from "react-router-dom"; import { BarsOutlined, DashboardOutlined, } from "@ant-design/icons"; const { Sider } = Layout; const SideMenu = () => { const { token: {colorBgHeader}} = theme.useToken(); const location = useLocation(); const navigate = useNavigate(); const [selectedKeys, setSelectedKeys] = useState("/"); useEffect(() => { const pathName = location.pathname; setSelectedKeys(pathName); }, [location.pathname]); const items = [ { label: "Dashboard", key: "/", icon: <DashboardOutlined /> }, { label: "Reservations", key: "/reservations", icon: <BarsOutlined /> }, { label: "Room", key: "room", icon: <BarsOutlined />, children: [ { label: "types", key: "/room-type" }, { label: "lists", key: "/rooms" }, ], }, { label: "Occupation", key: "occupied-rooms", icon: <BarsOutlined />, children: [ { label: "lists", key: "/occupied-rooms" }, { label: "Histories", key: "/occupation-history" }, ], }, ]; return ( <Sider width={200} style={{ background: colorBgHeader, overflow: 'auto', height: '100vh', position: 'fixed', left: 0, top: 0, zIndex: 2, bottom: 0 }} > <ConfigProvider theme={{ components: { Menu: { itemSelectedColor: "#fff", popupBg: "#34495E", itemHoverBg: "#4A6380",} } }}> <Typography.Title style={{marginTop: '0.5em',display: 'flex',justifyContent: 'center',alignContent: 'center'}}>N</Typography.Title> <Menu onClick={({ key }) => { navigate(key); }} selectedKeys={[selectedKeys]} mode="inline" items={items} style={{background: colorBgHeader, }} /> </ConfigProvider> </Sider> ); }; export default SideMenu;
import 'package:pickafrika/data/dummy_data/brand_dummy_data.dart'; import 'package:pickafrika/utils/constants/enums.dart'; import '../../features/shop/models/product_attribute_model.dart'; import '../../features/shop/models/product_model.dart'; import '../../features/shop/models/product_variation_model.dart'; import '../../utils/constants/image_strings.dart'; class ProductDummyData { static final List<ProductModel> products = [ // PRODUCT 1 // NIKE SHOE // ProductModel( // id: '001', // stock: 20, // price: 500, // salePrice: 400, // title: 'White Air max sport', // thumbnail: PImages.productShoe7, // isFeatured: true, // description: 'Embrace ', // categoryId: '1', // productType: ProductType.variable.name, // images: [ // PImages.productShoe7, // PImages.productShoe8, // PImages.productShoe9, // PImages.productShoe10, // PImages.productShoe11, // PImages.productShoe12, // PImages.productShoe13, // PImages.productShoe14, // PImages.productShoe15, // ], // productAttributes: [ // ProductAttributeModel(name: 'Color', values: ['Pink', 'Black', 'Red']), // ProductAttributeModel( // name: 'Size', values: ['EU 32', 'EU 40', 'EU 24']), // ], // productVariations: [ // ProductVariationModel( // id: '1', // attributeValues: { // 'Color': 'Black', // 'Size': 'EU 32', // }, // stock: 5, // price: 350, // salePrice: 300, // image: PImages.productShoe7, // description: 'A product description for White Air max sports'), // ProductVariationModel( // id: '2', // attributeValues: {'Color': 'Pink', 'Size': 'EU 24'}, // stock: 5, // price: 300, // salePrice: 250, // image: PImages.productShoe10, // description: 'A product description for Pink Air max sports'), // ProductVariationModel( // id: '3', // attributeValues: {'Color': 'Brown', 'Size': 'EU 32'}, // stock: 5, // price: 350, // salePrice: 290, // image: PImages.productShoe13, // description: 'A product description for Brown Air max sports'), // ], // brand: BrandDummyData.brandModels[1], // sku: 'ABR4563', // ), // // PRODUCT 2 // ProductModel( // id: '002', // stock: 50, // price: 1000, // salePrice: 700, // title: 'Womens pretty Jacket', // thumbnail: PImages.productWomen10, // isFeatured: true, // description: 'Womens pretty Jacket', // categoryId: '1', // productType: ProductType.variable.name, // images: [], // productAttributes: [ // ProductAttributeModel(name: 'Color', values: ['Green', 'Blue', 'Pink']), // ], // productVariations: [ // ProductVariationModel( // id: '5', // attributeValues: {'Color': 'Green'}, // stock: 20, // price: 600, // salePrice: 500, // image: PImages.productWomen10, // description: 'A product description for Womens pretty gown'), // ProductVariationModel( // id: '6', // attributeValues: {'Color': 'Pink'}, // stock: 10, // price: 700, // salePrice: 600, // image: PImages.productWomen8, // description: 'A product description for Womens pretty gown'), // ProductVariationModel( // id: '7', // attributeValues: {'Color': 'Blue'}, // stock: 20, // price: 650, // salePrice: 550, // image: PImages.productWomen9, // description: 'A product description forWomens pretty gown'), // ], // brand: BrandDummyData.brandModels[6], // sku: 'ABR4563', // ), // // PRODUCT 4 // ProductModel( // id: '003', // stock: 40, // price: 600, // salePrice: 400, // title: 'White Air Jordan sport', // thumbnail: PImages.productShoe3, // isFeatured: true, // description: 'White Air max sport', // categoryId: '1', // productType: ProductType.single.name, // images: [ // PImages.productShoe3, // PImages.productShoe1, // PImages.productShoe2 // ], // productVariations: [ // // ProductVariationModel(id: '8', attributeValues: {'Size':[]}) // ], // productAttributes: [ // ProductAttributeModel( // name: 'Size', values: ['EU 32', 'EU 40', 'EU 24']), // ], // brand: BrandDummyData.brandModels[8], // sku: 'ABR4563', // ), // // PRODUCT 3 // ProductModel( // id: '004', // stock: 20, // price: 500, // salePrice: 400, // title: 'Mens kellini suit, ', // thumbnail: PImages.productMen1, // isFeatured: true, // description: 'Mens kellini suit, ', // categoryId: '1', // productType: ProductType.single.name, // images: [ // PImages.productMen2, // ], // productVariations: [], // productAttributes: [], // brand: BrandDummyData.brandModels[0], // sku: 'ABR4563', // ), // PRODUCT 4 // ProductModel( // id: '005', // stock: 20, // price: 200, // salePrice: 150, // title: 'Mens Black Jacket, ', // thumbnail: PImages.productMen3, // isFeatured: false, // description: 'Mens Black Jacket suit, ', // categoryId: '1', // productType: ProductType.single.name, // images: [ // PImages.productMen4, // ], // productVariations: [], // productAttributes: [], // brand: BrandDummyData.brandModels[0], // sku: 'ABR4563', // ), // // PRODUCT 5 // ProductModel( // id: '006', // stock: 50, // price: 1500, // salePrice: 1200, // title: 'iphone x', // thumbnail: PImages.iphone3, // isFeatured: false, // description: '', // categoryId: '1', // productType: ProductType.variable.name, // images: [PImages.iphone2, PImages.iphone4], // productAttributes: [ // ProductAttributeModel(name: 'Color', values: [ // 'Black', // 'White', // ]), // ProductAttributeModel(name: 'Type', values: [ // 'Xmas', // 'Pro', // ]), // ], // productVariations: [ // ProductVariationModel( // id: '8', // attributeValues: {'Color': 'Black', 'Type': 'Xmas'}, // stock: 20, // price: 1500, // salePrice: 1300, // image: PImages.iphone3, // description: ''), // ProductVariationModel( // id: '9', // attributeValues: {'Color': 'White', 'Type': 'Pro'}, // stock: 10, // price: 1400, // salePrice: 1200, // image: PImages.iphone1, // description: ''), // ], // brand: BrandDummyData.brandModels[7], // sku: 'ABR4563', // ), // PRODUCT 6 ProductModel( id: '007', stock: 50, price: 3500, salePrice: 3300, title: 'Macbook Air', thumbnail: PImages.macbook1, isFeatured: false, description: '', categoryId: '1', productType: ProductType.variable.name, images: [PImages.macbook2, PImages.macbook4], productAttributes: [ ProductAttributeModel(name: 'Color', values: [ 'Grey', 'White', ]), ], productVariations: [ ProductVariationModel( id: '10', attributeValues: { 'Color': 'Grey', }, stock: 20, price: 3500, salePrice: 3400, image: PImages.macbook1, description: ''), ProductVariationModel( id: '11', attributeValues: { 'Color': 'White', }, stock: 10, price: 3400, salePrice: 3300, image: PImages.macbook3, description: ''), ], brand: BrandDummyData.brandModels[7], sku: 'ABR4563', ), // PRODUCT 7 ProductModel( id: '008', stock: 50, price: 2000, salePrice: 1700, title: 'Dell superior', thumbnail: PImages.dell1, isFeatured: false, description: '', categoryId: '1', productType: ProductType.variable.name, images: [PImages.dell3, PImages.dell2], productAttributes: [ ProductAttributeModel(name: 'Color', values: [ 'Black', 'White', ]), ], productVariations: [ ProductVariationModel( id: '12', attributeValues: {'Color': 'Black'}, stock: 20, price: 2000, salePrice: 1800, image: PImages.dell4, description: ''), ProductVariationModel( id: '13', attributeValues: {'Color': 'White'}, stock: 10, price: 1900, salePrice: 1700, image: PImages.dell3, description: ''), ], brand: BrandDummyData.brandModels[7], sku: 'ABR4563', ), // PRODUCT 8 ProductModel( id: '009', stock: 20, price: 200, salePrice: 150, title: 'Retractable Chair, ', thumbnail: PImages.productChair1, isFeatured: true, description: '', categoryId: '1', productType: ProductType.single.name, images: [ PImages.productMen4, ], productVariations: [], productAttributes: [], brand: BrandDummyData.brandModels[4], sku: 'ABR4563', ), // PRODUCT 9 ProductModel( id: '010', stock: 20, price: 200, salePrice: 150, title: 'Fancy Chair, ', thumbnail: PImages.productChair2, isFeatured: true, description: '', categoryId: '1', productType: ProductType.single.name, images: [ PImages.productMen4, ], productVariations: [], productAttributes: [], brand: BrandDummyData.brandModels[4], sku: 'ABR4563', ), // PRODUCT 10 ProductModel( id: '011', stock: 50, price: 500, salePrice: 300, title: 'Headset Xp', thumbnail: PImages.headphones1, isFeatured: true, description: '', categoryId: '1', productType: ProductType.variable.name, images: [], productAttributes: [], productVariations: [ ProductVariationModel( id: '14', attributeValues: {}, stock: 20, price: 3500, salePrice: 3400, image: PImages.headphones1, description: ''), ProductVariationModel( id: '15', attributeValues: {}, stock: 10, price: 3400, salePrice: 3300, image: PImages.headphones2, description: ''), ProductVariationModel( id: '16', attributeValues: {}, stock: 10, price: 3400, salePrice: 3300, image: PImages.headphones3, description: ''), ], brand: BrandDummyData.brandModels[7], sku: 'ABR4563', ), // PRODUCT 11 ]; }
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.wait import WebDriverWait from webdriver_manager.chrome import ChromeDriverManager @pytest.fixture(scope="session") def driver(): driver_service = Service(ChromeDriverManager().install()) chrome_options = Options() chrome_options.add_argument("--headless") driver = webdriver.Chrome(service=driver_service, options=chrome_options) yield driver driver.quit() @pytest.fixture(scope="session") def wait(driver): wait = WebDriverWait(driver, 16) yield wait
package br.gasmartins.sensors.infra.persistence.repository; import br.gasmartins.sensors.infra.persistence.config.ElasticsearchConfiguration; import br.gasmartins.sensors.infra.persistence.config.ObjectMapperConfiguration; import br.gasmartins.sensors.infra.persistence.support.ElasticsearchContainerSupport; import lombok.RequiredArgsConstructor; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.elasticsearch.DataElasticsearchTest; import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer; import org.springframework.context.annotation.Import; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import static br.gasmartins.sensors.infra.persistence.support.SensorDataEntitySupport.defaultSensorDataEntity; import static org.assertj.core.api.Assertions.assertThat; @DataElasticsearchTest @Import({ElasticsearchConfiguration.class, ObjectMapperConfiguration.class}) @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @ActiveProfiles("test") @ContextConfiguration(initializers = ConfigDataApplicationContextInitializer.class) class SensorDataElasticSearchRepositoryTest extends ElasticsearchContainerSupport { private final SensorDataElasticSearchRepository repository; @Test @DisplayName("Given Sensor Data When Store Then Return Stored Sensor Data") public void givenSensorDataWhenStoreThenReturnStoredSensorData() { var sensorDataEntity = defaultSensorDataEntity().build(); var storedSensorDataEntity = this.repository.save(sensorDataEntity); assertThat(storedSensorDataEntity).isNotNull(); } @Test @DisplayName("Given Sensor Id When Exists Then Return Sensor Data") public void givenSensorIdWhenExistsThenReturnSensorData() { var sensorDataEntity = defaultSensorDataEntity().build(); this.repository.save(sensorDataEntity); var id = sensorDataEntity.getSensorId(); var optionalSensorDataEntity = this.repository.findById(id); assertThat(optionalSensorDataEntity).isPresent(); } @Test @DisplayName("Given Vehicle Id And Interval When Exists Then Return Sensor Data Page") public void givenVehicleIdAndIntervalWhenExistsThenReturnSensorDataPage() { var sensorDataEntity = defaultSensorDataEntity().build(); this.repository.save(sensorDataEntity); var id = sensorDataEntity.getSensorId(); var startOccurredOn = sensorDataEntity.getOccurredOn().minusDays(1); var endOccurredOn = startOccurredOn.plusDays(2); var pageable = PageRequest.of(0,30); var page = this.repository.findByVehicleIdAndOccurredOnBetween(id, startOccurredOn, endOccurredOn, pageable); assertThat(page).isNotNull(); } }
package com.mycompany.app; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.Assert; //import junit.framework.Assert; public class LaunchBrowserusingTestNG { public WebDriver driver; @BeforeMethod public void launchchrome() { System.setProperty("webdriver.chrome.driver","C:\\Program Files\\chromedriver_win32_v100\\chromedriver.exe"); driver=new ChromeDriver(); } @Test public void launchkite() { driver.get("https://kite.zerodha.com"); driver.manage().window().maximize(); //Here actual title has platform and not Platform so the test case will fail bcz expected and actual title are not equal String ExpectedTitle="Kite - Zerodha's fast and elegant flagship trading platform"; String ActualTitle=driver.getTitle(); Assert.assertEquals(ExpectedTitle, ActualTitle); } @Test public void CheckKiteLogo() { driver.get("https://kite.zerodha.com"); WebElement KiteLogo=driver.findElement(By.xpath("//img[contains(@src,'kite-logo.svg')]")); Assert.assertTrue(KiteLogo.isDisplayed()); } @Test public void launchFB() { driver.get("https://facebook.com"); driver.manage().window().maximize(); String ExpectedTitle="Facebook – log in or sign up"; String ActualTitle=driver.getTitle(); Assert.assertEquals(ExpectedTitle, ActualTitle); } @Test public void CheckFBLogo() { driver.get("https://facebook.com"); WebElement FBLogo=driver.findElement(By.xpath("//img[@class='fb_logo _8ilh img']")); Assert.assertTrue(FBLogo.isDisplayed()); } @Test public void launchgoogle() { driver.get("https://www.google.com/"); driver.manage().window().maximize(); String ExpectedTitle="Google"; String ActualTitle=driver.getTitle(); Assert.assertEquals(ExpectedTitle, ActualTitle); } @Test public void CheckGoogleLogo() { driver.get("https://www.google.com/"); WebElement GoogleLogo=driver.findElement(By.xpath("//img[@class='lnXdpd']")); Assert.assertTrue(GoogleLogo.isDisplayed()); } @AfterMethod() public void closechrome() { driver.close(); } //if we do not use beforemethod and aftermethod then we have to write entire code in both the test cases inside @test annotation /*@Test public void openbrowser() { System.setProperty("webdriver.chrome.driver","C:\\Program Files\\chromedriver_win32_v100\\chromedriver.exe"); driver=new ChromeDriver(); driver.get("https://kite.zerodha.com"); driver.manage().window().maximize(); driver.close(); } */ }
const router = require('express').Router(); const { Tag, Product, ProductTag } = require('../../models'); // The `/api/tags` endpoint router.get('/', async(req, res) => { // find all tags // be sure to include its associated Product data try{ const tagData = await Tag.findAll({ include: [{model:Product}] }); res.status(200).json(tagData); }catch(err){ res.status(500).json(res); } }); router.get('/:id', async(req, res) => { // find a single tag by its `id` // be sure to include its associated Product data try{ const tagData = await Tag.findByPk(req.params.id,{ include:[{model: Product}] }); res.status(200).json(tagData); }catch(err){ res.status(500).json(err); } }); router.post('/', async (req, res) => { // create a new tag try{ const tagData = await Tag.create(req.body); res.status(200).json(tagData); }catch(err){ res.status(500).json(err); } }); router.put('/:id', async(req, res) => { // update a tag's name by its `id` value try{ const tagID = await Tag.findOne({where: {tag_id : req.params.id}}); //res.status(200).json(tagID); if(!tagID){ throw Error(`Error: Tag ID ${tagID} is not updated`); } tagID.tag_name = req.body.tag_name; await tagID.save(); const tagData = await Tag.findOne({where: {tag_id : req.params.id}}); res.status(200).json(tagData); }catch(err){ res.status(500).json(err); } }); router.delete('/:id', (req, res) => { // delete on tag by its `id` value try{ Tag.destroy({ where: {tag_id:req.params.id} }).then((result) =>{ res.status(200).json({"message":"Record deleted"}); }) }catch(err){ res.status(500).json(err); } }); module.exports = router;
package homework.review_levelup; import homework.review_levelup.dao.MenuOption; import homework.review_levelup.model.Review; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; public class RatingAppl { private static final List<Review> reviews = new ArrayList<>(); private static final List<String> availableProducts = Arrays.asList("Футболка", "Платье", "Джинсы", "Куртка"); public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (true) { MenuOption.displayMenu(); int choice = scanner.nextInt(); scanner.nextLine(); switch (MenuOption.valueOf(choice)) { case DISPLAY_PRODUCTS: displayProducts(); break; case ADD_REVIEW: addReview(scanner); break; case ADD_LIKE: addLike(scanner); break; case GET_ANALYTICS: getAnalytics(); break; case EXIT: return; default: System.out.println("Неверный выбор. Попробуйте еще раз."); } } } private static void displayProducts() { System.out.println("Продукты:"); for (String product : availableProducts) { System.out.println("Продукт: " + product); // Фильтрация отзывов для данного продукта List<Review> productReviews = reviews.stream() .filter(review -> review.getProduct().equals(product)) .collect(Collectors.toList()); // Вывод отзывов и их количество лайков for (int i = 0; i < productReviews.size(); i++) { Review review = productReviews.get(i); System.out.println((i + 1) + ". Отзыв: " + review.getComment() + " Автор: " + review.getAuthor() +" | Количество лайков: " + review.getLiked()); } System.out.println(); } } // Добавление нового отзыва private static void addReview(Scanner scanner) { System.out.println("Выберите продукт:"); displayAvailableProducts(); int productChoice = scanner.nextInt(); scanner.nextLine(); System.out.println("Введите комментарий:"); String comment = scanner.nextLine(); System.out.println("Введите автора:"); String author = scanner.nextLine(); System.out.println("Введите оценку (от 1 до 10):"); int rating = scanner.nextInt(); scanner.nextLine(); if (productChoice >= 0 && productChoice < availableProducts.size()) { String product = availableProducts.get(productChoice); reviews.add(new Review(rating, comment, author, product, LocalDateTime.now())); System.out.println("Отзыв успешно добавлен!"); } else { System.out.println("Неверный выбор продукта."); } } // Постановка лайка отзыву private static void addLike(Scanner scanner) { System.out.println("Выберите продукт:"); // Печать отзывов и продуктов для выбора с использованием foreach int index = 0; for (Review review : reviews) { System.out.println(index + ". " + review.getProduct() + " - " + review.getComment()); index++; } // Запрос ввода номера отзыва System.out.println("Введите номер отзыва, к которому хотите поставить лайк:"); int reviewNumber = scanner.nextInt(); // Читаем номер отзыва scanner.nextLine(); // Считываем оставшийся перевод строки if (reviewNumber >= 0 && reviewNumber < reviews.size()) { Review review = reviews.get(reviewNumber); // Получаем отзыв по номеру review.setLiked(review.getLiked() + 1); // Увеличиваем количество лайков System.out.println("Лайк успешно поставлен!"); } else { System.out.println("Отзыва с таким номером не существует!"); } } private static void getAnalytics() { // получения статистики по отзывам Map<String, Double> avgRatingsByProduct = reviews.stream() .collect(Collectors.groupingBy(Review::getProduct, Collectors.averagingInt(Review::getRating))); Map<String, Long> reviewCountByProduct = reviews.stream() .collect(Collectors.groupingBy(Review::getProduct, Collectors.counting())); Map<String, Integer> likesByAuthor = reviews.stream() .collect(Collectors.groupingBy(Review::getAuthor, Collectors.summingInt(Review::getLiked))); displaySortedResults("Список продуктов, отсортированный по рейтингу:", getSortedProductsByRating()); displaySortedResults("Список продуктов, отсортированный по количеству отзывов:", reviewCountByProduct.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue().reversed()) .map(Map.Entry::getKey) .collect(Collectors.toList())); displaySortedResults("Список авторов, отсортированный по количеству лайков под их отзывами:", likesByAuthor.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) .map(Map.Entry::getKey) .collect(Collectors.toList())); } private static void displaySortedResults(String message, List<String> results) { System.out.println(message); results.forEach(System.out::println); } private static List<String> getSortedProductsByRating() { // список продуктов, отсортированных по рейтингу return reviews.stream() .collect(Collectors.groupingBy(Review::getProduct, Collectors.averagingInt(Review::getRating))) .entrySet().stream() .sorted(Map.Entry.<String, Double>comparingByValue().reversed()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private static void displayAvailableProducts() { System.out.println("Доступные продукты:"); for (int i = 0; i < availableProducts.size(); i++) { System.out.println(i + ". " + availableProducts.get(i)); } } }
import JobsService, { JobPriority, Job } from './jobs-service' import ResticClient, { ResticRepository } from './restic-client' import { NetworkLimit } from './application' import FnScheduler, { Schedule } from 'js-libs/fn-scheduler' import { Logger } from 'js-libs/logger' import { zipObject } from 'lodash' import httpRequest, { HttpRequestConfig } from 'js-libs/http-request' import jsonata from 'jsonata' import runProcess from 'js-libs/process' export interface RepositorySizeHttpMeasurement extends Pick<HttpRequestConfig, 'url' | 'method' | 'timeout' | 'retries' | 'outputType'> { type: 'http' jsonQuery?: string } export interface RepositorySizeAutoMeasurement { type: 'auto' } export type RepositorySizeMeasurement = RepositorySizeHttpMeasurement | RepositorySizeAutoMeasurement // | FsMeasurement => du export interface Repository extends ResticRepository { name: string check?: { schedules?: Schedule[] priority?: JobPriority } sizeMeasurement?: { schedules?: Schedule[] priority?: JobPriority } & RepositorySizeMeasurement } export interface RepositoriesSummary { [repositoryName: string]: { checkRepository: { lastEndedJob: Job<void> | undefined runningJob: Job<void> | undefined queuingJob: Job<void> | undefined nextSchedule: Date | undefined | null }, sizeMeasurement: { lastEndedJob: Job<number> | undefined } } } export default class RepositoriesService { protected jobsService: JobsService protected resticClient: ResticClient protected repositories: Repository[] protected networkLimit: NetworkLimit protected schedulers: FnScheduler[] = [] protected logger: Logger protected started: boolean = false constructor( {jobsService, resticClient, repositories, networkLimit, logger}: {jobsService: JobsService, resticClient: ResticClient, repositories: Repository[], networkLimit: NetworkLimit, logger: Logger } ) { this.jobsService = jobsService this.resticClient = resticClient this.repositories = repositories this.networkLimit = networkLimit this.logger = logger this.schedulers.push( ...this.repositories .filter((repository) => repository.check?.schedules) .map((repository) => new FnScheduler({ id: { operation: 'checkRepository', repository: repository.name }, fn: () => this.checkRepository(repository.name, 'scheduler'), logger: this.logger, schedules: repository.check!.schedules!, runOnStart: true })) ) this.schedulers.push( ...this.repositories .filter((repository) => repository.sizeMeasurement?.schedules) .map((repository) => new FnScheduler({ id: { operation: 'measureRepositorySize', repository: repository.name }, fn: () => this.measureRepositorySize(repository.name, 'scheduler'), logger: this.logger, schedules: repository.sizeMeasurement!.schedules!, runOnStart: true })) ) } public async start() { this.started = true await this.initRepositories() // Yes it can happen ! if (!this.started) { throw new Error('Interrupted start') } this.schedulers.forEach(fnSch => fnSch.start()) } public async stop() { this.started = false this.schedulers.forEach(fnSch => fnSch.stop()) } public getRepositories() { return this.repositories } public getRepository(name: string) { const repository = this.repositories.find((repo) => repo.name === name) if (!repository) { throw new Error('Unknown repository ' + name) } return repository } protected async initRepositories() { return Promise.all(this.repositories.map((repository) => this.initRepository(repository))) } protected async initRepository(repository: Repository) { try { await this.jobsService.run({ id: { trigger: null, operation: 'initRepository', subjects: { repository: repository.name } }, logger: this.logger, fn: async ({abortSignal, logger}) => { try { await this.resticClient.initRepository({ logger, abortSignal, repository, networkLimit: this.networkLimit }) } catch (e) { logger.info('Repository Init failed, probably because of already initialized (ignoring)') } } }, true) } catch {} } public checkRepository(repositoryName: string, trigger: 'scheduler' | 'api', priority?: JobPriority) { const repository = this.getRepository(repositoryName) this.jobsService.run({ priority: priority || repository.check?.priority, id: { trigger, operation: 'checkRepository', subjects: { repository: repository.name } }, logger: this.logger, fn: async ({abortSignal, logger}) => { await this.resticClient.checkRepository({ logger, abortSignal, repository, networkLimit: this.networkLimit }) } }) } public measureRepositorySize(repositoryName: string, trigger: 'scheduler' | 'api', priority?: JobPriority) { const repository = this.getRepository(repositoryName) if (!repository.sizeMeasurement) { throw new Error('Undefined sizeMeasurement on repository ' + repository.name) } this.jobsService.run<number>({ priority: priority || repository.sizeMeasurement.priority, id: { trigger, operation: 'measureRepositorySize', subjects: { repository: repository.name } }, keepResult: true, logger: this.logger, fn: async ({abortSignal, logger}) => { // Typescript cause, I don't know what to do more simple if (!repository.sizeMeasurement) { return } switch(repository.sizeMeasurement.type) { case 'http': let result: unknown = await httpRequest({outputType: 'auto', ...repository.sizeMeasurement, abortSignal, logger}) if (repository.sizeMeasurement.jsonQuery && typeof result === 'object') { result = jsonata(repository.sizeMeasurement.jsonQuery).evaluate(result) } if (typeof result === 'string' && /^[0-9]+$/.test(result)) { result = parseInt(result, 10) } if (typeof result !== 'number') { throw new Error('Expected Http result to be a number or number-like string, received ' + JSON.stringify(result)) } return result case 'auto': const { provider, container, path } = this.resticClient.explainLocation(repository.location) switch(provider) { case 'fs': const processResult: string = await runProcess({ cmd: 'du', args: ['-s', path], outputType: 'text', abortSignal, logger }, true) const cols = processResult.split('\t') return parseInt(cols[0], 10) * 1024 case 'os': if (path !== '/') { throw new Error('This sizeMeasurer only works with root bucket path') } try { const SwiftClient = require('openstack-swift-client'); const authenticator = new SwiftClient.KeystoneV3Authenticator({ endpointUrl: repository.locationParams?.authUrl, username: repository.locationParams?.username, password: repository.locationParams?.password, domainId: repository.locationParams?.projectDomainId, projectId: repository.locationParams?.projectId, regionId: repository.locationParams?.regionName }) const client = new SwiftClient(authenticator); const swiftContainers: Array<{bytes: number, name: string}> = await client.list(); //const ovhShortContainers: OvhContainer[] = await ovh.requestPromised('GET', '/cloud/project/' + encodeURIComponent(repository.locationParams?.projectId!) + '/storage') const swiftContainer = swiftContainers.find(swiftContainer => swiftContainer.name === container) if (!swiftContainer) { throw new Error('Unable to find ' + container) } return swiftContainer.bytes } catch (e) { // Swift Error are very riched on informations, sensible and cyclic ref throw new Error((e as Error).message) } default: throw new Error('Unhandled ' + provider) } default: throw new Error('We should not reach here') } } }) } public async getSummary(): Promise<RepositoriesSummary> { return zipObject( this.repositories.map(r => r.name), await Promise.all(this.repositories.map(async repository => { return { checkRepository: { lastEndedJob: await this.jobsService .findEndedJob({'id.operation': 'checkRepository', 'id.subjects.repository': repository.name}, {endedAt: -1}), runningJob: await this.jobsService .findRunningJob({'id.operation': 'checkRepository', 'id.subjects.repository': repository.name}), queuingJob: await this.jobsService .findQueuingJob({'id.operation': 'checkRepository', 'id.subjects.repository': repository.name}), nextSchedule: this.schedulers .find(scheduler => scheduler.getId().operation === 'checkRepository' && scheduler.getId().repository === repository.name) ?.getNextScheduledDate() }, sizeMeasurement: { lastEndedJob: await this.jobsService .findEndedJob({'id.operation': 'measureRepositorySize', 'id.subjects.repository': repository.name}, {endedAt: -1}) } } })) ) } } // public async getRepositoriesStats() { // const sharedResolutions: any = { // size: {}, // billing: {} // } // // TODO refacto and call parallel // const getStat = async (statConfig: StatFetch) => { // if (statConfig.type !== 'http') { // throw new Error('Only http implemented') // } // return Math.round(Math.random() * 100) // // const request = got({ // // method: statConfig.method as GotMethod || 'GET', // // url: statConfig.url, // // timeout: statConfig.timeout ? durationToSeconds(statConfig.timeout) * 1000 : undefined, // // retry: statConfig.retries || 0, // // hooks: { // // beforeRequest: [options => {this.logger.info('Calling stat ' + options.url)}], // // afterResponse: [response => { this.logger.info('Stat returned code ' + response.statusCode) ; return response }], // // beforeError: [error => { this.logger.info('Stat returned error ' + error.message) ; return error }] // // } // // }) // // return request.json() // } // return await asyncReduce(Object.keys(this.config.repositories), async (stats, repositoryName) => { // const repositoryStatsConf = this.config.repositories[repositoryName].stats // return {...stats, ...{ // [repositoryName]: { // size: repositoryStatsConf && repositoryStatsConf.size ? { // value: await (async () => { // if (repositoryStatsConf.size.shareName && sharedResolutions.size[repositoryStatsConf.size.shareName]) { // return sharedResolutions.size[repositoryStatsConf.size.shareName] // } // const resolver = getStat(repositoryStatsConf.size) // if (repositoryStatsConf.size.shareName) { // sharedResolutions.size[repositoryStatsConf.size.shareName] = resolver // } // return resolver // })(), // shareName: repositoryStatsConf.size.shareName // } : null, // billing: repositoryStatsConf && repositoryStatsConf.billing ? { // value: await (async () => { // if (repositoryStatsConf.billing.shareName && sharedResolutions.billing[repositoryStatsConf.billing.shareName]) { // return sharedResolutions.billing[repositoryStatsConf.billing.shareName] // } // const resolver = getStat(repositoryStatsConf.billing) // if (repositoryStatsConf.billing.shareName) { // sharedResolutions.billing[repositoryStatsConf.billing.shareName] = resolver // } // return resolver // })(), // currency: repositoryStatsConf.billing.currency, // shareName: repositoryStatsConf.billing.shareName // } : null // } // }} // }, {}) // }
"use client"; import { cmsContract } from "@/cms-shared/api"; import { UpdateSourceBodySchema } from "@/cms-shared/validation"; import { Button } from "@/ui-shared/components/button"; import { FormCheckbox } from "@/ui-shared/components/checkbox"; import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/ui-shared/components/dialog"; import { DefaultValues } from "@/ui-shared/components/form"; import { FormInput } from "@/ui-shared/components/input"; import { FormSelect, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue, } from "@/ui-shared/components/select"; import { toast } from "@/ui-shared/components/toaster"; import { ClientInferRequest, ClientInferResponses } from "@ts-rest/core"; import { FC, useState } from "react"; import { useUpdateSourceForm } from "./hooks"; export type UpdateSourceProps = { defaultValues: DefaultValues<UpdateSourceBodySchema>; handleUpdateSource: ( data: ClientInferRequest<typeof cmsContract.sources.update>["body"], ) => Promise<ClientInferResponses<typeof cmsContract.sources.update>>; }; export const UpdateSource: FC<UpdateSourceProps> = ({ defaultValues, handleUpdateSource }) => { const { control, handleSubmit, reset } = useUpdateSourceForm(defaultValues); const [isDialogOpened, setIsDialogOpened] = useState(false); const handleFormSubmit = handleSubmit(async data => { const response = await handleUpdateSource(data); setIsDialogOpened(false); if (response.status === 200) { toast({ description: `Updated ${response.body.name} source`, title: "Success!", }); } else { toast({ description: response.body.message, title: "Error!", }); } reset(); }); return ( <Dialog onOpenChange={setIsDialogOpened} open={isDialogOpened}> <DialogTrigger asChild> <Button variant="outline">Update</Button> </DialogTrigger> <DialogContent className="sm:max-w-[512px]"> <form onSubmit={handleFormSubmit}> <DialogHeader> <DialogTitle>Update Source</DialogTitle> </DialogHeader> <FormInput containerClassName="mt-4" control={control} label="Name" name="name" /> <FormInput containerClassName="mt-4" control={control} label="URL" name="url" /> <FormInput containerClassName="mt-4" control={control} label="Key to description" name="descriptionKey" /> <FormInput containerClassName="mt-4" control={control} label="Key to id" name="idKey" /> <FormInput containerClassName="mt-4" control={control} label="Key to imageLink" name="imageLinkKey" /> <FormInput containerClassName="mt-4" control={control} label="Key to link" name="linkKey" /> <FormInput containerClassName="mt-4" control={control} label="Key to publicationDate" name="publicationDateKey" /> <FormInput containerClassName="mt-4" control={control} label="Key to title" name="titleKey" /> <FormSelect containerClassName="mt-4" control={control} label="Periodicity" name="periodicity" > <SelectTrigger> <SelectValue placeholder="Select periodicity" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectItem value="DAILY">Daily</SelectItem> <SelectItem value="HOURLY">Hourly</SelectItem> </SelectGroup> </SelectContent> </FormSelect> <FormCheckbox containerClassName="mt-4" control={control} label="Is active" name="isActive" /> <DialogFooter className="mt-3"> <Button className="w-full max-w-44" type="submit"> Update </Button> </DialogFooter> </form> </DialogContent> </Dialog> ); };
import React, { useState } from 'react'; import FlightList from './FlightList'; import FlightServiceRest from '../services/FlightServiceRest'; import search from '../assets/logo/magnifying-glass.png'; const SearchFlight = () => { const service = new FlightServiceRest(); const [source, setSource] = useState(''); const [destination, setDestination] = useState(''); const [travelDate, setTravelDate] = useState(''); const [searched, setSearched] = useState(false); const [flights, setFlights] = useState([]); const handleInput = (event) => { const { name, value } = event.target; if (name === 'source') { setSource(value); } else if (name === 'destination') { setDestination(value); } else if (name === 'travelDate') { setTravelDate(value); } }; const getFlightsList = () => { setSearched(false); service.getFlightsForUser(source, destination, travelDate).then(data => { if (data.length > 0) { setFlights(data); setSearched(true); } else { alert('No Flights Found!!'); } }); }; return ( <div className="container-fluid p-4 m-3"> <h2 style={styling.heading}>Search your flight</h2> <div className="form-inline"> <div className="input-group mb-2 mr-sm-2"> {/* <!-- Drop down for source --> */} <select className="custom-select my-1 mr-sm-2" name="source" value={source} onChange={handleInput} required> {/* ... options */} <option value="Chennai">Chennai</option> <option value="Chennai" onClick={handleInput}>Chennai</option> <option value="Delhi" onClick={handleInput}>Delhi</option> <option value="Mumbai" onClick={handleInput}>Mumbai</option> <option value="Kolkata" onClick={handleInput}>Kolkata</option> <option value="Goa" onClick={handleInput}>Goa</option> <option value="Pune" onClick={handleInput}>Pune</option> <option value="Jaipur" onClick={handleInput}>Jaipur</option> <option value="Bangalore" onClick={handleInput}>Bangalore</option> <option value="Cochin" onClick={handleInput}>Cochin</option> <option value="Ahmadabad" onClick={handleInput}>Ahmadabad</option> </select> </div> {/* ... other dropdowns and input */} <div className="input-group mb-2 mr-sm-2"> {/* Drop down for destination */} <select className="custom-select my-1 mr-sm-2" name="destination" value={destination} onChange={handleInput} required> <option value="Chennai" onClick={handleInput}>Chennai</option> <option value="Delhi" onClick={handleInput}>Delhi</option> <option value="Mumbai" onClick={handleInput}>Mumbai</option> <option value="Kolkata" onClick={handleInput}>Kolkata</option> <option value="Goa" onClick={handleInput}>Goa</option> <option value="Pune" onClick={handleInput}>Pune</option> <option value="Jaipur" onClick={handleInput}>Jaipur</option> <option value="Bangalore" onClick={handleInput}>Bangalore</option> <option value="Cochin" onClick={handleInput}>Cochin</option> <option value="Ahmadabad" onClick={handleInput}>Ahmadabad</option> </select> </div> <div className="input-group mb-2 mr-sm-2"> {/* Input for travel date */} <input className="my-1 p-2 border border-darken-2 rounded" type="date" value={travelDate} name="travelDate" onChange={handleInput} defaultValue={Date.now()} required /> </div> <button onClick={getFlightsList} className="btn mb-2 mr-sm-2" style={styling.icon}> <img src={search} height="25" alt="Search" /> </button> </div> {searched && <FlightList flights={flights} />} </div> ); }; const styling = { heading: { color: "midnightblue", fontFamily: "fantasy", marginBottom: 20 }, icon: { background: "skyblue" } }; export default SearchFlight;
import { CartWidget } from "./CartWidget/CartWidget"; import { Boxes } from "react-bootstrap-icons"; import Container from "react-bootstrap/Container"; import Nav from "react-bootstrap/Nav"; import Navbar from "react-bootstrap/Navbar"; import NavDropdown from "react-bootstrap/NavDropdown"; import { Link } from "react-router-dom"; import { useGetCategories } from "../../hooks/useProducts"; function NavbarComponent() { const { categories } = useGetCategories(); return ( <Navbar expand="sm" fixed="top" className="bg-body-tertiary"> <Container> <Link className="me-3 link-dark link-underline-opacity-0" to="/"> <Boxes /> 3D2 </Link> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="me-auto"> <NavDropdown title="Productos" id="basic-nav-dropdown"> {categories.map((item, index) => { return ( <NavDropdown.Item key={index}> <Link to={`/category/${item}`}>{item}</Link> </NavDropdown.Item> ); })} </NavDropdown> </Nav> </Navbar.Collapse> <Link to="/Cart"> <CartWidget /> </Link> </Container> </Navbar> ); } export default NavbarComponent;
import React from 'react'; import Header from '../components/Header'; import RootContainer from '../components/RootContainer'; import PerbaruiField from '../components/perbarui_member/PerbaruiField'; import ConfirmButton from '../components/perbarui_member/ConfirmButton'; import firestore from '@react-native-firebase/firestore'; import RNFS from 'react-native-fs'; import DocumentPicker from 'react-native-document-picker'; import BottomSpace from '../components/BottomSpace'; import {Alert} from 'react-native'; import auth from '@react-native-firebase/auth'; import storage from '@react-native-firebase/storage'; import DisplayBukti from '../components/member/DisplayBukti'; import ModalLoader from '../components/ModalLoader'; interface PerbaruiMember { navigation: any; route: any; } const PerbaruiMember = ({navigation, route}: PerbaruiMember) => { const {id} = route.params; const [dataGOR, setDataGOR] = React.useState<any>({}); const [dataUser, setDataUser] = React.useState<any>({}); const [buktiPembayaran, setBuktiPembayaran] = React.useState(null); const [isLoading, setIsLoading] = React.useState(false); const fetchGOR = React.useCallback(async () => { try { const query = await firestore().collection('gor').doc(id).get(); const data = query.data(); setDataGOR(data); } catch (error) { console.log(error); } }, [id]); const fetchUser = React.useCallback(async () => { try { const query = await firestore().collection('users').doc(id).get(); const data = query.data(); setDataUser(data); } catch (error) { console.log(error); } }, [id]); React.useEffect(() => { fetchGOR(); fetchUser(); }, [fetchGOR, fetchUser]); const uploadFile = async () => { try { const res = await DocumentPicker.pickSingle({ type: [DocumentPicker.types.images, DocumentPicker.types.pdf], }); const selectedFile = res.uri; const selectedFileName = res.name; const fileType = res.type; console.log({ selectedFile, selectedFileName, fileType, }); const fileData = await RNFS.readFile(selectedFile, 'base64'); setBuktiPembayaran({ data: `data:${fileType};base64,${fileData}`, type: fileType, uri: selectedFile, name: selectedFileName, }); } catch (err) { if (DocumentPicker.isCancel(err)) { console.info(err); } else { throw err; } } }; const handlePembayaranMember = async () => { setIsLoading(true); if (!buktiPembayaran) { Alert.alert( 'Perbarui Member gagal', 'Upload bukti pembayaran terlebih dahulu', ); setIsLoading(false); return; } try { const user = auth().currentUser; const buktiPembayaranFileName = `buktiPembayaran/${ user?.uid }/buktiPembayaran${user?.uid}/${new Date().getTime()}`; const buktiPembayaranReference = storage().ref(buktiPembayaranFileName); const buktiPembayaranFilePath = `${RNFS.DocumentDirectoryPath}/${buktiPembayaran}`; if (buktiPembayaran) { await RNFS.copyFile(buktiPembayaran.uri, buktiPembayaranFilePath); } const buktiPembayaranBlob = await RNFS.readFile( buktiPembayaranFilePath, 'base64', ); await buktiPembayaranReference.putString(buktiPembayaranBlob, 'base64'); const buktiPembayaranURL = await buktiPembayaranReference.getDownloadURL(); const date = new Date(); const month = date.toLocaleString('id-ID', { month: 'long', year: 'numeric', }); if (buktiPembayaranURL) { const userUidSubstring = user?.uid.substring(0, 10); const gorUidSubstring = dataGOR.user_uid.substring(0, 10); const docId = `${userUidSubstring}${gorUidSubstring}`; const memberRef = firestore().collection('member').doc(docId); memberRef.set({ createdAt: firestore.FieldValue.serverTimestamp(), gor_uid: dataGOR.user_uid, user_uid: user?.uid, masaAktif: month, member_uid: docId, jumlahPembayaran: dataGOR.hargaMember, buktiPembayaran: buktiPembayaranURL, status: 'Menunggu Aktivasi', namaLengkap: dataUser.namaLengkap, }); const notifikasiRef = firestore().collection('notifikasi'); await notifikasiRef.add({ createdAt: firestore.FieldValue.serverTimestamp(), user_uid: dataGOR.user_uid, title: 'Terdapat Member Melakukan Pembayaran', pesan: 'Anda memiliki member baru yang perlu diaktivasi', member_uid: docId, }); } else { console.log('Failed to upload bukti pembayaran'); } } catch (error) { console.log(error); } finally { setIsLoading(false); Alert.alert( 'Berhasil mengirim bukti pembayaran', 'Mohon menunggu member anda diaktivasi oleh pemilik GOR', [ { text: 'OK', onPress: () => navigation.navigate('Home'), }, ], ); } }; return ( <> <RootContainer backgroundColor="white"> <Header title="Perbarui Member" /> <PerbaruiField data={dataGOR} dataUser={dataUser} onPress={uploadFile} /> <DisplayBukti buktiPembayaran={buktiPembayaran} /> <ConfirmButton onPress={handlePembayaranMember} /> <BottomSpace marginBottom={40} /> <ModalLoader isLoading={isLoading} /> </RootContainer> </> ); }; export default PerbaruiMember;
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const dotenv_1 = __importDefault(require("dotenv")); dotenv_1.default.config(); const screat_key = process.env.JWT_SCREAT_KEY; if (!screat_key) { process.exit(1); } const authenticationMiddleWare = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { const token = req.headers.authorization; // check if token is present if (!token) { return res.status(401).json({ "Authentication Error": "User is not authenticated" }); } // if present verify the token const verfication = yield jsonwebtoken_1.default.verify(token, screat_key, (err, decoded) => { if (err) { console.log(err); res.status(401).json({ "Authentication Error": "The token is invalid !" }); } else { if (decoded) { // req.user = decoded; next(); } else { res.status(401).json({ "Authentication Error": "Unknown auth error" }); } } }); // if(!verfication){ // return res.status(401).json({"Authentication Error": "User is not authenticated"}); // } else { // next(); // } }); exports.default = authenticationMiddleWare;
import { useState } from "react"; interface Props{ listGroupItems: string[]; heading: string; onSelectItem: (item: string) => void; } const ListGroup = ({listGroupItems, heading, onSelectItem}: Props) => { const [selectedItem, setSelectedItem] = useState(0); // listGroupItems = [] return ( <> <h1>{heading}</h1> <p> Use the Bootstrap List Group component to display a series of content. </p> {listGroupItems.length === 0 && <p>No items to display</p>} <ul className="list-group"> {listGroupItems.map((item, index) => ( <li key={item} onClick={() => { setSelectedItem(index); onSelectItem(item); }} className={ selectedItem === index ? "list-group-item active" : "list-group-item" } > {item} </li> ))} </ul> </> ); }; export default ListGroup;
const User = require('../models/user'); const RefreshToken = require('../models/refreshToken'); const jwt = require('jsonwebtoken'); const { errorHandler } = require('../helpers/errorHandler'); require('dotenv').config(); exports.signup = (req, res) => { const { firstname, lastname, email, phone, password } = req.body; const user = new User({ firstname, lastname, email, phone, password }); user.save((error, user) => { if (error || !user) { return res.status(400).json({ error: errorHandler(error), }); } return res.json({ success: 'Đăng ký thành công, bạn có thể đăng nhập ngay bây giờ', }); }); }; exports.signin = (req, res, next) => { const { email, phone, password } = req.body; User.findOne({ $or: [ { email: { $exists: true, $ne: null, $eq: email }, }, { phone: { $exists: true, $ne: null, $eq: phone }, }, ], }) .exec() .then((user) => { if (!user) { return res.status(404).json({ error: 'Tài khoản không tồn tại', }); } if (!user.authenticate(password)) { return res.status(401).json({ error: "Mật khẩu không khớp", }); } //create token req.auth = user; next(); }) .catch((error) => { res.status(404).json({ error: 'Tài khoản không tồn tại', }); }); }; exports.createToken = (req, res) => { const user = req.auth; const accessToken = jwt.sign( { _id: user._id }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '168h' }, ); // process.env.ACCESS_TOKEN_SECRET = accessToken const refreshToken = jwt.sign( { _id: user._id }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '9999 days' }, ); // process.env.REFRESH_TOKEN_SECRET = refreshToken const token = new RefreshToken({ jwt: refreshToken }); token.save((error, t) => { if (error) { return res.status(500).json({ error: 'Tạo JWT thất bại, vui lòng đăng nhập lại', }); } return res.json({ success: 'Đăng nhập thành công', accessToken, refreshToken, _id: user._id, role: user.role, }); }); }; exports.signout = (req, res) => { const refreshToken = req.body.refreshToken; if (refreshToken == null) return res.status(401).json({ error: 'refreshToken là bắt buộc' }); RefreshToken.deleteOne({ jwt: refreshToken }) .exec() .then(() => { return res.json({ success: 'Đăng xuất thành công', }); }) .catch((error) => { return res.status(500).json({ error: 'Đăng xuất và xóa refresh token thất bại', }); }); }; exports.refreshToken = (req, res) => { const refreshToken = req.body.refreshToken; if (refreshToken == null) return res.status(401).json({ error: 'refreshToken là bắt buộc' }); RefreshToken.findOne({ jwt: refreshToken }) .exec() .then((token) => { if (!token) { return res.status(404).json({ error: 'refreshToken không có hiệu lực', }); } else { const decoded = jwt.decode(token.jwt); const accessToken = jwt.sign( { _id: decoded._id }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '168h' }, ); const newRefreshToken = jwt.sign( { _id: decoded._id }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '9999 days' }, ); RefreshToken.findOneAndUpdate( { jwt: refreshToken }, { $set: { jwt: newRefreshToken } }, ) .exec() .then((t) => { if (!t) { return res.status(500).json({ error: 'Tạo JWT thất bại, thử lại sau', }); } return res.json({ success: 'Refresh token thành công', accessToken, refreshToken: newRefreshToken, }); }) .catch((error) => { return res.status(500).json({ error: 'Tạo JWT thất bại, thử lại sau', }); }); } }) .catch((error) => { return res.status(401).json({ error: 'refreshToken không có hiệu lực', }); }); }; exports.forgotPassword = (req, res, next) => { const { email, phone } = req.body; const forgot_password_code = jwt.sign( { email, phone }, process.env.JWT_FORGOT_PASSWORD_SECRET, ); // process.env.JWT_FORGOT_PASSWORD_SECRET = forgot_password_code User.findOneAndUpdate( { $or: [ { email: { $exists: true, $ne: null, $eq: email } }, { phone: { $exists: true, $ne: null, $eq: phone } }, ], }, { $set: { forgot_password_code } }, { new: true }, ) .exec() .then((user) => { if (!user) { return res.status(404).json({ error: 'Tài khoản không tồn tại', }); } //send email or phone const msg = { email: email ? email : '', phone: phone ? phone : '', name: user.firstname + ' ' + user.lastname, title: 'Yêu cầu thay đổi mật khẩu', text: 'Vui lòng nhấp vào liên kết sau để thay đổi mật khẩu của bạn.', code: forgot_password_code, }; req.msg = msg; next(); return res.json({ success: 'Yêu cầu thành công, chờ email', }); }) .catch((error) => { return res.status(404).json({ error: 'Tài khoản không tồn tại', }); }); }; exports.changePassword = (req, res) => { const forgot_password_code = req.params.forgotPasswordCode; const { password } = req.body; User.findOneAndUpdate( { forgot_password_code: forgot_password_code }, { $unset: { forgot_password_code: '' } }, ) .then((user) => { if (!user) { return res.status(404).json({ error: 'Tài khoản không tồn tại', }); } user.hashed_password = user.encryptPassword(password, user.salt); user.save((e, u) => { if (e) { // console.log(e) return res.status(500).json({ error: 'Cập nhật mật khẩu không thành công, vui lòng yêu cầu gửi lại thư', }); } return res.json({ success: 'Cập nhật mật khẩu thành công', }); }); }) .catch((error) => { return res.status(404).json({ error: 'Tài khoản không tồn tại', }); }); }; //check current password exports.verifyPassword = (req, res, next) => { const { currentPassword } = req.body; User.findById(req.user._id, (error, user) => { if (error || !user) { return res.status(404).json({ error: 'Tài khoản không tồn tại', }); } if (!user.authenticate(currentPassword)) { return res.status(401).json({ error: "Mật khẩu hiện tại không khớp", }); } else next(); }); }; exports.isAuth = (req, res, next) => { if ( req.headers && req.headers.authorization && req.headers.authorization.split(' ')[1] ) { const token = req.headers.authorization.split(' ')[1]; jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (error, decoded) => { if (error) { return res.status(401).json({ error: 'Không được phép! Vui lòng đăng nhập lại', }); } if (req.user._id == decoded._id) { next(); } else { return res.status(403).json({ error: 'Quyền truy cập bị từ chối', }); } }); } else { return res.status(401).json({ error: 'Không có mã token nào được cung cấp! Vui lòng đăng nhập lại', }); } }; //owner and staff of store exports.isManager = (req, res, next) => { if ( !req.user._id.equals(req.store.ownerId) && req.store.staffIds.indexOf(req.user._id) == -1 ) { return res.status(403).json({ error: 'Tài nguyên quản lý cửa hàng! Quyền truy cập bị từ chối', isManager: false, }); } next(); }; exports.isOwner = (req, res, next) => { if (!req.user._id.equals(req.store.ownerId)) { return res.status(403).json({ error: 'Tài nguyên của chủ cửa hàng! Quyền truy cập bị từ chối', isOwner: false, }); } else next(); }; exports.isAdmin = (req, res, next) => { if (req.user.role !== 'admin') { return res.status(403).json({ error: 'Tài nguyên quản trị viên! Quyền truy cập bị từ chối', }); } next(); };
package com.cs29.api.dtos; import com.cs29.api.models.Entry; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.Builder; import lombok.Data; import lombok.NonNull; import lombok.experimental.Accessors; import org.springframework.data.annotation.Id; import java.util.List; @Data @Builder @Accessors(chain = true) @JsonDeserialize(builder = EntryDto.EntryDtoBuilder.class) @JsonInclude(value = JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class EntryDto { @Id @JsonProperty("entry_id") @NonNull private String entryId; @JsonProperty("office_id") @NonNull private String officeId; @JsonProperty("tag") @NonNull private String tag; @JsonProperty("consumption") private double consumption; @JsonProperty("original") private double original; @JsonProperty("converted") private double converted; @JsonProperty("source") @NonNull private String source; @JsonProperty("units") @NonNull private String units; @JsonProperty("level1") private String level1; @JsonProperty("level2") private String level2; @JsonProperty("level3") private String level3; @JsonProperty("level4") private String level4; @JsonProperty("further_info") private String furtherInfo; @JsonProperty("percentage") private double percentage; @JsonProperty("components") private List<Entry> components; }
import * as React from "react"; import * as css from "./CL4R.scss"; import gql from "graphql-tag"; import Loading from "components/Shared/Loading"; import withSubscription, { ISubscriptionProps } from "components/Shared/withSubscription"; import { getArcByDAOAddress, standardPolling, getNetworkByDAOAddress, toWei, ethErrorHandler, fromWei, formatTokens } from "lib/util"; import { Address, CL4RScheme, IDAOState, ISchemeState, Token } from "@daostack/arc.js"; import { RouteComponentProps } from "react-router-dom"; import LockRow from "./LockRow"; import PeriodRow from "./PeriodRow"; import * as classNames from "classnames"; import * as moment from "moment"; import Countdown from "components/Shared/Countdown"; import { first } from "rxjs/operators"; import { combineLatest, of } from "rxjs"; import { enableWalletProvider } from "arc"; import { lock, releaseLocking, extendLocking, redeemLocking, approveTokens } from "@store/arc/arcActions"; import { showNotification } from "@store/notifications/notifications.reducer"; import { connect } from "react-redux"; import Tooltip from "rc-tooltip"; import { calculateTotalRedeemedAmount, getCL4RParams, getLockingIdsForRedeem, ICL4RParams } from "./CL4RHelper"; import BN from "bn.js"; import humanizeDuration from "humanize-duration"; interface IDispatchProps { lock: typeof lock; releaseLocking: typeof releaseLocking; extendLocking: typeof extendLocking; redeemLocking: typeof redeemLocking; showNotification: typeof showNotification; approveTokens: typeof approveTokens; } const mapDispatchToProps = { lock, releaseLocking, extendLocking, redeemLocking, showNotification, approveTokens, }; type SubscriptionData = [any, BN, BN]; type IProps = IExternalProps & ISubscriptionProps<SubscriptionData> & IDispatchProps; type IExternalProps = { daoState: IDAOState; scheme: ISchemeState; onCreateProposal: () => void; currentAccountAddress: Address; } & RouteComponentProps<any>; const CL4R = (props: IProps) => { const { data, daoState, currentAccountAddress } = props; const [loading, setLoading] = React.useState(true); const [schemeParams, setSchemeParams] = React.useState({} as ICL4RParams); const [showYourLocks, setShowYourLocks] = React.useState(false); const [lockDuration, setLockDuration] = React.useState(1); const [lockAmount, setLockAmount] = React.useState(0); const [cl4rScheme, setCL4RScheme] = React.useState<CL4RScheme>(); const [isLocking, setIsLocking] = React.useState(false); const [isApprovingToken, setIsApprovingToken] = React.useState(false); const [isRedeeming, setIsRedeeming] = React.useState(false); const [currentTime, setCurrentTime] = React.useState(moment().unix()); const isAllowance = data[1]?.gt(new BN(0)); const isEnoughBalance = fromWei(data[2]) >= lockAmount; const cl4Rlocks = (data as any)[0].data?.cl4Rlocks ?? []; const [redeemableAmount, setRedeemableAmount] = React.useState(0); React.useEffect(() => { setRedeemableAmount(0); }, [currentAccountAddress]); const isLockingStarted = React.useMemo(() => { return (moment().isAfter(moment.unix(Number(schemeParams.startTime)))); }, [schemeParams]); const endTime = React.useMemo(() => { return Number(schemeParams.startTime) + (schemeParams.batchTime * schemeParams.batchesIndexCap); }, [schemeParams]); const isLockingEnded = React.useMemo(() => { return (moment().isAfter(moment.unix(endTime))); }, [schemeParams, currentTime]); const handleRelease = React.useCallback(async (lockingId: number, setIsReleasing: any) => { if (!await enableWalletProvider({ showNotification: props.showNotification }, getNetworkByDAOAddress(daoState.address))) { return; } props.releaseLocking(cl4rScheme, currentAccountAddress, lockingId, setIsReleasing); }, [cl4rScheme, currentAccountAddress]); const handleExtend = React.useCallback(async (extendPeriod: number, batchIndexToLockIn: number, lockingId: number, setIsExtending: any) => { if (!await enableWalletProvider({ showNotification: props.showNotification }, getNetworkByDAOAddress(daoState.address))) { return; } props.extendLocking(cl4rScheme, extendPeriod, batchIndexToLockIn, lockingId, schemeParams.agreementHash, setIsExtending); }, [cl4rScheme, schemeParams, currentAccountAddress]); const handleRedeem = React.useCallback(async (lockingIds: number[], setIsRedeeming: any) => { if (!await enableWalletProvider({ showNotification: props.showNotification }, getNetworkByDAOAddress(daoState.address))) { return; } props.redeemLocking(cl4rScheme, currentAccountAddress, lockingIds, setIsRedeeming, setRedeemableAmount); }, [cl4rScheme, schemeParams, currentAccountAddress]); const handleTokenApproving = React.useCallback(async () => { if (!await enableWalletProvider({ showNotification: props.showNotification }, getNetworkByDAOAddress(daoState.address))) { return; } props.approveTokens(props.scheme.address, getArcByDAOAddress(daoState.address), schemeParams.token, schemeParams.tokenSymbol, setIsApprovingToken); }, [schemeParams]); React.useEffect(() => { const getSchemeInfo = async () => { const arc = getArcByDAOAddress(daoState.id); setSchemeParams(await getCL4RParams(daoState.id, props.scheme.id)); const schemes = await arc.schemes({ where: { id: props.scheme.id.toLowerCase() } }).pipe(first()).toPromise(); setCL4RScheme(schemes[0].CTL4R as CL4RScheme); setLoading(false); }; getSchemeInfo(); }, []); const redeemedAmount = React.useMemo(() => { return calculateTotalRedeemedAmount(cl4Rlocks); }, [schemeParams, cl4Rlocks]); const durations = [] as any; for (let duration = 1; duration <= schemeParams.maxLockingBatches; duration++) { if (moment().unix() + (duration * schemeParams.batchTime) <= endTime) { durations.push(<option key={duration} value={duration} selected={duration === 1}>{duration}</option>); } } const startTime = Number(schemeParams.startTime); const timeElapsed = currentTime - startTime; const currentLockingBatch = isLockingEnded ? schemeParams.batchesIndexCap : Math.trunc(timeElapsed / schemeParams.batchTime); const nextBatchStartTime = moment.unix(startTime + ((currentLockingBatch + 1) * schemeParams.batchTime)); const redeemable = moment().isSameOrAfter(moment.unix(Number(schemeParams.redeemEnableTime))); const handleLock = React.useCallback(async () => { if (!await enableWalletProvider({ showNotification: props.showNotification }, getNetworkByDAOAddress(daoState.address))) { return; } props.lock(cl4rScheme, toWei(Number(lockAmount)), lockDuration, currentLockingBatch, schemeParams.agreementHash, setIsLocking); }, [cl4rScheme, lockAmount, lockDuration, currentLockingBatch]); const allLockingIdsForRedeem = React.useMemo(() => { return getLockingIdsForRedeem(cl4Rlocks, currentLockingBatch, schemeParams.startTime, schemeParams.batchTime); }, [cl4Rlocks, currentAccountAddress, currentTime, schemeParams]); const periods = []; for (let period = 0; period <= currentLockingBatch; period++) { periods.push(<PeriodRow key={period} period={period} schemeParams={schemeParams} lockData={cl4Rlocks} cl4rScheme={cl4rScheme} currentLockingBatch={currentLockingBatch} isLockingEnded={isLockingEnded} redeemableAmount={redeemableAmount} setRedeemableAmount={setRedeemableAmount} />); } if (isLockingEnded) { periods.splice(-1, 1); } periods.reverse(); const lockings = (cl4Rlocks?.map((lock: any) => { return <LockRow key={lock.id} schemeParams={schemeParams} lockData={lock} handleRelease={handleRelease} handleExtend={handleExtend} endTime={endTime} currentLockingBatch={currentLockingBatch} isLockingEnded={isLockingEnded} />; })); let prefix = "Next in"; if (!isLockingStarted) { prefix = "Starts in"; } if (currentLockingBatch + 1 === schemeParams.batchesIndexCap) { prefix = "Ends in"; } const periodsClass = classNames({ [css.title]: true, [css.active]: !showYourLocks, }); const locksClass = classNames({ [css.title]: true, [css.active]: showYourLocks, }); const lockButtonClass = classNames({ [css.actionButton]: true, [css.disabled]: !lockAmount || !lockDuration || isLocking || !isEnoughBalance, }); const approveTokenButtonClass = classNames({ [css.actionButton]: true, [css.disabled]: isApprovingToken, }); const actionButtonClass = classNames({ [css.actionButton]: true, [css.disabled]: isRedeeming || !redeemable || redeemableAmount === 0, }); return ( !loading ? <div className={css.wrapper}> <div className={css.leftWrapper}> <div className={css.top}> <div className={css.countersWrapper}> <div className={css.currentPeriod}>Current Period: {isLockingEnded ? schemeParams.batchesIndexCap : currentLockingBatch + 1} of {schemeParams.batchesIndexCap}</div> <div className={css.nextPeriod}>{isLockingEnded ? "Locking Ended" : <div>{prefix} <Countdown toDate={nextBatchStartTime} onEnd={() => setCurrentTime(moment().unix())} /></div>}</div> </div> <div className={css.redeemWrapper}> <div className={css.redeemButtonWrapper}> <button className={actionButtonClass} onClick={() => handleRedeem(allLockingIdsForRedeem, setIsRedeeming)} disabled={isRedeeming || !redeemable || redeemableAmount === 0}>{`Redeem ${formatTokens(toWei(redeemableAmount))} REP`} </button> {!redeemable && <Tooltip trigger={["hover"]} overlay={`Redeem Enable Time: ${moment.unix(Number(schemeParams.redeemEnableTime)).utc().format("h:mm A [UTC] on MMMM Do, YYYY")}`}> <img style={{ marginLeft: "10px" }} width="15px" src="/assets/images/Icon/question-help.svg" /> </Tooltip>} </div> <div className={css.redeemedAmountLabel}>{`Total Redeemed: ${formatTokens(redeemedAmount, "REP")}`}</div> </div> </div> <div className={css.tableTitleWrapper}> <div className={periodsClass} onClick={() => { setShowYourLocks(false); setRedeemableAmount(0); }}>All Periods</div> <div className={locksClass} onClick={() => setShowYourLocks(true)}>Your Locks</div> </div> { showYourLocks ? cl4Rlocks.length > 0 ? <table> <thead> <tr> <th style={{ padding: "10px" }}>Period</th> <th>Amount</th> <th>Duration</th> <th>Releasable</th> <th>Action</th> </tr> </thead> <tbody> {lockings} </tbody> </table> : <span className={css.noLockLabel}>No locks yet.</span> : <table> <thead> <tr> <th style={{ padding: "10px" }}>Period</th> <th>You Locked</th> <th>Total Reputation</th> <th>You Will Receive</th> </tr> </thead> <tbody> {periods} </tbody> </table> } </div> {!isLockingEnded && isLockingStarted && <div className={css.lockWrapper}> <div className={css.lockTitle}>New Lock</div> <div className={css.lockDurationLabel}> <span style={{ marginRight: "5px" }}>Lock Duration</span> <Tooltip trigger={["hover"]} overlay={`Period: ${humanizeDuration(schemeParams.batchTime * 1000)}`}> <img width="15px" src="/assets/images/Icon/question-help.svg" /> </Tooltip> </div> <select onChange={(e: any) => setLockDuration(e.target.value)} disabled={!isAllowance}> {durations} </select> <span style={{ marginBottom: "5px" }}>Lock Amount ({schemeParams.tokenSymbol})</span> <input type="number" onChange={(e: any) => setLockAmount(e.target.value)} disabled={!isAllowance} /> {!isEnoughBalance && <span className={css.lowBalanceLabel}>{`Not enough ${schemeParams.tokenSymbol}!`}</span>} {<span className={css.releasableLable}>Releasable: {moment().add(lockDuration * schemeParams.batchTime, "seconds").format("DD.MM.YYYY HH:mm")}</span>} {isAllowance && <button onClick={handleLock} className={lockButtonClass} disabled={!lockAmount || !lockDuration}>Lock</button>} {!isAllowance && <Tooltip trigger={["hover"]} overlay={`Upon activation, the smart contract will be authorized to receive up to 100,000 ${schemeParams.tokenSymbol}`}> <button onClick={handleTokenApproving} className={approveTokenButtonClass} disabled={isApprovingToken}>Enable Locking</button> </Tooltip>} </div>} </div> : <Loading /> ); }; const SubscribedCL4R = withSubscription({ wrappedComponent: CL4R, loadingComponent: <Loading />, errorComponent: (props) => <div>{props.error.message}</div>, checkForUpdate: ["currentAccountAddress"], createObservable: async (props: IProps) => { if (props.currentAccountAddress) { const arc = getArcByDAOAddress(props.daoState.id); const schemeToken = gql` query SchemeInfo { controllerSchemes(where: {id: "${props.scheme.id.toLowerCase()}"}) { continuousLocking4ReputationParams { id token } } } `; const schemeTokenData = await arc.sendQuery(schemeToken); const tokenString = schemeTokenData.data.controllerSchemes[0].continuousLocking4ReputationParams.token; const locksQuery = gql` query Locks { cl4Rlocks(where: {scheme: "${props.scheme.id.toLowerCase()}", locker: "${props.currentAccountAddress}"}) { id lockingId locker amount lockingTime period released releasedAt redeemed { id lock amount redeemedAt batchIndex } } } `; const token = new Token(tokenString, arc); const allowance = token.allowance(props.currentAccountAddress, props.scheme.address); const balanceOf = token.balanceOf(props.currentAccountAddress); return combineLatest( arc.getObservable(locksQuery, standardPolling()), allowance.pipe(ethErrorHandler()), balanceOf.pipe(ethErrorHandler()) ); } else { return of([[], new BN(0), new BN(0)] as SubscriptionData); } }, }); export default connect( null, mapDispatchToProps, )(SubscribedCL4R);
import React, { useState, useEffect } from 'react'; const COLORS = ['purple', 'green', 'red', 'blue']; const Grid = () => { const [cells, setCells] = useState([]); useEffect(() => { const grid = []; // Create the grid with empty cells for (let i = 0; i < 10; i++) { const row = []; for (let j = 0; j < 10; j++) { row.push(null); } grid.push(row); } console.log(grid, "grid area"); // Create a block of 15 purple cells in the middle of the grid const startX = 3; const startY = 3; for (let i = startX; i < startX + 5; i++) { for (let j = startY; j < startY + 3; j++) { grid[i][j] = 'purple'; console.log(grid[i][j], "cells"); } } // Randomly assign the remaining cells to the other colors for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { if (grid[i][j] === null) { grid[i][j] = COLORS[Math.floor(Math.random() * COLORS.length)]; } } } setCells(grid); }, []); return ( <div> <p>The biggest area contains {COLORS.length} cells with purple color.</p> {cells.map((row, rowIndex) => ( <div key={rowIndex} style={{ display: 'flex' }}> {row.map((color, colIndex) => ( <div key={`${rowIndex}-${colIndex}`} style={{ width: '50px', height: '50px', backgroundColor: color, border: '1px solid black', }} /> ))} </div> ))} </div> ); }; export default Grid;
#ifdef ARDUINO #include <Arduino.h> #endif #ifndef Coloring_h #define Coloring_h #include "Color.h" #include "Voxel.h" class Coloring { public: virtual ~Coloring() = default; virtual Color getColor(const Voxel &vox) = 0; virtual Color getColor(uint8_t voxelX, uint8_t voxelY, uint8_t voxelZ) = 0; }; class SolidColoring : public Coloring { public: SolidColoring(); SolidColoring(Color *c); ~SolidColoring(); void setColor(const Color &c); Color getColor(const Voxel &vox); Color getColor(uint8_t voxelX, uint8_t voxelY, uint8_t voxelZ); private: Color *_c; }; class ColorSpace : public Coloring { public: ColorSpace(); ColorSpace(int width, int depth, int height); ~ColorSpace(){}; Color getColor(const Voxel &vox); Color getColor(uint8_t voxelX, uint8_t voxelY, uint8_t voxelZ); void print(); private: int width, depth, height; Brightness red(const Voxel &vox); Brightness green(const Voxel &vox); Brightness blue(const Voxel &vox); Brightness colorSpace(const int i); }; #endif
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'; import { SubscribeMessage, WebSocketGateway, WebSocketServer, OnGatewayConnection, OnGatewayDisconnect, } from '@nestjs/websockets'; import { Match, User } from '@prisma/client'; import { Server, Socket } from 'socket.io'; import { ClientEvent } from 'src/shared/types/events/client-event.enum'; import { MatchInstanceEvent } from 'src/shared/types/events/match-instance-event.enum'; import { ServerEvent } from 'src/shared/types/events/server-event.enum'; import { AppLoggerService } from '../logger/logger.service'; import { MatchInstance } from './match-instance'; @WebSocketGateway({ cors: { origin: '*' } }) export class MatchGateway implements OnGatewayConnection, OnGatewayDisconnect { private logger = new AppLoggerService(MatchGateway.name); @WebSocketServer() server: Server; private clients = new Map< Socket['id'], { userId: User['id']; matchInstance: MatchInstance } >(); private matches = new Map<MatchInstance['id'], MatchInstance>(); constructor(private readonly eventEmitter: EventEmitter2) {} private getUserIdForClient(clientId: Socket['id']) { return this.clients.get(clientId)?.userId; } private getMatchInstanceForClient(clientId: Socket['id']) { return this.clients.get(clientId)?.matchInstance; } async handleConnection(client: Socket) { const { matchId, userId } = client.handshake.query; if (typeof matchId !== 'string' || typeof userId !== 'string') { this.logger.error( `Incomplete connection query. userId: "${userId}", match: "${matchId}"`, ); client.disconnect(); return; } this.logger.verbose( `Incoming connection from "${userId}" to match "${matchId}"`, ); let matchInstance = this.matches.get(matchId); if (!matchInstance) { matchInstance = new MatchInstance(matchId, this.eventEmitter); await matchInstance.init(); } this.matches.set(matchId, matchInstance); this.clients.set(client.id, { userId, matchInstance }); try { await matchInstance.connect(client, userId); await this.cleanup(); } catch (e) { this.logger.error(e); client.disconnect(); } this.server .to(matchId) .emit(ServerEvent.PLAYER_CONNECTED_TO_MATCH, matchInstance.Match); this.logger.verbose(`Client connected to match "${matchId}"`); this.logger.verbose( `Current clients in match "${matchId}": ${Array.from( Array.from(matchInstance.sockets.values()).map((v) => v.id), )}`, ); this.logger.verbose(`Current clients: ${Array.from(this.clients.keys())}`); } handleDisconnect(client: Socket) { const { matchInstance } = this.clients.get(client.id) ?? {}; const { matchId, userId } = client.handshake.query; if (typeof userId !== 'string') { return; } if (matchInstance) { matchInstance.disconnect(client, userId); } this.clients.delete(client.id); this.logger.verbose(`Client "${client.id}" disconnected`); this.logger.verbose(`Current clients: ${Array.from(this.clients.keys())}`); } async cleanup() { const sockets = await this.server.sockets.fetchSockets(); const socketIds: string[] = []; for (const socket of sockets) { socketIds.push(socket.id); } Array.from(this.clients.keys()).forEach((clientId) => { if (!socketIds.includes(clientId)) { this.clients.delete(clientId); } }); } @SubscribeMessage(ClientEvent.DISCONNECT_FROM_MATCH) handleDisconnectFromMatch( client: Socket, data: { userId: string; matchId: string }, ) { // Handle leave match request const { matchId, userId } = data; console.log('Leave match:', matchId); const matchInstance = this.matches.get(matchId); if (matchInstance) { matchInstance.disconnect(client, userId); this.server.to(matchId).emit('disconnectedFromMatch', matchId); } else { client.emit('matchNotFound', matchId); } } @SubscribeMessage(ClientEvent.UPDATE_GAME_SETTINGS) async handleUpdateGameSettings(client: Socket, data: { [x: string]: any }) { const matchInstance = this.getMatchInstanceForClient(client.id); if (!matchInstance) { this.logger.error(`No connection for client ${client.id} found`); return; } try { const updatedGameSettings = await matchInstance.setGameSettings(data); this.server .to(matchInstance.Match.id) .emit(ServerEvent.UPDATED_GAME_SETTINGS, updatedGameSettings); } catch (e) { this.logger.error(e); client.disconnect(); } console.log('success'); console.log(this.getUserIdForClient(client.id)); // const matchInstance = this.matches.get(matchId); // if (matchInstance) { // matchInstance.disconnect(client, userId); // this.server.to(matchId).emit('disconnectedFromMatch', matchId); // } else { // client.emit('matchNotFound', matchId); // } } @OnEvent(MatchInstanceEvent.END_TURN) handleTimer(id: Match['id'], remainingTime: number) { console.log('handleTimer', id, remainingTime); this.server.to(id).emit(ServerEvent.TIME_REMAINING, remainingTime); } }
<!doctype html> <html class="pages css view"> <?php require_once 'include/_head.php' ?> <body> <article id="wrap"> <!-- Header --> <v-header></v-header> <v-ihead></v-ihead> <main class="inside-wrap"> <section class="inside-main"> <!-- 文章標題 --> <div class="inside-view"> <hgroup> <time>2019-08-10</time> <h1>max-height</h1> </hgroup> </div> <!-- 文章內容 --> <div class="inside-edit"> <!-- start --> <p><em>max-height</em> 主要用來設置元素的最大高度,如果元素 <em>height</em> 值大於 <em>max-height</em>值,則會以後者設定的值作為元素高度的基準。</p> <h3 class="rule"></h3> <div class="code-area"> <pre id="area01" class="code-text"><code class="css">selector { max-height: value; }</code></pre> <button class="copy-btn" data-clipboard-target="#area01"> <span>COPY</span> </button> </div> <h3 class="ex"></h3> <div class="code-area"> <pre id="area02" class="code-text"><code class="css">div { max-height: 10rem; }</code></pre> <button class="copy-btn" data-clipboard-target="#area02"> <span>COPY</span> </button> </div> <!-- 屬性值 --> <h2 class="cssproperty"><em>max-height</em></h2> <div class="t-form"> <div class="t-head"> <span class="t-flex1">Value</span> <span class="t-flex5">Description</span> </div> <div class="t-row"> <span class="t-flex1">none</span> <span class="t-flex5">取決瀏覽器預設【預設值】</span> </div> <div class="t-row"> <span class="t-flex1">length</span> <span class="t-flex5">固定數字單位</span> </div> <div class="t-row"> <span class="t-flex1">%</span> <span class="t-flex5">百分比</span> </div> <div class="t-row"> <span class="t-flex1">inherit</span> <span class="t-flex5">繼承父元素的設定值</span> </div> <div class="t-row"> <span class="t-flex1">initial</span> <span class="t-flex5">使用 CSS 官方制定的初始值</span> </div> </div> <h3 class="demo"></h3> <code> <p class="codepen" data-height="480" data-theme-id="0" data-default-tab="css,result" data-user="itrong" data-slug-hash="ZgqaVm" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="css-max-height"> <span>See the Pen <a href="https://codepen.io/itrong/pen/ZgqaVm/"> css-max-height</a> by Trong (<a href="https://codepen.io/itrong">@itrong</a>) on <a href="https://codepen.io">CodePen</a>.</span> </p> </code> <!-- JS調用 --> <h2 class="cssjs"></h2> <h3 class="js"></h3> <div class="code-area"> <pre id="area03" class="code-text"><code class="js">object.style.maxHeight="10rem"</code></pre> <button class="copy-btn" data-clipboard-target="#area03"> <span>COPY</span> </button> </div> <!-- 瀏覽器支援性 --> <h2 class="browser"></h2> <div class="is-browser"> <div class="t-form"> <div class="t-head"> <span class="t-flex1">Chrome</span> <span class="t-flex1">Firefox</span> <span class="t-flex1">IE9以下</span> <span class="t-flex1">IE Edge</span> <span class="t-flex1">Safari</span> <span class="t-flex1">Opera</span> </div> <div class="t-row"> <span class="t-flex1"><i class="fab fa-chrome"></i></span> <span class="t-flex1"><i class="fab fa-firefox"></i></span> <span class="t-flex1"><i class="fab fa-internet-explorer"></i></span> <span class="t-flex1"><i class="fab fa-edge"></i></span> <span class="t-flex1"><i class="fab fa-safari"></i></span> <span class="t-flex1"><i class="fab fa-opera"></i></span> </div> <div class="t-row"> <span class="t-flex1 is-none">-webkit-</span> <span class="t-flex1 is-none">-moz-</span> <span class="t-flex1 is-none">-ms-</span> <span class="t-flex1 is-none">-ms-</span> <span class="t-flex1 is-none">-webkit-</span> <span class="t-flex1 is-none">-o- / -webkit-</span> </div> </div> </div> <!-- end --> </div> </section> </main> <!-- Footer --> <v-footer></v-footer> </article> <?php require_once 'include/_viewjs.php' ?> </body> </html>
import React, { useEffect, useState } from "react"; import Table from "@mui/material/Table"; import TableBody from "@mui/material/TableBody"; import TableCell from "@mui/material/TableCell"; import TableContainer from "@mui/material/TableContainer"; import TableHead from "@mui/material/TableHead"; import TableRow from "@mui/material/TableRow"; import Paper from "@mui/material/Paper"; import Container from "@mui/material/Container"; import Box from "@mui/material/Box"; import Typography from "@mui/material/Typography"; import Cookies from "js-cookie"; import logo from "./invoismart-logo.png"; import { Link } from "@mui/material"; import { useTranslation } from "react-i18next"; const ListInvoices = () => { useEffect(() => { fetchInvoices("accounts"); }, []); const [invoice, setInvoice] = useState([]); const cred = Cookies.get("cred"); const subId = Cookies.get("accId"); const subName = Cookies.get("accName"); const { t } = useTranslation(); const close_window_button = '<br></br><Button type="submit" style="margin-left: 46%" onclick="self.close()">Close window </Button> '; /* useEffect(() => { if(!refresh) setRefresh(true) }, [Refresh]); if (Cookies.get("cred")) { console.log("Cookie found"); navigate("/ui/Viewinvoices"); } */ let URL = process.env.REACT_APP_BASE_URL + "accounts/" + subId + "/invoices?includeInvoiceComponents=true"; const fetchInvoices = (a) => { fetch(URL, { method: "GET", headers: new Headers({ Authorization: "Basic " + cred, Accept: "*/*", "X-Killbill-ApiKey": process.env.REACT_APP_API_KEY, "X-Killbill-ApiSecret": process.env.REACT_APP_API_SECRET, }), }) .then((response) => { return response.json(); }) .then((data) => { setInvoice(data); }); }; function htmlView(a) { var w = window.open("", "_blank" ); const URI_INV_VIEW = "invoices/"; const URI_HTML = "/html"; fetch(process.env.REACT_APP_BASE_URL + URI_INV_VIEW + a + URI_HTML, { method: "GET", headers: new Headers({ Authorization: "Basic " + cred, Accept: "*/*", "X-Killbill-ApiKey": process.env.REACT_APP_API_KEY, "X-Killbill-ApiSecret": process.env.REACT_APP_API_SECRET, }), }) .then((response) => { return response.text(); }) .then((html) => { w.document.body.innerHTML = html + close_window_button; }); } return ( <Container component="main" maxWidth="sm"> <Box sx={{ marginTop: 8, display: "flex", flexDirection: "column", alignItems: "center", }} ></Box> <Typography component="h1" variant="h5" align="center"> <Link href="/ui/landingpage" underline="none"> <img src={logo} alt="Logo" width="250" height="83" class="left" /> </Link> <br></br> </Typography> <Typography component="h1" variant="h5" align="center"> <br></br> <p> {t("subscriber")}: {subName} </p> </Typography> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell align="right">{t("date")} </TableCell> <TableCell align="right">{t("invoicenumber")}</TableCell> <TableCell align="right">{t("amount")}($)</TableCell> </TableRow> </TableHead> <TableBody> {invoice.map((invField) => ( <TableRow> <TableCell align="right">{invField.invoiceDate}</TableCell> <TableCell align="right"> <a href="#" onClick={() => { htmlView(`${invField.invoiceId}`); <a href="/ui/InvoiceList"></a>; }} > {invField.invoiceNumber} </a> </TableCell> <TableCell align="right"> {invField.amount.toFixed(2)} </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </Container> ); }; export default ListInvoices;
<html> <head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect(); socket.on('connect', function() { console.log("Connected"); }); // Receive a message socket.on('message', function(data) { console.log("Got: " + data); document.getElementById('messages').innerHTML += data; }); socket.on("position", function(data) { //console.log(data); }); // Receive from any event socket.on('news', function (data) { console.log(data); }); socket.on('image', function(imageData) { // Incoming image.. console.log(imageData.image); document.getElementById('otherimage').src = imageData.image; }); var sendmessage = function() { var message = document.getElementById('message').value; console.log("Sending: " + message); // Send a messaage socket.send(message); }; var sendother = function() { var othermessage = document.getElementById('message').value; console.log("sending: " + othermessage); // Send any kind of data with a custom event //socket.emit('otherevent',{ othermessage: othermessage }); socket.emit('otherevent', othermessage); }; window.addEventListener('load', function() { // The video element on the page to display the webcam let video = document.getElementById('myvideo'); // Constraints - what do we want? let constraints = { audio: true, video: true } // Prompt the user for permission, get the stream navigator.mediaDevices.getUserMedia(constraints).then(function(stream) { /* Use the stream */ // Attach to our video object video.srcObject = stream; // Wait for the stream to load enough to play video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { /* Handle the error */ alert(err); }); var canvas = document.getElementById('mycanvas'); var context = canvas.getContext('2d'); context.fillStyle="#FF0000"; context.fillRect(0,0,canvas.width,canvas.height); window.addEventListener('click', function(e) { context.drawImage(video, 10, 10); //console.log(canvas.toDataURL("image/jpeg")); let v = { image: canvas.toDataURL("image/jpeg") } socket.emit('image', v); }); window.addEventListener('mousemove', function(e) { //console.log(e); let p = { x: e.pageX, y: e.pageY }; socket.emit('position', p); // let p = new Object(); // p.x = e.pageX; // p.y = e.pageY; // e.pageX // e.pageY }); }); </script> </head> <body> <video id="myvideo" width="400" height="300" muted></video> <canvas width="600" height="600" id="mycanvas"></canvas> <img id="otherimage" width="600" height="600" src="" /> <div id="messages"> No Messages Yet </div> <div> <input type="text" id="message" name="message"> <input type="button" value="message" onclick="sendmessage();"> <input type="button" value="other" onclick="sendother();"> </div> </body> </html>
import { ensureJQuerySupport } from "../jquery-support.js"; import { isActive, toName, NOT_LOADED, NOT_BOOTSTRAPPED, NOT_MOUNTED, MOUNTED, LOAD_ERROR, SKIP_BECAUSE_BROKEN, LOADING_SOURCE_CODE, shouldBeActive, } from "./app.helpers.js"; import { reroute } from "../navigation/reroute.js"; import { find } from "../utils/find.js"; import { toUnmountPromise } from "../lifecycles/unmount.js"; import { toUnloadPromise, getAppUnloadInfo, addAppToUnload, } from "../lifecycles/unload.js"; import { formatErrorMessage } from "./app-errors.js"; import { isInBrowser } from "../utils/runtime-environment.js"; import { assign } from "../utils/assign"; // 所有接入微前端的app const apps = []; /** * 获取下一步要变动【需要 加载 | 挂载 | 卸载 | 移除】 的应用 * @returns */ export function getAppChanges() { const appsToUnload = [], //要移除的子应用 appsToUnmount = [], //要卸载的子应用 appsToLoad = [], //要加载的子应用 appsToMount = []; //要挂载的子应用 // We re-attempt to download applications in LOAD_ERROR after a timeout of 200 milliseconds // 超时200毫秒后,我们重新尝试在 LOAD_ERROR 中加载 app const currentTime = new Date().getTime(); apps.forEach((app) => { //app是否处于激活状态 const appShouldBeActive = app.status !== SKIP_BECAUSE_BROKEN && shouldBeActive(app); switch (app.status) { case LOAD_ERROR: if (appShouldBeActive && currentTime - app.loadErrorTime >= 200) { appsToLoad.push(app); } break; case NOT_LOADED: case LOADING_SOURCE_CODE: if (appShouldBeActive) { appsToLoad.push(app); } break; case NOT_BOOTSTRAPPED: case NOT_MOUNTED: if (!appShouldBeActive && getAppUnloadInfo(toName(app))) { appsToUnload.push(app); } else if (appShouldBeActive) { appsToMount.push(app); } break; case MOUNTED: if (!appShouldBeActive) { appsToUnmount.push(app); } break; // all other statuses are ignored } }); return { appsToUnload, appsToUnmount, appsToLoad, appsToMount }; } /** * 获取已挂载的应用名 * @returns */ export function getMountedApps() { return apps.filter(isActive).map(toName); } /** * 获取所有应用名 * @returns */ export function getAppNames() { return apps.map(toName); } /** * 获取原始应用数据。 * 仅在 devtools 中使用,不作为single-spa API 公开 * @returns */ export function getRawAppData() { return [...apps]; } /** * 获取指定应用的状态 * @param {string} appName * @returns */ export function getAppStatus(appName) { const app = find(apps, (app) => toName(app) === appName); return app ? app.status : null; } /** * 应用注册 * 1.清洗整理入参 * 2.apps是否已包含要注册的应用,有,则抛错 * 3.给要注册的应用增加内部属性 * loadErrorTime 加载错误时记录时间 * status 应用的状态 * parcels 包裹 * devtools:{overlays:{options:{},selectors:[]}} * 4.将其push到apps中 * 5.执行重新路由 * @param {string|object} appNameOrConfig 应用名字或者配置 * @param {func|app} appOrLoadApp 加载函数或者promise类型的app【加载好的app】 * @param {func} activeWhen 必须是个纯函数, 该函数由window.location作为第一个参数被调用, 当应用应该被激活时它应该返回一个真值。 * @param {object} customProps 子应用生命周期钩子函数 执行时传入的参数 */ export function registerApplication( appNameOrConfig, appOrLoadApp, activeWhen, customProps ) { const registration = sanitizeArguments( appNameOrConfig, appOrLoadApp, activeWhen, customProps ); if (getAppNames().indexOf(registration.name) !== -1) throw Error( formatErrorMessage( 21, __DEV__ && `There is already an app registered with name ${registration.name}`, registration.name ) ); apps.push( assign( { loadErrorTime: null, status: NOT_LOADED, parcels: {}, devtools: { overlays: { options: {}, selectors: [], }, }, }, registration ) ); if (isInBrowser) { ensureJQuerySupport(); reroute(); } } /** * 检查当前location下能激活的app * @param {*} location * @returns 返回激活状态的app名字数组 */ export function checkActivityFunctions(location = window.location) { return apps.filter((app) => app.activeWhen(location)).map(toName); } /** * 注销应用 * 1.apps中是否有要注销的应用,如果没有抛错 * 2.完成应用卸载过程 unloadApplication(appName) * 3.从apps中删除对应的数据 * @param {*} appName * @returns */ export function unregisterApplication(appName) { if (apps.filter((app) => toName(app) === appName).length === 0) { throw Error( formatErrorMessage( 25, __DEV__ && `Cannot unregister application '${appName}' because no such application has been registered`, appName ) ); } return unloadApplication(appName).then(() => { const appIndex = apps.map(toName).indexOf(appName); apps.splice(appIndex, 1); }); } /** * 卸载应用程序 * waitForUnmount * @param {*} appName * @param {*} opts waitForUnmount 是否等待其他已有卸载完成 * @returns */ export function unloadApplication(appName, opts = { waitForUnmount: false }) { if (typeof appName !== "string") { throw Error( formatErrorMessage( 26, __DEV__ && `unloadApplication requires a string 'appName'` ) ); } const app = find(apps, (App) => toName(App) === appName); if (!app) { throw Error( formatErrorMessage( 27, __DEV__ && `Could not unload application '${appName}' because no such application has been registered`, appName ) ); } const appUnloadInfo = getAppUnloadInfo(toName(app)); if (opts && opts.waitForUnmount) { // We need to wait for unmount before unloading the app // 在移除应用程序之前,我们需要等待程序卸载 if (appUnloadInfo) { // 其他人也已经在等待这个,则直接返回它的promise对象 return appUnloadInfo.promise; } else { // 我们是第一个希望移除该应用程序的人。 const promise = new Promise((resolve, reject) => { addAppToUnload(app, () => promise, resolve, reject); }); return promise; } } else {// 不等待 // 我们应该卸载该应用,卸载它,然后立即重新挂载它。 let resultPromise; if (appUnloadInfo) { // 其他人也已经在等待这个 resultPromise = appUnloadInfo.promise; immediatelyUnloadApp(app, appUnloadInfo.resolve, appUnloadInfo.reject); } else { // 我们是第一个希望移除该应用程序的人。 resultPromise = new Promise((resolve, reject) => { addAppToUnload(app, () => resultPromise, resolve, reject); immediatelyUnloadApp(app, resolve, reject); }); } return resultPromise; } } /** * 立即卸载应用程序 * 1.解除app的挂载 * 2.卸载app * 3.执行resolve, * 4.卸载promise完成后,重新路由 * @param {*} app * @param {*} resolve * @param {*} reject */ function immediatelyUnloadApp(app, resolve, reject) { toUnmountPromise(app) .then(toUnloadPromise) .then(() => { resolve(); setTimeout(() => { // reroute, but the unload promise is done reroute(); }); }) .catch(reject); } /** * 校验注册应用时的参数 * @param {*} config */ function validateRegisterWithArguments( name, appOrLoadApp, activeWhen, customProps ) { if (typeof name !== "string" || name.length === 0) throw Error( formatErrorMessage( 20, __DEV__ && `The 1st argument to registerApplication must be a non-empty string 'appName'` ) ); if (!appOrLoadApp) throw Error( formatErrorMessage( 23, __DEV__ && "The 2nd argument to registerApplication must be an application or loading application function" ) ); if (typeof activeWhen !== "function") throw Error( formatErrorMessage( 24, __DEV__ && "The 3rd argument to registerApplication must be an activeWhen function" ) ); if (!validCustomProps(customProps)) throw Error( formatErrorMessage( 22, __DEV__ && "The optional 4th argument is a customProps and must be an object" ) ); } /** * 校验注册应用时的对象参数 * @param {*} config */ export function validateRegisterWithConfig(config) { if (Array.isArray(config) || config === null) throw Error( formatErrorMessage( 39, __DEV__ && "Configuration object can't be an Array or null!" ) ); const validKeys = ["name", "app", "activeWhen", "customProps"]; // 找到非validKeys中的key const invalidKeys = Object.keys(config).reduce( (invalidKeys, prop) => validKeys.indexOf(prop) >= 0 ? invalidKeys : invalidKeys.concat(prop), [] ); if (invalidKeys.length !== 0) throw Error( formatErrorMessage( 38, __DEV__ && `The configuration object accepts only: ${validKeys.join( ", " )}. Invalid keys: ${invalidKeys.join(", ")}.`, validKeys.join(", "), invalidKeys.join(", ") ) ); if (typeof config.name !== "string" || config.name.length === 0) throw Error( formatErrorMessage( 20, __DEV__ && "The config.name on registerApplication must be a non-empty string" ) ); if (typeof config.app !== "object" && typeof config.app !== "function") throw Error( formatErrorMessage( 20, __DEV__ && "The config.app on registerApplication must be an application or a loading function" ) ); const allowsStringAndFunction = (activeWhen) => typeof activeWhen === "string" || typeof activeWhen === "function"; if ( !allowsStringAndFunction(config.activeWhen) && !( Array.isArray(config.activeWhen) && config.activeWhen.every(allowsStringAndFunction) ) ) throw Error( formatErrorMessage( 24, __DEV__ && "The config.activeWhen on registerApplication must be a string, function or an array with both" ) ); if (!validCustomProps(config.customProps)) throw Error( formatErrorMessage( 22, __DEV__ && "The optional config.customProps must be an object" ) ); } /** * 校验主应用传入子应用的参数 * 1.必须传 * 2.可以是函数 * 3.也可以是非数组且非null的对象 * @param {*} customProps * @returns */ function validCustomProps(customProps) { return ( !customProps || typeof customProps === "function" || (typeof customProps === "object" && customProps !== null && !Array.isArray(customProps)) ); } /** * 处理(消毒)参数 * 1.参数错误时,抛错 * 2.确保:应用名类型为 string 且不为 '' * 应用加载器 必传 类型要么是object,要么是function * 应用激活器必须为string 或 function 且最终整合为function * 主应用传入子应用的数据类型为 非null对象 或 数组 * @param {*} appNameOrConfig * @param {*} appOrLoadApp * @param {*} activeWhen * @param {*} customProps * @returns { name, loadApp, activeWhen, customProps} */ function sanitizeArguments( appNameOrConfig, appOrLoadApp, activeWhen, customProps ) { const usingObjectAPI = typeof appNameOrConfig === "object"; const registration = { name: null, loadApp: null, activeWhen: null, customProps: null, }; if (usingObjectAPI) { registration.name = appNameOrConfig.name; validateRegisterWithConfig(appNameOrConfig); registration.loadApp = appNameOrConfig.app; registration.activeWhen = appNameOrConfig.activeWhen; registration.customProps = appNameOrConfig.customProps; } else { validateRegisterWithArguments( appNameOrConfig, appOrLoadApp, activeWhen, customProps ); registration.name = appNameOrConfig; registration.loadApp = appOrLoadApp; registration.activeWhen = activeWhen; registration.customProps = customProps; } registration.loadApp = sanitizeLoadApp(registration.loadApp); registration.customProps = sanitizeCustomProps(registration.customProps); registration.activeWhen = sanitizeActiveWhen(registration.activeWhen); return registration; } /** * 处理(消毒)loadApp: * 需要保证loadApp 是一个函数,如果不是,则将其包裹为一个函数,且该函数返回pormise * @param {*} loadApp * @returns */ function sanitizeLoadApp(loadApp) { if (typeof loadApp !== "function") { return () => Promise.resolve(loadApp); } return loadApp; } // 确保 主应用传递给微应用的数据 不为空 function sanitizeCustomProps(customProps) { return customProps ? customProps : {}; } /** * 处理(消毒)activeWhen: * 1. 整合为数组。传入的activeWhen可以是单个字符串/函数,也可以是两者的数组。需要判断整合 * 2. 确保上述整合数组中的元素都是函数。如果不是函数,转为接受location参数的函数。 * 3. 返回整体函数,返回上述整合数组执行中为true。 * @param {*} activeWhen * @returns */ function sanitizeActiveWhen(activeWhen) { // 整合为数组 let activeWhenArray = Array.isArray(activeWhen) ? activeWhen : [activeWhen]; // 将activeWhen全部转为接受window.location参数的函数。【activeWhen可能为字符串】 activeWhenArray = activeWhenArray.map((activeWhenOrPath) => typeof activeWhenOrPath === "function" ? activeWhenOrPath : pathToActiveWhen(activeWhenOrPath) ); return (location) => activeWhenArray.some((activeWhen) => activeWhen(location)); } /** * 将字符串路径转为activeWhen函数 * @param {string} path 用户传入的activeWhen字符串 * @param {boolean} exactMatch 完全符合。严格匹配? * @returns activeWhen函数 */ export function pathToActiveWhen(path, exactMatch) { const regex = toDynamicPathValidatorRegex(path, exactMatch); return (location) => { // compatible with IE10 let origin = location.origin; if (!origin) { origin = `${location.protocol}//${location.host}`; } const route = location.href .replace(origin, "") .replace(location.search, "") .split("?")[0]; return regex.test(route); }; } /** * 动态路径校验的正则表达式。例如: /users/:userId/profile' * @param {string} path 用户传入的activeWhen字符串 * @param {boolean} exactMatch 完全符合。严格匹配? * @returns 正则表达式regex */ function toDynamicPathValidatorRegex(path, exactMatch) { let lastIndex = 0, inDynamic = false, //动态flag regexStr = "^"; // 确保path用/开头 if (path[0] !== "/") { path = "/" + path; } for (let charIndex = 0; charIndex < path.length; charIndex++) { const char = path[charIndex]; const startOfDynamic = !inDynamic && char === ":"; const endOfDynamic = inDynamic && char === "/"; if (startOfDynamic || endOfDynamic) { // 执行两次,动态路劲开始和动态路径结束时 appendToRegex(charIndex); } } appendToRegex(path.length); return new RegExp(regexStr, "i"); function appendToRegex(index) { // 任何字符可能尾随斜杠正则表达式 。 // 1.[^/]匹配非/的所有字符 // 2.[^/]+ 匹配1次或多次非/的所有字符 const anyCharMaybeTrailingSlashRegex = "[^/]+/?"; const commonStringSubPath = escapeStrRegex(path.slice(lastIndex, index)); regexStr += inDynamic ? anyCharMaybeTrailingSlashRegex : commonStringSubPath; console.log('regexStr', regexStr); if (index === path.length) { if (inDynamic) { if (exactMatch) { // Ensure exact match paths that end in a dynamic portion don't match // urls with characters after a slash after the dynamic portion. // 翻译:确保以动态部分结尾的完全匹配路径不会与动态部分后斜线后的字符匹配 url regexStr += "$"; } } else { // For exact matches, expect no more characters. Otherwise, allow any characters. // 对于完全匹配,不需要更多字符。否则,允许任何字符。 const suffix = exactMatch ? "" : ".*"; regexStr = // 1.因为我们不能使用 es6 方法 endsWith,故使用 charAt 代替 // 2.判断末尾是否有/: // 有则表示输入的path只是一个url的子路径,不需要考虑路径的serach参数匹配 // 没有,则需要考虑search参数及后面的匹配 regexStr.charAt(regexStr.length - 1) === "/" ? `${regexStr}${suffix}$` : `${regexStr}(/${suffix})?(#.*)?$`; } } inDynamic = !inDynamic; lastIndex = index; } // 转义具有特殊含义的字符。 function escapeStrRegex(str) { // borrowed from https://github.com/sindresorhus/escape-string-regexp/blob/master/index.js return str.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&"); } }
# PyStegosploit - Exploit Delivery via Steganography and Polyglots by Charmve - yidazhang1 [at] gmail[dot]com, [@Charmve](https://github.com/Charmve) [@therealsaumil](https://twitter.com/therealsaumil) [@amichael](https://github.com/amichael7) May 2021 ![stego_imajs.png](stego/static/img/stego_imajs.png) Stegosploit creates a new way to encode "drive-by" browser exploits and deliver them through image files. These payloads are undetectable using current means. This paper discusses two broad underlying techniques used for image based exploit delivery - Steganography and Polyglots. Drive-by browser exploits are steganographically encoded into JPG and PNG images. The resultant image file is fused with HTML and Javascript decoder code, turning it into an HTML+Image polyglot. The polyglot looks and feels like an image, but is decoded and triggered in a victim's browser when loaded. ## A Tour of the Stegosploit Toolkit <sup>[1]</sup> <p>Stegosploit comprises of tools that let a user analyse images, steganographically encode exploit data onto JPG and PNG files, and turn the encoded images into polyglot files that can be rendered as HTML or executed as Javascript.</p> <p>The current version of Stegosploit is 0.2 and can be found in <a href="https://www.alchemistowl.org/pocorgtfo/pocorgtfo08.pdf">Issue 0x08 of the International Journal of Proof-of-Concept or Get The Fuck Out (Poc||GTFO)</a>. Note that you will have to read through the end of the article in PoC||GTFO to find the hint on how to extract the toolkit.</p> ### 🔍 Browse Folders - 📄 <code>README.md</code> - 📄 <code>copying.txt</code> - WTFPL - 📁 <code>stego/</code> - 📄 <code>image_layer_analysis.html</code> - Analyse an image's bit layers - 📄 <code>iterative_encoding.html</code> - Encode an exploit onto a JPG or PNG image - 📄 <code>imagedecoder.html</code> - Decode a steganographically encoded image - 📄 <code>imagedecode.js</code> - 📄 <code>histogram.js</code> - 📄 <code>md5.js</code> - 📄 <code>base64.js</code> - 📁 <code>exploits/</code> - 📄 <code>exploits.js</code> - Canned exploit code - 📄 <code>decoder_cve_2014_0282.html</code> - Decoder code + CVE-2014-0282 HTML elements - 📁 <code>imajs/</code> - 📄 <code>html_in_jpg_ie.pl</code> - Generate JPG+HTML polyglot for IE - 📄 <code>html_in_jpg_ff.pl</code> - Generate JPG+HTML polyglot for Firefox - 📄 <code>html_in_png.pl</code> - Generate a PNG+HTML polyglot (for any browser) - 📄 <code>pngenum.pl</code> - Enumerate a PNG file's FourCC chunks - 📄 <code>jpegdump.c</code> - Enumerate a JPG file's segments - 📄 <code>CRC32.pm</code> - 📄 <code>PNGDATA.pm</code> - ★ 📁 <code>project-stegosploit/</code> - Core Part [<i><u>video show 1</u></i>](https://www.youtube.com/watch?v=O9vSSQIZPlI) | [<i><u>text show 1</u></i>](https://stegosploit.info/#22-steganographically-encoding-the-exploit-code) - 📁 <code>encoding/</code> - core - 📄 <code>iterative_encoding.html</code> - Steganographically Encoding the Exploit Code - 📄 <code>image_layer_analysis.html</code> - 📄 <code>imagedevoder.html</code> - 📄 <code>decode_and_run_cinput_withjs.html</code> - 📁 <code>exploits/</code> - decoder.html - 📁 <code>images/</code> - encoded and original images - 📁 <code>polyglots/</code> - lena_poly_demo.html - 📁 <code>scripts/</code> - Creates an HTML+PNG polyglot ``polyglot_with_jpg.py`` - 📁 <code>tmp/</code> run ``--/tools/msf4$ ./msfconsole -r ./tmp/load_meterpreter.rc`` [<i><u>video show 2</u></i>](https://www.youtube.com/watch?v=fAyuOhB4uvo) - 📄 <code>README.md</code> - Show how to use this project-stegosploit <p><code>jpegdump.c</code> is written by Ralph Giles and can be downloaded from <a href="https://svn.xiph.org/experimental/giles/jpegdump.c">https://svn.xiph.org/experimental/giles/jpegdump.c</a></p> In this repo, importantly, ``project-stegosploit`` is key part, which show how to hidden <i>Exploit Code</i> into image, to encode/decode, and to execute the <i>meterpreter framework</i>. ## 🔧 How Stegosploit Works The exploit code is inserted within the pixels of the image so that the image contains the exploit code. IMAJS then creates a polyglot image that will be read as an image and contains a decoder that will extract and run the javascript exploit. The exploit that we will use is an Internet Explorer Use-after-free exploit ([CVE-2014-0282](https://nvd.nist.gov/vuln/detail/CVE-2014-0282)). ## 🔨 Requirements - Ubuntu 18.04 / Kali / Debian 9 - web service - ``python -m http.server 8000`` - Metasploit Framework - [How to Install](https://computingforgeeks.com/how-to-install-metasploit-framework-on-ubuntu-18-04-debian-9/) ![msfconsole.png](stego/static/img/msfconsole.png) ## 📆 What we have done so far __Highlights:__ * The server can serve images to the VM over `10.0.2.2:5000` * The jpg.py program can build a polyglot file (valid `.html` and `.jpg`) ## 📝 Checklist - [X] Refactor `CRC32.pm` - [X] Refactor `PNGDATA.pm` - [ ] Refactor `html_in_jpg_ie.pl` - [X] Refactor `pngenum.pl` - [ ] Demo Server - [X] Move all static exploit files in demo pages to `/static` - [ ] Make sure all static files are passed parsed using `template_render` - [ ] Add an image picker for the image_layer_analysis.html \(Optional\) ## ✨ Related Works *Stegosploit* My repo - [steganography.js](https://github.com/Charmve/xss-test) - Hide secret messages with JavaScript with steganography.js https://charmve.github.io/xss-test/examples/showcase/ - [StegaStamp-plus](https://github.com/Charmve/StegaStamp-plus) - Improved the original repo, 'Invisible Hyperlinks in Physical Photographs', without datasets and training parameters ## ❕ Disclaimer - This repo follows the GPL open source agreement, please be sure to understand. - We strictly prohibit all acts that violate any national laws through this program, please use this program within the legal scope. - By default, using this item will be deemed as your agreement to our rules. Please be sure to abide by the moral and legal standards. - If you do not comply, you will be responsible for the consequences, and the author will not bear any responsibility! ## 📎 References [1] https://stegosploit.info/ [2] https://conference.hitb.org/hitbsecconf2015ams/sessions/stegosploit-hacking-with-pictures/ [3] https://www.vulnerability-db.com/?q=articles/2015/06/17/exploit-delivery-steganography-using-stegosploit-tool-v02 [4] https://www.blackhat.com/docs/eu-15/materials/eu-15-Shah-Stegosploit-Exploit-Delivery-With-Steganography-And-Polyglots.pdf [5] https://stackoverflow.com/questions/4110964/how-does-heap-spray-attack-work [6] https://www.youtube.com/watch?time_continue=1&v=6lYUtIZHlJA [7] https://www.owasp.org/images/0/01/OWASL_IL_2010_Jan_-_Moshe_Ben_Abu_-_Advanced_Heapspray.pdf [8] https://en.wikipedia.org/wiki/Heap_spraying [9] https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/ ## ✉️ Contact yidazhang1[#]gmail[dot]com <br> <div align="right"> <a href="https://github.com/Charmve" target="_blank">Zhang Wei (Charmve)</a> </div>
"use client"; import Link from "next/link"; import React from "react"; import { usePathname } from "next/navigation"; import { FcLinux } from "react-icons/fc"; import classNames from "classnames"; const Navbar = () => { const currentPath = usePathname(); const links = [ { href: "/dashboard", label: "Dashboard" }, { href: "/issues", label: "Issues" }, ]; return ( <nav className="flex items-center space-x-2 border-b "> <Link href="/"> <FcLinux style={{ fontSize: "5rem" }} /> </Link> <ul className="flex"> {links.map((link) => ( <li key={link.label}> <Link className={classNames({ "mx-3 hover:text-zinc-900 transition-colors": true, "text-zinc-900": link.href === currentPath, "text-zinc-600": link.href !== currentPath, })} href={link.href} > {link.label} </Link> </li> ))} </ul> </nav> ); }; export default Navbar;
package com.example.imageEditor.apiService import android.util.Log import com.example.imageEditor.base.CustomFuture import com.example.imageEditor.base.OnListenProcess import com.example.imageEditor.model.CollectionModel import com.example.imageEditor.model.PhotoModel import com.example.imageEditor.model.PhotoSearchModel import com.example.imageEditor.model.request.AuthorizeRequest import com.example.imageEditor.model.response.AuthorizeResponse import com.example.imageEditor.utils.AUTHORIZE_ENDPOINT import com.example.imageEditor.utils.COLLECTION_ENDPOINT import com.example.imageEditor.utils.PAGE import com.example.imageEditor.utils.PER_PAGE import com.example.imageEditor.utils.PHOTO_SEARCH_ENDPOINT import com.example.imageEditor.utils.QUERY_SEARCH import com.example.imageEditor.utils.deleteMethodHttpWithBearToken import com.example.imageEditor.utils.fromJsonToList import com.example.imageEditor.utils.getMethodHttp import com.example.imageEditor.utils.getMethodHttpWithBearToken import com.example.imageEditor.utils.postMethodHttp import com.example.imageEditor.utils.postMethodHttpWithBearToken import com.example.imageEditor.utils.toJson import com.google.gson.Gson import java.util.concurrent.Callable import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.FutureTask class ApiImpl(private val onListenProcess: OnListenProcess) : Api { private var mToken: String? = "" private val executorService: ExecutorService = Executors.newFixedThreadPool(5) override fun getCollections( page: Int, onResult: (List<CollectionModel>?) -> Unit, ) { val futureTask: CustomFuture<List<CollectionModel>> = CustomFuture( Callable { try { val query = mapOf(Pair(PAGE, page.toString())) return@Callable Gson().fromJsonToList<CollectionModel>( getMethodHttp(COLLECTION_ENDPOINT, query), ) } catch (e: Exception) { throw Throwable(e) } }, onListenProcess, ) executorService.submit(futureTask) try { onResult.invoke(futureTask.get()) } catch (e: Exception) { onListenProcess.onError(Throwable(e)) } } override fun searchPhotos( page: Int, query: String, perPage: Int?, onResult: (PhotoSearchModel?) -> Unit, ) { val futureTask: CustomFuture<PhotoSearchModel> = CustomFuture( Callable { try { val queryValue = mapOf( Pair(PAGE, page.toString()), Pair(QUERY_SEARCH, query), Pair( PER_PAGE, perPage.toString(), ), ) return@Callable Gson().fromJson( getMethodHttp(PHOTO_SEARCH_ENDPOINT, queryValue), PhotoSearchModel::class.java, ) } catch (e: Exception) { throw Throwable(e) } }, onListenProcess, ) executorService.submit(futureTask) try { onResult.invoke(futureTask.get()) } catch (e: Exception) { onListenProcess.onError(Throwable(e)) } } override fun authorize( body: AuthorizeRequest, onResult: (AuthorizeResponse) -> Unit, ) { val futureTask: CustomFuture<AuthorizeResponse> = CustomFuture( Callable { try { return@Callable Gson().fromJson( postMethodHttp( AUTHORIZE_ENDPOINT, body.toJson(), ), AuthorizeResponse::class.java, ) } catch (e: Exception) { Log.e(">>>>>>>>>>", e.message.toString()) throw Throwable(e) } }, onListenProcess, ) executorService.submit(futureTask) try { val response = futureTask.get() mToken = response.accessToken onResult.invoke(response) } catch (e: Exception) { onListenProcess.onError(Throwable(e)) } } override fun likeImage( id: String, onFailure: () -> Unit, ) { if (mToken.isNullOrBlank()) { onFailure() } val futureTask: FutureTask<Unit> = FutureTask( Callable { try { mToken?.let { postMethodHttpWithBearToken( "photos/$id/like", "", it, onFailure, ) } return@Callable } catch (e: Exception) { Log.e(">>>>>>>>>>", e.message.toString()) throw Throwable(e) } }, ) try { executorService.submit(futureTask) } catch (e: Exception) { Log.e(">>>>>>>>>>", e.message.toString()) } } override fun dislikeImage( id: String, onFailure: () -> Unit, ) { if (mToken.isNullOrBlank()) { onFailure() } val futureTask: FutureTask<Unit> = FutureTask( Callable { try { mToken?.let { deleteMethodHttpWithBearToken( "photos/$id/like", it, onFailure, ) } return@Callable } catch (e: Exception) { Log.e(">>>>>>>>>>", e.message.toString()) throw Throwable(e) } }, ) try { executorService.submit(futureTask) } catch (e: Exception) { Log.e(">>>>>>>>>>", e.message.toString()) } } override fun getFavoriteList( name: String, page: Int, onResult: (List<PhotoModel>) -> Unit, onFailure: () -> Unit, ) { if (mToken.isNullOrBlank()) { onFailure() } val executorService: ExecutorService = Executors.newCachedThreadPool() val futureTask: CustomFuture<List<PhotoModel>> = CustomFuture( Callable { try { val queryValue = mapOf( Pair(PAGE, page.toString()), ) return@Callable Gson().fromJsonToList<PhotoModel>( getMethodHttpWithBearToken( "users/$name/likes", queryValue, mToken.toString(), onFailure, ), ) } catch (e: Exception) { Log.e(">>>>>>>>", e.message.toString()) throw Throwable(e) } }, onListenProcess, ) executorService.submit(futureTask) try { onResult.invoke(futureTask.get()) } catch (e: Exception) { onListenProcess.onError(Throwable(e)) Log.e(">>>>>>>>", e.message.toString()) } } companion object { private var instance: ApiImpl? = null @JvmStatic fun getInstance(onListenProcess: OnListenProcess): ApiImpl = instance ?: ApiImpl(onListenProcess).also { instance = it } } }
'use client'; import Image from 'next/image'; import Link from 'next/link'; import { motion } from 'framer-motion'; import PostCountInfo from '../common/PostCountInfo'; interface PostCardProps { title: string; imageSrc?: string; likesNum: number; commentsNum: number; postId: number; } export default function PostCard({ title, imageSrc, likesNum, commentsNum, postId, }: PostCardProps) { return ( <motion.li whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}> <Link href={`/post/${postId}`} className="w-[200px] h-[175px] pt-[0.875rem] px-[0.625rem] pb-[0.625rem] flex flex-col bg-brown-10 border-2 border-brown-50 rounded-lg shadow-outer/down overflow-hidden"> <div className="w-[121px] h-[92px] rounded-lg overflow-hidden mb-2 mx-auto border-2 border-brown-40"> <Image className="object-cover object-center w-full h-full bg-brown-20 isolate" src={imageSrc || '/assets/img/bg_default_post.png'} alt="" width={235} height={178} /> </div> <h2 className="text-center text-sm leading-[0.875rem] text-brown-80 font-bold mb-[17px] overflow-hidden whitespace-nowrap text-ellipsis break-words"> {title} </h2> <PostCountInfo likesNum={likesNum} commentNum={commentsNum} usage="board" /> </Link> </motion.li> ); }
$cWhite: white; $cBlack: black; $breakpoints: ( // 480px以上(スマホの横向き)のモニタで適用 // "sm": "screen and (min-width: 480px)", // 600px以上のタブレットやモニタで適用 "md": "screen and (min-width: 834px)", // 960px以上のモニタで適用 // "lg": "screen and (min-width: 960px)", // 1280px以上のモニタで適用 // "xl": "screen and (min-width: 1280px)" ) !default; @mixin mq($breakpoint: md) { @media #{map-get($breakpoints, $breakpoint)} { @content; } } body { font-family: "Helvetica Neue", "Arial", "Hiragino Sans", "Meiryo", sans-serif; } ul { list-style: none; padding-left: 0; } ol { padding-left: 20px; } a { text-decoration: none; } img { max-width: 100%; } .mb-sm { margin-bottom: 16px !important; } .mb-lg { margin-bottom: 80px !important; // @include mq(lg) { // margin-bottom: 150px !important; // } } .pb-sm { padding-bottom: 16px !important; } .pb-lg { padding-bottom: 80px !important; // @include mq(lg) { // padding-bottom: 150px !important; // } } // .content-width { // width: 90%; // margin: 0 auto; // max-width: $contentMaxWidth; // } .flex { display: flex; flex-direction: column; @include mq(md) { flex-direction: row; flex-wrap: wrap; } } // font .font-sm { font-size: 12px; // @include mq(lg) { // font-size: 16px; // } } .font-md { font-size: 17px; // @include mq(lg) { // font-size: 19px; // } } .font-lr { font-size: 20px; // @include mq(lg) { // font-size: 23px; // } } .font-lg { font-size: 30px; // @include mq(lg) { // font-size: 36px; // } } .main-title { @extend .font-lg; // font-weight: 600; // margin-bottom: 0; // display: block; } // .sub-title { // @extend .font-sm; // @extend .mb-sm; // }
import Vuex from "vuex"; import VuePersist from "vuex-persist"; import Vue from "vue"; import { profile_settings } from "./profile"; import { sessions, currentSession } from "./sessions"; Vue.use(Vuex); const vuexLocal = new VuePersist({ storage: window.localStorage }); let initialstate = { currentSession: currentSession, sessions: sessions, // all sessions created by user audios: [], // Last audios retrieved from api server biblio: [], // Bibliotheque userProfile: undefined, user: null, // TODO: Use cookie insteand of store the token in the local storage token: null, alerts: [], main_theme: "bg-dark", width: null, theme: "dark", // ? --------------------- commentsPanel: { audioid: 0, audio: { id: null, }, open: false, }, }; export default new Vuex.Store({ plugins: [vuexLocal.plugin], state: { ...initialstate }, mutations: { setUserProfile: function (state, profile) { state.userProfile = profile; }, setCurrentSession: function (state, session) { state.currentSession = session; }, setPistPlaylist: function (state, playlist) { state.biblio = playlist; }, setToken: function (state, token) { state.token = token; }, setUser: function (state, user) { console.log("Set User:", user); state.user = user; }, setWidth: function (state, width) { state.width = width; }, updateUser: function (state, data) { if (Object.keys(state.user).includes(data.field)) { state.user[data.field] = data.value; } }, push_alert: function (state, alert) { alert.id = state.alerts.length + 1; state.alerts.push(alert); }, remove_alert: function (state, id) { state.alerts = state.alerts.filter((alert) => alert.id !== id); }, appendSession: function (state, session) { state.sessions.push(session); }, updateSession: function (state, data) { state.sessions.forEach((session, key) => { if (session.id == data.sessionid) { if (session.includes(data.field)) { state.sessions[key][data.field] = data.value; } } }); }, removeSession: function (state, sessionid) { state.Sessions = state.sessions.filter( (session) => session.id != sessionid ); }, setBiblio: function (state, pists) { state.biblio = pists; }, pushInBiblio: function (state, pist) { state.biblio.push(pist); }, removeInBiblio: function (state, pist_id) { state.biblio = state.biblio.filter((pist) => pist.id != pist_id); }, pusProfileSettings: function (state, settings) { for (const setting in settings) { if (Object.keys(state.profile_settings).includes(setting)) { state.profile_settings[setting] = settings[setting]; } else { state.profile_settings = { ...state.profile_settings, [setting]: settings[setting], }; } } }, updateProfileSettings: function (state, data) { if (profile_settings.includes(data.field)) state.profile_settings[data.field] = data.value; }, logout: function (state) { Object.assign(state, initialstate); window.location.href = "/"; }, // ? --------------------------- toggleCommentsPanel: function (state, data = null) { if (data != null) state.commentsPanel.open; else state.commentsPanel.open = !state.commentsPanel.open; }, setCommentsPanelAudio(state, audio) { state.commentsPanel.audio = audio; }, }, actions: { get_pistdata: function (context, data) { let toreturn; context.state.pists.filter((imported) => { if (imported.id === data.pistid) { switch (data.field) { case "volume": toreturn = imported.volume; break; } } }); return toreturn; }, getState: function (context) { console.log(context.state); return JSON.parse(context.state); }, }, });
import { LightningElement, api, wire } from 'lwc'; import { getListUi } from 'lightning/uiListApi'; import type { ShadowRootTheGoodPart } from 'lwc'; import type { OrgRecord, RecordError, RecordPayload } from 'example/data'; // Chart.js interfaces declare global { interface Window { // eslint-disable-next-line @typescript-eslint/no-explicit-any Chart: any; } } interface ChartData { labels: string[]; datasets: { backgroundColor: string[]; borderColor: string[]; borderWidth: number; data: number[]; }[]; } interface ChartElement { index: number; } interface Chart extends Element { ctx: CanvasRenderingContext2D; data: ChartData; update: () => void; getElementsAtEventForMode: ( e: Event, mode: string, options: unknown, useFinalPosition: boolean, ) => ChartElement[]; } export default class ExampleDataChart extends LightningElement { @api listView = 'AllOpportunities'; records: OrgRecord[] = []; loading = true; showLogin = false; errorMsg?: string; @wire(getListUi, { objectApiName: 'Opportunity', listViewApiName: '$listView', }) getRecords({ error, data }: { error: RecordError; data: RecordPayload }): void { if (data) { this.records = data.records.records; this.loading = false; // Redraw the chart when the list of records changes this.drawChart(); } else if (error) { if (error.status === 401) { this.showLogin = true; } this.errorMsg = `Data chart failed to fetch records. ${error.body.message}`; this.loading = false; } } // Update the field used on the chart's x axis _field = 'StageName'; @api get field(): string { return this._field; } set field(value: string) { this._field = value; this.drawChart(); } // Chart and canvas rendered = false; renderedCallback(): void { this.rendered = true; } _chart: Chart | undefined; _canvas: HTMLCanvasElement | undefined; get canvas(): HTMLCanvasElement { // The chart must be manually placed in the DOM if (!this._canvas) { this._canvas = document.createElement('canvas'); const canvasContainer = (this.template as ShadowRootTheGoodPart).querySelector('div.canvas'); if (canvasContainer) { canvasContainer.appendChild(this._canvas); } } return this._canvas; } backgroundcolor = [ 'rgba(63, 15, 64, 0.3)', // purple 'rgba(53, 196, 239, 0.3)', // light blue 'rgba(237, 178, 46, 0.3)', // yellow 'rgba(46, 181, 124, 0.3)', // green 'rgba(225, 29, 89, 0.3)', // pink 'rgba(18, 100, 163, 0.3)', // dark blue 'rgba(63, 15, 64, 0.3)', // purple 'rgba(53, 196, 239, 0.3)', // light blue 'rgba(237, 178, 46, 0.3)', // yellow 'rgba(46, 181, 124, 0.3)', // green 'rgba(225, 29, 89, 0.3)', // pink 'rgba(18, 100, 163, 0.3)', // dark blue ]; get bordercolor(): string[] { // Border is an opaque version of the background fill color return this.backgroundcolor.map((color) => color.replace('0.3', '1')); } get chartData(): ChartData { // Chart.js options return { labels: this.dataLabels, datasets: [ { backgroundColor: this.backgroundcolor, borderColor: this.bordercolor, borderWidth: 2, data: this.dataAmounts, }, ], }; } drawChart(): void { if (this.rendered) { try { if (!this._chart || !this._chart.ctx) { this._chart = new window.Chart(this.canvas.getContext('2d'), { type: 'bar', data: this.chartData, options: { scales: { y: { type: 'linear', min: 0, ticks: { stepSize: 1 } } }, plugins: { legend: { display: false, labels: { boxHeight: 0 } } }, }, }); this.canvas.addEventListener('click', this.barClickHandler.bind(this)); } else { const newData = this.chartData; this._chart.data.labels = newData.labels; this._chart.data.datasets[0].data = newData.datasets[0].data; this._chart.update(); } } catch (error) { console.error('Error drawing chart:', error); } } } // Record data manipulation get dataLabels(): string[] { return Array.from(this.chartRecords.keys()); } get dataAmounts(): number[] { return Array.from(this.chartRecords.values()); } get chartRecords(): Map<string, number> { // Get dataset.data for the chart from the records let data: Map<string, number> = // Put stage names into the correct pipeline order this.field === 'StageName' ? new Map([ ['Prospecting', 0], ['Needs Analysis', 0], ['Proposal/Price Quote', 0], ['Negotiation/Review', 0], ['Closed Won', 0], ['Closed Lost', 0], ]) : new Map(); // Sum up the number of Opportunities for each field value this.records.forEach((r) => { const key = r.fields[this.field].displayValue; if (data.has(key)) { data.set(key, (data.get(key) as number) + 1); } else { data.set(key, 1); } }); // Alphabetize values from the Account field if (this.field === 'Account') { data = new Map([...data.entries()].sort()); } return data; } // Sidebar data table handling barClickHandler(event: Event): void { // Open a data table for all the records with the given field value const index = (this._chart as Chart).getElementsAtEventForMode( event, 'nearest', { intersect: true }, false, )[0]?.index; if (index >= 0) { // Notify "example/data" that a chart bar has been clicked // The "detail" is the field value (e.g. "Closed Won") this.dispatchEvent(new CustomEvent('barclick', { detail: this.dataLabels[index] })); } } }
import * as THREE from 'three'; import utils from 'toolkit/utils'; import fragmentShader from './shaders/cloud.frag'; import vertexShader from './shaders/cloud.vert'; // https://tympanus.net/codrops/2020/01/28/how-to-create-procedural-clouds-using-three-js-sprites/ // https://github.com/dghez/THREEJS_Procedural-clouds/blob/c836e00be15dc92a36cbaf11453f754e1dbcaed0/src/js/components/Canvas/Environment/Cloud/index.js export class Cloud { constructor({ shapeTexture, noiseTexture, centerCoord = new THREE.Vector3(), angle, }) { this.minY = -50; this.maxY = -35; this.centerCoord = new THREE.Vector3( centerCoord.x, utils.randomFloatBetween(this.minY, this.maxY), centerCoord.z, ); this.minRadius = utils.randomFloatBetween(40, 50); this.maxRadius = utils.randomFloatBetween(70, 90); this.radius = 70; this.angle = angle; this.angleVelocity = utils.randomFloatBetween(0.001, 0.005); this.yVelocity = utils.randomFloatBetween(0.01, 0.04); const size = utils.randomFloatBetween(70, 90); this.geometry = new THREE.PlaneGeometry(size, size, size * 3, size * 3); this.material = new THREE.ShaderMaterial({ vertexShader, fragmentShader, uniforms: { ...THREE.UniformsUtils.clone(THREE.ShaderLib.sprite.uniforms), uTime: { value: 0 }, uTxtShape: { value: shapeTexture }, uTxtCloudNoise: { value: noiseTexture }, uFac1: { value: utils.randomFloatBetween(8, 10) }, uFac2: { value: utils.randomFloatBetween(2, 3) }, uTimeFactor1: { value: utils.randomFloatBetween(0.001, 0.007) }, uTimeFactor2: { value: utils.randomFloatBetween(0.0001, 0.003) }, uDisplStrenght1: { value: utils.randomFloatBetween(0.04, 0.08) }, uDisplStrenght2: { value: utils.randomFloatBetween(0.02, 0.15) }, }, transparent: true, side: THREE.DoubleSide, }); this.pivot = new THREE.Mesh(this.geometry, this.material); this.updatePostion(); } get position() { return this.pivot.position; } dispose() { this.geometry.dispose(); this.material.dispose(); } updateRadius() { this.radius = utils.remap(this.minY, this.maxY, this.minRadius, this.maxRadius, this.centerCoord.y); } updatePostion() { this.position.x = this.centerCoord.x + this.radius * Math.cos(this.angle); this.position.z = this.centerCoord.z + this.radius * Math.sin(this.angle); this.centerCoord.y += this.yVelocity; this.position.y = this.centerCoord.y; } update(uTime) { this.material.uniforms.uTime.value = uTime; } }
package com.CachWeb.Cach.controller; import com.CachWeb.Cach.entity.Currency; import com.CachWeb.Cach.entity.ExchangeRate; import com.CachWeb.Cach.entity.ExchangeRequest; import com.CachWeb.Cach.entity.Image; import com.CachWeb.Cach.repository.ImageRepository; import com.CachWeb.Cach.service.*; import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.math.BigDecimal; import java.security.Principal; import java.util.List; @Controller @RequestMapping("/admin") public class AdminController { @Autowired private CurrencyService currencyService; @Autowired private ExchangeRateService exchangeRateService; @Autowired private ContactService contactService; @Autowired private ExchangeRequestService exchangeRequestService; @Autowired private ImageRepository imageRepository; @GetMapping({"/list",""}) public String listCurrencies(Model model, HttpServletRequest request, Principal principal) { List<Currency> currencies = currencyService.getAllCurrencies(); model.addAttribute("currencies", currencies); // Check if the user is authenticated boolean isAuthenticated = principal != null; // Add a flag to the model to indicate whether the user is authenticated model.addAttribute("isAuthenticated", isAuthenticated); return "admin/currency_list"; } //To add Now Currency @GetMapping("/add") public String showAddCurrencyForm(Model model) { model.addAttribute("currency", new Currency()); return "admin/add_currency_form"; } @PostMapping("/add") public String addCurrency(@ModelAttribute Currency currency) { currencyService.addCurrency(currency); return "redirect:/admin/list"; } @GetMapping("/delete/currency/{id}") public String deleteCurrency(@PathVariable Long id) { currencyService.remove(id); return "redirect:/admin/list"; } //exchange @GetMapping("/exchange-list") public String listExchange(Model model , HttpServletRequest request, Principal principal) { List<ExchangeRate> rateList = exchangeRateService.getAllExchangeRates(); model.addAttribute("rateList", rateList); // Check if the user is authenticated boolean isAuthenticated = principal != null; // Add a flag to the model to indicate whether the user is authenticated model.addAttribute("isAuthenticated", isAuthenticated); return "admin/exchange_list"; } @GetMapping("/contacts") public String listcontact(Model model , HttpServletRequest request, Principal principal) { model.addAttribute("contact", contactService.getAllContacts()); // Check if the user is authenticated boolean isAuthenticated = principal != null; // Add a flag to the model to indicate whether the user is authenticated model.addAttribute("isAuthenticated", isAuthenticated); return "admin/contactreq"; } @GetMapping("/delete/contact/{id}") public String deleteContact(@PathVariable Long id){ contactService.remove(id); return "redirect:/admin/contacts"; } //To add Exchange @GetMapping("/addExchange") public String addExtchange(Model model){ List<Currency> currencies = currencyService.getAllCurrencies(); model.addAttribute("currencies",currencies); model.addAttribute("exchangrate", new ExchangeRate()); return "admin/addExchange"; } @PostMapping("/addExchange") public String saveExchange( @ModelAttribute ExchangeRate exchangeRate){ exchangeRateService.save(exchangeRate); return "redirect:/admin/exchange-list"; } @GetMapping("/delete/exchange/{id}") public String deleteExchange(@PathVariable Long id) { exchangeRateService.remove(id); return "redirect:/admin/exchange-list"; } @GetMapping("/exchange-requests") public String showEntities(Model model) { List<ExchangeRequest> exchange = exchangeRequestService.getAllRequestsWithoutArchived(); model.addAttribute("exchange", exchange); return "admin/excahngeRequests"; } @PostMapping("/update-request") public String updateRequest(@RequestParam Long requestId, @RequestParam("sendingAmount") BigDecimal sendingAmount, @RequestParam("receivingAmount") BigDecimal receivingAmount, @RequestParam("walletNumber") String walletNumber) { // Logic to handle the update action // System.out.println("JRERE"); // System.out.println(requestId); // System.out.println(walletNumber); // System.out.println(sendingAmount); // System.out.println(receivingAmount); exchangeRequestService.updateRequest(requestId, sendingAmount, receivingAmount, walletNumber); return "redirect:/admin/exchange-requests"; } @GetMapping("/images/{id}") public ResponseEntity<byte[]> getImage(@PathVariable Long id) { Image image = imageRepository.getReferenceById(id); if (image != null && image.getData() != null) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); return new ResponseEntity<>(image.getData(), headers, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @PostMapping("/exchange/delete/{id}") public String deleteRequests(@PathVariable("id") Long id) { exchangeRequestService.remove(id); return "redirect:/admin/all-requests-including-archived"; } @GetMapping("/all-requests-including-archived") public String getAllRequestsWithArchived(Model model) { List<ExchangeRequest> allRequests = exchangeRequestService.getAllRequestsIncludingArchived(); model.addAttribute("allRequests", allRequests); return "admin/all_requests_including_archived"; } @PostMapping("/archive-request") public String archiveRequest(@RequestParam Long requestId) { exchangeRequestService.archiveRequest(requestId); return "redirect:/admin/all-requests-including-archived"; } }
<script > import TipoDataService from '../services/TipoDataService'; import Tipo from '../models/Tipo' import Loading from "vue-loading-overlay"; export default { name: 'tipos-novo', data() { return { isLoading: false, tipo: new Tipo(), salvo: false } }, components: { Loading }, methods: { salvar() { this.isLoading = true; TipoDataService.atualizar(this.tipo.id, this.tipo) .then(resposta => { this.tipo.id = resposta.id; this.salvo = true; this.isLoading = false; }) .catch(erro => { console.log(erro); this.salvo = false; this.isLoading = false; }) }, voltar() { this.$router.push({ name: 'tipos-lista' }); }, carregarTipo(id) { this.isLoading = true; TipoDataService.buscarPeloId(id) .then(resposta => { this.tipo = resposta; this.isLoading = false; }) .catch(erro => { console.log(erro); this.isLoading = false; }) } }, mounted() { this.carregarTipo(this.$route.params.id) } } </script> <template> <h2 class="mt-4">Editar tipo </h2> <div class="border p-2 rounded row-1 col-6 " style="max-width: 450px;"> <div v-if="!salvo"> <loading v-model:active="isLoading" is-full-page="false" /> <form class="row"> <div class="mb-3 "> <label for="nome" class="form-label">Nome do Tipo a ser editado</label> <input type="Text" class="form-control" v-model="tipo.nome" id="nome" placeholder="ex. Água" required> </div> <div> <button @click.prevent="salvar" class="btn btn-dark row-1">Salvar</button> </div> </form> </div> <div v-else> <div class="row"> <h4 class="mt-2">Tipo atualizado com sucesso!</h4> <span>Tipo id: {{tipo.id}}</span> </div> <div class="row-sm"> <button @click="voltar" class="btn btn-dark mt-2">Voltar</button> </div> </div> </div> </template>
package com.lrc.ocr.config; import com.lrc.ocr.prop.WechatPayProp; import com.wechat.pay.java.core.Config; import com.wechat.pay.java.core.RSAAutoCertificateConfig; import com.wechat.pay.java.core.notification.NotificationConfig; import com.wechat.pay.java.core.notification.NotificationParser; import com.wechat.pay.java.service.payments.nativepay.NativePayService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import javax.annotation.Resource; import java.io.File; import java.io.InputStream; @Slf4j @Configuration public class WeChatPayConfig { @Resource private WechatPayProp wechatPayProp; @Bean public NativePayService buildNativePayService() { // 支付配置 Config config = new RSAAutoCertificateConfig.Builder() .merchantId(wechatPayProp.getMchId()) .privateKeyFromPath(getFilePath(wechatPayProp.getPrivateKeyFilePath())) .merchantSerialNumber(wechatPayProp.getMchSerialNo()) .apiV3Key(wechatPayProp.getApiV3Key()) .build(); // NativePay 支付服务 return new NativePayService.Builder().config(config).build(); } @Bean public NotificationConfig buildNotificationConfig() { return new RSAAutoCertificateConfig.Builder() .merchantId(wechatPayProp.getMchId()) .privateKeyFromPath(getFilePath(wechatPayProp.getPrivateKeyFilePath())) .merchantSerialNumber(wechatPayProp.getMchSerialNo()) .apiV3Key(wechatPayProp.getApiV3Key()) .build(); } @Bean public NotificationParser buildNotificationParser(NotificationConfig notificationConfig) { return new NotificationParser(notificationConfig); } public static String getFilePath(String classFilePath) { String filePath = ""; try { String templateFilePath = "tempfiles/classpathfile/"; File tempDir = new File(templateFilePath); if (!tempDir.exists()) { tempDir.mkdirs(); } String[] filePathList = classFilePath.split("/"); String checkFilePath = "tempfiles/classpathfile"; for (String item : filePathList) { checkFilePath += "/" + item; } File tempFile = new File(checkFilePath); if (tempFile.exists()) { filePath = checkFilePath; } else { //解析 ClassPathResource classPathResource = new ClassPathResource(classFilePath); InputStream inputStream = classPathResource.getInputStream(); checkFilePath = "tempfiles/classpathfile"; for (int i = 0; i < filePathList.length; i++) { checkFilePath += "/" + filePathList[i]; if (i == filePathList.length - 1) { //文件 File file = new File(checkFilePath); if (!file.exists()) { FileUtils.copyInputStreamToFile(inputStream, file); } } else { //目录 tempDir = new File(checkFilePath); if (!tempDir.exists()) { tempDir.mkdirs(); } } } inputStream.close(); filePath = checkFilePath; } } catch (Exception e) { e.printStackTrace(); } return filePath; } }
// // LemmatizerTests.swift // LyraPlayTests // // Created by Azat Kaiumov on 22.07.22. // import Foundation import XCTest import LyraPlay class LemmatizerTests: XCTestCase { typealias SUT = Lemmatizer func createSUT() -> SUT { let lemmatizer = LemmatizerImpl() detectMemoryLeak(instance: lemmatizer) return lemmatizer } func test_lemmatize__empty_text() async throws { let sut = createSUT() // Given let emptyText = "" // When let result = sut.lemmatize(text: emptyText) // Then let receivedItems = result.map { ExpectedLemma(from: $0, text: emptyText) } XCTAssertEqual(receivedItems, []) } func test_lemmatize__not_empty_text() async throws { // Given let notEmptyText = "What is she doing? She speaks English very well" let sut = createSUT() // When let result = sut.lemmatize(text: notEmptyText) // Then let expectedItems: [ExpectedLemma] = [ .init(lemma: "what", text: "What"), .init(lemma: "be", text: "is"), .init(lemma: "she", text: "she"), .init(lemma: "do", text: "doing"), .init(lemma: "she", text: "She"), .init(lemma: "speak", text: "speaks"), .init(lemma: "English", text: "English"), .init(lemma: "very", text: "very"), .init(lemma: "well", text: "well"), ] let receivedItems = result.map { ExpectedLemma(from: $0, text: notEmptyText) } AssertEqualReadable(receivedItems, expectedItems) } } // MARK: - Helpers struct ExpectedLemma: Equatable { var lemma: String var text: String init(lemma: String, text: String) { self.lemma = lemma self.text = text } init(from item: LemmaItem, text: String) { self.lemma = item.lemma self.text = String(text[item.range]) } }
import React, { useContext, useEffect, useRef, useState } from 'react'; import noteContext from '../context/notes/noteContext'; import Noteitem from './Noteitem'; import AddNote from './AddNote'; import { useNavigate } from 'react-router'; const Notes = (props) => { const context = useContext(noteContext); let history = useNavigate(); const { notes, getNotes, editNote } = context; useEffect(() => { if (localStorage.getItem('token')) { getNotes(); } else { history("/login"); } // eslint-disable-next-line }, []) const [note, setnote] = useState({ id: "", etitle: "", edescription: "", etag: "General" }) const updateNote = (currentNote) => { ref.current.click(); setnote({ id: currentNote._id, etitle: currentNote.title, edescription: currentNote.description, etag: currentNote.tag }); } const ref = useRef(null) const refClose = useRef(null) const handleClick = (e) => { e.preventDefault(); editNote(note.id, note.etitle, note.edescription, note.etag) refClose.current.click(); props.showAlert("Note updated successfully", "success"); } const handleChange = (e) => { setnote({ ...note, [e.target.name]: e.target.value }) } const handleAdd = () => { if (document.getElementById("addform").hidden === true) document.getElementById("addform").hidden = false; else document.getElementById("addform").hidden = true; } return ( <> <AddNote showAlert={props.showAlert} /> <button ref={ref} type="button" className="btn btn-primary d-none" data-bs-toggle="modal" data-bs-target="#exampleModal"> Launch demo modal </button> <div className="modal fade" id="exampleModal" tabIndex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" style={{color:"black"}}> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h1 className="modal-title fs-5" id="exampleModalLabel">Edit Note</h1> <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div className="modal-body"> <form className='my-3'> <div className="mb-3"> <label htmlFor="etitle" className="form-label">Title</label> <input type="text" className="form-control" id="etitle" name="etitle" aria-describedby="" onChange={handleChange} required value={note.etitle} /> </div> <div className="mb-3"> <label htmlFor="edescription" className="form-label">Description</label> <input type="text" className="form-control" id="edescription" name="edescription" onChange={handleChange} required value={note.edescription} /> </div> <div className="mb-3"> <label htmlFor="etag" className='form-label' value={note.etag}>Tag</label> <input type='text' className='form-control' id='etag' name='etag' /> </div> </form> </div> <div className="modal-footer"> <button ref={refClose} type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" className="btn btn-primary" onClick={handleClick}>Update Note</button> </div> </div> </div> </div> <div> <div className="container row my-3" style={{border:"1px solid black",borderRadius:"10px",padding:"10px",backgroundColor:"rgb(73 88 86)"}}> <div className='row justify-content-between'> <h2 style={{color:"white"}} className='col-3'>Your notes</h2> <button onClick={handleAdd} style={{ marginTop: "10px", marginBottom: "50px", backgroundColor: "#323232", color: "white" }} className="btn btn-dark col-3">Add a new note</button> </div> <div className="container mx-2"> {notes.length === 0 && 'No notes to display.'} </div> {notes.map((note) => { return <Noteitem key={note._id} updateNote={updateNote} note={note} showAlert={props.showAlert} /> })} </div> </div> </> ) } export default Notes
<?php namespace App\Http\Controllers\Admin\Website; use Alert; use App\Models\Alur; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class AlurController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $data = array( 'title' => 'Alur Pendaftaran', 'alur' => Alur::orderBy('id', 'DESC')->get() ); return view('pages.admin.website.alur.index', $data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return abort(403); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $judul = $request->judul; $deskripsi = $request->deskripsi; $data = array( 'judul' => $judul, 'deskripsi' => $deskripsi, ); $add = Alur::create($data); if ($add) { Alert::success('Berhasil', 'Data berhasil di tambahkan !'); return redirect()->route('admin.alur.index'); } else { Alert::error('Gagal', 'Data gagal di tambahkan !'); return redirect()->route('admin.alur.index'); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return abort(403); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { return abort(403); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $judul = $request->judul; $deskripsi = $request->deskripsi; $data = array( 'judul' => $judul, 'deskripsi' => $deskripsi, ); $edit = Alur::where('id', $id)->update($data); if ($edit) { Alert::success('Berhasil', 'Data berhasil di edit !'); return redirect()->route('admin.alur.index'); } else { Alert::error('Gagal', 'Data gagal di edit !'); return redirect()->route('admin.alur.index'); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $del = Alur::destroy($id); if ($del) { Alert::success('Berhasil', 'Data berhasil di hapus !'); return redirect()->route('admin.alur.index'); } else { Alert::error('Gagal', 'Data gagal di hapus !'); return redirect()->route('admin.alur.index'); } } }
class Ticket < ActiveRecord::Base paginates_per 50 # 200 seems to be a common number to use for API return objects per request. belongs_to :project belongs_to :user belongs_to :state has_many :comments has_many :assets has_and_belongs_to_many :tags has_and_belongs_to_many :watchers, :join_table => "ticket_watchers", :class_name => "User" accepts_nested_attributes_for :assets validates :title, :presence => true validates :description, :presence => true, :length => {:minimum => 10} after_create :creator_watches_me searcher do label :tag, :from => :tags, :field => :name label :state, :from => :state, :field => :name end def tag!(tags) tags = tags.split(" ").map do |tag| Tag.find_or_create_by_name(tag) end self.tags << tags end def creator_watches_me self.watchers << self.user end end
/* * DISTRHO Cardinal Plugin * Copyright (C) 2021-2022 Filipe Coelho <falktx@falktx.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of * the License, or 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. * * For a full copy of the GNU General Public License see the LICENSE file. */ /** * This file is an edited version of VCVRack's window/Window.cpp * Copyright (C) 2016-2021 VCV. * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. */ #include <map> #include <queue> #include <thread> #include <window/Window.hpp> #include <asset.hpp> #include <widget/Widget.hpp> #include <app/Scene.hpp> #include <context.hpp> #include <patch.hpp> #include <settings.hpp> #include <plugin.hpp> // used in Window::screenshot #include <system.hpp> // used in Window::screenshot #ifdef NDEBUG # undef DEBUG #endif #include "DistrhoUI.hpp" #include "Application.hpp" #include "../CardinalCommon.hpp" #include "../WindowParameters.hpp" #ifndef DGL_NO_SHARED_RESOURCES # include "src/Resources.hpp" #endif namespace rack { namespace window { static const math::Vec WINDOW_SIZE_MIN = math::Vec(648, 538); struct FontWithOriginalContext : Font { int ohandle = -1; std::string ofilename; }; struct ImageWithOriginalContext : Image { int ohandle = -1; std::string ofilename; }; Font::~Font() { // There is no NanoVG deleteFont() function yet, so do nothing } void Font::loadFile(const std::string& filename, NVGcontext* vg) { this->vg = vg; std::string name = system::getStem(filename); size_t size; // Transfer ownership of font data to font object uint8_t* data = system::readFile(filename, &size); // Don't use nvgCreateFont because it doesn't properly handle UTF-8 filenames on Windows. handle = nvgCreateFontMem(vg, name.c_str(), data, size, 0); if (handle < 0) { std::free(data); throw Exception("Failed to load font %s", filename.c_str()); } INFO("Loaded font %s", filename.c_str()); } std::shared_ptr<Font> Font::load(const std::string& filename) { return APP->window->loadFont(filename); } Image::~Image() { // TODO What if handle is invalid? if (handle >= 0) nvgDeleteImage(vg, handle); } void Image::loadFile(const std::string& filename, NVGcontext* vg) { this->vg = vg; std::vector<uint8_t> data = system::readFile(filename); // Don't use nvgCreateImage because it doesn't properly handle UTF-8 filenames on Windows. handle = nvgCreateImageMem(vg, NVG_IMAGE_REPEATX | NVG_IMAGE_REPEATY, data.data(), data.size()); if (handle <= 0) throw Exception("Failed to load image %s", filename.c_str()); INFO("Loaded image %s", filename.c_str()); } std::shared_ptr<Image> Image::load(const std::string& filename) { return APP->window->loadImage(filename); } struct Window::Internal { std::string lastWindowTitle; DISTRHO_NAMESPACE::UI* ui = nullptr; DISTRHO_NAMESPACE::WindowParameters params; DISTRHO_NAMESPACE::WindowParametersCallback* callback = nullptr; DGL_NAMESPACE::Application hiddenApp; DGL_NAMESPACE::Window hiddenWindow; NVGcontext* r_vg = nullptr; NVGcontext* r_fbVg = nullptr; NVGcontext* o_vg = nullptr; NVGcontext* o_fbVg = nullptr; math::Vec size = WINDOW_SIZE_MIN; int mods = 0; int currentRateLimit = 0; int frame = 0; int frameSwapInterval = 1; double monitorRefreshRate = 60.0; double frameTime = 0.0; double lastFrameDuration = 0.0; std::map<std::string, std::shared_ptr<FontWithOriginalContext>> fontCache; std::map<std::string, std::shared_ptr<ImageWithOriginalContext>> imageCache; bool fbDirtyOnSubpixelChange = true; int fbCount = 0; Internal() : hiddenApp(false), hiddenWindow(hiddenApp) { hiddenApp.idle(); } }; #ifndef DGL_NO_SHARED_RESOURCES static int loadFallbackFont(NVGcontext* const vg) { const int font = nvgFindFont(vg, NANOVG_DEJAVU_SANS_TTF); if (font >= 0) return font; using namespace dpf_resources; return nvgCreateFontMem(vg, NANOVG_DEJAVU_SANS_TTF, (uchar*)dejavusans_ttf, dejavusans_ttf_size, 0); } #endif Window::Window() { internal = new Internal; DGL_NAMESPACE::Window::ScopedGraphicsContext sgc(internal->hiddenWindow); // Set up NanoVG const int nvgFlags = NVG_ANTIALIAS; vg = nvgCreateGL(nvgFlags); DISTRHO_SAFE_ASSERT_RETURN(vg != nullptr,); #ifdef NANOVG_GLES2 fbVg = nvgCreateSharedGLES2(vg, nvgFlags); #else fbVg = nvgCreateSharedGL2(vg, nvgFlags); #endif // Load default Blendish font #ifndef DGL_NO_SHARED_RESOURCES uiFont = std::make_shared<Font>(); uiFont->vg = vg; uiFont->handle = loadFallbackFont(vg); std::shared_ptr<FontWithOriginalContext> uiFont2; uiFont2 = std::make_shared<FontWithOriginalContext>(); uiFont2->vg = vg; uiFont2->handle = loadFallbackFont(vg); uiFont2->ofilename = asset::system("res/fonts/DejaVuSans.ttf"); internal->fontCache[uiFont2->ofilename] = uiFont2; #else uiFont = loadFont(asset::system("res/fonts/DejaVuSans.ttf")); #endif if (uiFont != nullptr) bndSetFont(uiFont->handle); } void WindowSetPluginUI(Window* const window, DISTRHO_NAMESPACE::UI* const ui) { if (ui != nullptr) { const GLubyte* vendor = glGetString(GL_VENDOR); const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); INFO("Renderer: %s %s", vendor, renderer); INFO("OpenGL: %s", version); window->internal->ui = ui; window->internal->size = rack::math::Vec(ui->getWidth(), ui->getHeight()); // Set up NanoVG window->internal->r_vg = ui->getContext(); #ifdef NANOVG_GLES2 window->internal->r_fbVg = nvgCreateSharedGLES2(window->internal->r_vg, NVG_ANTIALIAS); #else window->internal->r_fbVg = nvgCreateSharedGL2(window->internal->r_vg, NVG_ANTIALIAS); #endif // swap contexts window->internal->o_vg = window->vg; window->internal->o_fbVg = window->fbVg; window->vg = window->internal->r_vg; window->fbVg = window->internal->r_fbVg; // also for fonts and images window->uiFont->vg = window->vg; window->uiFont->handle = loadFallbackFont(window->vg); for (auto& font : window->internal->fontCache) { font.second->vg = window->vg; font.second->ohandle = font.second->handle; font.second->handle = nvgCreateFont(window->vg, font.second->ofilename.c_str(), font.second->ofilename.c_str()); } for (auto& image : window->internal->imageCache) { image.second->vg = window->vg; image.second->ohandle = image.second->handle; image.second->handle = nvgCreateImage(window->vg, image.second->ofilename.c_str(), NVG_IMAGE_REPEATX | NVG_IMAGE_REPEATY); } // Init settings WindowParametersRestore(window); widget::Widget::ContextCreateEvent e; APP->scene->onContextCreate(e); } else { widget::Widget::ContextDestroyEvent e; APP->scene->onContextDestroy(e); // swap contexts window->uiFont->vg = window->internal->o_vg; window->vg = window->internal->o_vg; window->fbVg = window->internal->o_fbVg; window->internal->o_vg = nullptr; window->internal->o_fbVg = nullptr; // also for fonts and images window->uiFont->vg = window->vg; window->uiFont->handle = loadFallbackFont(window->vg); for (auto& font : window->internal->fontCache) { font.second->vg = window->vg; font.second->handle = font.second->ohandle; font.second->ohandle = -1; } for (auto& image : window->internal->imageCache) { image.second->vg = window->vg; image.second->handle = image.second->ohandle; image.second->ohandle = -1; } #if defined NANOVG_GLES2 nvgDeleteGLES2(window->internal->r_fbVg); #else nvgDeleteGL2(window->internal->r_fbVg); #endif window->internal->ui = nullptr; window->internal->callback = nullptr; } } void WindowSetMods(Window* const window, const int mods) { window->internal->mods = mods; } Window::~Window() { { DGL_NAMESPACE::Window::ScopedGraphicsContext sgc(internal->hiddenWindow); internal->hiddenWindow.close(); internal->hiddenApp.idle(); // Fonts and Images in the cache must be deleted before the NanoVG context is deleted internal->fontCache.clear(); internal->imageCache.clear(); #if defined NANOVG_GLES2 nvgDeleteGLES2(internal->o_fbVg != nullptr ? internal->o_fbVg : fbVg); nvgDeleteGLES2(internal->o_vg != nullptr ? internal->o_vg : vg); #else nvgDeleteGL2(internal->o_fbVg != nullptr ? internal->o_fbVg : fbVg); nvgDeleteGL2(internal->o_vg != nullptr ? internal->o_vg : vg); #endif } delete internal; } math::Vec Window::getSize() { return internal->size; } void Window::setSize(math::Vec size) { size = size.max(WINDOW_SIZE_MIN); internal->size = size; if (DISTRHO_NAMESPACE::UI* const ui = internal->ui) ui->setSize(internal->size.x, internal->size.y); } void Window::run() { internal->frame = 0; } void Window::step() { DISTRHO_SAFE_ASSERT_RETURN(internal->ui != nullptr,); double frameTime = system::getTime(); double lastFrameTime = internal->frameTime; internal->frameTime = frameTime; internal->lastFrameDuration = frameTime - lastFrameTime; internal->fbCount = 0; // DEBUG("%.2lf Hz", 1.0 / internal->lastFrameDuration); // Make event handlers and step() have a clean NanoVG context nvgReset(vg); if (uiFont != nullptr) bndSetFont(uiFont->handle); // Set window title std::string windowTitle = APP_NAME + " " + APP_EDITION_NAME + " " + APP_VERSION; if (APP->patch->path != "") { windowTitle += " - "; if (!APP->history->isSaved()) windowTitle += "*"; windowTitle += system::getFilename(APP->patch->path); } if (windowTitle != internal->lastWindowTitle) { internal->ui->getWindow().setTitle(windowTitle.c_str()); internal->lastWindowTitle = windowTitle; } // Get desired pixel ratio float newPixelRatio = internal->ui->getScaleFactor(); if (newPixelRatio != pixelRatio) { pixelRatio = newPixelRatio; APP->event->handleDirty(); } // Get framebuffer/window ratio int winWidth = internal->ui->getWidth(); int winHeight = internal->ui->getHeight(); int fbWidth = winWidth;// * newPixelRatio; int fbHeight = winHeight;// * newPixelRatio; windowRatio = (float)fbWidth / winWidth; if (APP->scene) { // DEBUG("%f %f %d %d", pixelRatio, windowRatio, fbWidth, winWidth); // Resize scene APP->scene->box.size = math::Vec(fbWidth, fbHeight).div(pixelRatio); // Step scene APP->scene->step(); // Render scene { // Update and render nvgScale(vg, pixelRatio, pixelRatio); // Draw scene widget::Widget::DrawArgs args; args.vg = vg; args.clipBox = APP->scene->box.zeroPos(); APP->scene->draw(args); glViewport(0, 0, fbWidth, fbHeight); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } } ++internal->frame; } void Window::activateContext() { } void Window::screenshot(const std::string&) { } void Window::screenshotModules(const std::string&, float) { } void Window::close() { DISTRHO_SAFE_ASSERT_RETURN(internal->ui != nullptr,); internal->ui->getWindow().close(); } void Window::cursorLock() { } void Window::cursorUnlock() { } bool Window::isCursorLocked() { return false; } int Window::getMods() { return internal->mods; } void Window::setFullScreen(bool) { } bool Window::isFullScreen() { return false; } double Window::getMonitorRefreshRate() { return internal->monitorRefreshRate; } double Window::getFrameTime() { return internal->frameTime; } double Window::getLastFrameDuration() { return internal->lastFrameDuration; } double Window::getFrameDurationRemaining() { double frameDurationDesired = internal->frameSwapInterval / internal->monitorRefreshRate; return frameDurationDesired - (system::getTime() - internal->frameTime); } std::shared_ptr<Font> Window::loadFont(const std::string& filename) { const auto& pair = internal->fontCache.find(filename); if (pair != internal->fontCache.end()) return pair->second; // Load font std::shared_ptr<FontWithOriginalContext> font; try { font = std::make_shared<FontWithOriginalContext>(); font->ofilename = filename; font->loadFile(filename, vg); } catch (Exception& e) { WARN("%s", e.what()); font = nullptr; } internal->fontCache[filename] = font; return font; } std::shared_ptr<Image> Window::loadImage(const std::string& filename) { const auto& pair = internal->imageCache.find(filename); if (pair != internal->imageCache.end()) return pair->second; // Load image std::shared_ptr<ImageWithOriginalContext> image; try { image = std::make_shared<ImageWithOriginalContext>(); image->ofilename = filename; image->loadFile(filename, vg); } catch (Exception& e) { WARN("%s", e.what()); image = nullptr; } internal->imageCache[filename] = image; return image; } bool& Window::fbDirtyOnSubpixelChange() { return internal->fbDirtyOnSubpixelChange; } int& Window::fbCount() { return internal->fbCount; } void init() { } void destroy() { } } // namespace window } // namespace rack START_NAMESPACE_DISTRHO void WindowParametersSave(rack::window::Window* const window) { if (d_isNotEqual(window->internal->params.cableOpacity, rack::settings::cableOpacity)) { window->internal->params.cableOpacity = rack::settings::cableOpacity; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterCableOpacity, rack::settings::cableOpacity); } if (d_isNotEqual(window->internal->params.cableTension, rack::settings::cableTension)) { window->internal->params.cableTension = rack::settings::cableTension; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterCableTension, rack::settings::cableTension); } if (d_isNotEqual(window->internal->params.rackBrightness, rack::settings::rackBrightness)) { window->internal->params.rackBrightness = rack::settings::rackBrightness; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterRackBrightness, rack::settings::rackBrightness); } if (d_isNotEqual(window->internal->params.haloBrightness, rack::settings::haloBrightness)) { window->internal->params.haloBrightness = rack::settings::haloBrightness; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterHaloBrightness, rack::settings::haloBrightness); } if (d_isNotEqual(window->internal->params.knobScrollSensitivity, rack::settings::knobScrollSensitivity)) { window->internal->params.knobScrollSensitivity = rack::settings::knobScrollSensitivity; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterWheelSensitivity, rack::settings::knobScrollSensitivity); } if (window->internal->params.knobMode != rack::settings::knobMode) { window->internal->params.knobMode = rack::settings::knobMode; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterKnobMode, rack::settings::knobMode); } if (window->internal->params.tooltips != rack::settings::tooltips) { window->internal->params.tooltips = rack::settings::tooltips; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterShowTooltips, rack::settings::tooltips); } if (window->internal->params.knobScroll != rack::settings::knobScroll) { window->internal->params.knobScroll = rack::settings::knobScroll; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterWheelKnobControl, rack::settings::knobScroll); } if (window->internal->params.lockModules != rack::settings::lockModules) { window->internal->params.lockModules = rack::settings::lockModules; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterLockModulePositions, rack::settings::lockModules); } if (window->internal->params.rateLimit != rack::settings::rateLimit) { window->internal->params.rateLimit = rack::settings::rateLimit; if (window->internal->callback != nullptr) window->internal->callback->WindowParametersChanged(kWindowParameterUpdateRateLimit, rack::settings::rateLimit); } } void WindowParametersRestore(rack::window::Window* const window) { rack::settings::cableOpacity = window->internal->params.cableOpacity; rack::settings::cableTension = window->internal->params.cableTension; rack::settings::rackBrightness = window->internal->params.rackBrightness; rack::settings::haloBrightness = window->internal->params.haloBrightness; rack::settings::knobScrollSensitivity = window->internal->params.knobScrollSensitivity; rack::settings::knobMode = static_cast<rack::settings::KnobMode>(window->internal->params.knobMode); rack::settings::tooltips = window->internal->params.tooltips; rack::settings::knobScroll = window->internal->params.knobScroll; rack::settings::lockModules = window->internal->params.lockModules; rack::settings::rateLimit = window->internal->params.rateLimit; } void WindowParametersSetCallback(rack::window::Window* const window, WindowParametersCallback* const callback) { window->internal->callback = callback; } void WindowParametersSetValues(rack::window::Window* const window, const WindowParameters& params) { window->internal->params = params; } END_NAMESPACE_DISTRHO
<?php /** procédure principale de mise à jour des cartes ShomGT V4 - 4/8/2023 * * Variable_d'Environnement: * SHOMGT3_SERVER_URL: url du serveur de cartes en 7z * SHOMGT3_MAPS_DIR_PATH: répertoire dans lequel les cartes expansées doivent être copiées * * A faire: * - afficher à la fin une synthèse du traitement * journal: | * - 17/8/2023: * - correction de la version des cartes spéciales * - 8/8/2023: * - ajout d'un verrou pour interdire des exécutions simultanées * - 3/8/2023: * - chgt de la constante VERSION en '4' pour obtenir les vraies versions des cartes spéciales * - modif de findCurrentMapVersion() sur les cartes spéciales * - 18/6/2023: * - déplacement lib dans ../lib * - 1/8/2022: * - ajout déclarations PhpStan pour level 6 * - 22/6/2022: * - correction d'un bug * - 20/6/2022: * - correction d'un bug * - 19/6/2022: * - ajout mention d'une version dans l'appel à $SERVER_URL/maps.json * - 17/6/2022: * - adaptation au transfert de update.yaml dans mapcat.yaml * - 30/5/2022: * - ajout suppression du cache de tuiles * - passage en paramètres des variables globales * - mise en oeuvre du nouveau protocole du serveur de ce jour * - 19/5/2022: * - ajout création du répertoire $MAPS_DIR_PATH s'il n'existe pas * - définition de valeurs par défaut pour $SERVER_URL et $MAPS_DIR_PATH * - 18/5/2022: * - évolution du code pour fonctionner en contenenur * - utilisation des 2 variables d'environnement * - formalisation sous la forme de variables globales en majuscules - plus faciles à utiliser * - en php:cli le répertoire par défaut est / et non le répertoire dans lequel php est lancé * - il faut donc que les références aux fichiers soient toutes absolues * - création du dossier temp au démarrage s'il n'existe pas * - transfert de temp dans SHOMGT3_MAPS_DIR_PATH * - pour permettre le déplacement du répertoire de carte de temp vers SHOMGT3_MAPS_DIR_PATH * - 16/5/2022: * - détection de la liste des cartes obsolètes dans maps.json * - construction du layers.yaml et transfert dans le répertoire data * - effacement des cartes obsolètes * - le bug sur 0101 provenait d'un bug de sgserver * - 15/5/2022: * - initialisation de la liste des cartes par interrogation du serveur sur /maps.json * - test KO sur nouveau patrimoine * - pourquoi avec ajout de incoming/20200225, obsoleteMaps=Array([0] => 0101) ? * - l'utilisation de mapcat pour fabriquer la liste des cartes ne permet pas de tester la gestion des cartes obsolètes * - 13/5/2022: * - création initiale * - gestion du cas particuliers des cartes sans métadonnées * - test OK sur un patrimoine courant identique au patrimoine archivé * @package shomgt\sgupdt */ $VERSION[basename(__FILE__)] = date(DATE_ATOM, filemtime(__FILE__)); require_once __DIR__.'/../lib/envvar.inc.php'; require_once __DIR__.'/../lib/execdl.inc.php'; require_once __DIR__.'/../lib/readmapversion.inc.php'; require_once __DIR__.'/../lib/mapcat.inc.php'; require_once __DIR__.'/../vendor/autoload.php'; use Symfony\Component\Yaml\Yaml; define ('SGSERVER_VERSION', '4'); // no de version utilisée dans l'appel au serveur sgserver define ('CMDE_VERBOSE', 1); // degré de verbosité de l'exécution des cmdes // phase d'initialisation $SERVER_URL = EnvVar::val('SHOMGT3_SERVER_URL'); $MAPS_DIR_PATH = EnvVar::val('SHOMGT3_MAPS_DIR_PATH'); $UPDATE_DURATION = EnvVar::val('SHOMGT3_UPDATE_DURATION'); // créée le répertoire $MAPS_DIR_PATH s'il n'existe pas déjà if (!@is_dir($MAPS_DIR_PATH)) if (!@mkdir($MAPS_DIR_PATH)) throw new Exception("Erreur de création du répertoire $MAPS_DIR_PATH"); // $TEMP est le répertoire dans lequel sont créées les cartes avant d'être déplacées une fois terminées dans $MAPS_DIR_PATH $TEMP = "$MAPS_DIR_PATH/../temp"; // créée le répertoire temp s'il n'existe pas déjà if (!@is_dir($TEMP)) if (!@mkdir($TEMP)) throw new Exception("Erreur de création du répertoire $TEMP"); $TEMP = realpath($TEMP); // __DIR__.'/temp' est le répertoire dans lequel sont téléchargées maps.json et cat.json if (!@is_dir(__DIR__.'/temp')) { if (!@mkdir(__DIR__.'/temp')) throw new Exception("Erreur de création du répertoire ".__DIR__.'/temp'); } if (($argc > 1) && ($argv[1]=='-v')) { // génération des infos de version echo "Dates de dernière modification des fichiers sources:\n"; foreach (['maketile.php', 'layers.php'] as $phpScript) { $result_code = null; $output = []; exec("php ".__DIR__."/$phpScript -v", $output, $result_code); array_shift($output); $VERSION[$phpScript] = Yaml::parse(implode("\n",$output)); } echo Yaml::dump($VERSION); die(); } /** Verrou d'utilisation pour garantir que le script n'est pas utilisé plusieurs fois simultanément. * 3 opération: * - locked() pour connaitre l'état du verrou * - lock() pour le vérouiller * - unlock() pour le dévérouiller */ class Lock { const LOCK_FILEPATH = __DIR__.'/LOCK.txt'; static function locked(): ?string { // Si le verrou existe alors renvoie le contenu du fichier avec la date de verrou if (is_file(self::LOCK_FILEPATH)) return file_get_contents(self::LOCK_FILEPATH); else return null; } static function lock(): bool { // verouille, renvoie vrai si ok, false si le verrou existait déjà if (is_file(self::LOCK_FILEPATH)) return false; else { file_put_contents(self::LOCK_FILEPATH, "Verrou déposé le ".date('c')."\n"); return true; } } static function unlock(): void { unlink(self::LOCK_FILEPATH); } }; /** stocke les informations téléchargées de $SERVER_URL/maps.json */ class UpdtMaps { /** @var array<string, string> $validMaps */ static array $validMaps=[]; // liste des numéros de cartes non obsoletes trouvés dans maps.json avec leur version /** @var array<int, string> $obsoleteMaps */ static array $obsoleteMaps=[]; // liste des numéros de cartes obsolètes trouvés dans maps.json /** @var array<int, string> $downloaded */ static array $downloaded=[]; // liste des numéros de cartes effectivement téléchargées static function init(string $SERVER_URL): void { $httpCode = download("$SERVER_URL/maps.json?version=".SGSERVER_VERSION, __DIR__.'/temp/maps.json', CMDE_VERBOSE); if ($httpCode <> 200) throw new Exception("Erreur de download sur maps.json, httpCode=$httpCode"); $maps = json_decode(file_get_contents(__DIR__.'/temp/maps.json'), true, 512, JSON_THROW_ON_ERROR); //unlink(__DIR__.'/temp/maps.json'); // ne pas le détruire car utilisé dans layers.php foreach ($maps as $mapnum => $map) { if (is_int($mapnum) || ctype_digit($mapnum)) { // on se limite aux cartes dont l'id est un nombre if ($map['status'] == 'ok') // on distingue les cartes valides de celles qui sont obsolètes self::$validMaps[$mapnum] = $map['lastVersion']; else self::$obsoleteMaps[] = $mapnum; } } //echo '$validMaps='; print_r(self::$validMaps); //echo '$obsoleteMaps='; print_r(self::$obsoleteMaps); } }; /** lit dans le fichier layers.yaml les zones effacées et permet de les comparer par mapnum avec celles à effacer de mapcat.yaml */ class ShomGtDelZone { /** @var array<string, array<string, array<string, mixed>>> $deleted */ static array $deleted=[]; // [{mapnum} => [{gtname} => {toDel}]] /** lit le fichier et structure les zones à effacer par mapnum et gtname */ static function init(): void { if (is_file(__DIR__.'/../data/layers.yaml')) $yaml = Yaml::parseFile(__DIR__.'/../data/layers.yaml'); else $yaml = []; foreach ($yaml as $layerName => $layer) { if (substr($layerName, 0, 2)<>'gt') continue; // ce n'est pas une couche foreach ($layer as $gtname => $gt) { if (isset($gt['deleted'])) { $mapnum = substr($gtname, 0, 4); self::$deleted[$mapnum][$gtname] = $gt['deleted']; } } } } // retourne pour un mapnum la définition par gtname des zones effacées de layers.yaml ou [] si aucune zone n'est définie /** @return array<string, array<string, array<string, mixed>>> */ static function deleted(string $mapnum): array { if (isset(self::$deleted[$mapnum])) { $deleted = self::$deleted[$mapnum]; ksort($deleted); return $deleted; } else return []; } /** Teste si pour un $mapnum les zones à effacer de TempMapCat sont ou non identiques aux zones effacées de layers.yaml */ static function sameDelZones(string $mapnum): bool { //echo "ShomGtDelZone::deleted="; print_r(ShomGtDelZone::deleted($mapnum)); //echo "TempMapCat::toDeleteByGtname="; print_r(TempMapCat::toDeleteByGtname("FR$mapnum")); return TempMapCat::toDeleteByGtname("FR$mapnum") == ShomGtDelZone::deleted($mapnum); } }; /** Renvoit le libellé de la version courante de la carte $mapnum ou '' si la carte n'existe pas */ function findCurrentMapVersion(string $MAPS_DIR_PATH, string $mapnum): string { /* cherche un des fichiers de MD ISO dans le répertoire de carte et en extrait la version */ $mappath = ''; if (!is_dir("$MAPS_DIR_PATH/$mapnum")) { // la carte est absente des cartes courantes return ''; } foreach (new DirectoryIterator("$MAPS_DIR_PATH/$mapnum") as $filename) { if ($filename == "CARTO_GEOTIFF_{$mapnum}_pal300.xml") { //echo "$filename\n"; $currentMapVersion = readMapVersion("$MAPS_DIR_PATH/$mapnum/$filename"); //echo "findCurrentMapVersion() returns $currentMapVersion[version]\n"; return $currentMapVersion['version']; } } // Cas où il n'existe pas de fichier de MD ISO standard // j'utilise l'extension .tfw à la place de .tif car en local le .tif a été effacé //echo "il n'existe pas de fichier de MD ISO standard\n"; $fileNamePerType = []; foreach (new DirectoryIterator("$MAPS_DIR_PATH/$mapnum") as $filename) { //echo " filename=$filename\n"; if (in_array(substr($filename, -4), ['.xml','.tfw','.pdf']) && (substr($filename, -12)<>'.png.aux.xml')) { //echo "$filename match condition\n"; $fileNamePerType[substr($filename, -3)][] = (string)$filename; } } //print_r($fileNamePerType); // si il existe un seul fichier .xml je l'utilise if (count($fileNamePerType['xml'] ?? []) == 1) { $filename = $fileNamePerType['xml'][0]; //echo "j'utilise le seul fichier .xml '$filename'\n"; $currentMapVersion = readMapVersion("$MAPS_DIR_PATH/$mapnum/$filename"); //echo "findCurrentMapVersion() returns $currentMapVersion[version]\n"; return $currentMapVersion['version']; } // sinon, si il existe un seul fichier .tif if (count($fileNamePerType['tfw'] ?? []) == 1) { $filename = $fileNamePerType['tfw'][0]; //echo "j'utilise le seul fichier .tfw '$filename'\n"; $version = substr($filename, 5, -4); // je prends le nom du .tfw sans le numéro de carte et sans l'extension //echo "findCurrentMapVersion() returns $version\n"; return $version; } // sinon, si il existe un seul fichier .pdf if (count($fileNamePerType['pdf'] ?? []) == 1) { $filename = $fileNamePerType['pdf'][0]; $version = substr($filename, 5, -4); // je prends le nom du .pdf sans le numéro de carte et sans l'extension return $filename; // je prends le nom du .pdf AVEC l'extension } //echo "findCurrentMapVersion() returns 'undefined'\n"; return 'undefined'; // sinon undefined } /** expanse une carte téléchargée comme 7z au path indiqué */ function expand(string $map7zpath): void { echo "expand($map7zpath)\n"; $mapdir = dirname($map7zpath); $mapbasename = basename($map7zpath); !execCmde("7z x -y -o$mapdir $map7zpath", CMDE_VERBOSE) // dezip le fichier du Shom or throw new Exception("Erreur dans 7z x -y -o$mapdir $map7zpath"); $mapdir = dirname($map7zpath).'/'.basename($map7zpath, '.7z'); echo "mapdir=$mapdir\n"; $gtiffs = []; // liste des fichiers (*.tif|*.pdf) foreach (new DirectoryIterator($mapdir) as $gtiff) { $gtiff = $gtiff->getBasename(); //echo "gtiff=$gtiff, substr=",substr($gtiff, -4),"\n"; if (!in_array(substr($gtiff, -4), ['.tif','.pdf'])) continue; $gtiffs[] = $gtiff; } //echo "gtiffs="; print_r($gtiffs); foreach ($gtiffs as $gtiff) { echo " gtiff=$gtiff\n"; $gtname = basename($gtiff, '.tif'); // pour un .tif je prends le basename, pour un .pdf je garde le nom entier !execCmde("gdalinfo -json $mapdir/$gtiff > $mapdir/$gtname.info.json", CMDE_VERBOSE) // sauvegarde du géoréf. du GéoTiff/PDF or throw new Exception("erreur dans gdalinfo -json $mapdir/$gtiff"); //if (1) continue; // Pour le test je n'effectue pas les commandes suivantes !($result = execCmde("gdal_translate -of PNG $mapdir/$gtiff $mapdir/$gtname.png", CMDE_VERBOSE)) // conversion en PNG or throw new Exception("erreur dans gdal_translate sur $mapdir$gtiff, result=".json_encode($result)); //echo "unlink(\"$mapdir/$gtiff\"); // suppression du fichier GéoTiff/PDF\n"; unlink("$mapdir/$gtiff"); // suppression du fichier GéoTiff/PDF !($result = execCmde("php ".__DIR__."/maketile.php $mapdir/$gtname.png", CMDE_VERBOSE)) or throw new Exception("erreur dans php maketile.php $mapdir/$gtname.png, result=".json_encode($result)); //echo "unlink(\"$mapdir/$gtname.png\");\n"; unlink("$mapdir/$gtname.png"); } } /** télécharge la carte, l'expanse et l'installe dans le répertoire courant, retourne le libellé du code http */ function dlExpandInstallMap(string $SERVER_URL, string $MAPS_DIR_PATH, string $TEMP, string $mapnum): string { $url = "$SERVER_URL/maps/$mapnum.7z"; //echo "\$url=$url\n"; switch ($httpCode = download($url, "$TEMP/$mapnum.7z", CMDE_VERBOSE)) { case 200: { // OK expand("$TEMP/$mapnum.7z"); // On copie l'ancien répertoire dans un .bak pour que le remplacement soit le plus rapide possible // Le répertoire .bak est supprimé ensuite if (is_dir("$MAPS_DIR_PATH/$mapnum")) rename("$MAPS_DIR_PATH/$mapnum", "$MAPS_DIR_PATH/$mapnum.bak") or throw new Exception("Erreur rename($MAPS_DIR_PATH/$mapnum, $MAPS_DIR_PATH/$mapnum.bak)"); rename("$TEMP/$mapnum", "$MAPS_DIR_PATH/$mapnum") or throw new Exception("Erreur rename($TEMP/$mapnum, $MAPS_DIR_PATH/$mapnum)"); if (is_dir("$MAPS_DIR_PATH/$mapnum.bak")) execCmde("rm -r $MAPS_DIR_PATH/$mapnum.bak &", CMDE_VERBOSE); unlink("/$TEMP/$mapnum.7z"); return 'OK'; } case 400: { // Bad Request die("Erreur $httpCode sur $mapnum.7z ligne ".__LINE__."\n"); } case 401: { // Unauthorized die("Erreur $httpCode sur $mapnum.7z ligne ".__LINE__."\n"); } case 404: { // Not Found - la carte n'a jamais existé echo "La carte $mapnum.7z n'a pas été téléchargée car elle n'a pas été trouvée sur le serveur\n"; return 'Not Found'; } default: return ''; } } while (true) { // si $UPDATE_DURATION est défini alors le process boucle avec une attente de UPDATE_DURATION if ($lock = Lock::locked()) { die("Exécution impossible, un autre utilisateur est en train d'utiliser ce script<br>\n$lock<br>\n"); } Lock::lock(); try { // efface le contenu du répertoire $TEMP !execCmde("rm -rf $TEMP/*", CMDE_VERBOSE) or throw new Exception("erreur dans rm -r $TEMP/*"); // efface le contenu du répertoire temp !execCmde("rm -rf ".__DIR__."/temp/*", CMDE_VERBOSE) or throw new Exception("erreur dans rm -r ".__DIR__."/temp/*"); UpdtMaps::init($SERVER_URL); // télécharge ${SHOMGT3_SERVER_URL}/maps.json et stocke les informations TempMapCat::init(); // lit le fichier mapcat.yaml en le téléchargeant s'il n'existe pas ShomGtDelZone::init(); // lit dans le fichier layers.yaml les zones effacées pour les comparer avec celles à effacer // téléchargement des cartes et transfert au fur et à mesure dans SHOMGT3_MAPS_DIR_PATH foreach (UpdtMaps::$validMaps as $mapnum => $mapVersion) { echo "mapnum=$mapnum\n"; $currentVersion = findCurrentMapVersion($MAPS_DIR_PATH, $mapnum); if ($currentVersion == $mapVersion) { if (ShomGtDelZone::sameDelZones($mapnum)) { echo " Pas de téléchargement pour la carte $mapnum.7z car la version $mapVersion est déjà présente", " et les zones à effacer sont identiques\n"; continue; } else { echo "Les zones à effacer dans la carte $mapnum.7z ont été modifiées donc la carte est rechargée\n"; } } elseif (!$currentVersion) { echo "La carte $mapnum.7z est absente et la version proposée est $mapVersion\n"; } else { echo "Pour la carte $mapnum.7z, la version présente est $currentVersion et la version proposée est $mapVersion\n"; } if (dlExpandInstallMap($SERVER_URL, $MAPS_DIR_PATH, $TEMP, $mapnum) == 'OK') UpdtMaps::$downloaded[] = $mapnum; } // construction du layers.yaml dans $TEMP et si ok alors transfert dans SHOMGT3_MAPS_DIR_PATH/../ if (execCmde("php ".__DIR__."/layers.php $TEMP/layers.yaml", CMDE_VERBOSE)) { echo "Erreur dans la génération de layers.yaml\n"; Lock::unlock(); die(1); } rename("$TEMP/layers.yaml", "$MAPS_DIR_PATH/../layers.yaml") or throw new Exception("Erreur rename($TEMP/layers.yaml, $MAPS_DIR_PATH/../layers.yaml)"); // effacement du cache des tuiles s'il existe if (is_dir("$MAPS_DIR_PATH/../tilecache")) { execCmde("rm -r $MAPS_DIR_PATH/../tilecache &", CMDE_VERBOSE); } // effacement des cartes obsolètes foreach (UpdtMaps::$obsoleteMaps as $mapnum) { if (is_dir("$MAPS_DIR_PATH/$mapnum")) execCmde("rm -r $MAPS_DIR_PATH/$mapnum &", CMDE_VERBOSE); } echo "Fin Ok de mise à jour des cartes\n"; Lock::unlock(); } catch (Exception $e) { Lock::unlock(); throw $e; } if (!$UPDATE_DURATION) { die(0); } else { echo "Endormissement pendant $UPDATE_DURATION jours à compter de ",date(DATE_ATOM),"\n"; sleep(intval($UPDATE_DURATION) * 24 * 3600); // en jours //sleep($UPDATE_DURATION * 60); // en minutes pour tests echo "Réveil à ",date(DATE_ATOM),"\n"; } }
import React, {useEffect, useState} from 'react'; import { Button, StyleSheet, Text, View } from 'react-native'; import {Slider} from 'react-native-elements'; /** * formatSecondsToTimeCode formats the given seconds into the following format * hh:mm:ss/mm:ss/m:ss depending on the value of the input. * @param {number} seconds - The seconds to be formatted * @return {string} - The formatted time code */ const formatSecondsToTimeCode = (seconds: number): string => { const formattedHours = Math.floor(seconds / 3600); if (formattedHours !== 0) { seconds /= 3600; } const formattedMinutes = Math.floor(seconds / 60); const paddedSeconds = Math.floor(seconds % 60) .toString() .padStart(2, '0'); if (formattedHours === 0 && formattedMinutes === 0) { return `0:${paddedSeconds}`; } else if (formattedHours === 0) { return `${formattedMinutes}:${paddedSeconds}`; } const paddedMinutes = formattedMinutes.toString().padStart(2, '0'); return `${formattedHours}:${paddedMinutes}:${paddedMinutes}`; }; type AudioPlayerProps = { position: number; duration: number; startSeeking: () => void; stopSeeking: (seekedPosition: number) => void; onUpdateRate: (rate: number) => void; onPressJumpBack: (jumpBackSeconds: number) => void; onPressJumpForward: (jumpForwardSeconds: number) => void; }; const AudioPlayer = ({ duration, position, startSeeking, stopSeeking, onUpdateRate, onPressJumpBack, onPressJumpForward, }: AudioPlayerProps) => { const [sliderPosition, setSliderPosition] = useState(position); useEffect(() => { setSliderPosition(position); }, [position]); if (!duration) { return <Text>Loading</Text>; } return ( <View style={styles.container}> <Slider maximumValue={duration} minimumValue={0} step={1} onValueChange={setSliderPosition} onSlidingStart={() => { startSeeking(); }} onSlidingComplete={seekedPosition => { stopSeeking(seekedPosition); }} value={position} thumbTintColor={'blue'} thumbProps={{ height: 15, width: 15, }} /> <View style={styles.timeContainer}> <Text>{formatSecondsToTimeCode(sliderPosition)}</Text> <Text>{formatSecondsToTimeCode(duration)}</Text> </View> <Button title={'2x'} onPress={() => onUpdateRate(2)} /> <Button title={'1x'} onPress={() => onUpdateRate(1)} /> <Button title={'prev 10 seconds'} onPress={() => onPressJumpBack(10)} /> <Button title={'next 10 seconds'} onPress={() => onPressJumpForward(10)} /> </View> ); }; const styles = StyleSheet.create({ container: { padding: 16, }, timeContainer: { flexDirection: 'row', justifyContent: 'space-between', marginTop: -10, }, }); const AudioControls = () => { }; export default AudioPlayer;
package Data.OtherClasses; import Data.Interfaces.Pet9; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.logging.Logger; @Component("Person8bean") public class Person8 { private Pet9 pet; private String surname; private int age; private static Logger log = Logger.getLogger(Person8.class.getName()); @Autowired // Если конструктор 1, То @Autowired будет применен к конструктору неявно, без его прописи. public Person8(Pet9 pet) { this.pet = pet; log.info("Person8 bean is created!"); } public void setPet9(Pet9 pet) { log.info("Class Person7: set pet!"); this.pet = pet; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void callYourPet() { System.out.println("Hello, my lovely Pet!"); pet.say(); } @Override public String toString() { return "Person8{" + "pet=" + pet + ", surname='" + surname + '\'' + ", age=" + age + '}'; } }
<?php namespace App\DataFixtures\Factory; use App\Entity\Unicorn; use App\Enum\UnicornStatusEnum; use App\Repository\UnicornRepository; use Zenstruck\Foundry\ModelFactory; use Zenstruck\Foundry\Proxy; use Zenstruck\Foundry\RepositoryProxy; /** * @extends ModelFactory<Unicorn> * * @method Unicorn|Proxy create(array|callable $attributes = []) * @method static Unicorn|Proxy createOne(array $attributes = []) * @method static Unicorn|Proxy find(object|array|mixed $criteria) * @method static Unicorn|Proxy findOrCreate(array $attributes) * @method static Unicorn|Proxy first(string $sortedField = 'id') * @method static Unicorn|Proxy last(string $sortedField = 'id') * @method static Unicorn|Proxy random(array $attributes = []) * @method static Unicorn|Proxy randomOrCreate(array $attributes = []) * @method static UnicornRepository|RepositoryProxy repository() * @method static Unicorn[]|Proxy[] all() * @method static Unicorn[]|Proxy[] createMany(int $number, array|callable $attributes = []) * @method static Unicorn[]|Proxy[] createSequence(iterable|callable $sequence) * @method static Unicorn[]|Proxy[] findBy(array $attributes) * @method static Unicorn[]|Proxy[] randomRange(int $min, int $max, array $attributes = []) * @method static Unicorn[]|Proxy[] randomSet(int $number, array $attributes = []) */ final class UnicornFactory extends ModelFactory { /** * @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#factories-as-services * * @todo inject services if required */ public function __construct() { parent::__construct(); } /** * @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#model-factories * * @todo add your default values here */ protected function getDefaults(): array { return [ 'description' => self::faker()->text(255), 'name' => self::faker()->name(), 'price' => self::faker()->randomFloat(), // 'status' => self::faker()->randomElement(UnicornStatusEnum::cases()), 'status' => UnicornStatusEnum::PUBLISHED, ]; } /** * @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#initialization */ protected function initialize(): self { return $this // ->afterInstantiate(function(Unicorn $unicorn): void {}) ; } protected static function getClass(): string { return Unicorn::class; } }
import { useEffect } from 'react'; import { Link } from 'react-router-dom'; import Swal from 'sweetalert2'; import { useAuthStore, useForm } from '../../hooks'; import './LoginPage.css'; import {Navbar, Footer} from "../../ui" const loginFormFields = { loginEmail: '', loginPassword: '', } const registerFormFields = { registerName: '', registerEmail: '', registerPassword: '', registerPassword2: '', } export const LoginPage = () => { const { startLogin, errorMessage } = useAuthStore() const { loginEmail, loginPassword, onInputChange:onLoginInputChange } = useForm(loginFormFields); const loginSubmit = ( event ) => { event.preventDefault(); startLogin({email: loginEmail, password: loginPassword}) } useEffect(() => { if ( errorMessage !== undefined ) { Swal.fire('Error en la autenticación', errorMessage, 'error') } }, [errorMessage]) return ( <> <Navbar /> <div className="container login-container"> <div className="row"> <div className="col login-form-1"> <h3>Ingreso</h3> <form onSubmit={ loginSubmit }> <div className="form-group mb-2"> <input type="text" className="form-control" placeholder="Correo" name="loginEmail" value={ loginEmail } onChange={ onLoginInputChange } /> </div> <div className="form-group mb-2"> <input type="password" className="form-control" placeholder="Contraseña" name="loginPassword" value={ loginPassword } onChange={ onLoginInputChange } /> </div> <div className="form-group mb-2 text-center"> <input type="submit" className="btnSubmit" value="Login" /> </div> <div className="form-group text-center"> <Link to="/auth/register" className="link login__link" > Crear un nuevo usuario </Link> <br/> <Link to="/" className="link login__link" > Volver </Link> </div> </form> </div> </div> </div> <Footer /> </> ) }
<?php namespace App\Imports\Sheets; use Illuminate\Support\Carbon; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Maatwebsite\Excel\Concerns\Importable; use Maatwebsite\Excel\Concerns\RegistersEventListeners; use Maatwebsite\Excel\Concerns\SkipsEmptyRows; use Maatwebsite\Excel\Concerns\ToCollection; use Maatwebsite\Excel\Concerns\WithEvents; use Maatwebsite\Excel\Concerns\WithHeadingRow; use Maatwebsite\Excel\Events\BeforeSheet; class ThemeSheetImport implements ToCollection, WithEvents, SkipsEmptyRows, WithHeadingRow { use Importable, RegistersEventListeners; /** * @param BeforeSheet $event * @return void */ public static function beforeSheet(BeforeSheet $event) { DB::statement('SET FOREIGN_KEY_CHECKS=0;'); DB::table('themes')->delete(); DB::statement('SET FOREIGN_KEY_CHECKS=1;'); } /** * @param Collection $rows * @return void */ public function collection(Collection $rows) { foreach ($rows as $row) { DB::table('themes')->insert([ 'id' => $row['id'], 'theme' => $row['theme'], 'page' => $row['page'], 'url' => $row['url'], 'title' => $row['title'], 'slug' => $row['slug'], 'template' => $row['template'], 'setting' => $row['setting'], 'created_at' => Carbon::create($row['created_at'])->format('Y-m-d H:i:s'), 'updated_at' => Carbon::create($row['updated_at'])->format('Y-m-d H:i:s') ]); } } }
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Models\User; use PhpParser\Parser\Tokens; class AuthController extends Controller { public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|max:191', 'email' => 'required|email|max:191|unique:users,email', 'password' => 'required|min:8' ]); if ($validator->fails()) { return response()->json([ 'validation_errors' => $validator->messages(), ]); } else { $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); $token = $user->createToken($user->email . '_Token')->plainTextToken; return response()->json([ 'status' => 200, 'username' => $user->name, 'token' => $token, 'message' => 'Registered successfully' ]); } } public function login(Request $request) { $validator = Validator::make($request->all(), [ "email" => 'required', "password" => "required|min:8" ]); if($validator->fails()) { return response()->json([ 'validation_errors' => $validator->messages(), ]); }else { $user = User::where('email', $request->email)->first(); if (! $user || !Hash::check($request->password, $user->password)) { return response()->json([ 'status' => 401, 'message' => 'You are Unauthorized' ]); }else{ if($user->role_as == 1) { $role = "admin"; $token = $user->createToken($user->email . '_AdminToken', ['server:admin'])->plainTextToken; }else{ $role = ""; $token = $user->createToken($user->email . '_Token', [''])->plainTextToken; } return response()->json([ 'status' => 200, 'username' => $user->name, 'token' => $token, 'message' => 'Login successfully', 'role' => $role ]); } } } public function logout() { auth()->user()->tokens()->delete(); return response()->json([ "status" => 200, "message" => "Loged out susccessfully" ]); } }
/* * Copyright (c) 2013-2015 Netcrest Technologies, LLC. All rights reserved. * * 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. */ package com.netcrest.pado.gemfire; import java.util.Properties; import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.CacheFactory; import com.gemstone.gemfire.cache.Declarable; import com.gemstone.gemfire.cache.EntryEvent; import com.gemstone.gemfire.cache.util.CacheListenerAdapter; import com.netcrest.pado.info.GridInfo; import com.netcrest.pado.internal.util.PadoUtil; import com.netcrest.pado.internal.util.QueueDispatcher; import com.netcrest.pado.internal.util.QueueDispatcherListener; import com.netcrest.pado.log.Logger; import com.netcrest.pado.server.PadoServerManager; /** * GridInfoCacheListenerImpl is registered to this grid to listen on child * GridInfos. Upon receipt of child GridInfo, this grid updates its child list * by opening grid-to-grid communication channels via the child pool information * provided by GridInfo. It also updates AppInfo and GridRouterInfo. * * @author dpark * */ public class GridInfoCacheListenerImpl extends CacheListenerAdapter<String, GridInfo> implements Declarable { private static boolean isLogGridInfoReceived = PadoUtil.getBoolean("log.gridInfo", true); private QueueDispatcher queueDispatcher = new QueueDispatcher(); public GridInfoCacheListenerImpl() { queueDispatcher.setQueueDispatcherListener(new QueueDispatcherListener() { @Override public void objectDispatched(Object obj) { GridInfo gridInfo = null; try { Cache cache = null; try { cache = CacheFactory.getAnyInstance(); } catch (Exception ex) { // ignore } if (cache != null && cache.isClosed() == false) { gridInfo = (GridInfo)obj; update(gridInfo); } } catch (Throwable th) { Logger.warning("Error occurred while updating GridInfo. This maybe due to a startup or shutdown race condition. If so, please ignore this message. The next update will perform properly. " + th.getMessage(), th); String gridId = PadoServerManager.getPadoServerManager().getGridId(); if (gridInfo != null && gridId.equals(gridInfo.getGridId()) == false) { // Remove it so that the next event can be served // from scratch. Only child supported. PadoServerManager.getPadoServerManager().removeGrid(gridInfo, false); } } } }); queueDispatcher.start(); } @Override public void init(Properties props) { } /** * Updates all AppInfo objects found in the app region that have the * matching received grid Id. Region: &lt;gridId, GridInfo&gt; * * @param event */ private synchronized void update(GridInfo gridInfo) { // Drop events generated from this grid // if (gridInfo.getGridId().equals(PadoServerManager.getPadoServerManager().getGridId())) { // return; // } // Log GridInfo only from the grids other than this one. if (gridInfo.getGridId().equals(PadoServerManager.getPadoServerManager().getGridId()) == false) { if (isLogGridInfoReceived) { Logger.config("GridInfo received: gridId = " + gridInfo.getGridId()); } } // Update PadoManager with the new GridInfo received. This // applies the update only if GridInfo differs from PadoManager's // grid info. Supports only child for now. GemfirePadoServerManager.getPadoServerManager().updateGrid(gridInfo, false); if (Logger.isFineEnabled()) { Logger.fine("GridInfo received and child grid regions, AppInfo and GridRouterInfo updated. gridId=" + gridInfo.getGridId()); } } public static void setLogGridInfoReceived(boolean isLogGridInfoReceived) { GridInfoCacheListenerImpl.isLogGridInfoReceived = isLogGridInfoReceived; } public static boolean isLogGridInfoReceived() { return isLogGridInfoReceived; } @Override public void afterCreate(EntryEvent<String, GridInfo> event) { queueDispatcher.enqueue(event.getNewValue()); // update(event); } @Override public void afterUpdate(EntryEvent<String, GridInfo> event) { try { queueDispatcher.enqueue(event.getNewValue()); // update(event); } catch (Throwable th) { // The following exception was seen during failover: // com.gemstone.gemfire.SerializationException: An IOException was // thrown while deserializing // What's causing it? Ignore it for now. Since it continues to // receive GridInfo periodically, not an issue at this time. Logger.warning(th); } } /** * This method is invoked upon expiration. It cleans up all relevant pado * regions. */ @Override public void afterDestroy(EntryEvent<String, GridInfo> event) { GridInfo gridInfo = event.getOldValue(); // Remove the grid. Supports only child for now. PadoServerManager.getPadoServerManager().removeGrid(gridInfo, false); } @Override public void close() { queueDispatcher.stop(); } }
import psutil import json # Function to collect CPU metrics def collect_cpu_metrics(): cpu_metrics = { "cpu_times": psutil.cpu_times()._asdict(), "cpu_percent": psutil.cpu_percent(interval=1, percpu=True), "cpu_times_percent": [entry._asdict() for entry in psutil.cpu_times_percent(interval=1, percpu=True)], "cpu_count": psutil.cpu_count(logical=False), # Physical CPU count "cpu_stats": psutil.cpu_stats()._asdict(), "cpu_freq": psutil.cpu_freq(percpu=True), "load_avg": psutil.getloadavg(), } return cpu_metrics # Function to collect memory metrics def collect_memory_metrics(): memory_metrics = { "virtual_memory": psutil.virtual_memory()._asdict(), "swap_memory": psutil.swap_memory()._asdict(), } return memory_metrics # Function to collect disk metrics def collect_disk_metrics(): partitions = psutil.disk_partitions() disk_metrics = {} for partition in partitions: try: usage = psutil.disk_usage(partition.mountpoint)._asdict() io_counters = psutil.disk_io_counters(perdisk=True).get(partition.device, {}) disk_metrics[partition.device] = { "usage": usage, "io_counters": io_counters, } except (PermissionError, FileNotFoundError) as e: # Handle the exception, e.g., print a message or log it print(f"Error accessing {partition.device}: {e}") return disk_metrics # Function to collect network metrics def collect_network_metrics(): network_metrics = { "net_io_counters": psutil.net_io_counters()._asdict(), "net_connections": [conn._asdict() for conn in psutil.net_connections(kind="inet")], "net_if_addrs": {iface: [addr._asdict() for addr in addrs] for iface, addrs in psutil.net_if_addrs().items()}, } return network_metrics # Function to collect sensor metrics (if available) def collect_sensor_metrics(): try: sensor_metrics = { "sensors_temperatures": psutil.sensors_temperatures(fahrenheit=False), "sensors_fans": psutil.sensors_fans(), } return sensor_metrics except AttributeError: return {} # Some systems may not support sensors # Function to collect other system metrics def collect_other_metrics(): other_metrics = { "boot_time": psutil.boot_time(), "users": [user._asdict() for user in psutil.users()], } return other_metrics # Main function to collect all metrics def collect_all_metrics(): all_metrics = { "cpu_metrics": collect_cpu_metrics(), "memory_metrics": collect_memory_metrics(), "disk_metrics": collect_disk_metrics(), "network_metrics": collect_network_metrics(), "sensor_metrics": collect_sensor_metrics(), "other_metrics": collect_other_metrics(), } return all_metrics if __name__ == "__main__": metrics_data = collect_all_metrics() # You can now use metrics_data in your main Python script. # For example, you can convert it to JSON and save it to a file. with open("metrics.json", "w") as f: json.dump(metrics_data, f, indent=4) print("Metrics data collected and saved to 'metrics.json'")
<template lang="html"> <label class="container-check"> <input :class="[this.type]" :type="this.type" v-model="currentCheckboxValue" @change="newCheckboxValue(currentCheckboxValue)"> <span :class="[this.type]"></span> <span class="check-text"> {{ this.text }} </span> </label> </template> <script> export default { name: 'Checkbox', data () { return { currentCheckboxValue: false } }, props: { checked: { type: Array }, text: { type: String, required: false, default: '' }, type: { type: String, required: false, default: 'checkbox' }, data: { type: Array, required: false }, index: { type: Number, requiered: false } }, watch: { checked: function (newVal, oldVal) { this.currentCheckboxValue = newVal[this.index].value }, newCheckboxValue: function (newVal, oldVal) { this.checked = newVal } // data: function () { // if (this.data) { // if (this.data.includes(this.index + 1)) { // this.currentCheckboxValue = true // } else { // if (this.data.includes(true)) { // this.currentCheckboxValue = true // } // } // } // } }, methods: { newCheckboxValue (newValue) { this.$emit('newCheckboxValue', {idxCheck: this.index, checkboxValue: newValue}) }, refreshData () { if (this.data.includes(this.index + 1)) { this.currentCheckboxValue = true } else { if (this.data.includes(true)) { this.currentCheckboxValue = true } } } }, created () { if (this.data) { this.refreshData() } } } </script> <style scoped> </style>
import React, { useEffect, useState } from "react"; import { View, Image, Text } from "react-native"; import styles from "./styles"; import LnadingImg from "../../assets/images/landing.png"; import studyIcon from "../../assets/images/icons/study.png"; import giveClassesIcon from "../../assets/images/icons/give-classes.png"; import HeartIcon from "../../assets/images/icons/heart.png"; import { useNavigation } from "@react-navigation/native"; import { RectButton } from "react-native-gesture-handler"; import api from "../../services/api"; function Landing() { const { navigate } = useNavigation(); const [totalConnections, setTotalCOnnections] = useState(0); useEffect(() => { api .get("connections") .then((response) => setTotalCOnnections(response.data.total)); }, []); function handleNavigateToGiveClassesPage() { navigate("GiveClasses"); } function handleNavigateToStudyingPage() { navigate("Study"); } return ( <View style={styles.container}> <Image source={LnadingImg} style={styles.banner} /> <Text style={styles.title}> Seja Bem Vindo, {"\n"} <Text style={styles.titleBold}> O que deseja fazer?</Text> </Text> <View style={styles.buttonContainer}> <RectButton style={[styles.button, styles.buttonPrimary]} onPress={handleNavigateToStudyingPage} > <Image source={studyIcon} /> <Text style={styles.buttonText}>Estudar</Text> </RectButton> <RectButton style={[styles.button, styles.buttonSecondary]} onPress={handleNavigateToGiveClassesPage} > <Image source={giveClassesIcon} /> <Text style={styles.buttonText}>Dar aulas</Text> </RectButton> </View> <Text style={styles.totalConnections}> Total de {totalConnections} Conexoes ja reealizadas{" "} <Image source={HeartIcon} /> </Text> </View> ); } export default Landing;
import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:hweight_mobile_app/api/api.dart'; import 'package:hweight_mobile_app/configs/colors.dart'; import 'package:hweight_mobile_app/configs/const.dart'; import 'package:hweight_mobile_app/configs/images.dart'; import 'package:hweight_mobile_app/models/service/services.dart'; import 'package:hweight_mobile_app/routes/routes.dart'; import 'package:hweight_mobile_app/screens/authorization/components/title_auth.dart'; import 'package:hweight_mobile_app/widget/app_button.dart'; import 'package:hweight_mobile_app/widget/app_input.dart'; class ForgotPasswordScreen extends StatefulWidget { final String mail; const ForgotPasswordScreen({super.key, required this.mail}); @override State<ForgotPasswordScreen> createState() => _ForgotPasswordScreenState(); } class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> { TextEditingController passwordController = TextEditingController(); TextEditingController confirmPasswordController = TextEditingController(); FocusNode passwordFocus = FocusNode(); FocusNode confirmPasswordFocus = FocusNode(); bool isChanging = false; @override void initState() { super.initState(); confirmPasswordController.addListener(_onFocusChange); passwordFocus.addListener(_onFocusChange); } @override void dispose() { super.dispose(); confirmPasswordFocus.removeListener(_onFocusChange); confirmPasswordFocus.dispose(); passwordFocus.removeListener(_onFocusChange); passwordFocus.dispose(); confirmPasswordController.clear(); passwordController.clear(); } void _onFocusChange() { setState(() {}); } Future<bool> _requestChangePW() async { if (mounted) { final requestTag = Api.buildIncreaseTagRequestWithID("change_password"); ForgotPWModel forgotPWModel = await Api.requestChangePWAfterVerified( mail: widget.mail, password: passwordController.text.trim(), repeatPassword: confirmPasswordController.text.trim(), tagRequest: requestTag, ); Fluttertoast.showToast( msg: forgotPWModel.message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER, timeInSecForIosWeb: 1, backgroundColor: primaryColor, textColor: Colors.white, fontSize: 16.0); return forgotPWModel.isSuccess; } return false; } Widget mainBody() { return Padding( padding: const EdgeInsets.symmetric(horizontal: defaultPadding), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Container( margin: EdgeInsets.only( top: padding15 * 2, ), child: AppInput( name: "password", keyboardType: TextInputType.emailAddress, icon: Icons.alternate_email, controller: passwordController, focusNode: passwordFocus, placeHolder: "Password", isPassword: true, ), ), Container( margin: EdgeInsets.only( top: padding15 * 2, ), child: AppInput( name: "confirmpassword", keyboardType: TextInputType.visiblePassword, icon: Icons.lock_reset, controller: confirmPasswordController, focusNode: confirmPasswordFocus, placeHolder: "Confirm Password", isPassword: true, ), ), SizedBox( height: 80, ), AppButton( "Confirm Password", mainAxisSize: MainAxisSize.max, loading: isChanging, onPressed: () async { setState(() { isChanging = true; }); bool isChanged = await _requestChangePW(); setState(() { isChanging = false; }); if (isChanged && mounted) { Navigator.pushNamed( context, Routes.signIn, ); } }, ), SizedBox( height: 20, ), InkWell( onTap: () { Navigator.pushNamed(context, Routes.signIn); }, child: RichText( text: TextSpan( style: Theme.of(context) .textTheme .bodySmall ?.copyWith(fontSize: 12), children: [ TextSpan(text: "Already have an account? Click"), TextSpan( text: " here ", style: Theme.of(context) .textTheme .bodySmall ?.copyWith(fontSize: 12, color: primaryColor), ), TextSpan(text: "to Sign In"), ], ), ), ), ], ), ); } @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return Scaffold( backgroundColor: backgroundColor, body: CustomScrollView( slivers: [ SliverAppBar( backgroundColor: subBgColor, automaticallyImplyLeading: false, pinned: true, expandedHeight: size.height * 0.3, collapsedHeight: 130, elevation: 0, flexibleSpace: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( Images.logoApp, width: 200, ), ], ), bottom: PreferredSize( preferredSize: Size.fromHeight(0), child: TitleAuth( title: "Forgot Password", ), ), ), SliverToBoxAdapter( child: Container( width: double.infinity, height: size.height * 0.7, decoration: BoxDecoration(color: backgroundColor), padding: const EdgeInsets.only(top: defaultPadding), child: mainBody(), ), ), ], ), ); } }
import { Segment, Form, Divider, Button, Icon, Dimmer, Popup } from "semantic-ui-react" import { useQuery, useMutation, useLazyQuery } from "@apollo/react-hooks" import QUERY_CLASSES from "../../queries/query/classes" import QUERY_COURSES from "../../queries/query/listOfCourses" import QUERY_DEPARTMENTS from "../../queries/query/listOfDepartments" import NEW_SESSION from "../../queries/mutation/newSession" import React, { useState, useEffect, useContext } from "react" import { AuthContext } from "../../common/context" import MutationError from "../shared/MutationError" import AreYouSure from "../shared/AreYouSure" import Loading from "../shared/Loading" import Error from "../shared/Error" import { getName } from "../shared/helpers" import { toast } from "react-toastify" import SingleClass from "./SingleClass" const NewSesssion = ({ theme }) => { const { user: { department, access }, } = useContext(AuthContext) const [course, setCourse] = useState({}) const [modal, setModal] = useState(false) const [courses, setCourses] = useState([]) const [teachers, setTeachers] = useState([]) const [variables, setVariables] = useState({}) const [override, setOverride] = useState(false) const [session, setSession] = useState(new Date().getMonth() < 6) // TO EVEN => TRUE const { loading, error, data } = useQuery(QUERY_COURSES, { variables: { department } }) const [getDepartments, { loading: loadingDepartments, data: list }] = useLazyQuery( QUERY_DEPARTMENTS ) const [getCourses, { loading: loadingCourses, data: courseList }] = useLazyQuery(QUERY_COURSES) const [newSession, { loading: savingSession }] = useMutation(NEW_SESSION, { update: (proxy, { data: { newSession } }) => { try { // const data = proxy.readQuery({ // query: QUERY_CLASSES, // variables: { course: variables.course }, // }) // data.classes.push(...newSession) proxy.writeQuery({ query: QUERY_CLASSES, variables: { course: variables.course }, data: { classes: newSession }, }) } catch (error) { console.error(error) } toast.success(<h3>Session Saved ✔</h3>) setVariables({ course: variables.course }) setModal(false) // history.push(`/classes`) }, onError: e => MutationError(e), variables, }) const timeElapsed = new Date().getFullYear() - new Date(course.createdAt).getFullYear() useEffect(() => { if (courseList) { setCourses(courseList.courses) setTeachers(courseList.teachers) } else if (data) { setCourses(data.courses) setTeachers(data.teachers) } }, [data, courseList]) if (loading) return <Loading /> if (error) return <Error /> document.title = `New Session | ` + new Date().getFullYear() return ( <> <h1 className="distributed_ends"> <Dimmer active={savingSession} inverted={!theme} /> <div>New Session</div> <div className="floated right"> {variables.course && timeElapsed < course.duration && ( <Popup style={{ opacity: `93%` }} trigger={ <Button onClick={() => { setVariables({ course: variables.course }) setOverride(override => !override) }} icon="flag" color={override ? `red` : theme ? `black` : `brown`} /> } content="Currently the system hides some classes if the course is introduced recently, use this flag to OVERRIDE this feature" inverted={theme} /> )} {course.semesterBased && ( <Button color={theme ? `black` : `grey`} size="medium" onClick={() => { setVariables({ course: variables.course }) setSession(session => !session) }} > {session ? `To Even (Update Classes)` : `To Odd (Add New Class)`} </Button> )} </div> </h1> <Divider /> <Form widths="equal" inverted={theme} onSubmit={e => { setModal(true) e.preventDefault() }} > <Form.Group> {access === `Director` && ( <Form.Select fluid onClick={getDepartments} label="Change Department" loading={loadingDepartments} placeholder="Select Department to get list of courses" options={ list ? list.departments.map(x => { return { text: x.name, value: x._id } }) : [] } onChange={(_, { value }) => getCourses({ variables: { department: value } })} /> )} <Form.Select fluid required label="Select Course" loading={loadingCourses} placeholder="Select a Course to change session of" options={ courses ? courses.map(x => { return { text: x.name, value: x._id } }) : [] } onChange={(_, { value }) => { setVariables({ course: value }) const [course] = courses.filter(x => x._id === value) setCourse({ ...course, duration: Number(course.duration.match(/\d/)[0]) }) }} /> </Form.Group> {variables.course && ( <Segment.Group> {[ ...Array( timeElapsed < course.duration && !override ? timeElapsed + 1 : session ? course.duration : course.duration + 1 ), ].map((_, idx) => ( <SingleClass key={idx} loop={idx} theme={theme} course={course} session={session} variables={variables} setVariables={setVariables} teachers={teachers.map(x => { return { text: getName(x.name), value: x._id } })} /> ))} </Segment.Group> )} <Form.Button fluid animated="fade" disabled={!variables.course} content={ <> <Button.Content visible content={<Icon name="save" />} /> <Button.Content hidden content="Change Session" /> </> } /> </Form> <AreYouSure theme={theme} open={modal} onConfirm={newSession} onCancel={() => setModal(false)} content={`This transaction will add new Classes to ${course.name} course.`} /> </> ) } export default NewSesssion
var express = require('express') var path = require('path'); var bodyParser = require('body-parser') var cookieParser = require('cookie-parser'); var logger = require('morgan'); var app = express() var dotenv = require('dotenv') dotenv.config(); var port = process.env.PORT; app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) var indexRoute = require('../src/index') // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; res.status(err.status || 500).send({ error: err }) }); app.use('/', indexRoute) app.listen(port, () => { console.log('running server on port', port) })
// This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/03/a/RAM64.hdl /** * Memory of 64 registers, each 16 bit-wide. Out holds the value * stored at the memory location specified by address. If load==1, then * the in value is loaded into the memory location specified by address * (the loaded value will be emitted to out from the next time step onward). */ CHIP RAM64 { IN in[16], load, address[6]; OUT out[16]; PARTS: // Put your code here: DMux8Way(in=load, sel=address[0..2], a=tmp7, b=tmp6, c=tmp5, d=tmp4, e=tmp3, f=tmp2, g=tmp1, h=tmp0); RAM8(in=in, load=tmp7, address=address[3..5], out=ramout7); RAM8(in=in, load=tmp6, address=address[3..5], out=ramout6); RAM8(in=in, load=tmp5, address=address[3..5], out=ramout5); RAM8(in=in, load=tmp4, address=address[3..5], out=ramout4); RAM8(in=in, load=tmp3, address=address[3..5], out=ramout3); RAM8(in=in, load=tmp2, address=address[3..5], out=ramout2); RAM8(in=in, load=tmp1, address=address[3..5], out=ramout1); RAM8(in=in, load=tmp0, address=address[3..5], out=ramout0); Mux8Way16(a=ramout7,b=ramout6,c=ramout5,d=ramout4,e=ramout3,f=ramout2,g=ramout1,h=ramout0,sel=address[0..2],out=out); }
import React, { useState } from "react"; import Slider from "@material-ui/core/Slider"; import { FaEthereum } from "react-icons/fa"; function Filter({ data, setData }) { const [filterData, setFilterData] = useState({ name: "", sold: "", range: [0, 100], }); const { name, sold, range } = filterData; // Changing State when volume increases/decreases const rangeSelector = (event, newValue) => { event.preventDefault(); setFilterData({ ...filterData, range: newValue }); }; const handleChange = (event) => { event.preventDefault(); const { name, value } = event.target; const newValue = name == "sold" ? value == "true" ? true : value == "false" ? false : value : value; setFilterData({ ...filterData, [name]: newValue }); }; const handleFilter = (filterObject) => { const nftName = filterObject.name; const nftSold = filterObject.sold; const [start, end] = filterObject.range; var i, newData; // Loop through all list items, and hide those who don't match the search query newData = []; for (i = 0; i < data.length; i++) { const item = data[i]; const itemName = item.name; const itemSold = item.isSold; const itemPrice = item.price; let pushStatus = false; if (nftName && itemName.toUpperCase().indexOf(nftName) > -1) { pushStatus = true; } if (nftSold) { if (itemSold && nftSold == "yes") { pushStatus = true; } if (!itemSold && nftSold == "no") { pushStatus = true; } } if (itemPrice >= start && itemPrice <= end) { pushStatus = true; } if (pushStatus) { newData.push(item); } } setData(newData); }; const handleSubmit = (event) => { event.preventDefault(); handleFilter(filterData); }; const handleReset = (event) => { event.preventDefault(); setFilterData({ name: "", sold: null, range: [0, 100], }); setData(data); }; return ( <div> <form className="w-full mb-10 mt-10" onSubmit={handleSubmit} data-aos="fade-left" data-aos-duration="3000" > <div className="grid lg:grid-cols-4 md:grid-cols-5 grid-cols-1"> <div className=" px-3 mb-6 md:mb-0"> <label className="block dark:text-[#fff] text-[#363434] text-md mb-2" htmlFor="grid-city" > Name </label> <div className=""> <input type="text" name="name" className="block shadow appearance-none w-full bg-transparent border-2 border-[#ffffff14] rounded py-3 px-4 leading-tight dark:text-white text-[#7d7d7d] text-sm" placeholder="Enter Name" value={name} onChange={handleChange} /> <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700"> <svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" > <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /> </svg> </div> </div> </div> <div className=" px-3 mb-6 md:mb-0"> <label className="block dark:text-[#fff] text-[#363434] text-md mb-2" htmlFor="grid-state" > Sold </label> <div className=""> <select className="block shadow appearance-none w-full bg-transparent border-2 border-[#ffffff14] rounded py-3 px-4 leading-tight dark:text-white text-[#7d7d7d] text-sm" name="sold" onChange={handleChange} > <option value="">Select Sold</option> <option value={sold == "yes"}> Yes </option> <option value={sold == "no"}> No </option> </select> <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700"> <svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" > <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /> </svg> </div> </div> </div> <div className=" px-3 mb-6 md:mb-0"> <label className="block dark:text-[#fff] text-[#363434] text-md mb-2" htmlFor="grid-zip" > Price range </label> <div className="dark:text-white text-[#969696]" style={{ margin: "0", display: "block", width: "fit-content", }} > <Slider value={range} onChange={rangeSelector} valueLabelDisplay="auto" min={0} max={500} /> Your range of Price is between{" "} <FaEthereum className="inline-flex -mt-1" /> {range[0]} and{" "} <FaEthereum className="inline-flex -mt-1" /> {range[1]} </div> </div> <div className=" px-3 mb-6 md:mb-0"> <button type="submit" className="border-2 rounded-full mr-1 text-white hover:bg-[#571a81] hover:border-[#571a81] font-bold py-2 px-6" > Submit </button>{" "} <button type="button" onClick={handleReset} className="border-2 rounded-full text-white hover:bg-[#571a81] hover:border-[#571a81] font-bold py-2 px-6" > Reset </button> </div> </div> </form> </div> ); } export default Filter;
package com.epam.gymtaskapplication.controller; import com.epam.gymtaskapplication.dao.SpecializationRepository; import com.epam.gymtaskapplication.model.Specialization; import com.epam.gymtaskapplication.service.SpecializationService; import com.epam.gymtaskapplication.util.Utility; import lombok.extern.java.Log; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Optional; @RestController @RequestMapping("/api/specialization") public class SpecializationController { // fields private final SpecializationService specializationService; private final Logger LOG = LoggerFactory.getLogger(SpecializationController.class); private static final Utility utility = new Utility(); // injection public SpecializationController( SpecializationService specializationService ){ this.specializationService = specializationService; } // Create, Read // Create @PostMapping("/add/{name}") public ResponseEntity<Specialization> addSpecialization( @PathVariable String name ){ // instantiate call String transactionId = utility.generateTransactionId(); MDC.put("transactionId",transactionId); LOG.info("CALL: (POST) ?/api/specialization/add/{name}"); // validate if(name.isEmpty()){ LOG.error("FAILED: Unable to create Specialization. Name was" + " missing or null"); MDC.remove("transactionId"); return new ResponseEntity<>( HttpStatus.BAD_REQUEST ); } // call service Optional<Specialization> opSpec = specializationService.addSpecialization(name); if(opSpec.isPresent()){ LOG.info("SUCCESS: Created and saved Specialization to Database"); MDC.remove("transactionId"); return new ResponseEntity<>( opSpec.get(), HttpStatus.OK ); } else { LOG.error("FAILED: Error occurred when saving Specialization to " + "Database"); MDC.remove("transactionId"); return new ResponseEntity<>( HttpStatus.INTERNAL_SERVER_ERROR ); } } // Read @GetMapping("/get/{name}") public ResponseEntity<Specialization> getSpecialization( @PathVariable String name ){ // instantiate call String transactionId = utility.generateTransactionId(); MDC.put("transactionId",transactionId); LOG.info("CALL: (POST) ?/api/specialization/get/{name}"); // validate name if(name.isEmpty()){ LOG.error("FAILED: Name provided for GET was null or missing"); MDC.remove("transactionId"); return new ResponseEntity<>( HttpStatus.BAD_REQUEST ); } // call service Optional<Specialization> opSpec = specializationService.getSpecialization(name); if(opSpec.isPresent()){ LOG.info("SUCCESS: Specialization with provided name retrieved"); MDC.remove("transactionId"); return new ResponseEntity<>( opSpec.get(), HttpStatus.OK ); } else { LOG.info("COMPLETED: Specialization with name provided was not found"); MDC.remove("transactionId"); return new ResponseEntity<>( HttpStatus.NOT_FOUND ); } } }
import React, {useState,useEffect,useRef} from 'react'; const Dropdown = ({options,selectedText,onSelectedText}) => { const [open, setOpen] = useState(false); const ref = useRef(); useEffect(() => { const onBodyClick = (event) => { if(ref.current.contains(event.target)){ return; } setOpen(false); } document.body.addEventListener('click', onBodyClick); return () => { document.body.removeEventListener('click',onBodyClick); } },[]); const renderOption = options.map((option) => { if(option.label === selectedText.label) { return ''; } return ( <div onClick={() => onSelectedText(option)} key={option.value} className="item"> {option.label} </div> ); }); return ( <div ref={ref} className="ui form"> <div className="field"> <label className="label">Select a color</label> <div onClick={() => setOpen(!open)} className={`ui selection dropdown ${ open ? 'visible active' :'' }`} > <i className="dropdown icon"></i> <div className="text">{selectedText.label}</div> <div className={`menu ${open ? 'visible transition':''}`} > {renderOption} </div> </div> </div> </div> ); }; export default Dropdown;
// // ToolTipsHelperUIView.swift // SwiftUILab // // Created by Kamrul Hasan on 4/9/23. // import SwiftUI //----------Step 2 create showcase preference key------------------ fileprivate struct ShowcasePreferenceKey : PreferenceKey{ static var defaultValue: [Int:ShowcaseModel] = [:] static func reduce(value: inout [Int : ShowcaseModel], nextValue: () -> [Int : ShowcaseModel]) { value.merge(nextValue()) { key, value in value } } } //----------Step 3 Creating extension to apply anchorPreference------------------ extension View{ @ViewBuilder func showCase(order:Int, title:String, cornerRadius:CGFloat, style:RoundedCornerStyle = .continuous, scale:CGFloat = 1) -> some View{ self.anchorPreference(key: ShowcasePreferenceKey.self, value: .bounds) { anchor in let highlight = ShowcaseModel(anchor: anchor, title: title, cornerRadius: cornerRadius,style: style,scale: scale) return [order:highlight] } } } //----------Step 4 Creating ShowcaseRootViewModifier and showcase view------------------ struct ShowcaseRootViewModifier : ViewModifier{ var isVisibileShowCaseRootView:Bool var onFinished: ()-> () @State private var showCaseViewKeyOrderList:[Int] = [] @State private var currentShowCaseViewKey:Int = 0 @State private var isVisibleShowView:Bool = true @State private var isVisbleShowCaseTitle:Bool = false func body(content: Content) -> some View { content .onPreferenceChange(ShowcasePreferenceKey.self){value in showCaseViewKeyOrderList = Array(value.keys).sorted() } .overlayPreferenceValue(ShowcasePreferenceKey.self){preferences in if showCaseViewKeyOrderList.indices.contains(currentShowCaseViewKey), isVisibileShowCaseRootView, isVisibleShowView { if let hightlight = preferences[showCaseViewKeyOrderList[currentShowCaseViewKey]]{ ShowcaseView(hightlight) } } } } @ViewBuilder func ShowcaseView(_ highlight:ShowcaseModel) -> some View{ GeometryReader{proxy in let frame = proxy[highlight.anchor] let safeArea = proxy.safeAreaInsets Rectangle() .fill(.black.opacity(0.5)) .mask{ Rectangle() .overlay(alignment: .topLeading) { Rectangle() .frame(width: frame.width + 5,height: frame.height + 5) .clipShape(RoundedRectangle(cornerRadius: highlight.cornerRadius,style: highlight.style)) .scaleEffect(highlight.scale) .offset(x:frame.minX - 2.5, y:frame.minY + safeArea.top - 2.5) .blendMode(.destinationOut) } } .ignoresSafeArea() .onTapGesture { isVisbleShowCaseTitle = false if currentShowCaseViewKey >= showCaseViewKeyOrderList.count - 1{ withAnimation(.easeOut(duration: 0.5)){ isVisibleShowView = false onFinished() } }else{ withAnimation(.interactiveSpring(response: 0.3,dampingFraction: 0.7, blendDuration: 0.7)){ DispatchQueue.main.asyncAfter(deadline: .now()+0.6){ self.isVisbleShowCaseTitle = true } currentShowCaseViewKey += 1 } } } .onAppear{ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1){ isVisbleShowCaseTitle = true } } Rectangle() .foregroundColor(.clear) .frame(width: frame.width + 20,height: frame.height + 20) .clipShape(RoundedRectangle(cornerRadius: highlight.cornerRadius,style: highlight.style)) .popover(isPresented: $isVisbleShowCaseTitle) { Text(highlight.title) .padding(.horizontal,10) .presentationCompactAdaptation(.popover) .interactiveDismissDisabled() } .scaleEffect(highlight.scale) .offset(x:frame.minX - 10, y:frame.minY - 10) } } } struct ShowcaseHelper_Previews: PreviewProvider { static var previews: some View { ShowcaseUIView() } }
import React, {useState} from 'react'; import { View, StyleSheet, Text, Button, TouchableWithoutFeedback, Keyboard, //api Alert, } from 'react-native'; import Card from '../components/Card'; import Input from '../components/Input'; import NumberContainer from '../components/NumberContainer'; import Colors from '../constants/colors'; const StartGameScreen = props => { const [enteredValue, setEnteredValue] = useState(''); const [confirmed, setConfirmed] = useState(false); const [selectedNumber, setSelectedNumber] = useState(); const numberInputHandler = inputText => { setEnteredValue(inputText.replace(/[^0-9]/g, '')); //this expression says that we are replacing everything that is not 0 to 9 globally with an empty string }; const resetInputHandler = () => { setEnteredValue(''); setConfirmed(false); }; const confirmInputHandler = () => { const chosenNumber = parseInt(enteredValue); if (isNaN(chosenNumber) || chosenNumber <= 0 || chosenNumber > 99) { Alert.alert( 'Invalid number', 'Number has to be a number between 1 and 99.', [{text: 'Okay', style: 'destructive', onPress: resetInputHandler}], ); return; //if chosen number is a number or ir less than zero we simply return, we do not confirm } setConfirmed(true); setSelectedNumber(chosenNumber); setEnteredValue(''); }; let confirmedOutput; if (confirmed) { confirmedOutput = ( <Card style={styles.summaryContainer}> <Text>You selected</Text> <NumberContainer>{selectedNumber}</NumberContainer> <Button title="START GAME" onPress={() => props.onStartGame(selectedNumber)} /> </Card> ); }; //what touchablewithoutfeedback allows us is to exit the keyboard whenever we are touching any other side of the screen return ( <TouchableWithoutFeedback onPress={() => { Keyboard.dismiss(); }}> <View style={styles.screen}> <Text style={styles.title}>Game Screen</Text> <Card style={styles.inputContainer}> <Text>Select a number</Text> <Input style={styles.input} blurOnSubmit autoCapitalize="none" autoCorrect={false} keyboardType="numeric" maxLength={2} onChangeText={numberInputHandler} value={enteredValue} /> <View style={styles.buttonContainer}> <View style={styles.button}> <Button title="Reset" onPress={resetInputHandler} color={Colors.accent} /> </View> <View style={styles.button}> <Button title="Confirm" onPress={confirmInputHandler} color={Colors.primary} /> </View> </View> </Card> {confirmedOutput} </View> </TouchableWithoutFeedback> ); }; const styles = StyleSheet.create({ screen: { flex: 1, padding: 10, alignItems: 'center', }, title: { fontSize: 20, marginVertical: 10, //marginVertical replaces marginBottom and marginTop }, inputContainer: { width: 300, maxWidth: '80%', //if the device is too small we make sure that the width doesn't exceed the 80 percent alignItems: 'center', //ltr bc flexdirection is default --> column }, buttonContainer: { flexDirection: 'row', width: '100%', justifyContent: 'space-between', paddingHorizontal: 15, //horizontal --> left and right }, button: { width: 100, }, input: { width: 50, textAlign: 'center', //we center the input text because it looks nice for only adding a number }, summaryContainer: { marginTop: 20, alignItems: 'center', }, }); export default StartGameScreen;
import React, { useEffect, useState } from "react"; import MyEditor from "./Editor"; import date from "date-and-time"; import { CreateToast } from "../../../App"; import { UPLOADPHOTO, GETCOLLECTION, GETDOC, SETDOC, Distributor, decrypt, } from "../../../server"; import sortBy from "sort-by"; import "./ArticleBuilder.css"; import Upload from "../../../assets/upload.png"; import NotFound from "../../NotFound/NotFound"; const pattern = date.compile("HH A ,MMM DD YYYY"); const ArticleBuilder = () => { const [Categories, setCategories] = useState(null); const [authorList, setAuthorList] = useState([]); const [chosenAuthor, setChosenAuthor] = useState(null); const [ActiveUser, setActiveUser] = useState( sessionStorage.getItem("activeUser") ? decrypt(JSON.parse(sessionStorage.getItem("activeUser")).id) : "" ); const [Article, setArticle] = useState({ DateAdded: "", Description: "", PostBody: "", ReadTime: "", Title: "", category: "", id: "", liked: [], replies: [], imageContainer: [], thumbnail: "", views: 0, }); const [Updated, SetUpdated] = useState(false); const handleInput = async (e) => { const now = new Date(); const { name, value } = e.target; if (name === "Thumbnail") { CreateToast("uploading thumbnail", "info"); const Photo = e.target.files[0]; const url = await UPLOADPHOTO(`Blog/${Article.id}/thumbnail`, Photo); setArticle((prev) => { return { ...prev, thumbnail: url, DateAdded: date.format(now, pattern), }; }); CreateToast("thumbnail uploaded", "success"); return; } else { setArticle((prev) => { return { ...prev, [name]: value, DateAdded: date.format(now, pattern) }; }); } }; const handlePostBodyChange = (value) => { function calculateReadTime(html) { const wordsPerMinute = 200; // Parse the HTML into a document object const parser = new DOMParser(); const doc = parser.parseFromString(html, "text/html"); // Extract the text content from the document const text = doc.body.textContent || ""; // Count the number of words in the extracted text const wordCount = text.trim().split(/\s+/).length; // Calculate the read time in minutes const readTimeInMinutes = Math.ceil(wordCount / wordsPerMinute); return readTimeInMinutes; } setArticle((prevArticle) => ({ ...prevArticle, PostBody: value, ReadTime: calculateReadTime(value), })); }; const RenderAuthor = authorList?.map((author) => { return ( <option key={author.id} value={author.id}> {author.Fname} {author.Lname} </option> ); }); const handleOnBehalfChange = (event) => { const Author = authorList.find((author) => { return author.id === event.target.value; }); setChosenAuthor(Author); }; const setImageContainer = (imageContainer) => { setArticle((prev) => { return { ...prev, imageContainer }; }); }; const RenderCategories = Categories?.map((category) => { return ( <option key={category.id} value={category.Name}> {category.Name} </option> ); }); const handleCategoryChange = (event) => { setArticle((prev) => { return { ...prev, category: event.target.value }; }); }; const updatePost = async (e) => { e.preventDefault(); if (!Updated) { CreateToast("Please click on Save first", "warning"); } else { if (isArticleEmpty()) { CreateToast("please fill all the fields", "error"); return; } CreateToast("uploading Article", "info"); await SETDOC( "Articles", Article.id, { ...Article, OriginallyMadeBy: ActiveUser, Author: chosenAuthor === null ? ActiveUser : chosenAuthor, }, true ); const articles = await GETCOLLECTION("Articles"); Distributor(articles, Categories); CreateToast("Article Uploaded", "info"); setArticle((prev) => ({ ...prev, thumbnail: "", Description: "", Title: "", })); setChosenAuthor(null); GetID(); } }; const isArticleEmpty = () => { for (const key in Article) { if (!Array.isArray(Article[key]) && Article[key] === "") { return true; } } return false; }; useEffect(() => { const fetchData = async () => { const Category = await GETCOLLECTION("categories"); const users = await GETCOLLECTION("users"); const authorList = users.filter((user) => { return user.Role === "Author" && user.deleteUser === false; }); setAuthorList(authorList); setCategories(Category); }; fetchData(); }, []); useEffect(() => { const DetectUser = async () => { if (!ActiveUser) { return; } const FetchedUser = await GETDOC("users", ActiveUser); setActiveUser(FetchedUser); if (FetchedUser.Role === "Author") { setArticle((prev) => { return { ...prev, Author: FetchedUser }; }); } }; DetectUser(); GetID(); }, []); const GetID = async () => { let id; const Articles = await GETCOLLECTION("Articles"); if (Articles.length === 0) { id = 1; } else { Articles.sort(sortBy("id")); Articles.forEach((product) => { id = +product.id + 1; }); } setArticle((prev) => { return { ...prev, id }; }); }; return ( <> {ActiveUser ? ( <> {ActiveUser.Role === "User" ? ( <NotFound /> ) : ( <form className="ArticleBuilder"> <div className="FormItem" id="Title"> <label htmlFor="Title">Title:</label> <input type="text" required id="Title" name="Title" value={Article.Title} onChange={handleInput} /> </div> <div className="FormItem" id="Category"> <label htmlFor="last-name">Category:</label> <div className="select-container"> <select className="styled-select" value={Article.category} required onChange={handleCategoryChange} > <option value="">Choose a Category</option> {RenderCategories} </select> </div> </div> <div className="FormItem" id="Thumbnail"> <span>Thumbnail:</span> <label htmlFor="thumbnailInput"> <img src={Upload} style={{ width: "25px", cursor: "pointer" }} /> </label> <input type="file" hidden required id="thumbnailInput" name="Thumbnail" onChange={handleInput} /> </div> <div className="FormItem" id="Description"> <label htmlFor="Description">Description:</label> <textarea id="Description" name="Description" required value={Article.Description} onChange={handleInput} /> </div> <div className="FormItem" id="UnderName"> <label htmlFor="last-name">Post on behalf of:</label> <div className="select-container"> <select className="styled-select" onChange={handleOnBehalfChange} > <option value={null}>myself</option> {RenderAuthor} </select> </div> </div> {Article.id && ( <MyEditor handlePostBodyChange={handlePostBodyChange} SetUpdated={SetUpdated} ArticleID={Article.id} updatePhotoList={(photolist) => { setImageContainer(photolist); }} /> )} <input id="Save" type="submit" className="Button" value="Upload" onClick={(e) => { updatePost(e); }} style={{ margin: "20px auto", width: "20%" }} /> </form> )} </> ) : ( <NotFound /> )} </> ); }; export default ArticleBuilder;
--- type Link = { title: string; href: string; }; type Links = Link[]; const links = [ { title: 'Words', href: '/#words' }, { title: 'Reading', href: '/#reading' }, { title: 'Speaking', href: '/#speaking' }, { title: 'Music', href: '/#music' }, { title: 'Photos', href: '/#photos' }, { title: 'Tweets & Toots', href: '/#tweetsAndToots' }, { title: 'Places', href: '/#places' }, { title: 'Work', href: '/work' }, { title: 'Contact', href: '/contact' }, { title: 'Starred', href: '/github-stars' }, ] as Links; const currentPath = Astro.url.pathname; --- <header role="banner" class="pw-header w-full h-12 sticky top-0 z-20 focus-within:z-50 bg-binding-dark text-white py-2 px-5 sm:px-2" x-ignore ax-load="idle" x-data="PwHeader" x-on:pw-header-active-section-id.window="activeSection = $event.detail" style={currentPath === '/' ? `content-visibility: hidden; contain-intrinsic-height: 48px` : ``} > <div class="section__inner mx-auto flex space-x-4"> <a href="/#content" rel="home" class="block flex-shrink-0 size-8"> <span class="sr-only">Home</span> <img hidden alt="Phil Wolstenholme" class="inline-block size-8 bg-yellow-300 rounded-full" src="https://wolstenhol.me/proxy/cloudinary/image/upload/c_scale,f_auto,w_32,q_auto:eco/v1545084898/avatar_egzcjk.png" srcset="https://wolstenhol.me/proxy/cloudinary/image/upload/c_scale,f_auto,w_64,q_auto:eco/v1545084898/avatar_egzcjk.png 2x" width="32" height="32" loading="lazy" /> </a> <nav id="PwHeaderList" class="header-nav relative flex flex-1 items-center overscroll-contain overflow-x-auto hide-scrollbars" role="navigation" tabindex={-1} aria-labelledby="in-page-navigation" > <h2 id="in-page-navigation" class="sr-only">In-page navigation</h2> <ul class="header-nav__list flex align-center space-x-3"> { links.map(item => { const id = item.href.replace('/#', '').replace('#', ''); const linkFirstChar = item.href.slice(0, 1); const linkSecondChars = item.href.slice(0, 2); let itemClass = ``; if (linkFirstChar === '#' || linkSecondChars === '/#') { itemClass = `{'text-yellow-300': activeSection === '${id}'}`; } else { itemClass = `{'text-yellow-300': window.location.pathname === '${id}'}`; } return ( <li class="flex-shrink-0"> <a href={item.href} class="font-bold font-serif underline hocus:text-yellow-300" x-bind:class={itemClass} x-on:click.prevent={`activeSection = '${id}'; onLinkActivate($event)`} x-on:keydown.enter.prevent={`activeSection = '${id}'; onLinkActivate($event)`} > {item.title} </a> </li> ); }) } </ul> </nav> </div> <div class="-mx-5 sm:-mx-2 bg-binding-dark h-3 transform shadow-hard" style={{ '--tw-skew-y': '-0.3deg !important' }}></div> </header> <script> (() => { let url = new URL(window.location.href); let params = new URLSearchParams(url.search); if (window.location.search.includes('hsp=')) { const scrollLeft = params.get('hsp'); const headerList = document.getElementById('PwHeaderList'); if (headerList) { headerList.scrollLeft = parseInt(scrollLeft || '0', 10); } params.delete('hsp'); url.search = params.toString(); history.replaceState({}, '', url.toString()); } if (window.location.search.includes('hc=')) { const header = document.querySelector('header'); header?.classList.add('z-50'); setTimeout(() => { // The class only neees to be there long enough to scroll down to an anchor. header?.classList.remove('z-50'); }, 5 * 1000); params.delete('hc'); url.search = params.toString(); history.replaceState({}, '', url.toString()); } document.querySelector(`a[href*="${CSS.escape(window.location.hash)}"]`)?.classList.add('text-yellow-300'); })(); </script>
#include "system.h" #include "linux_parser.h" // Return the system's CPU Processor& System::GetCpu() { return cpu_; } // Return a container composed of the system's processes std::vector<Process>& System::GetProcesses() { processes_ = {}; auto pids = LinuxParser::Pids(); for (int pid : pids) { Process p(pid); processes_.push_back(p); } std::sort(processes_.begin(), processes_.end()); return processes_; } // Return the system's kernel identifier (string) std::string System::GetKernel() { return LinuxParser::Kernel(); } // Return the system's memory utilization float System::GetMemoryUtilization() { return LinuxParser::MemoryUtilization(); } // Return the operating system name std::string System::GetOperatingSystem() { return LinuxParser::OperatingSystem(); } // Return the number of processes actively running on the system int System::GetRunningProcesses() { return LinuxParser::RunningProcesses(); } // Return the total number of processes on the system int System::GetTotalProcesses() { return LinuxParser::Pids().size(); } // Return the number of seconds since the system started running long int System::GetSystemUpTime() { return LinuxParser::UpTime(); }
import { sendEmail, setEmailConfig } from '../lib/email'; import prisma from '@/lib/prisma'; export async function sendNotification(userId: string, message: string, link: string, email: boolean, push: boolean, inApp: boolean) { // Implement the logic to send notifications based on the user's preferences if (email) { // Retrieve the user's email address from the database const user = await prisma.user.findUnique({ where: { id: userId }, select: { email: true }, }); if (user && user.email) { // Retrieve the email configuration from the database const config = await prisma.adminSettings.findFirst(); if(!config) { return; } const emailSet = await setEmailConfig({ provider: config.emailProvider || 'smtp', smtp: { host: config.smtpHost || '', port: config.smtpPort || 587, secure: config.smtpSecure || false, auth: { user: config.smtpAuthUser || '', pass: config.smtpAuthPass || '', }, }, ses: { region: config.sesRegion || '', accessKeyId: config.sesAccessKey || '', secretAccessKey: config.sesSecretAccessKey || '', }, from: config.emailFrom || '', }); console.log('Email set:', emailSet); // Send email notification using the existing sendEmail function await sendEmail({ to: user.email, subject: 'New Notification', text: message, html: `<p>${message}</p>`, }); } } if (push) { // Send push notification // ... } if (inApp) { // Create an in-app notification record in the database await prisma.notification.create({ data: { userId, message, link, }, }); } }
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> <script> function Student(name, kor, mat, eng, sci) { this.name = name; this.kor = kor; this.mat = mat; this.eng = eng; this.sci = sci; this.getSum = function () { return this.kor + this.mat + this.eng + this.sci; }; this.getAvg =function () { return this.getSum() / 4; }; this.toString = function () { var output = ''; for (var key in this) { if (key != 'getSum' && key != 'getAvg' && key != 'toString') { output += key + ':' + this[key] + '<br>'; } else if (key == 'getSum' || key == 'getAvg') { output += key.substring(3).toUpperCase() + this[key]() + '<br>'; //getSum이 아니라 Sum이라고 쓰고 싶어서 substring 하는 것 //string이라는 내장객체에 substring이라는 함수가 있어서 쓸 수 있는 것 }//else if }//for return output; }; //tostring }//function 생성자 함수기 때문에 return 없음 var students = [new Student('홍길동', 100, 100, 100, 100), new Student('마길동', 100, 100, 99, 100), new Student('윤길동', 900, 80, 90, 70), new Student('지울애', 10, 20, 30, 40) ]; //생성자에 매개변수 5개 이상 들어와도 뒷부분 무시됨 students.pop(); //마지막 idx값 제거 document.write('제거후<br>'); students.forEach(function (data, idx) { document.write(idx + '번째<br>' + data + '<hr>'); }); </script> </head> <body> </body> </html>
package com.bt1.qltv1.controller.common; import com.bt1.qltv1.dto.SuccessResponseDTO; import com.bt1.qltv1.dto.password.ChangePasswordRequest; import com.bt1.qltv1.dto.register.OtpVerifyRequest; import com.bt1.qltv1.dto.user.VerifySms; import com.bt1.qltv1.service.ProfileService; import com.bt1.qltv1.validation.Phone; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.Email; @RestController @RequiredArgsConstructor @RequestMapping("/api/v1") @Validated public class ProfileController { private final ProfileService profileService; @GetMapping("/common/reset-password") public ResponseEntity<SuccessResponseDTO> resetPassword(@RequestParam @Email(message = "{user.email.invalid}") String email){ profileService.resetPassword(email); return ResponseEntity.ok(new SuccessResponseDTO(HttpStatus.OK, "Send new password to email successful!")); } @PostMapping("/user/change-password") public ResponseEntity<SuccessResponseDTO> changePassword(@RequestBody @Valid ChangePasswordRequest changePasswordRequest){ profileService.changePassword(changePasswordRequest); return ResponseEntity.ok(new SuccessResponseDTO(HttpStatus.OK, "Change password successful!Please login again!")); } @PostMapping("/user/change-email") public ResponseEntity<SuccessResponseDTO> changeEmail(@RequestParam(name = "email") @Email(message = "{user.email.invalid}") String newEmail){ profileService.changeEmail(newEmail); return ResponseEntity.ok(new SuccessResponseDTO(HttpStatus.OK, "Send mail success! Please confirm your new email!")); } @PostMapping("user/change-phone/{phone}") public ResponseEntity<SuccessResponseDTO> changePhone(@Phone @PathVariable(name = "phone") String newPhone){ profileService.changePhone(newPhone); return ResponseEntity.ok(new SuccessResponseDTO(HttpStatus.OK, "Send otp to your sms success!")); } @PostMapping("/user/new-phone/verify-sms-otp") public ResponseEntity<SuccessResponseDTO> verifySms(@Valid @RequestBody VerifySms verifySms) { profileService.verifyNewPhoneSms(verifySms); return ResponseEntity.ok(new SuccessResponseDTO(HttpStatus.OK, "Change phone successful")); } @PostMapping("/user/new-email/verify-otp") public ResponseEntity<SuccessResponseDTO> verifyNewEmailWithOtp(@Valid @RequestBody OtpVerifyRequest otpVerifyRequest) { profileService.verifyNewEmailOtp(otpVerifyRequest); return ResponseEntity.ok(new SuccessResponseDTO(HttpStatus.OK, "Your email has been verified! Please login!")); } }
const mongoose = require('mongoose'); const validator = require('validator'); const bcrypt = require('bcryptjs'); const UnauthorizedError = require('../errors/UnauthorizedError'); const { errorMessages } = require('../errors/errors'); const { linkRegex } = require('../utils/regex'); const userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true, validate: { validator: (v) => validator.isEmail(v), message: 'Неверный формат email.', }, }, password: { type: String, required: true, select: false, }, name: { type: String, default: 'Жак-Ив Кусто', minlength: 2, maxlength: 30, }, about: { type: String, default: 'Исследователь', minlength: 2, maxlength: 30, }, avatar: { type: String, default: 'https://pictures.s3.yandex.net/resources/jacques-cousteau_1604399756.png', validate: { validator: (v) => linkRegex.test(v), message: 'Неверный формат ссылки.', }, }, }); userSchema.statics.findUserByCredentials = function (email, password) { return this.findOne({ email }).select('+password') .then((user) => { if (!user) { throw new UnauthorizedError(errorMessages.MESSAGE_ERROR_UNAUTHORIZED); } return bcrypt.compare(password, user.password) .then((matched) => { if (!matched) { throw new UnauthorizedError(errorMessages.MESSAGE_ERROR_UNAUTHORIZED); } return user; }); }); }; module.exports = mongoose.model('user', userSchema);
import java.util.ArrayList; public class TestArrayList_11_8 { public static void main(String[] args) { // Create a list to store cities ArrayList<String> cityList = new ArrayList<>(); // Add some cities in the list cityList.add("London"); // cityList now contains [London] cityList.add("Denver"); // cityList now contains [London,Denver] cityList.add("Paris"); // cityList now contains [London,Denver,Paris] cityList.add("Miami"); // cityList now contains [London,Denver,Paris,Miami] cityList.add("Seoul"); // cityList now contains [London,Denver,Paris,Miami,Seoul] cityList.add("Tokyo"); // cityList now contains [London,Denver,Paris,Miami,Seoul,Tokyo] System.out.println("List size? " + cityList.size()); System.out.println("Is Miami in the list? " + cityList.contains("Miami")); System.out.println("The location of Denver in the list? " + cityList.indexOf("Denver")); System.out.println("Is the list empty? " + cityList.isEmpty()); // Insert a new city at index 2 cityList.add(2,"Xian"); // Contains [London,Denver,Xian,Paris,Miami,Seoul,Tokyo] cityList.remove("Miami"); // Contains [London,Denver,Xian,Paris,Seoul,Tokyo] // Display the contents in the list System.out.println(cityList.toString()); // Display the contents in the list in reverse order for (int i = cityList.size()-1; i >= 0; i--) { System.out.print(cityList.get(i) + " "); } System.out.println(); // Create a list to store two circles ArrayList<Circle_11_2> list = new ArrayList<>(); // Add two circles list.add(new Circle_11_2(2)); list.add(new Circle_11_2(3)); // Display the area of the first circle in the list */ System.out.println("The area of the circle " + list.get(0).getArea()); } }
import { Card, CardContent, CardMedia, Button } from '@mui/material'; import React from 'react'; import styled from '@emotion/styled'; import AddIcon from './AddIcon'; import { useNavigate } from 'react-router-dom'; const StyledCard = styled(Card)` display: flex; max-width: 1072.41px; height: 149px; padding: 15px; gap: 20px; border: 0px; background-color: rgba(217, 217, 217, 0.4); `; const Img = styled(CardMedia)` max-width: 180px; `; const Content = styled(CardContent)` position: relative; padding: 0; h4 { margin: 0 0 8px 0; } span, p { font-size: 12px; color: #595959; } p { margin-bottom: 18px; } `; const CardButton = styled(Button)` font-size: 10px; background-color: #d18e8e; border-radius: 50px; font-weight: 600; position: absolute; bottom: 0; right: 0; color: white; `; const StoreCard = ({ item: { _id, name, location, favoriteUsersSize, favoriteUsers, description, photo, }, }) => { let user = localStorage.getItem('user'); if (user === '[object Object]' || user === 'null') user = ''; const userId = user ? JSON.parse(user)._id : null; const { state, city, postcode } = location; const address = `${postcode} ${city} ${state}`; const navigate = useNavigate(); return ( <StyledCard variant="outlined"> {/* need data <Img component="img" image={food} alt="" /> */} <Img component="img" image={photo[0]} alt="" /> <Content> <h4>{name}</h4> <span>{`${address} | ${favoriteUsersSize} people add to booklet`}</span> <p>{description}</p> <AddIcon userId={userId} id={_id} favoriteUsers={favoriteUsers} /> <CardButton onClick={() => navigate(`/BookingPage/${_id}`)} variant="contained" size="small" > Learn more </CardButton> </Content> </StyledCard> ); }; export default StoreCard;
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import * as cdk from "aws-cdk-lib"; import { Construct } from "constructs"; import { NagSuppressions } from "cdk-nag"; import * as iam from "aws-cdk-lib/aws-iam"; import * as ssm from "aws-cdk-lib/aws-ssm"; import { OPAEnvironmentParams } from "@aws/aws-app-development-common-constructs"; export interface EKSControlPlaneConstructProps extends cdk.StackProps { readonly opaEnv: OPAEnvironmentParams; /** * Scope for CfnOutput */ cfnOutputScope: any } const defaultProps: Partial<EKSControlPlaneConstructProps> = {}; export class EKSControlPlaneRoleConstruct extends Construct { public IAMRole: iam.Role; public controlPlaneRoleParam: ssm.StringParameter; public controlPlaneRoleArnParam: ssm.StringParameter; constructor(parent: Construct, name: string, props: EKSControlPlaneConstructProps) { super(parent, name); /* eslint-disable @typescript-eslint/no-unused-vars */ props = { ...defaultProps, ...props }; const envIdentifier = `${props.opaEnv.prefix.toLowerCase()}-${props.opaEnv.envName}`; const envPathIdentifier = `/${props.opaEnv.prefix.toLowerCase()}/${props.opaEnv.envName.toLowerCase()}`; // Create Iam role this.IAMRole = new iam.Role(this, `${envIdentifier}-role`, { assumedBy: new iam.ServicePrincipal("eks.amazonaws.com"), roleName: name, managedPolicies: [ iam.ManagedPolicy.fromAwsManagedPolicyName("AmazonEKSClusterPolicy"), ], maxSessionDuration: cdk.Duration.seconds(43200), }); NagSuppressions.addResourceSuppressions(this.IAMRole, [ { id: "AwsSolutions-IAM4", reason: "Assumed roles will use AWS managed policies for demonstration purposes. Customers will be advised/required to assess and apply custom policies based on their role requirements" }, { id: "AwsSolutions-IAM5", reason: "Assumed roles will require permissions to perform multiple ecs, ddb, and ec2 for demonstration purposes. Customers will be advised/required to assess and apply minimal permission based on role mappings to their idP groups" }, ], true ); // now save the Role in SSM Param const roleParam = new ssm.StringParameter(this, `${envIdentifier}-role-param`, { allowedPattern: ".*", description: `The EKS Control Plane Role for OPA Solution: ${props.opaEnv.envName} Environment`, parameterName: `${envPathIdentifier}/eks-control-plane-role`, stringValue: this.IAMRole.roleName, }); const roleArnParam = new ssm.StringParameter(this, `${envIdentifier}-role-arn-param`, { allowedPattern: ".*", description: `The EKS Cluster Control Plane Role Arn for OPA Solution: ${props.opaEnv.envName} Environment`, parameterName: `${envPathIdentifier}/eks-control-plane-role-arn`, stringValue: this.IAMRole.roleArn, }); // Post params to output new cdk.CfnOutput(props.cfnOutputScope, "ContolPlaneRoleParam", { value: roleParam.parameterName, }); // Post params to output new cdk.CfnOutput(props.cfnOutputScope, "ControlPlaneRoleArnParam", { value: roleArnParam.parameterName, }); this.controlPlaneRoleParam = roleParam; this.controlPlaneRoleArnParam = roleArnParam; } }
import React, {forwardRef }from 'react'; import './Post.css'; import { Avatar } from '@mui/material'; import { ChatOutlined, SendOutlined, ShareOutlined, ThumbUp } from '@mui/icons-material'; import InputOption from './InputOption'; const Post = forwardRef ( ({ post: { name, description, message, photoUrl }}, ref) => { console.log(name) console.log(photoUrl) return ( <div ref={ref} className="post"> <div className="post__header"> <Avatar src={photoUrl || ''}> {(name ? name[0] : '')} </Avatar> <div className="post__info"> <h2>{name}</h2> <p>{description}</p> </div> </div> <div className="post__body"> <p>{message}</p> </div> <div className="post__buttons"> <InputOption Icon={ThumbUp} title="Like" color="#B6B6B6" /> <InputOption Icon={ChatOutlined} title="Chat" color="#B6B6B6" /> <InputOption Icon={ShareOutlined} title="Share" color="#B6B6B6" /> <InputOption Icon={SendOutlined} title="Send" color="#B6B6B6" /> </div> </div> ); }) export default Post;
class Stack { static final int Max=1000; int top; int a[]=new int[Max]; boolean isEmpty(){ return (top<0); } Stack(){ top=-1; } boolean push(int x){ if (top>=(Max-1)){ System.out.println("Stack Overflow"); return false; } else{ a[++top]=x; System.out.println(x+" pushed"); return true; } } int pop(){ if (top < 0) { System.out.println("Stack Underflow"); return 0; } else { int x = a[top--]; return x; } } int peek(){ if (top<0){ System.out.println("Stack Underflow"); return 0; } else{ int x=a[top]; return x; } } void print(){ while(top!=-1){ System.out.print(a[top] +" "); top--; } } public static void main (String[] args) { Stack s=new Stack(); s.push(10); s.push(2); s.push(3); s.push(5); System.out.println(s.pop() + " popped element"); System.out.println(s.peek() +" top element"); System.out.print("after pop element "); s.print(); } }
## About Data Source Google Merchandise Store](https://shop.merch.google/) is an online store that sells Google-branded merchandise. The site uses Google Analytics 4's standard web ecommerce implementation along with enhanced measurement. The ga4_obfuscated_sample_ecommerce dataset available through the [BigQuery Public Datasets](https://console.cloud.google.com/bigquery) program contains a sample of obfuscated BigQuery event export data for three months from 2020-11-01 to 2021-01-31. ## Power User Modeling for Mailing Campaign Welcome to the Power User Modeling for Mailing Campaign repository! This project features a Streamlit interface to analyze user behavior and predict user spending. Below you will find information about the project, data, models, and how to run the Streamlit application. ### Streamlit Interface You can access the Streamlit interface for this project [here](https://stpoweruserapp.streamlit.app/). Through this interface, you can analyze the user's 90-day revenue based on their first 15-day behavior and predict whether the user is likely to spend more money. ### About the Data The dataset used in this project includes user transaction data and various features related to user behavior. - **LTV Prediction**: Predicting the Lifetime Value (LTV) of users over 90 days. - **Power User Prediction**: Initially, power users were identified based on a z-score method. However, this method resulted in very few power users, making it insufficient. Therefore, based on the distributions, users who spent more than $110 were identified as power users, forming the basis for the classification target. ### LTV Prediction We used Random Forest Regressor for predicting LTV. After hyperparameter optimization. ### Power User Prediction ### 1. Model Training and Oversampling - **Training Dataset Preparation**: The training dataset was adjusted using various oversampling methods to handle class imbalances. - **Oversampling Techniques**: Methods like RandomOverSample, SMOTE, and ADASYN were employed to balance the dataset, ensuring that the models could effectively learn from both the majority and minority classes. ### 2. Model Selection - **Hyperparameter Optimization**: GridSearchCV was used for hyperparameter tuning to find the best model configurations. - **Comparison of Models**: Several models were compared based on their performance metrics, including KNN, XGBoost, Logistic Regression, and Random Forest. The XGBoost model with ADASYN oversampling showed the best performance. | Model | Recall | Precision | Log Loss | |---------------------------------------------|---------|-----------|----------| | KNN | 51.65% | 88.70% | 6.88% | | KNN_RandomOverSample | 47.25% | 23.50% | 15.45% | | KNN_SMOTE | 62.64% | 19.40% | 19.13% | | KNN_ADASYN | 28.57% | 35.60% | 24.31% | | XGBoost | 71.43% | 100.00% | 5.23% | | XGBoost_RandomOverSample | 71.43% | 55.60% | 2.70% | | XGBoost_SMOTE | 71.43% | 97.00% | 1.41% | | **XGBoost_ADASYN** | 71.43% | 100.00% | 1.33% | | Logistic Regression | 67.03% | 89.70% | 1.21% | | Logistic Regression_RandomOverSample | 78.02% | 10.50% | 14.46% | | Logistic Regression_SMOTE | 76.92% | 11.60% | 12.64% | | Logistic Regression_ADASYN | 84.62% | 6.40% | 24.08% | | RandomForest | 70.33% | 100.00% | 4.49% | | RandomForest_RandomOverSample | 63.74% | 87.90% | 5.12% | | RandomForest_SMOTE | 72.53% | 42.00% | 3.16% | | RandomForest_ADASYN | 74.73% | 32.70% | 4.43% | ### 4. Threshold Adjustment and Model Evaluation - **Threshold Tuning**: The threshold value of the model was adjusted to optimize performance. Despite testing various thresholds, the default value of 0.5 was retained as it provided the best balance between recall and precision. - **ROC AUC Curve Analysis**: The performance of the XGBoost ADASYN model was further validated using the ROC AUC curve, demonstrating strong predictive capabilities. ### Running the Streamlit Application Run the Streamlit app by uploading the `powerUser_streamlit_v002_df_pickle.py` file to Streamlit.io. The `requirements.txt` file in the repository contains all the necessary dependencies.
const { pool, MENSAJE_ERROR_SERVIDOR } = require("../config/config"); const Ruta = require("./ruta.model"); const Utilidades = require("./utilidades.model"); class Rol { async getRoles() { return new Promise((resolve, reject) => { let query = `SELECT * FROM public.roles ORDER BY rol`; pool.query(query, async (error, results) => { if (error) { reject({ Status: true, Response: MENSAJE_ERROR_SERVIDOR + error }) } const rutaModel = new Ruta(); const roles = results.rows; for (const rol of roles) { rol.rutas = await rutaModel.getRutasByRolSimple(rol.idrol); } resolve({ Status: true, Response: 'Los roles se obtuvieron correctamente', Results: results.rows }); }) }); } async getRolByIdSimple(idrol) { return new Promise((resolve, reject) => { let query = `SELECT * FROM public.roles WHERE idrol='${idrol}'`; pool.query(query, async (error, results) => { if (error) { reject({ Status: true, Response: MENSAJE_ERROR_SERVIDOR + error }) } const rutaModel = new Ruta(); const rol = results.rows[0]; rol.rutas = await rutaModel.getRutasByRolSimple(rol.idrol); resolve(rol); }) }); } async postRol(datos) { return new Promise((resolve, reject) => { let idrol = new Utilidades().generarID(); let {rol} = datos; let query = `INSERT INTO public.roles (idrol, rol) VALUES ($1, $2)`; pool.query(query, [idrol, rol], (error, results) => { if (error) { reject({ Status: false, Response: MENSAJE_ERROR_SERVIDOR + error }); } resolve({ Status: true, Response: 'El rol se creó correctamente' }); }); }); } async putRol(datos) { return new Promise((resolve, reject) => { let {idrol, rol} = datos; let query = `UPDATE public.roles SET rol=$1 WHERE idrol='${idrol}'`; pool.query(query, [rol], (error, results) => { if (error) { reject({ Status: false, Response: MENSAJE_ERROR_SERVIDOR + error }); } resolve({ Status: true, Response: 'El rol se actualizó correctamente' }); }); }); } async postRolRuta(datos) { return new Promise((resolve, reject) => { let idrolruta = new Utilidades().generarID(); let {idrol, idruta, ruta} = datos; let query = `INSERT INTO public.rolrutas (idrolruta, idrol, idruta, ruta) VALUES ($1, $2, $3, $4) RETURNING *`; pool.query(query, [idrolruta, idrol, idruta, ruta], (error, results) => { if (error) { reject({ Status: false, Response: MENSAJE_ERROR_SERVIDOR + error }); } resolve({ Status: true, Response: 'La ruta se vinculó correctamente', ObjectResult: results.rows[0] }); }); }); } async deleteRolById(idrol) { return new Promise((resolve, reject) => { let query = `DELETE FROM public.roles WHERE idrol='${idrol}'`; pool.query(query, (error, results) => { if (error) { reject({ Status: false, Response: MENSAJE_ERROR_SERVIDOR + error }); } resolve({ Status: true, Response: 'El rol se eliminó correctamente' }); }); }); } async deleteRolRutaById(idrolruta) { return new Promise((resolve, reject) => { let query = `DELETE FROM public.rolrutas WHERE idrolruta='${idrolruta}'`; pool.query(query, (error, results) => { if (error) { reject({ Status: false, Response: MENSAJE_ERROR_SERVIDOR + error }); } resolve({ Status: true, Response: 'La ruta se desvinculó correctamente' }); }); }); } } module.exports = Rol;
# V2V-OMNET-SUMO-GTFS Service placement is a an optimization problem, which can be applied to any problem where two or metrics are supposed to be the variables that are to be optimized. In that way Service Placement Problem is a wrapper. It and can be wrapped around any problem statement like VM placement, static RSU in smart city, dynamic RSU in smart city, Multi-tenant architectural platform optimizations etc) Service placement when considered in IoT and especially smart city domains for placing services, optimizes the energy consumed (one of the variables, most popular) and QoS (like latency, response time) parameter when interacting with the devices. This optimization problem when is generally done in systems that consider static RSUs. For dynamic RSUs the dynamicity in a smart city environment can be considered as that of moving vehicles. From that perspective, a V2V scenario and model that assumes the movements of the microscopic traffic model can be applied, where one vehicle can be considered a consumer and another the producer. The producer has OBUs installed on them, to make their range of interaction stronger. There are multiple configurations like master-slave, clustering of moving nodes etc which have been considered in literature and previous research work. There’s none to the best of my knowledge that considers the past data of public vehicles and considers a system where their future location is predicted and hence an interaction map or interaction time windows of these moving vehicles are considered. The following is a system that takes GTFS data of public buses in Dublin, and based on the predictions of the model, generates and interaction map. Since interaction map has to be generated using a formula or a set of rules, that are is unexplored and the interaction maps are generated based on the simulations instead. These simulations are then varied based on – how off – the prediction can be and its impact evaluated. The definition of a system is extremely critical before wrapping it around with a Service Placement Optimization problem. The following defines a step-by-step process for the setup of all the tools and ide-s required for generating V2V simulations. • Omnet++ v5.3 • SUMO 0.32 • VEINS 4.7 • INET 3.6.8 1) In windows, download omnet++ v5.3 from https://omnetpp.org/download/old , the current version is 6.0.1, but these modules are not perfectly backward compatible or wholistically upgraded, so there are issues if the exact versions are not used together. 2) Follow the basic setup guideline from Omnet++ installation guide. This is an exact process, and is not mentioned here to avoid discripencies. 3) SUMO and older versions of SUMO can be downloaded and installed from here - https://sumo.dlr.de/docs/Downloads.php 4) Veins 4.7 can be downloaded from here, and doesn’t have to be installed – just imported to omnet++ directory. https://veins.car2x.org/download/ 5) INET 3.6.8 would be downloaded automatically by the omnet ide on startup and imported to the workspace. After the setup the project can be imported. There are 4 projects overall and they are slightly different from each other in terms of v2v setup in the following way: V2v_app_5 – implements interaction of moving vehicle with static RSUS and records the message exchange between car-rsu throughout the simulation. V2v_app_5_1 – static RSU-RSU RTT is recorded by re-using the components of the above project. V2v_app_6 – implements interaction of moving vehicle with other moving vehicle and records the message exchange between car-car throughout the simulation. V2V_app_6_1 – car-car RTT is recorded by re-using the components of the above project. While an overview of OMNET++ and its use in different applications is available across multiple sources, a concise view of its most important files and properties that are used to create a simulation are missing to the best of my knowledge. Thus a brief view of the files is provided below along with information about the different properties. The overall critical files are interacting with each other in the the following way: a) The simulation starts and reads the .ini file to determine the setup. b) Using the specified network in the .ini file, OMNeT++ constructs the network using the appropriate .ned file(s). c) Once the network structure is in place, the simulation runs the behavior defined in the .cc files. d) The simulation proceeds, with nodes (like vehicles and RSUs) interacting based on the logic in the .cc files, until the simulation ends (based on criteria like a time limit). To visualize this, the .ini file serves as the blueprint, the .ned files as the architectural design, and the .cc files as the construction details of a building. In this analogy, The simulation then lives in this building, following the rules set in the code   Codebase Overview: NED File Description IntersectionApp - Extends BaseWaveApplLayer, inheriting its capabilities for vehicular applications. - @class(IntersectionApp); is a decorator indicating the associated C++ class. - @display("i=block/app2"); sets the graphical display characteristics in the simulation environment. IntersectionScenario - Extends Scenario, which is a custom base scenario class. - rsu[13]: RSU declares 13 Road-Side Units (RSUs) in the scenario. - @display("bgb=1000,1000;bgl=3"); sets the background dimensions and grid line characteristics. CarMessage extends WaveShortMessage, inheriting its features and adding more fields - helloMsg: A string containing a "Hello World" message, priority: An integer representing the priority of the message, rsuId: The ID of the RSU involved in the message exchange, carId: The ID of the car sending the message. Header File (C++) Inherited Class - BaseWaveApplLayer: This is the base class for WAVE (Wireless Access in Vehicular Environments) application layers. It provides methods to handle lower and self-messages, as well as position updates. Data Members - RSU related - delayTimeRSU: The time delay before an RSU can send another message. - lastSentRSU: The last time an RSU sent a message. - RSUData: A vector storing IntersectMessage objects, probably containing data related to intersections. - Vehicle related - delayTimeCars: The time delay before a car can send another message. - lastSent: The last time a car sent a message. - canGo: A flag to indicate whether the car can go through an intersection or not. - General - isRSU: A boolean flag indicating if the current node is an RSU. Static Data Members - carDistances, carPositions, rsuPositions: Maps that store distances between cars, and the positions of cars and RSUs, respectively. - messageExchangeCount: Stores the count and timestamps of messages exchanged between nodes. - interestingIds: A set of IDs that the application is particularly interested in. - msgQueue: A priority queue that sorts incoming CarMessage objects by priority. - car1Speeds,bus0Speeds, etc.: Maps that store the speeds of specific vehicles at different simulation times. Methods - Initialize and Finish - initialize(int stage): Sets initial parameters and flags. - finish(): Called at the end of the simulation to perform any required cleanup or data export. - Position Updates - handlePositionUpdate(cObject* obj): Called when the position of a car or RSU changes. - Message Handling - handleSelfMsg(cMessage* msg): Handles self-sent messages. - handleLowerMsg(cMessage *msg): Handles messages received from lower layers. - populateCMBrodcast(CarMessage* cm): Populates a CarMessage before it's sent. - onCarMessage(CarMessage* cm): Custom handling for received CarMessage objects. - Utility Functions - calculateDistance(const Coord& pos1, const Coord& pos2): Calculates the distance between two coordinates. - exportMessageExchangeCounts(): Exports message exchange data to a CSV file. Note: WaveShortMessage is a predefined class for WAVE (Wireless Access in Vehicular Environments) short messages in the Veins framework. It's designed to encapsulate the data and attributes associated with short messages sent between vehicles or between vehicles and infrastructure. It typically includes attributes like sender and receiver addresses, data payload, etc. BaseWaveApplLayer :This is the base class for WAVE application layers in the Veins framework. The class defines the basic functionality required for applications that need to send and receive WAVE short messages. It provides essential methods for handling messages, including methods to deal with messages from the network layer (handleLowerMsg) and self-messages (handleSelfMsg), as well as methods for updating positions (handlePositionUpdate). Implementation Overview: 1. Initialization (initialize) During the initialization phase, the simulation identifies whether the node is a Road-Side Unit (RSU) or a vehicle. 2. Position Update (handlePositionUpdate) This method is triggered every time a vehicle moves. It updates the position of the car in the carPositions map. It also calculates the distance to every other car and updates this in the carDistances map. 3. Message Sending If the distance between two cars is less than or equal to 40 units, a new CarMessage is created. The priority of the message is set based on the vehicle ID. If the channel is busy (dataOnSch), the message is scheduled for later sending. Otherwise, it's sent immediately. 4. Message Receiving (handleLowerMsg) Received messages are placed in a priority queue (msgQueue). The message with the highest priority is then processed by the onCarMessage function. 5. Self Messages (handleSelfMsg) This function is responsible for managing messages that are scheduled for later. When the message is received (from "self"), it is sent down to the lower layers for actual transmission. 6. Message Logging (onCarMessage) Logs the received CarMessage. The messageExchangeCount map is updated with the new message data. 7. Simulation End (finish) At the end of the simulation, all logged data, such as message counts and vehicle speeds, are exported to CSV files. INI File Description General Settings cmdenv-express-mode, cmdenv-autoflush, etc.: These settings configure how the simulation runs and how it interacts with the user. network = IntersectionScenario: Specifies that the network configuration is based on the IntersectionScenario NED file. sim-time-limit = 1000s: The simulation will run for 1000 seconds. Simulation Parameters *.scalar-recording = true and *.vector-recording = true: Enable the recording of scalar and vector data, useful for post-simulation analysis. *.playgroundSizeX, *.playgroundSizeY, *.playgroundSizeZ: Set the dimensions of the simulation playground. Annotation Parameters *.annotations.draw = true: Enables drawing of annotations, probably for debugging or visualization. TraCIScenarioManager Parameters *.manager.updateInterval = 1s: The TraCI (Traffic Control Interface) updates every second, which aligns with the 1-second update rate in the code. RSU Settings *.rsu[*].mobility.x/y/z: These set the positions of the Road-Side Units (RSUs) in the simulated environment. *.rsu[*].applType = "IntersectionApp": Specifies that the application type running on the RSUs is IntersectionApp, aligning with the C++ class. 11p Specific Parameters *.connectionManager.sendDirect = true: Enables direct sending of messages. *.connectionManager.maxInterfDist = 40m: Sets the maximum interference distance to 40m, aligning with the 40-unit distance check in the code. WaveAppLayer *.node[*].applType = "IntersectionApp": Specifies that the nodes (vehicles) will run the IntersectionApp application. *.node[*].appl.sendBeacons = false: Vehicles won't send beacons by default, focusing on data messages. Mobility *.node[*].veinsmobilityType.debug = true: Enables debugging for mobility, useful for tracking position updates. Config Sections [Config Default]: The default configuration. [Config WithBeaconing]: Enables beaconing for RSUs and nodes. [Config WithChannelSwitching]: Enables channel switching, allowing for the use of service channels in addition to the control channel. Connections to Code RSU and Node Positions: The .ini file directly sets the positions of RSUs, which would be read into rsuPositions in the code. Update Intervals: The update interval in the .ini file (*.manager.updateInterval = 1s) corresponds to how often handlePositionUpdate would likely be called in the code. Application Types: The application type specified for both RSUs and nodes is IntersectionApp, tying back to the main class in the C++ code. Max Interference Distance: The maximum interference distance (*.connectionManager.maxInterfDist = 40m) aligns with the distance check (if (distance <= 40)) in the handlePositionUpdate method in the code. To start the simulation, right-click on the omnet.ini and the run the simulation in WithChannelSwitching mode. Sumo-gui also needs to be started in the background, and can be started with this command python "path to veins-4.7.1\sumo-launchd.py" -vv -c sumo-gui Ending the simulation generates the csv files in the project structure itself, and they can then be used to do analysis. End.
using System.Globalization; var builder = WebApplication.CreateBuilder(args); //1- Resource path builder.Services.AddLocalization(option=>option.ResourcesPath="Resources"); //2-- add mvc view localization builder.Services.AddMvc() .AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix) .AddDataAnnotationsLocalization(); //3-add supported languages builder.Services.Configure<RequestLocalizationOptions>(options => { var supportedCulture = new[] { new CultureInfo("en-US"), new CultureInfo("ar-EG") }; options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(culture: "en-US", uiCulture: "en-US"); options.SupportedCultures= supportedCulture; options.SupportedUICultures= supportedCulture; }); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); //4- app.UseRequestLocalization(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
import matplotlib.pyplot as plt from matplotlib.widgets import Button from matplotlib.patches import Polygon import numpy as np import pandas as pd from scipy import optimize, signal import os import warnings plt.ion() colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] # plt.style.use('C:/Users/orozc/Google Drive (miguelorozco@ucsb.edu)/Research/Spyder/scientific.mplstyle') # data_folder = r'C:/Users/orozc/Google Drive (miguelorozco@ucsb.edu)/Research/Spyder/Run' plt.style.use('C:/Users/BRoehrich/Desktop/git/echem/scientific.mplstyle') data_folder = r'C:\Users\BRoehrich\Desktop\Miguel data' correct_baselines = False start_after = 100 # cut off first (n) seconds min_s_to_fit = 10 # Requires n seconds of data to accept the fit delay = 10 # Points after "fast" spike to skip fitting on thresh = 0.01 # Used to determine acceptable baseline "flatness" # Smaller = more picky, need flatter baseline to accept spike apply_filter = False filter_freq = 25 # fit = 'monoexponential' fit = 'monoexp-linear' # fit = 'biexponential' # fit = 'linear' ''' TO-DO Interactive picking/deleting points ''' # Define fit function and parameters if fit == 'biexponential': params=['a/ A', 'b/ s-1', 'c/ A', 'd/ s-1', 'e/ A'] def exp_func(x, a,b,c,d,e): return a * np.exp(-b * x) + c * np.exp(-d * x) + e elif fit == 'monoexponential': params = ['a/ A', 'b/ s-1', 'c/ A'] def exp_func(x, a,b,c): return a * np.exp(-b * x) + c elif fit == 'linear': params = ['a/ A s-1', 'b/ A'] def exp_func(x, a, b): return a*x + b elif fit == 'monoexp-linear': params = ['a/ A', 'b/ s-1', 'm/ A s-1', 'c/ A'] def exp_func(x, a, b, m, c): return a*np.exp(-b * x) + m*x + c # Filtering functions def lowpass(y, t, cutoff): fs = 1/np.mean([t[i] - t[i-1] for i in range(1, len(t))]) fc = cutoff/(fs/2) try: b, a = signal.butter(8, fc) filt_y = signal.filtfilt(b, a, y, padlen=150) return filt_y except ValueError: print('Bad filter_freq, not filtering.') print(f'Valid filter_freq from 0 < f < {fs/2}') return y def thresholding_algo(y, lag, threshold, influence): ''' Taken from https://stackoverflow.com/questions/22583391/peak-signal-detection-in- realtime-timeseries-data/43512887#43512887 Returns: signals: array of [-1, 0, 1]. 0 = no spike at this point, +- 1 = positive/ negative spike at this point avgFilter: array, filtered data stdFilter: array, standard devation of filtered data ''' signals = np.zeros(len(y)) filteredY = np.array(y) avgFilter = [0]*len(y) stdFilter = [0]*len(y) avgFilter[lag - 1] = np.mean(y[0:lag]) stdFilter[lag - 1] = np.std(y[0:lag]) for i in range(lag, len(y)): if abs(y[i] - avgFilter[i-1]) > threshold * stdFilter [i-1]: if y[i] > avgFilter[i-1]: signals[i] = 1 else: signals[i] = -1 filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i-1] avgFilter[i] = np.mean(filteredY[(i-lag+1):i+1]) stdFilter[i] = np.std(filteredY[(i-lag+1):i+1]) else: signals[i] = 0 filteredY[i] = y[i] avgFilter[i] = np.mean(filteredY[(i-lag+1):i+1]) stdFilter[i] = np.std(filteredY[(i-lag+1):i+1]) return signals, np.array(avgFilter), np.array(stdFilter) class InteractivePicker: global colors def __init__(self, file, fig, ax, params, exp_func, plot=True): self.file = file self.fig = fig self.ax = ax self.plot = plot self.params = params self.exp_func = exp_func self.fits = [] self.points = [] self.line = None self.fitline = None self.drawnpoints = None self.save_fits = [] self.integrals = [] self.chi_sqs = [] self.points = [] self.ms = [] def __call__(self, event): if not self.plot: return # Set xtol based on current axis limits upper = self.ax.get_xlim()[1] lower = self.ax.get_xlim()[0] diff = upper-lower xtol = 0.01*diff if event.inaxes and self.fig.canvas.manager.toolbar.mode == "": # print(xtol) clickX = event.xdata if (self.ax is None) or (self.ax is event.inaxes): # Prioritizing removing marked point for x in self.t[self.idxs]: if (clickX-xtol < x < clickX+xtol): # Remove point print(f'Removing closest point: {x}') idx = np.where(self.t == x)[0][0] i = np.where(self.idxs == idx)[0][0] self.idxs.remove(idx) t = [(i, x, y) for (i, x, y) in self.fits if i == idx][0] self.fits.remove(t) self.draw_fits(xlim=self.ax.get_xlim(), ylim=self.ax.get_ylim()) # Remove from output lists self.save_fits = np.delete(self.save_fits, i, axis=1) self.areas = np.delete(self.areas, i) self.integrals = np.delete(self.integrals, i) self.chi_sqs = np.delete(self.chi_sqs, i) self.points = np.delete(self.points, i) self.ms = np.delete(self.ms, i) else: continue def keypress_event_handler(self, event): # Pressing arrow keys pans around graph key = event.key if key in ['left', 'right', 'up', 'down']: shift_axes(self.ax, key) self.ax.figure.canvas.draw_idle() def scroll_event_handler(self, event): # Scrolling mousewheel zooms in/out key = event.button x, y = event.xdata, event.ydata if key in ['down', 'up']: zoom_axes(self.ax, key, (x,y)) self.ax.figure.canvas.draw_idle() def _reset(self, event): file = self.file fig = self.fig ax = self.ax params = self.params exp_func = self.exp_func self.line.remove() self.fitline.remove() self.drawnpoints.remove() self.ax.clear() self.fig.canvas.draw() for attr, _ in list(self.__dict__.items()): delattr(self, attr) self.__init__(file, fig, ax, params, exp_func) self.fig.canvas.mpl_connect('button_press_event', self) fits, integrals, chi_sqs, points, ms = self.analyze_file( correct_baselines, apply_filter, delay, start_after, self.params, self.exp_func, thresh ) return def draw_fits(self, xlim=[], ylim=[]): if not self.plot: return # Plot fit curves if self.fitline: self.fitline.remove() self.fitline, = self.ax.plot([0], [0], 'o', color='gold', ms=1) xs = np.array([]) ys = np.array([]) for (idx, x_data, y_data) in self.fits: xs = np.hstack([xs, x_data]) ys = np.hstack([ys, y_data]) self.fitline.set_data(xs, ys) # Plot point labels if self.drawnpoints: self.drawnpoints.remove() self.drawnpoints, = self.ax.plot([0], [0], 'ro') xs = [] ys = [] for idx in self.idxs: xs.append(self.t[idx]) ys.append(0.95*self.i[idx]) self.drawnpoints.set_data(xs, ys) self.fitline.figure.canvas.draw() if len(xlim) != 0: self.ax.set_xlim(xlim) if len(ylim) != 0: self.ax.set_ylim(ylim) return # Function for reading data def extract_data(self, file, start_after): df = pd.read_csv(file, names=('t', 'v', 'i'), skiprows=1, sep='\t') df = df[df['t'] > start_after] t = np.array(df['t']) i = np.array(df['i'])/1000 # Calculate sampling rate sara = np.average([t[i] - t[i-1] for i in range(1, len(t))]) self.t = t self.i = i return t, i, sara def refine_peaks(self, y, signals): ''' Finds local maxima to refine peak locations Parameters ---------- y : array Raw data. signals : array Output from thresholding_algo, array of [-1, 0, 1]. Must be same length as y. Returns ------- idxs : list List of indices corresponding to spike locations. ''' # Determine index of this peak and next peak idxs = list(np.where(signals != 0)[0]) # Remove double labelled spikes for idx in idxs: for i in range(idx-10, idx+10): if i in idxs and i != idx: #print(f'Removing {i} because of duplicate') idxs.remove(i) # Refine peak location for idx in idxs[:]: if any(abs(y[idx-10:idx+10]) > abs(y[idx])): i = np.where(abs(y) == max(abs(y[idx-10:idx+10])))[0][0] #print(f'Moving {idx} to {i}') idxs.remove(idx) idxs.append(i) idxs.sort() return idxs def integrate_spikes(self, t, y, idxs, avg): ''' Parameters ---------- t : array Time. y : array Raw data. idxs : list List of spike indices. avg : array Filtered current data from thresholding_algo(). Returns ------- integrals : list List of peak integrals. Unit Amperes. ''' integrals = [] pops = [] for idx in idxs: # Determine left and right bounds for integration. # Defaults to peak location +- 1 point # Try to refine bounds by looking for where the data crosses # the filtered "avg" line (prev used to detect where spikes are), # if there are crossings within +- 3 points, use those as the # bounds instead. try: left_bound = idx - 3 + np.where(abs(y[idx-3:idx]) < abs(avg[idx-3:idx]))[0][-1] except: left_bound = idx-1 try: right_bound = idx + np.where(abs(y[idx:idx+3]) < abs(avg[idx:idx+3]))[0][0] except: right_bound = idx+1 bounds = [left_bound, right_bound] y1 = y[bounds[0]] y2 = y[bounds[1]] dt = t[bounds[1]] - t[bounds[0]] baseline_area = (1/2) * (y1 + y2) * dt total_area = np.trapz(y[bounds[0]:bounds[1]], x = t[bounds[0]:bounds[1]]) integral = total_area - baseline_area if integral < 0: pops.append(idx) print(f'Negative integral: {idx}') else: integrals.append(integral) # fig = plt.figure(figsize=(5,5), dpi=100) # plt.plot(t[idx-500:idx+500], y[idx-500:idx+500]) # plt.plot(t[idx], y[idx], 'ro') # plt.plot(t[idx-500:idx+500], avg[idx-500:idx+500]) # plt.plot(t[bounds], y[bounds], 'o', color = 'orange') # print(integral) return integrals, pops def fit_peaks(self, t, y, idxs, sara, ax=None, t_max=60, t_min=min_s_to_fit, delay = 10, baseline_correct=True, app_filter=False, thresh= 0.005): ''' Fit exponential decay betweek this peak and next peak, or the next n seconds Parameters ---------- t : array Time. y : array Raw data. idxs : list List of spike indices. sara : float Sampling rate from extract_data(). ax : plt.Axes, optional ax to plot exponential fits on top of. t_max : int, optional Maximum time to use for fitting each spike. The default is 10. t_min: int, optional Minimum time necessary to choose a spike for fitting. Default 1 s delay : int, optional Number of points after fast spike to skip for curve fitting thresh: float, optional Used to determine acceptable baseline "flatness" Returns ------- fits : list List of fitted [a, b, c] parameters for each spike. ''' fits = [] chi_sqs = [] integrals = [] pops = [] ms = [] if app_filter: y = lowpass(y, t, filter_freq) for i, _ in enumerate(idxs): # Get this index, either use next index or + (delay) pts this_idx = idxs[i] + delay try: next_idx = min(idxs[i+1] - 2, this_idx + int(round(t_max/sara))) except: # Last point next_idx = min(len(y)-1, this_idx + int(round(t_max/sara))) # Subtract out baseline # Either use previous 500 pts, or last index if i > 0: last_idx = max(idxs[i-1] + delay, this_idx - 500) elif i == 0: # first spike last_idx = max(0, this_idx - 500) if (this_idx-delay - last_idx) < 100: print(f'Not enough points to fit baseline {t[this_idx-delay]} s.') pops.append(this_idx - delay) continue # Calculate the baseline m, b = np.polyfit(t[last_idx:this_idx-delay-5], y[last_idx:this_idx-delay-5], deg=1) if abs(m/y[last_idx]) > thresh: print(f'Baseline not flat enough {t[this_idx-delay]} s.') pops.append(this_idx - delay) continue if baseline_correct: baseline = m*t + b else: baseline = 0*t + 0 if (next_idx - this_idx) < int(round(t_min/sara)): print(f'Not enough points to fit {t[this_idx - delay]} s.') pops.append(this_idx - delay) continue ### Do fitting ### ts = t[this_idx:next_idx] - t[this_idx] data = y[this_idx:next_idx] - baseline[this_idx:next_idx] if fit == 'biexponential': bounds=(-np.inf, [1., np.inf, np.inf, np.inf, np.inf]) elif fit == 'monoexponential': bounds=(-np.inf, [1., np.inf, np.inf]) try: with warnings.catch_warnings(): warnings.simplefilter('ignore') popt, pcov = optimize.curve_fit(exp_func, ts, data, maxfev=100000, # bounds=bounds ) except: popt = [0,0,0,0,0] # Calculate chi^2 fit_y = exp_func(ts, *popt) # Fits residuals = abs((data - fit_y)/fit_y) chi_sq = np.sum(residuals**2)/len(residuals) ### Calculate integral (excludes initial sharp spike) # area to draw verts = [(t[this_idx], fit_y[-1]), *zip(t[this_idx:next_idx], data), (t[next_idx], fit_y[-1])] poly = Polygon(verts, color= colors[0], alpha = 0.7) ax.add_patch(poly) # actual calculation xs = t[this_idx:next_idx] ys = data - fit_y[-1] integ = np.trapz(ys, xs) # fig, ax2 = plt.subplots(figsize=(5,5), dpi=100) # ax2.plot(ts, data, '.') # ax2.plot(ts, fit_y) ### Remove point based on fit criteria ### # Remove if a > 0 (reductive spikes should have a < 0) a_idx = [idx for idx, param in enumerate(self.params) if 'a' in param] if popt[a_idx] > 0: print(f'Fitted a > 0 at {t[this_idx-delay]} s. Removing point.') pops.append(this_idx - delay) continue c_idx = [idx for idx, param in enumerate(self.params) if 'c' in param] if popt[c_idx] > 0: print(f'Fitted c > 0 at {t[this_idx-delay]} s. Removing point.') pops.append(this_idx - delay) continue # Plot fit to main graph self.fits.append( (this_idx - delay, ts+t[this_idx], fit_y + baseline[this_idx:next_idx]) ) # ax.plot(ts+t[this_idx], fit_y + baseline[this_idx:next_idx], 'gold') if baseline_correct: ax.plot(t[last_idx:next_idx], baseline[last_idx:next_idx], 'r--') fits.append(popt) integrals.append(integ) ms.append(m) chi_sqs.append(chi_sq) return fits, integrals, chi_sqs, pops, ms def analyze_file(self, baseline_correct, app_filter, delay, start_after, params, exp_func, thresh): ''' Main function to call to detect and fit spikes ''' fname = self.file.split('\\')[-1] print(f'\nAnalyzing {fname}') # Get data t, i, sara = self.extract_data(self.file, start_after) # Find peaks signals, avgFilter, stdFilter = thresholding_algo(i, lag=50, threshold=5, influence = 0.6) # Refine peak locations self.idxs = self.refine_peaks(i, signals) # Make figure # if 'inline' in matplotlib.get_backend(): # fig, ax = plt.subplots(figsize=(5,5), dpi=300) # else: # fig, ax = plt.subplots(figsize=(5,5), dpi=100) if app_filter: self.line, = self.ax.plot(t, lowpass(i,t,filter_freq)) else: self.line, = self.ax.plot(t, i, color = colors[0]) self.ax.set_xlabel('Time/ s') self.ax.set_ylabel('Current/ A') self.ax.set_title(fname, fontsize=9, ) # Fit peaks. Optionally plot fits onto same ax fits, areas, chi_sqs, pops, ms = self.fit_peaks(t, i, self.idxs, sara, self.ax, baseline_correct=baseline_correct, app_filter = app_filter, delay=delay, thresh = thresh ) for pt in pops: # Remove spike indices that we couldn't fit self.idxs.pop(np.where(self.idxs==pt)[0][0]) # Calculate spike integrals integrals, pops = self.integrate_spikes(t, i, self.idxs, avgFilter) for pt in pops: # Remove spike indices with negative integrals self.idxs.pop(np.where(self.idxs==pt)[0][0]) # Get time points points = t[self.idxs] self.draw_fits() # Transpose data for saving fits = np.array(fits).T self.save_fits = fits self.areas = areas self.integrals = integrals self.chi_sqs = chi_sqs self.points = points self.ms = ms return fits, areas, integrals, chi_sqs, points, ms class Index: def __init__(self, folder, fig, ax, params, exp_func): self.ind = 0 self.folder= folder self.files = [os.path.join(folder, file) for file in os.listdir(folder) if file.endswith('.txt')] self.inds = [i for i in range(len(self.files))] self.file = self.files[0] self.fig = fig self.ax = ax self.Picker = {} self.data = {} self.params = params self.exp_func = exp_func self.Picker[self.ind] = InteractivePicker(self.file, self.fig, self.ax, self.params, self.exp_func) self.Picker[self.ind].analyze_file(correct_baselines, apply_filter, delay, start_after, self.params, self.exp_func, thresh) self.load_cids(self.Picker[self.ind]) plt.show() def load_cids(self, Picker): if hasattr(self, 'cid'): for cid in [self.cid, self.cid2, self.cid3]: self.fig.canvas.mpl_disconnect(cid) self.cid = self.fig.canvas.mpl_connect('button_press_event', Picker) self.cid2 = self.fig.canvas.mpl_connect('key_press_event', Picker.keypress_event_handler) self.cid3 = self.fig.canvas.mpl_connect('scroll_event', Picker.scroll_event_handler) def _next(self, event): self.store_data() self._del_picker(self.Picker[self.ind]) self.ind += 1 if self.ind > self.inds[-1]: self.ind = self.inds[0] self.file = self.files[self.ind] self.ax.clear() self.Picker[self.ind] = InteractivePicker(self.file, self.fig, self.ax, self.params, self.exp_func) self.Picker[self.ind].analyze_file(correct_baselines, apply_filter, delay, start_after, self.params, self.exp_func, thresh) self.load_cids(self.Picker[self.ind]) plt.show() def _prev(self, event): self.store_data() self._del_picker(self.Picker[self.ind]) self.ind -= 1 if self.ind < self.inds[0]: self.ind = self.inds[-1] self.file = self.files[self.ind] self.ax.clear() self.Picker[self.ind] = InteractivePicker(self.file, self.fig, self.ax, self.params, self.exp_func) self.Picker[self.ind].analyze_file(correct_baselines, apply_filter, delay, start_after, self.params, self.exp_func, thresh) self.load_cids(self.Picker[self.ind]) plt.show() def _del_picker(self, picker): for attr, _ in list(picker.__dict__.items()): delattr(picker, attr) def reset(self, event): self.Picker[self.ind]._reset(event) def store_data(self): d = {} d['Index'] = [] d['time/ s'] = [] d.update({param: [] for param in self.params}) d['Catalytic area/ C'] = [] d['baseline slope'] = [] d['integral/ C'] = [] d['Reduced Chi^2'] = [] d['File'] = [] p = self.Picker[self.ind] for i in range(len(p.integrals)): d['Index'].append(i+1) for i in range(len(self.params)): for x in p.save_fits[i]: d[params[i]].append(x) for x in p.areas: d['Catalytic area/ C'].append(x) for x in p.ms: d['baseline slope'].append(x) for x in p.integrals: d['integral/ C'].append(x) for x in p.chi_sqs: d['Reduced Chi^2'].append(x) for x in p.points: d['time/ s'].append(x) d['File'].append(p.file) d['File'].append(f'Fit: {fit}') d['File'].append(f'Baseline correct: {correct_baselines}') d['File'].append(f'Delay: {delay} pts') for key in d: while len(d[key]) < max([len(d[key]) for key in d]): d[key].append(' ') for key in d: d[key].append(' ') self.data[self.ind] = d def save(self, event): self.store_data() dout = {} dicts = [self.data[key] for key in self.data.keys()] for key in dicts[0].keys(): dout[key] = list(d[key] for d in dicts) # Magic one liner # for sublist in list: for item in sublist: yield item dout[key] = [item for sublist in dout[key] for item in sublist] df = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in dout.items() ])) writer = pd.ExcelWriter(self.folder + '/output.xlsx', engine='xlsxwriter') df.to_excel(writer, index=False, header=True, startcol=0) writer.save() print(f'Saved as {self.folder}/output.xlsx') return def shift_axes(ax, direction): # Pan axes if arrow keys are pressed xlim = ax.get_xlim() ylim = ax.get_ylim() xdelta = 0.2*(xlim[1] - xlim[0]) ydelta = 0.2*(ylim[1] - ylim[0]) if direction == 'right': xlim = [ xlim[0] + xdelta, xlim[1] + xdelta, ] if direction == 'left': xlim = [ xlim[0] - xdelta, xlim[1] - xdelta, ] if direction == 'up': ylim = [ ylim[0] + ydelta, ylim[1] + ydelta, ] if direction == 'down': ylim = [ ylim[0] - ydelta, ylim[1] - ydelta, ] ax.set_xlim(xlim) ax.set_ylim(ylim) return def zoom_axes(ax, direction, center): # Zoom axes by mouse scroll wheel xlim = ax.get_xlim() ylim = ax.get_ylim() # Shift (almost) to new center x, y = center shift_x = x - (xlim[0] + xlim[1])/2 shift_y = y - (ylim[0] + ylim[1])/2 if direction == 'down': shift_x = -shift_x shift_y = -shift_y xlim = [ xlim[0] + 0.7*shift_x, xlim[1] + 0.7*shift_x, ] ylim = [ ylim[0] + 0.7*shift_y, ylim[1] + 0.7*shift_y, ] # Zoom in or out xdelta = 0.2*(xlim[1] - xlim[0]) ydelta = 0.2*(ylim[1] - ylim[0]) if direction == 'down': xdelta = -xdelta ydelta = -ydelta xlim = [ xlim[0] + xdelta, xlim[1] - xdelta, ] ylim = [ ylim[0] + ydelta, ylim[1] - ydelta, ] ax.set_xlim(xlim) ax.set_ylim(ylim) return if __name__ == '__main__': fig, ax = plt.subplots(figsize=(5,6), dpi=100) plt.subplots_adjust(bottom=0.3) index = Index(data_folder, fig, ax, params, exp_func) axcalc = plt.axes([0.4, 0.1, 0.25, 0.05]) bcalc = Button(axcalc, 'Reset') bcalc.on_clicked(index.reset) axprev = plt.axes([0.15, 0.1, 0.25, 0.05]) bnext = Button(axprev, 'Previous') bnext.on_clicked(index._next) axnext = plt.axes([0.65, 0.1, 0.25, 0.05]) bprev = Button(axnext, 'Next') bprev.on_clicked(index._prev) axsave = plt.axes([0.4, 0.025, 0.25, 0.05]) bsave = Button(axsave, 'Save') bsave.on_clicked(index.save)
import { Component, OnInit } from '@angular/core'; import { DateFormatPipe } from 'ngx-moment'; import { TeacherService } from '../teacher.service'; import { TeacherRun } from '../teacher-run'; import { ConfigService } from '../../services/config.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-teacher-run-list', templateUrl: './teacher-run-list.component.html', styleUrls: ['./teacher-run-list.component.scss'] }) export class TeacherRunListComponent implements OnInit { runs: TeacherRun[] = []; personalRuns: TeacherRun[] = []; sharedRuns: TeacherRun[] = []; filteredRuns: TeacherRun[] = []; loaded: boolean = false; searchValue: string = ''; periods: string[] = []; filterOptions: any[] = [{ value: '', label: 'All Periods' }]; filterValue: string = ''; isPersonalRunsRetrieved: boolean = false; isSharedRunsRetrieved: boolean = false; showAll: boolean = false; constructor( private teacherService: TeacherService, private configService: ConfigService, router: Router ) { teacherService.newRunSource$.subscribe((run) => { const teacherRun: TeacherRun = new TeacherRun(run); teacherRun.isHighlighted = true; this.runs.unshift(teacherRun); this.runs.sort(this.sortByStartTimeDesc); this.populatePeriods([teacherRun]); this.periods.sort(); this.populateFilterOptions(); this.reset(); if (!this.showAll) { const index = this.getRunIndex(teacherRun); if (index > 9) { this.showAll = true; } } router.navigateByUrl('teacher/home/schedule').then(() => { setTimeout(() => { document.getElementById(`run${teacherRun.id}`).scrollIntoView(); }, 1000); }); }); } ngOnInit() { this.getRuns(); this.getSharedRuns(); } getRuns(): void { this.teacherService.getRuns().subscribe((runs) => { this.personalRuns = []; for (const personalRun of runs) { this.personalRuns.push(new TeacherRun(personalRun)); } this.isPersonalRunsRetrieved = true; this.processRunsIfReady(); }); } getRunIndex(run: TeacherRun) { for (let i = 0; i < this.runs.length; i++) { if (this.runs[i].id === run.id) { return i; } } return null; } getSharedRuns(): void { this.teacherService.getSharedRuns().subscribe((runs) => { this.sharedRuns = []; for (const sharedRun of runs) { const teacherRun = new TeacherRun(sharedRun); teacherRun.shared = true; this.sharedRuns.push(teacherRun); } this.isSharedRunsRetrieved = true; this.processRunsIfReady(); }); } processRunsIfReady() { if (this.isPersonalRunsRetrieved && this.isSharedRunsRetrieved) { this.processRuns(); } } processRuns() { const runs = this.personalRuns.concat(this.sharedRuns); this.runs = runs; this.filteredRuns = runs; this.populatePeriods(runs); this.periods.sort(); this.populateFilterOptions(); this.performSearchAndFilter(); this.loaded = true; } sortByStartTimeDesc(a, b) { if (a.startTime < b.startTime) { return 1; } else if (a.startTime > b.startTime) { return -1; } else { return 0; } } populatePeriods(runs: TeacherRun[]): void { for (const run of runs) { const periods = run.periods; for (const period of periods) { if (this.periods.indexOf(period) < 0) { this.periods.push(period); } } } } populateFilterOptions(): void { for (const period of this.periods) { this.filterOptions.push({ value: period, label: period }); } } runSpansYears(run: TeacherRun) { const startYear = new DateFormatPipe().transform(run.startTime, 'Y'); const endYear = new DateFormatPipe().transform(run.endTime, 'Y'); return startYear != endYear; } runSpansMonths(run: TeacherRun) { if (this.runSpansYears(run)) { return true; } const startMonth = new DateFormatPipe().transform(run.startTime, 'M'); const endMonth = new DateFormatPipe().transform(run.endTime, 'M'); return startMonth != endMonth; } runSpansDays(run: TeacherRun) { if (this.runSpansMonths(run)) { return true; } const startDay = new DateFormatPipe().transform(run.startTime, 'D'); const endDay = new DateFormatPipe().transform(run.endTime, 'D'); return startDay != endDay; } activeTotal(): number { let total = 0; const now = this.configService.getCurrentServerTime(); for (const run of this.filteredRuns) { if (run.isActive(now)) { total++; } } return total; } completedTotal(): number { let total = 0; const now = this.configService.getCurrentServerTime(); for (const run of this.filteredRuns) { if (run.isCompleted(now)) { total++; } } return total; } scheduledTotal(): number { let total = 0; const now = this.configService.getCurrentServerTime(); for (const run of this.filteredRuns) { if (run.isScheduled(now)) { total++; } } return total; } performSearchAndFilter(): void { this.filteredRuns = this.searchValue ? this.performSearch(this.searchValue) : this.runs; this.performFilter(this.filterValue); } searchChanged(searchValue: string): void { this.searchValue = searchValue; this.performSearchAndFilter(); } filterChanged(value: string): void { this.filterValue = value; this.performSearchAndFilter(); } performFilter(value: string) { this.filteredRuns = this.filteredRuns.filter((run: TeacherRun) => { if (value !== '') { return run.periods.indexOf(value) !== -1; } else { return true; } }); } performSearch(searchValue: string) { searchValue = searchValue.toLocaleLowerCase(); // TODO: extract this for global use? return this.runs.filter((run: TeacherRun) => Object.keys(run).some((prop) => { const value = run[prop]; if (typeof value === 'undefined' || value === null) { return false; } else if (typeof value === 'object') { return JSON.stringify(value).toLocaleLowerCase().indexOf(searchValue) !== -1; } else { return value.toString().toLocaleLowerCase().indexOf(searchValue) !== -1; } }) ); } reset(): void { this.searchValue = ''; this.filterValue = ''; this.performSearchAndFilter(); } isRunActive(run) { return run.isActive(this.configService.getCurrentServerTime()); } }
<?php namespace Microblog; use PDO, Exception; abstract class Banco { private static string $servidor = "localhost"; private static string $usuario = "root"; private static string $senha = ""; private static string $banco = "microblog_aline"; /* Operador ? "nullable typehinint" Quando usado, indica que a propriedade/atributo da classe pode conter um valor null OU pode ser um tipo PDO Neste caso, a propriedade conexão é inicializada como nula, mas a partir do momento em que uma conexão é feita ela passa a valer PDO */ private static ?PDO $conexao = null; public static function conecta():PDO { /* Só conecte se não houver conexão ... Se a conexão for nula, faça as ações do try/catch */ if(self::$conexao === null){ try { self::$conexao = new PDO( "mysql:host=".self::$servidor."; dbname=".self::$banco."; charset=utf8", self::$usuario, self::$senha ); self::$conexao->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (Exception $erro) { die("Deu ruim: ".$erro->getMessage()); } } return self::$conexao; } }
<script setup> import { Management, Promotion, UserFilled, User, Crop, EditPen, SwitchButton, CaretBottom, } from "@element-plus/icons-vue"; import { ElMessageBox, ElMessage } from "element-plus"; import avatar from "@/assets/default.png"; import useUserInfoStore from "@/stores/userInfo.js"; import { useTokenStore } from "@/stores/token.js"; import { userInfoService } from "@/api/user"; import { useRouter } from "vue-router"; const router = useRouter(); const userInfoStore = useUserInfoStore(); const tokenStore = useTokenStore(); const getUserInfo = async () => { let userInfo = await userInfoService(); userInfoStore.setUserInfo(userInfo.data); }; getUserInfo(); const handleCommand = (key) => { if (key === "logout") { ElMessageBox.confirm("Are you sure you want to log out?", "Attention", { confirmButtonText: "Confirm", cancelButtonText: "Cancel", type: "warning", }) .then(async () => { tokenStore.removeToken(); userInfoStore.removeUserInfo(); router.push("/login"); ElMessage({ type: "success", message: "Log out successfully", }); }) .catch(() => { ElMessage({ type: "warning", message: "Log out cancelled", }); }); } else { router.push(`/user/${key}`); } }; </script> <template> <el-container class="layout-container"> <el-aside width="200px"> <div class="el-aside__logo"></div> <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff" router > <el-menu-item index="/article/category"> <el-icon><Management /></el-icon> <span>Article Category</span> </el-menu-item> <el-menu-item index="/article/manage"> <el-icon><Promotion /></el-icon> <span>Article Management</span> </el-menu-item> <el-sub-menu index="/user"> <template #title> <el-icon><UserFilled /></el-icon> <span>Account Setting</span> </template> <el-menu-item index="/user/profile"> <el-icon><User /></el-icon> <span>Profile</span> </el-menu-item> <el-menu-item index="/user/avatar"> <el-icon><Crop /></el-icon> <span>Change Avatar</span> </el-menu-item> <el-menu-item index="/user/password"> <el-icon><EditPen /></el-icon> <span>Change Password</span> </el-menu-item> </el-sub-menu> </el-menu> </el-aside> <el-container> <el-header> <div> Welcome! <strong>{{ userInfoStore.userInfo.nickname || userInfoStore.userInfo.username }}</strong> </div> <el-dropdown placement="bottom-end" @command="handleCommand"> <span class="el-dropdown__box"> <el-avatar :src="userInfoStore.userInfo.userPic || avatar" /> <el-icon><CaretBottom /></el-icon> </span> <template #dropdown> <el-dropdown-menu> <el-dropdown-item command="profile" :icon="User" >Basic Information</el-dropdown-item > <el-dropdown-item command="avatar" :icon="Crop" >Change Avatar</el-dropdown-item > <el-dropdown-item command="password" :icon="EditPen" >Change Password</el-dropdown-item > <el-dropdown-item command="logout" :icon="SwitchButton" >Log out</el-dropdown-item > </el-dropdown-menu> </template> </el-dropdown> </el-header> <el-main> <router-view></router-view> </el-main> <el-footer>Event Publisher ©2024 Created by ZZ</el-footer> </el-container> </el-container> </template> <style lang="scss" scoped> .layout-container { height: 100vh; .el-aside { background-color: #232323; &__logo { height: 120px; background: url("@/assets/logo2.png") no-repeat center / 120px auto; } .el-menu { border-right: none; } } .el-header { background-color: #fff; display: flex; align-items: center; justify-content: space-between; .el-dropdown__box { display: flex; align-items: center; .el-icon { color: #999; margin-left: 10px; } &:active, &:focus { outline: none; } } } .el-footer { display: flex; align-items: center; justify-content: center; font-size: 14px; color: #666; } } </style>
package fr.hamtec.locdvd; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import java.util.ArrayList; public class ListDVDFragment extends Fragment { private ListView list; private OnDVDSelectedListener onDVDSelectedListener; public interface OnDVDSelectedListener{ public void onDVDSelected(long dvdId); } @Nullable @Override public View onCreateView( @NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState ) { View view = inflater.inflate( R.layout.fragment_listdvd, container, false ); list = view.findViewById( R.id.main_List ); list.setOnItemClickListener( new AdapterView.OnItemClickListener( ) { @Override public void onItemClick( AdapterView < ? > parent, View view, int position, long id ) { if ( onDVDSelectedListener !=null ){ DVD selectedDvd = (DVD ) view.getTag(); onDVDSelectedListener.onDVDSelected( selectedDvd.getId() ); } } } ); return view; } @Override public void onAttach( Context activity ) { super.onAttach( activity ); onDVDSelectedListener = ( OnDVDSelectedListener ) activity; } private void startViewDVDActivity( long dvdId ) { Intent intent = new Intent( getActivity(), ViewDVDFragment.class ); intent.putExtra( "dvdId", dvdId ); startActivity( intent ); } @Override public void onResume( ) { super.onResume( ); updateDVDList(); } public void updateDVDList(){ ArrayList<DVD> dvdList = DVD.getDVDList( getActivity() ); DVDAdapter dvdAdapter = new DVDAdapter( getActivity(), dvdList ); list.setAdapter( dvdAdapter ); } }
using System.Collections.Generic; using System; using System.Linq; namespace Firis { public abstract class Entity : ISystem, IDisposable { public long ID { get; internal set; } public Entity Parent { get; private set; } public bool IsDisposed { get; private set; } public int ChildCount => m_Children.Count; public int ComponentCount => m_Components.Count; private SortedDictionary<long, Entity> m_Children = new SortedDictionary<long, Entity>(); private SortedDictionary<string, Component> m_Components = new SortedDictionary<string, Component>(); /// <summary> /// 已有Component实例,将其附在此entity上(如component已有父entity,则会先移除原关系) /// 若组件 是 DisallowMultipleComponent 目标如果已经拥有此组件 则操作无效 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="component"></param> /// <returns></returns> public T AddComponent<T>(T component) where T : Component { Type type = typeof(T); if (component == null) { Log.Error($"--- 传入 {type.Name} 组件 不允许为空 --- "); return null; } var have = m_Components.ContainsKey(typeof(T).FullName); if (have) { Log.Error($" --- {type.Name} 组件 不允许挂载多个 --- "); return null; } Entity raw = component.Entity; raw.RemoveComponent(component); m_Components.Add(typeof(T).FullName, component); component.Entity = this; return component; } public Component AddComponent(Type type) { Component component; var have = m_Components.ContainsKey(type.FullName); if (have) { Log.Error($" --- {type.Name} 组件 不允许挂载多个 --- "); return null; } component = this.Create(type); m_Components.Add(type.FullName, component); return component; } public T AddComponent<T>() where T : Component { Type type = typeof(T); var have = m_Components.ContainsKey(type.FullName); if (have) { Log.Error($" --- {type.Name} 组件 不允许挂载多个 --- "); return null; } var component = this.Create<T>(); m_Components.Add(type.FullName, component); return component as T; } public T AddComponent<T, A>(A a) where T : Component { Type type = typeof(T); var have = m_Components.ContainsKey(type.FullName); if (have) { Log.Error($" --- {type.Name} 组件 不允许挂载多个 --- "); return null; } var component = this.Create<T, A>(a); m_Components.Add(type.FullName, component); return component as T; } public T AddComponent<T, A, B>(A a, B b) where T : Component { Type type = typeof(T); var have = m_Components.ContainsKey(type.FullName); if (have) { Log.Error($" --- {type.Name} 组件 不允许挂载多个 --- "); return null; } var component = this.Create<T, A, B>(a, b); m_Components.Add(type.FullName, component); return component as T; } public T AddComponent<T, A, B, C>(A a, B b, C c) where T : Component { Type type = typeof(T); var have = m_Components.ContainsKey(type.FullName); if (have) { Log.Error($" --- {type.Name} 组件 不允许挂载多个 --- "); return null; } var component = this.Create<T, A, B, C>(a, b, c); m_Components.Add(type.FullName, component); return component as T; } public Component GetComponent(Type type) { var have = m_Components.ContainsKey(type.FullName); if (!have) { Log.Warn($" --- {type.Name} 组件 不存在 --- "); return null; } return m_Components[type.FullName]; } public T GetComponent<T>() where T : Component { Type type = typeof(T); var have = m_Components.ContainsKey(type.FullName); if (!have) { Log.Warn($" --- {type.Name} 组件 不存在 --- "); return null; } return m_Components[type.FullName] as T; } public bool RemoveComponent(Type type) { var have = m_Components.ContainsKey(type.FullName); if (!have) { Log.Warn($" --- {type.Name} 组件 不存在 --- "); return false; } m_Components.Remove(type.FullName); return true; } public bool RemoveComponent<T>() where T : Component { var type = typeof(T); return RemoveComponent(type); } public bool RemoveComponent(Component component) { var type = component.GetType(); return RemoveComponent(type); } public T AddChild<T>() where T : Entity { Entity entity; entity = EntityFactory.Creat<T>(); entity.Parent = this; m_Children.Add(entity.ID, entity); return entity as T; } public T AddChild<T, A>(A a) where T : Entity { Entity entity; entity = EntityFactory.Creat<T, A>(a); entity.Parent = this; m_Children.Add(entity.ID, entity); return entity as T; } public T AddChild<T, A, B>(A a, B b) where T : Entity { Entity entity; entity = EntityFactory.Creat<T, A, B>(a, b); entity.Parent = this; m_Children.Add(entity.ID, entity); return entity as T; } public T AddChild<T, A, B, C>(A a, B b, C c) where T : Entity { Entity entity; entity = EntityFactory.Creat<T, A, B, C>(a, b, c); entity.Parent = this; m_Children.Add(entity.ID, entity); return entity as T; } /// <summary> /// 使用时注意 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity"></param> /// <returns></returns> public bool AddChild<T>(T child) where T : Entity { if (child == null) { Log.Warn($" --- 不能为空! --- "); return false; } if (m_Children.ContainsKey(child.ID)) { Log.Warn($" --- 原本 {child} 就是 子物体! --- "); return false; } Entity parent = this.Parent; while (parent != null) { if (parent == child) { Log.Error("---禁止将上级Entity作下级Entity的子物体---"); return false; } parent = parent.Parent; } if (child.Parent != null) { Entity raw = child.Parent; raw.RemoveChild(child); } child.Parent = this; m_Children.Add(child.ID, child); return true; } /// <summary> /// 使用时注意 可能设及子父物体绑定 /// </summary> /// <param name="entity"></param> /// <returns></returns> public bool AddChild(Entity child) { if (child == null) { Log.Warn($" --- 不能为空! --- "); return false; } if (m_Children.ContainsKey(child.ID)) { Log.Warn($" --- 原本 {child} 就是 子物体! --- "); return false; } Entity parent = this.Parent; while (parent != null) { if (parent == child) { Log.Error("---禁止将上级Entity作下级Entity的子物体---"); return false; } parent = parent.Parent; } if (child.Parent != null) { Entity raw = child.Parent; raw.RemoveChild(child); } child.Parent = this; m_Children.Add(child.ID, child); return true; } public Entity GetChild(int index) { if (index < 0 || index >= ChildCount) { Log.Error(" --- 索引异常 --- "); return null; } return m_Children[index]; } public T GetChild<T>() where T : Entity { foreach (var child in m_Children.Values) { if (child is T) { return (T)child; } } return null; } public Entity GetChild(Type type) { foreach (var child in m_Children.Values) { if (child.GetType() == type) { return child; } } return null; } public IEnumerable<T> GetChildren<T>() where T : Entity { foreach (var child in m_Children.Values) { if (child is T) { yield return child as T; } } } public IEnumerable<Entity> GetChildren(Type type) { foreach (var child in m_Children.Values) { if (child.GetType() == type) { yield return child; } } } public void RemoveChild(Entity entity) { m_Children.Remove(entity.ID); } public virtual void Dispose() { if (IsDisposed) return; IsDisposed = true; if (Parent != null) { Parent.RemoveChild(this); Parent = null; } var cKeys = m_Components.Keys.ToList(); foreach (var key in cKeys) { m_Components[key].Dispose(); } var eKeys = m_Children.Keys.ToList(); foreach (var key in eKeys) { m_Children[key].Dispose(); } this.m_Components.Clear(); this.m_Children.Clear(); EventSystem.Instance.Remove(this); } } }
#include "arrays.h" int_array_t *int_array_new(size_t size) { int_array_t *array; if (my_calloc((void *)&array, 1, sizeof(int_array_t)) != 0) return NULL; array->size = 0; if (my_calloc((void *)&array->data, size, sizeof(int_array_type_t)) != 0) return NULL; array->size = size; return array; } void int_array_delete(int_array_t *array) { free(array->data); array->data = NULL; array->size = 0; free(array); } int int_array_copy(int_array_t *dst, int_array_t *src) { if (my_realloc((void *)&dst->data, src->size * sizeof(int_array_type_t)) != 0) return INT_ARRAY_COPY_ERROR_MALLOC; memmove(dst->data, src->data, src->size * sizeof(int_array_type_t)); dst->size = src->size; return INT_ARRAY_COPY_OK; } size_t int_array_tail_zeros_count(int_array_t *array) { size_t count = 0; for (size_t i = array->size - 1; array->data[i] == 0; i--, count++); return count; } int int_array_resize(int_array_t *array, size_t new_size) { if (new_size == 0) { free(array->data); array->data = NULL; array->size = 0; } if (my_realloc((void *)&(array->data), new_size * sizeof(int_array_type_t)) != 0) return INT_ARRAY_RESIZE_ERROR_ALLOC; if (new_size > array->size) memset(array->data + array->size, 0, (new_size - array->size) * sizeof(int_array_type_t)); array->size = new_size; return INT_ARRAY_RESIZE_OK; } void int_array_print(FILE *file, int_array_t *array) { for (size_t i = 0; i < array->size; i++) fprintf(file, "%"INT_ARRAY_OUTPUT" ", array->data[i]); } size_array_t *size_array_new(size_t size) { size_array_t *array; if (my_calloc((void *)&array, 1, sizeof(size_array_t)) != 0) return NULL; array->size = 0; if (my_calloc((void *)&array->data, size, sizeof(size_t)) != 0) return NULL; array->size = size; return array; } void size_array_delete(size_array_t *array) { free(array->data); array->data = NULL; array->size = 0; free(array); } int size_array_copy(size_array_t *dst, size_array_t *src) { if (my_realloc((void *)&dst->data, src->size * sizeof(size_t)) != 0) return INT_ARRAY_COPY_ERROR_MALLOC; memmove(dst->data, src->data, src->size * sizeof(size_t)); dst->size = src->size; return INT_ARRAY_COPY_OK; } void size_array_print(FILE *file, size_array_t *array) { for (size_t i = 0; i < array->size; i++) fprintf(file, "%zu ", array->data[i]); } int size_array_resize(size_array_t *array, size_t new_size) { if (new_size == 0) { free(array->data); array->data = NULL; array->size = 0; } if (my_realloc((void *)&(array->data), new_size * sizeof(size_t)) != 0) return SIZE_ARRAY_RESIZE_ERROR_ALLOC; if (new_size > array->size) memset(array->data + array->size, 0, (new_size - array->size) * sizeof(size_t)); array->size = new_size; return SIZE_ARRAY_RESIZE_OK; }
#---------------------------------------------------------------IMPORTACIÓN DE LIBRERÍAS----------------------------------------------------------------------------- #Importamos las librerías que vamos a utilizar import streamlit as st from streamlit_option_menu import option_menu import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.lines as mlines import seaborn as sns import datetime import geopandas as gpd import warnings import plotly.graph_objects as go from plotly.subplots import make_subplots import plotly.express as px import streamlit.components.v1 as components from PIL import Image from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import train_test_split #Paleta de colores #colores = ['#f07167', '#fed9b7', '#fdfcdc', '#00afb9', '#0081a7', '#13315c'] #https://coolors.co/palette/0081a7-00afb9-fdfcdc-fed9b7-f07167 #------------------------------------------------------------------LECTURA DE ARCHIVOS----------------------------------------------------------------------------- #Leemos los documentos csv que vamos a utilizar para este análisis cards = pd.read_csv("../Datasets/cards.txt", sep="|", decimal=',') weather = pd.read_csv("../Datasets/weather.csv", sep=";", decimal='.') dataframe_geojson = gpd.read_file("../Datasets/almeria_localizaciones.geojson") #------------------------------------------------------------------PREPARACIÓN DE LOS DATOS------------------------------------------------------------------------- #Conversión tipo de datos archivo CARDS cards['CP_CLIENTE'] = cards['CP_CLIENTE'].astype(str) #Tipo categórico cards['CP_COMERCIO'] = cards['CP_COMERCIO'].astype(str) #Tipo categórico cards['SECTOR'] = cards['SECTOR'].astype(str) #Tipo categórico cards['DIA'] = pd.to_datetime(cards['DIA'], format="%Y/%m/%d") #Tipo fecha cards['FRANJA_HORARIA'] = cards['FRANJA_HORARIA'].astype(str) #Tipo categórico cards['IMPORTE'] = cards['IMPORTE'].astype(float) #Tipo real cards['NUM_OP'] = cards['NUM_OP'].astype(int) #Tipo entero #Eliminación de columnas irrelevantes archivo WEATHER weather = weather.drop(columns= 'TMax') weather = weather.drop(columns= 'HTMax') weather = weather.drop(columns= 'TMin') weather = weather.drop(columns= 'HTMin') weather = weather.drop(columns= 'HumMax') weather = weather.drop(columns= 'HumMin') weather = weather.drop(columns= 'HumMed') weather = weather.drop(columns= 'VelViento') weather = weather.drop(columns= 'DirViento') weather = weather.drop(columns= 'Rad') weather = weather.drop(columns= 'ETo') #Conversión tipo de datos archivo WEATHER weather['FECHA'] = pd.to_datetime(weather['FECHA'], format="%Y/%m/%d") #Tipo fecha weather['DIA'] = weather['DIA'].astype(int) #Tipo entero weather['TMed'] = weather['TMed'].astype(float) #Tipo real weather['Precip'] = weather['Precip'].astype(float) #Tipo real #Columna DIA a FECHA en el archivo CARDS cards.columns = ['CP_CLIENTE', 'CP_COMERCIO', 'SECTOR', 'FECHA', 'FRANJA_HORARIA', 'IMPORTE', 'NUM_OP'] #Dataset final CARDS-WEATHER dataset = cards.merge(weather, on="FECHA", how="inner") #Archivo geojson dataframe_geojson = dataframe_geojson.dissolve(by='COD_POSTAL').reset_index() dataframe_geojson['COD_POSTAL'] = dataframe_geojson['COD_POSTAL'].astype(str) #Tipo categórico dataframe_geojson['COD_POSTAL'] = dataframe_geojson['COD_POSTAL'].str[1:] #-----------------------------------------------------------------------------PÁGINA WEB------------------------------------------------------------------------- #Título de la página web st.set_page_config(page_title="PBDII - Julieta Benítez", page_icon = Image.open('../Imagenes/icono.png'), layout='wide', initial_sidebar_state='expanded') #Menú with st.sidebar: selected = option_menu( menu_title="Manú principal", options = ["Análisis por sectores", "Influencia de la climatología", "Análisis por zonas", "Modelo de IA"], icons=["basket2-fill", "cloud-lightning-rain", "geo-fill", "robot"], menu_icon="list", ) #Secciones de la página web y su contenido #---------------------------------------------------------------PRIMERA SECCIÓN: ANÁLISIS POR SECTORES--------------------------------------------------------------- if selected == "Análisis por sectores": st.title(f"Has seleccionado {selected}") st.markdown( """ <style> .divider { width: 100%; height: 1px; background-color: white; border: none; border-top: 1px dashed white; margin: 20px 0; } </style> """ , unsafe_allow_html=True) st.markdown("<div class='divider'></div>", unsafe_allow_html=True) st.title(f" ") #FILTROS #Posiciones de los filtros dia, franja_horaria = st.columns([5, 5]) #Filtro de fecha with dia: initial_dia_choice, final_dia_choice = st.slider( "¿Qué rangos de días del 2015 te gustaría filtrar?", min_value=1, #Desde el 7 para que salgan todos los donuts dibujados de cada semana max_value=365, step=1, value=(1, 365), ) #Ayuda para saber que fecha corresponde a cada día en el primer filtro #st.markdown( #""" #<p style="text-align: center;"> #<small>* Puedes consultar la fecha a la que corresponde cada día del 2015 en el siguiente <a href="https://www.calendario-365.es/numeros-de-dias/2015.html"> enlace</a></small> #</p> #""", #unsafe_allow_html=True #) #Filtro de franja horaria with franja_horaria: franja_horaria_choice = st.selectbox( "¿Por qué franja horaria te gustaría filtrar?", ("Todas", '08-10', '10-12', '12-14', '14-16', '16-18', '18-20', '20-22', '22-24', '00-02', '02-04', '04-06', '06-08'), ) #Elección del cliente: Todas las franjas horarias o una específica -> En el primer caso, filtramos por el rango de días seleccionado # y en el segundo caso por el rango de días y franja horaria seleccionados .> Actualización del dataset que se utilizará en los gráficos (filtered_dataset) if franja_horaria_choice == "Todas": filtered_dataset = dataset[(initial_dia_choice <= dataset['DIA']) & (dataset['DIA'] <= final_dia_choice)] if franja_horaria_choice != "Todas": filtered_dataset = dataset[(initial_dia_choice <= dataset['DIA']) & (dataset['DIA'] <= final_dia_choice)] filtered_dataset = filtered_dataset[filtered_dataset['FRANJA_HORARIA'] == franja_horaria_choice] #Fecha inicial seleccionada por el usuario, para poder imprimirla fecha_filtrada_inicial = filtered_dataset.loc[filtered_dataset['DIA'] == initial_dia_choice, 'FECHA'].values[0] #Convertimos a formato segundos y luego a datetime para asegurarnos de poder quitar los 0 que quedan al final fecha_filtrada_inicial = np.datetime_as_string(fecha_filtrada_inicial, unit='s') fecha_filtrada_inicial = datetime.datetime.strptime(fecha_filtrada_inicial, "%Y-%m-%dT%H:%M:%S") # Formatear la fecha sin ceros finales fecha_filtrada_inicial = fecha_filtrada_inicial.strftime("%Y-%m-%d") #Fecha final seleccionada por el usuario, para poder imprimirla fecha_filtrada_final = filtered_dataset.loc[filtered_dataset['DIA'] == final_dia_choice, 'FECHA'].values[0] #Convertimos a formato segundos y luego a datetime para asegurarnos de poder quitar los 0 que quedan al final fecha_filtrada_final = np.datetime_as_string(fecha_filtrada_final, unit='s') fecha_filtrada_final = datetime.datetime.strptime(fecha_filtrada_final, "%Y-%m-%dT%H:%M:%S") # Formatear la fecha sin ceros finales fecha_filtrada_final = fecha_filtrada_final.strftime("%Y-%m-%d") #Franja horaria elegida por el usuario franja_horaria_filtrada = franja_horaria_choice #Imprimimos la el rango de fechas según la elecciónde días por parte del usuario st.markdown( f"<p style='text-align: center;'>Rango de fechas seleccionadas: <b><span style='color: #d45d5d;'>{fecha_filtrada_inicial} - {fecha_filtrada_final}</span></b> en la Franja Horaria: <b><span style='color: #d45d5d;'>{franja_horaria_filtrada}</span></b></p>", unsafe_allow_html=True ) st.markdown("---") #****************************************************************************GRÁFICOS 0 Y 0.2********************************************************************* #*******************************************************GRÁFICO 0: Vista temporal general de gastos por sector**************************************************** #Agrupamos por Fecha y Sector y realizamos la suma de IMPORTE importe_fecha_sector = filtered_dataset[["FECHA","SECTOR","IMPORTE"]].groupby(["FECHA","SECTOR"]).sum().reset_index() # GRÁFICO 0: Utilizaremos librería plotly fig0 = px.line(importe_fecha_sector, x="FECHA", y="IMPORTE", color='SECTOR') fig0.update_layout( legend=dict( x=0, # Leyenda empieza en la posición 1/4 del ancho total y=1.1, # Colocar arriba (valor mayor a 1) orientation="h" # Orientación horizontal ) ) #Creamos dos columnas para colocar los gráficos 0 y 0.2, en una proporción 2 y 0.7 colGraf0, colGraf02 = st.columns([2, 0.7]) #Pintamos Gráfico 0 en página web: Top 5 sectores con más gastos según el día de la semana with colGraf0: st.markdown("<h3 style='font-size: 23px; text-align: center; margin-left: 35%;'>Línea de tiempo de los gastos por sector en 2015</h3>", unsafe_allow_html=True) st.plotly_chart(fig0, use_container_width=True) #-------------------------GRÁFICO 0.2 para visualizar mejor el ranking de sectores con mayores gastos--------------------------- importe_por_sector = filtered_dataset[["SECTOR","IMPORTE"]].groupby(["SECTOR"]).sum().reset_index().sort_values('IMPORTE', ascending=True) fig02 = go.Figure(data=[go.Bar(x=importe_por_sector['IMPORTE'], y=importe_por_sector['SECTOR'], hovertext=importe_por_sector['IMPORTE'], orientation='h')]) # Customize aspect fig02.update_traces(marker_color='rgba(246, 126, 126, 0.3)', marker_line_color='#FD6060', marker_line_width=1.5, opacity=0.8) #Pintamos Gráfico 0.2 en página web: Ranking de sectores con mayores gastos with colGraf02: st.plotly_chart(fig02, use_container_width=True) #***************************************************************************GRÁFICOS 1 Y 1.2******************************************************************* #*******************************************************GRÁFICO 1: Sectores con más gastos según el día de la semana******************************************* #Asignamos los nombres de los días de la semana a los números correspondientes nombres_dias_semana = { 0: 'Lunes', 1: 'Martes', 2: 'Miércoles', 3: 'Jueves', 4: 'Viernes', 5: 'Sábado', 6: 'Domingo' } #Obtenemos número de día de la semana y los mapeamos en nueva columna nombres_dias_semana filtered_dataset['DIA_SEMANA'] = filtered_dataset['FECHA'].dt.dayofweek.map(nombres_dias_semana) #Calculamos suma de los importes por cada combinación de día de la semana y sector importe_por_sector = filtered_dataset.groupby(['DIA_SEMANA','SECTOR'])['IMPORTE'].sum().reset_index() #Hacemos un DataFrame por cada día de la semana lunes = importe_por_sector[importe_por_sector['DIA_SEMANA'] == 'Lunes'].sort_values(["IMPORTE"], ascending=False).head(5).copy() martes = importe_por_sector[importe_por_sector['DIA_SEMANA'] == 'Martes'].sort_values(["IMPORTE"], ascending=False).head(5).copy() miercoles = importe_por_sector[importe_por_sector['DIA_SEMANA'] == 'Miércoles'].sort_values(["IMPORTE"], ascending=False).head(5).copy() jueves = importe_por_sector[importe_por_sector['DIA_SEMANA'] == 'Jueves'].sort_values(["IMPORTE"], ascending=False).head(5).copy() viernes = importe_por_sector[importe_por_sector['DIA_SEMANA'] == 'Viernes'].sort_values(["IMPORTE"], ascending=False).head(5).copy() sabado = importe_por_sector[importe_por_sector['DIA_SEMANA'] == 'Sábado'].sort_values(["IMPORTE"], ascending=False).head(5).copy() domingo = importe_por_sector[importe_por_sector['DIA_SEMANA'] == 'Domingo'].sort_values(["IMPORTE"], ascending=False).head(5).copy() # GRÁFICO 1: Utilizaremos librería plotly # Crear subparcelas fig1 = make_subplots(rows=1, cols=7, specs=[[{'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}]]) fig1.add_trace(go.Pie(labels=lunes['SECTOR'], values=lunes['IMPORTE'], name="Lunes"), 1, 1) fig1.add_trace(go.Pie(labels=martes['SECTOR'], values=martes['IMPORTE'], name="Martes"),1, 2) fig1.add_trace(go.Pie(labels=miercoles['SECTOR'], values=miercoles['IMPORTE'], name="Miércoles"),1,3) fig1.add_trace(go.Pie(labels=jueves['SECTOR'], values=jueves['IMPORTE'], name="Jueves"),1,4) fig1.add_trace(go.Pie(labels=viernes['SECTOR'], values=viernes['IMPORTE'], name="Viernes"),1,5) fig1.add_trace(go.Pie(labels=sabado['SECTOR'], values=sabado['IMPORTE'], name="Sábado"),1,6) fig1.add_trace(go.Pie(labels=domingo['SECTOR'], values=domingo['IMPORTE'], name="Domingo"),1,7) #Crear un gráfico circular en forma de donut fig1.update_traces(hole=.4, hoverinfo="label+percent+name") fig1.update_layout( legend=dict( x=0.25, # Leyenda empieza en la posición 1/4 del ancho total y=1.1, # Colocar arriba (valor mayor a 1) orientation="h" # Orientación horizontal ), #Añadir anotaciones en el centro de los donuts annotations=[dict(text='Lunes', x=0.045, y=0.95, font_size=15, showarrow=False), dict(text='Martes', x=0.19, y=0.95, font_size=15, showarrow=False), dict(text='Miércoles', x=0.355, y=0.95, font_size=15, showarrow=False), dict(text='Jueves', x=0.50, y=0.95, font_size=15, showarrow=False), dict(text='Viernes', x=0.65, y=0.95, font_size=15, showarrow=False), dict(text='Sábado', x=0.81, y=0.95, font_size=15, showarrow=False), dict(text='Domingo', x=0.96, y=0.95, font_size=15, showarrow=False)]) #-------------------------GRÁFICO 1.2 para visualizar mejor el gasto por sectores según día de la semana--------------------------- #Generamos los días de la semana pero en versión numérica (La que ya viene por defecto en la función dayofweek) filtered_dataset['NUM_SEMANA'] = filtered_dataset['FECHA'].dt.dayofweek + 1 #Agrupamos por Número de la semana y Sector y realizamos la suma de IMPORTE importe_numsemana_sector = filtered_dataset[["NUM_SEMANA","SECTOR","IMPORTE"]].groupby(["NUM_SEMANA","SECTOR"]).sum().reset_index() # GRÁFICO 1.2: Utilizaremos librería plotly fig12 = px.line(importe_numsemana_sector, x="NUM_SEMANA", y="IMPORTE", color='SECTOR') fig12.update_layout( legend=dict( x=0.05, # Leyenda empieza en la posición 1/4 del ancho total y=1.1, # Colocar arriba (valor mayor a 1) orientation="h" # Orientación horizontal )) #Pintamos Gráfico 1 en página web: Top 5 sectores con más gastos según el día de la semana st.markdown("---") st.markdown("<h3 style='font-size: 23px; text-align: center;'>Top 5 sectores con más gastos según el día de la semana</h3>", unsafe_allow_html=True) st.plotly_chart(fig1, use_container_width=True) #Pintamos Gráfico 1.2 en página web: Gastos por sector según el día de la semana st.plotly_chart(fig12, use_container_width=True) st.markdown("---") #************************************************GRÁFICO 2: Sectores con más gastos según sea día laboral o fin de semana******************************************** # Definimos una lista denominada dias_laborables, que contiene los números de los días que no son fines de semana dias_laborables = [0, 1, 2, 3, 4] #Creamos nueva columna con el día de la semana a la que corresponde cada fecha filtered_dataset['DIA_SEMANA_NUMERO'] = filtered_dataset['FECHA'].dt.dayofweek #Creamos nueva columna basada en los valores de la anterior columna, comprobando si es día laboral o fin de semana filtered_dataset['TIPO_DIA'] = filtered_dataset['DIA_SEMANA_NUMERO'].apply(lambda x: 'Laboral' if x in dias_laborables else 'Fin de semana') #Eliminamos la columna DIA_SEMANA_NUMERO al ser irrelevante filtered_dataset = filtered_dataset.drop(columns= 'DIA_SEMANA_NUMERO') #Filtramos dataset por días laborables y fines de semana, creando dos nuevos dataframes Laboral = filtered_dataset[filtered_dataset['TIPO_DIA'] == 'Laboral'] Fin_de_semana = filtered_dataset[filtered_dataset['TIPO_DIA'] == 'Fin de semana'] #Agrupamos datos por sector, calculando la suma de los importes, en ambos dataframes nuevos gasto_dias_laborables = Laboral.groupby('SECTOR')['IMPORTE'].sum().reset_index() gasto_dias_laborables = pd.DataFrame(gasto_dias_laborables) gasto_dias_laborables["TIPO_DIA"] = "Laboral" gasto_fines_semana = Fin_de_semana.groupby('SECTOR')['IMPORTE'].sum().reset_index() gasto_fines_semana = pd.DataFrame(gasto_fines_semana) gasto_fines_semana["TIPO_DIA"] = "Fin de semana" #Unimos ambos dataframes en uno solo gasto_laborables_fines_semana = pd.concat([gasto_dias_laborables, gasto_fines_semana], axis=0) #GRÁFICO 2: Utilizaremos librería plotly colores = ['#FF6262', '#68D263'] fig2 = px.sunburst(gasto_laborables_fines_semana, path=['TIPO_DIA', 'SECTOR'], values='IMPORTE', color_discrete_sequence=colores) fig2.update_layout( width=800, # Ancho del gráfico en píxeles height=600 # Altura del gráfico en píxeles ) fig2.update_traces(textfont_color='white') #Pintamos Gráfico 2 en página web: Sectores con más gastos según sea día laboral o fin de semana st.markdown("<h3 style='font-size: 23px; text-align: center;'>Sectores con más gastos según sea día laboral o fin de semana</h3>", unsafe_allow_html=True) st.plotly_chart(fig2, use_container_width=True) #************FOOTER PRIMERA SECCIÓN************* st.markdown( """ <style> .divider { width: 100%; height: 1px; background-color: white; border: none; border-top: 1px dashed white; margin: 20px 0; } </style> """ , unsafe_allow_html=True) st.markdown("<div class='divider'></div>", unsafe_allow_html=True) col1Footer, col2Footer, col3Footer, col4Footer, col5Footer = st.columns(5) with col3Footer: st.title(f" ") st.image("../Imagenes/logo_footer.png", width=270) #---------------------------------------------------------------SEGUNDA SECCIÓN: INFLUENCIA DE LA CLIMATOLOGÍA----------------------------------------------------------- if selected == "Influencia de la climatología": st.title(f"Has seleccionado {selected}") st.markdown( """ <style> .divider { width: 100%; height: 1px; background-color: white; border: none; border-top: 1px dashed white; margin: 20px 0; } </style> """ , unsafe_allow_html=True) st.markdown("<div class='divider'></div>", unsafe_allow_html=True) st.title(f" ") #**************************************************************************GRÁFICOS 3 Y 4*************************************************************************** #-------FILTRO DE FECHA PARA EL GRÁFICO 3 Y 4------ initial_dia_choice1, final_dia_choice1 = st.slider( "¿Qué rangos de días del 2015 te gustaría filtrar?", min_value=1, #Desde el 7 para que salgan todos los donuts dibujados de cada semana max_value=365, step=1, value=(1, 365), ) #Elección del cliente: Rango de días seleccionados -> Actualización del dataset que se utilizará en los gráficos (filtered_dataset) filtered_dataset = dataset[(initial_dia_choice1 <= dataset['DIA']) & (dataset['DIA'] <= final_dia_choice1)] #Fecha inicial seleccionada por el usuario, para poder imprimirla fecha_filtrada_inicial1 = filtered_dataset.loc[filtered_dataset['DIA'] == initial_dia_choice1, 'FECHA'].values[0] #Convertimos a formato segundos y luego a datetime para asegurarnos de poder quitar los 0 que quedan al final fecha_filtrada_inicial1 = np.datetime_as_string(fecha_filtrada_inicial1, unit='s') fecha_filtrada_inicial1 = datetime.datetime.strptime(fecha_filtrada_inicial1, "%Y-%m-%dT%H:%M:%S") # Formatear la fecha sin ceros finales fecha_filtrada_inicial1 = fecha_filtrada_inicial1.strftime("%Y-%m-%d") #Fecha final seleccionada por el usuario, para poder imprimirla fecha_filtrada_final1 = filtered_dataset.loc[filtered_dataset['DIA'] == final_dia_choice1, 'FECHA'].values[0] #Convertimos a formato segundos y luego a datetime para asegurarnos de poder quitar los 0 que quedan al final fecha_filtrada_final1 = np.datetime_as_string(fecha_filtrada_final1, unit='s') fecha_filtrada_final1 = datetime.datetime.strptime(fecha_filtrada_final1, "%Y-%m-%dT%H:%M:%S") # Formatear la fecha sin ceros finales fecha_filtrada_final1 = fecha_filtrada_final1.strftime("%Y-%m-%d") #Imprimimos la el rango de fechas según la elecciónde días por parte del usuario st.markdown( f"<p style='text-align: center;'>Rango de fechas seleccionadas: <b><span style='color: #d45d5d;'>{fecha_filtrada_inicial1} - {fecha_filtrada_final1}</span></b>", unsafe_allow_html=True ) #Aviso de posibilidad de filtrar por rangos st.markdown( """ <p style="text-align: center;"> <small>Puedes filtrar por rangos, seleccionándolos o deseleccionándolos, en las leyendas correspondientes</small> </p> """, unsafe_allow_html=True ) st.markdown("---") #Gráficos 3 y 4 irán colocados en 2 columnas colGraf3, colGraf4 = st.columns([5, 5]) #*********************************GRÁFICO 3: Influencia del número de precipitaciones en los gastos de los clientes********************************* #El gráfico 3 irá en la primera columna with colGraf3: #Dividimos el número de precipitaciones por 5 rangos precip_min = filtered_dataset['Precip'].min() precip_max = filtered_dataset['Precip'].max() num_rangos_precip = 5 rangos_precipitaciones = np.linspace(precip_min, precip_max, num_rangos_precip+1) #Aplicamos los rangos filtered_dataset['Rango_Precip'] = pd.cut(filtered_dataset['Precip'], bins=rangos_precipitaciones, duplicates='drop', include_lowest=True) #Calculamos la suma de IMPORTE por cada combinación de Rango_Precip y SECTOR importe_por_precip = filtered_dataset.groupby(['Rango_Precip','SECTOR'])['IMPORTE'].sum().reset_index() #GRÁFICO 3: Utilizaremos librería plotly #Creamos radar chart radar_chart_Precip = pd.DataFrame({ 'r':importe_por_precip['IMPORTE'], 'theta': importe_por_precip['SECTOR'], 'color': importe_por_precip['Rango_Precip'] }) fig3 = px.line_polar(radar_chart_Precip, r='r', theta='theta', line_close=True , color='color') fig3.update_layout( polar=dict(bgcolor='rgba(0, 0, 0, 0)'), # Establecer el fondo transparente legend_title_text='Rango de precipitaciones existentes', #Nombre de la leyenda width=800, # Ancho del gráfico en píxeles height=470 # Altura del gráfico en píxeles ) fig3.update_polars( radialaxis=dict( linecolor='rgba(255, 255, 255, 0.3)', # Establecer el color de la línea del eje radial en blanco gridcolor='rgba(255, 255, 255, 0.3)' # Establecer el color de la cuadrícula del eje radial en blanco ), angularaxis=dict( linecolor='rgba(255, 255, 255, 0.3)', # Establecer el color de la línea del eje angular en blanco ) ) fig3.update_traces(fill='toself') #Imprimimos gráfico 3 st.markdown("<h3 style='font-size: 18px; text-align: center;'>Influencia del número de precipitaciones en los gastos de los clientes</h3>", unsafe_allow_html=True) st.plotly_chart(fig3, use_container_width=True) #*********************************GRÁFICO 4: Influencia de la temperatura en los gastos de los clientes********************************* #El gráfico 4 irá en la segunda columna with colGraf4: #Dividimos las temperaturas por 5 rangos TMed_min = filtered_dataset['TMed'].min() TMed_max = filtered_dataset['TMed'].max() num_rangos_TMed = 5 rangos_TMed = np.linspace(TMed_min, TMed_max, num_rangos_TMed+1) #Aplicamos los rangos filtered_dataset['Rango_TMed'] = pd.cut(filtered_dataset['TMed'], bins=rangos_TMed, duplicates='drop', include_lowest=True) #Calculamos la suma de IMPORTE por cada combinación de Rango_TMed y SECTOR importe_por_TMed = filtered_dataset.groupby(['Rango_TMed','SECTOR'])['IMPORTE'].sum().reset_index() #GRÁFICO 4: Utilizaremos librería plotly #Creamos radar chart radar_chart_TMed = pd.DataFrame({ 'r':importe_por_TMed['IMPORTE'], 'theta': importe_por_TMed['SECTOR'], 'color': importe_por_TMed['Rango_TMed'] }) fig4 = px.line_polar(radar_chart_TMed, r='r', theta='theta', line_close=True , color='color') fig4.update_layout( polar=dict(bgcolor='rgba(0, 0, 0, 0)'), # Establecer el fondo transparente legend_title_text='Rango de temperaturas existentes', #Nombre de la leyenda width=800, # Ancho del gráfico en píxeles height=470 # Altura del gráfico en píxeles ) fig4.update_polars( radialaxis=dict( linecolor='rgba(255, 255, 255, 0.3)', # Establecer el color de la línea del eje radial en blanco gridcolor='rgba(255, 255, 255, 0.3)' # Establecer el color de la cuadrícula del eje radial en blanco ), angularaxis=dict( linecolor='rgba(255, 255, 255, 0.3)', # Establecer el color de la línea del eje angular en blanco ) ) fig4.update_traces(fill='toself') #Imprimimos gráfico 4 st.markdown("<h3 style='font-size: 18px; text-align: center;'>Influencia del la temperatura en los gastos de los clientes</h3>", unsafe_allow_html=True) st.plotly_chart(fig4, use_container_width=True) #************FOOTER SEGUNDA SECCIÓN************* st.markdown( """ <style> .divider { width: 100%; height: 1px; background-color: white; border: none; border-top: 1px dashed white; margin: 20px 0; } </style> """ , unsafe_allow_html=True) st.markdown("<div class='divider'></div>", unsafe_allow_html=True) col1Footer, col2Footer, col3Footer, col4Footer, col5Footer = st.columns(5) with col3Footer: st.title(f" ") st.image("../Imagenes/logo_footer.png", width=270) #---------------------------------------------------------------TERCERA SECCIÓN: ANÁLISIS POR ZONAS----------------------------------------------------------- if selected == "Análisis por zonas": st.title(f"Has seleccionado {selected}") st.markdown( """ <style> .divider { width: 100%; height: 1px; background-color: white; border: none; border-top: 1px dashed white; margin: 20px 0; } </style> """ , unsafe_allow_html=True) st.markdown("<div class='divider'></div>", unsafe_allow_html=True) st.title(f" ") #FILTROS #Posiciones de los filtros dia, franja_horaria = st.columns([5, 5]) #Filtro de fecha with dia: initial_dia_choice, final_dia_choice = st.slider( "¿Qué rangos de días del 2015 te gustaría filtrar?", min_value=1, #Desde el 7 para que salgan todos los donuts dibujados de cada semana max_value=365, step=1, value=(1, 365), ) #Filtro de franja horaria with franja_horaria: franja_horaria_choice = st.selectbox( "¿Por qué franja horaria te gustaría filtrar?", ("Todas", '08-10', '10-12', '12-14', '14-16', '16-18', '18-20', '20-22', '22-24', '00-02', '02-04', '04-06', '06-08'), ) #Elección del cliente: Todas las franjas horarias o una específica -> En el primer caso, filtramos por el rango de días seleccionado # y en el segundo caso por el rango de días y franja horaria seleccionados .> Actualización del dataset que se utilizará en los gráficos (filtered_dataset) if franja_horaria_choice == "Todas": filtered_dataset = dataset[(initial_dia_choice <= dataset['DIA']) & (dataset['DIA'] <= final_dia_choice)] if franja_horaria_choice != "Todas": filtered_dataset = dataset[(initial_dia_choice <= dataset['DIA']) & (dataset['DIA'] <= final_dia_choice)] filtered_dataset = filtered_dataset[filtered_dataset['FRANJA_HORARIA'] == franja_horaria_choice] #Fecha inicial seleccionada por el usuario, para poder imprimirla fecha_filtrada_inicial = filtered_dataset.loc[filtered_dataset['DIA'] == initial_dia_choice, 'FECHA'].values[0] #Convertimos a formato segundos y luego a datetime para asegurarnos de poder quitar los 0 que quedan al final fecha_filtrada_inicial = np.datetime_as_string(fecha_filtrada_inicial, unit='s') fecha_filtrada_inicial = datetime.datetime.strptime(fecha_filtrada_inicial, "%Y-%m-%dT%H:%M:%S") # Formatear la fecha sin ceros finales fecha_filtrada_inicial = fecha_filtrada_inicial.strftime("%Y-%m-%d") #Fecha final seleccionada por el usuario, para poder imprimirla fecha_filtrada_final = filtered_dataset.loc[filtered_dataset['DIA'] == final_dia_choice, 'FECHA'].values[0] #Convertimos a formato segundos y luego a datetime para asegurarnos de poder quitar los 0 que quedan al final fecha_filtrada_final = np.datetime_as_string(fecha_filtrada_final, unit='s') fecha_filtrada_final = datetime.datetime.strptime(fecha_filtrada_final, "%Y-%m-%dT%H:%M:%S") # Formatear la fecha sin ceros finales fecha_filtrada_final = fecha_filtrada_final.strftime("%Y-%m-%d") #Franja horaria elegida por el usuario franja_horaria_filtrada = franja_horaria_choice #Imprimimos la el rango de fechas según la elecciónde días por parte del usuario st.markdown( f"<p style='text-align: center;'>Rango de fechas seleccionadas: <b><span style='color: #d45d5d;'>{fecha_filtrada_inicial} - {fecha_filtrada_final}</span></b> en la Franja Horaria: <b><span style='color: #d45d5d;'>{franja_horaria_filtrada}</span></b></p>", unsafe_allow_html=True ) st.markdown("---") #Gráficos 5 y 6 irán colocados en 2 columnas colGraf5, colGraf6 = st.columns([5, 5]) #************************************************GRÁFICO 5: Códigos postales con más gastos por sectores***************************************************** #El gráfico 5 irá en la primera columna with colGraf5: #Agrupamos por CP_COMERCIO y SECTOR y calculamos la suma del importe gastos_por_sector_cpcomercio = filtered_dataset.groupby(['CP_COMERCIO', 'SECTOR'])['IMPORTE'].sum().reset_index() #Cogemos las filas que tengan mayor IMPORTE por SECTOR max_gastos = gastos_por_sector_cpcomercio.groupby('SECTOR')['IMPORTE'].idxmax() #Creamos un dataframe con los resultados, filtrando por los índices resultantes de la anterior consulta cpcomercio_max_gastos_sector = gastos_por_sector_cpcomercio.loc[max_gastos, ['SECTOR', 'CP_COMERCIO', 'IMPORTE']] #Creamos un Choropleth map usando Plotly fig5 = px.choropleth_mapbox(cpcomercio_max_gastos_sector, geojson=dataframe_geojson, color='SECTOR', locations="CP_COMERCIO", featureidkey="properties.COD_POSTAL", color_continuous_scale = 'viridis', opacity = 0.5, center={"lat": 36.841709, "lon": -2.456918}, mapbox_style="carto-positron", zoom=9) fig5.update_layout( height=600 # Altura del gráfico en píxeles ) fig5.update_traces(visible="legendonly") #Deseleccionar todos los sectores fig5.data[0].visible=True #Seleccionar solo el primero #Imprimimos gráfico 5 st.markdown("<h3 style='font-size: 18px; text-align: center;'>Códigos postales con más gastos por sectores</h3>", unsafe_allow_html=True) st.plotly_chart(fig5, use_container_width=True) #************************************************GRÁFICO 6: Códigos postales de las personas con más gastos***************************************************** #El gráfico 6 irá en la segunda columna with colGraf6: #Suma de los importes agrupados por los códigos postales de los clientes gastos_por_cpcliente = filtered_dataset.groupby('CP_CLIENTE')['IMPORTE'].sum().reset_index() #Creamos un Choropleth map usando Plotly fig6 = px.choropleth_mapbox(gastos_por_cpcliente, geojson=dataframe_geojson, color='IMPORTE', locations="CP_CLIENTE", featureidkey="properties.COD_POSTAL", center={"lat": 36.841709, "lon": -2.456918}, mapbox_style="carto-positron", zoom=9, color_continuous_scale="RdYlGn_r", opacity = 0.5) fig6.update_layout( height=600 # Altura del gráfico en píxeles ) #Imprimimos gráfico 6 st.markdown("<h3 style='font-size: 18px; text-align: center;'> Códigos postales de las personas con más gastos</h3>", unsafe_allow_html=True) st.plotly_chart(fig6, use_container_width=True) st.markdown("---") #Gráficos 7 y 7.2 irán colocados en 2 columnas colGraf7, colGraf7_2 = st.columns([7, 3]) #************************************************GRÁFICO 7: Zonas con más compras de clientes que residen en otras************************************************** with colGraf7: #Filas de cards que cuentan con un CP_CLIENTE diferente a CP_COMERCIO, que resulta en ninguna cpcliente_desigual_cpcomercio = filtered_dataset[filtered_dataset['CP_CLIENTE'] != filtered_dataset['CP_COMERCIO']] #Suma del número de operaciones en cada combinación de CP_COMERCIO y CP_CLIENTE transacciones_por_zona = cpcliente_desigual_cpcomercio.groupby(['CP_COMERCIO', 'CP_CLIENTE'])['NUM_OP'].sum().reset_index(name='Transacciones') #Por cada código de comercio, realizamos la suma de las transacciones zonas_con_mas_transacciones = transacciones_por_zona.groupby('CP_COMERCIO')['Transacciones'].sum().reset_index() #Creamos un Choropleth map usando Plotly fig7 = px.choropleth_mapbox(zonas_con_mas_transacciones, geojson=dataframe_geojson, color='Transacciones', locations="CP_COMERCIO", featureidkey="properties.COD_POSTAL", center={"lat": 36.841709, "lon": -2.456918}, mapbox_style="carto-positron", zoom=9, color_continuous_scale="RdYlGn_r", opacity = 0.5) fig7.update_layout( height=550 # Altura del gráfico en píxeles ) #Imprimimos gráfico 7 st.markdown("<h3 style='font-size: 18px; text-align: center;'> Zonas con más compras de clientes que residen en otras</h3>", unsafe_allow_html=True) st.plotly_chart(fig7, use_container_width=True) #-------------------------GRÁFICO 7.2 para visualizar mejor el ranking de sectores con mayores gastos--------------------------- with colGraf7_2: #Guardamos el CP_COMERCIO con más operaciones de códigos postales diferentes al propio cp_comercio_mas_transacciones = zonas_con_mas_transacciones.sort_values('Transacciones', ascending=False).iloc[0]['CP_COMERCIO'] #Calculamos el número de operaciones por sector en ese código de comercio concreto num_op_cp_comercio_max = cards[cards['CP_COMERCIO'] == cp_comercio_mas_transacciones].groupby('SECTOR')['NUM_OP'].sum().reset_index() num_op_cp_comercio_max = num_op_cp_comercio_max.sort_values('NUM_OP', ascending=True) fig7_2 = go.Figure(data=[go.Bar(x=num_op_cp_comercio_max['NUM_OP'], y=num_op_cp_comercio_max['SECTOR'], hovertext=num_op_cp_comercio_max['NUM_OP'], orientation='h')]) # Customize aspect fig7_2.update_traces(marker_color='rgba(246, 126, 126, 0.3)', marker_line_color='#FD6060', marker_line_width=1.5, opacity=0.8) fig7_2.update_layout( height=500 # Altura del gráfico en píxeles ) #Imprimimos gráfico 7 st.markdown(f"<h3 style='font-size: 15px; text-align: center;'> Detalle de las proporciones de transacciones por cada sector, \nen la zona con mayores compras (CP: <b><span style='color: #d45d5d;'>{cp_comercio_mas_transacciones}</span></b>)</h3>", unsafe_allow_html=True) st.plotly_chart(fig7_2, use_container_width=True) #************FOOTER TERCERA SECCIÓN************* st.markdown( """ <style> .divider { width: 100%; height: 1px; background-color: white; border: none; border-top: 1px dashed white; margin: 20px 0; } </style> """ , unsafe_allow_html=True) st.markdown("<div class='divider'></div>", unsafe_allow_html=True) col1Footer, col2Footer, col3Footer, col4Footer, col5Footer = st.columns(5) with col3Footer: st.title(f" ") st.image("../Imagenes/logo_footer.png", width=270) #---------------------------------------------------------------CUARTA SECCIÓN: MODELO DE IA----------------------------------------------------------- if selected == "Modelo de IA": st.title(f"Has seleccionado {selected}") st.markdown( """ <style> .divider { width: 100%; height: 1px; background-color: white; border: none; border-top: 1px dashed white; margin: 20px 0; } </style> """ , unsafe_allow_html=True) st.markdown("<div class='divider'></div>", unsafe_allow_html=True) st.markdown( f"<p style='text-align: center;'>Nuestro modelo de IA te permite conocer el importe que tendría una transacción, según el día en el que se realiza, el número de operaciones que conlleva, el sector al que pertenece el comercio, y la temperatura media y cantidad de precipitaciones existentes.\n <b><span style='color: #d45d5d;'>¡Pruébalo!</span></b></p>", unsafe_allow_html=True ) st.markdown( """ <style> .divider { width: 100%; height: 1px; background-color: white; border: none; border-top: 1px dashed white; margin: 20px 0; } </style> """ , unsafe_allow_html=True) st.markdown("<div class='divider'></div>", unsafe_allow_html=True) st.title(f" ") #FILTROS #Posiciones de los filtros dia, num_op, sector, TMed, Precip = st.columns([5, 5, 5, 5, 5]) #Filtro de fecha with dia: dia_choice = st.slider( "¿En qué día del año se realiza la transacción?", min_value=1, max_value=365, step=1, value=365, ) #Filtro de número de operaciones with num_op: num_op_choice = st.slider( "¿Cuántas operaciones se realizan en la transacción?", min_value=1, max_value=200, step=1, value=2, ) #Filtro de sector with sector: sector_choice = st.selectbox( "Selecciona el sector al que pertenece la tienda", ("ALIMENTACIÓN", 'AUTO', 'BELLEZA', 'HOGAR', 'MODA Y COMPLEMENTOS', 'OCIO Y TIEMPO LIBRE', 'OTROS', 'RESTAURACIÓN', 'SALUD', 'TECNOLOGÍA'), ) #Filtro de temperatura media with TMed: TMed_choice = st.slider( "¿Qué temperatura media hay el día de la transacción?", min_value=0, max_value=40, step=1, value=15, ) #Filtro de cantidad de precipitaciones with Precip: Precip_choice = st.slider( "¿Cuántas precipitaciones hay el día de la transacción?", min_value=0, max_value=40, step=1, value=0, ) #Elección del cliente #SECTOR if sector_choice == "ALIMENTACIÓN": num_sector_choice = 0 if sector_choice == "AUTO": num_sector_choice = 1 if sector_choice == "BELLEZA": num_sector_choice = 2 if sector_choice == "HOGAR": num_sector_choice = 3 if sector_choice == "MODA Y COMPLEMENTOS": num_sector_choice = 4 if sector_choice == "OCIO Y TIEMPO LIBRE": num_sector_choice = 5 if sector_choice == "OTROS": num_sector_choice = 6 if sector_choice == "RESTAURACIÓN": num_sector_choice = 7 if sector_choice == "SALUD": num_sector_choice = 8 if sector_choice == "TECNOLOGÍA": num_sector_choice = 9 #Fecha seleccionada por el usuario, para poder imprimirla fecha_filtrada = dataset.loc[dataset['DIA'] == dia_choice, 'FECHA'].values[0] #Convertimos a formato segundos y luego a datetime para asegurarnos de poder quitar los 0 que quedan al final fecha_filtrada = np.datetime_as_string(fecha_filtrada, unit='s') fecha_filtrada = datetime.datetime.strptime(fecha_filtrada, "%Y-%m-%dT%H:%M:%S") # Formatear la fecha sin ceros finales fecha_filtrada = fecha_filtrada.strftime("%Y-%m-%d") #Imprimimos la el rango de fechas según la elecciónde días por parte del usuario st.markdown("---") st.markdown( f"<p style='text-align: center;'><b>CARACTERÍSTICAS SELECCIONADAS DE LA TRANSACCIÓN</b></p>", unsafe_allow_html=True ) st.markdown( f"<p style='text-align: center;'>Fecha seleccionada: <b><span style='color: #d45d5d;'>{fecha_filtrada}</span></b></p>", unsafe_allow_html=True ) st.markdown( f"<p style='text-align: center;'>Número de operaciones seleccionadas: <b><span style='color: #d45d5d;'>{num_op_choice}</span></b></p>", unsafe_allow_html=True ) st.markdown( f"<p style='text-align: center;'>Sector seleccionado: <b><span style='color: #d45d5d;'>{sector_choice}</span></b></p>", unsafe_allow_html=True ) st.markdown( f"<p style='text-align: center;'>Temperatura media seleccionada: <b><span style='color: #d45d5d;'>{TMed_choice}</span></b></p>", unsafe_allow_html=True ) st.markdown( f"<p style='text-align: center;'>Cantidad de precipitaciones seleccionadas: <b><span style='color: #d45d5d;'>{Precip_choice}</span></b></p>", unsafe_allow_html=True ) st.markdown("---") st.markdown( f"<p style='font-size: 20px; text-align: center;'><b>LA TRANSACCIÓN TENDRÁ UN IMPORTE DE...</b></p>", unsafe_allow_html=True ) st.markdown( f"<p style='font-size: 14px; text-align: center;'><b>Esto puede llevar unos segundos...</b></p>", unsafe_allow_html=True ) #MODELO DE IA # Crear un diccionario de mapeo de categorías a números, en este caso el SECTOR mapeo = {} for i, sector in enumerate(dataset['SECTOR'].unique()): mapeo[sector] = i # Aplicar la codificación de etiquetas a la columna SECTOR dataset['NUM_SECTOR'] = dataset['SECTOR'].map(mapeo) target_col = 'IMPORTE' #Variables de características X = dataset[['NUM_SECTOR', 'DIA', 'NUM_OP', 'TMed','Precip']] #Variable objetivo y = dataset[target_col] #Dividimos conjunto de datos en entrenamiento y test, con un proporción del 80% y 20% respectivamente. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=1) # Primer DecisionTreeRegressor inner_tree = DecisionTreeRegressor(max_depth=10, min_samples_leaf=15, min_samples_split=12) inner_tree.fit(X_train, y_train) # Obtener las predicciones del primer DecisionTreeRegressor predictions_inner = inner_tree.predict(X_train) # Segundo DecisionTreeRegressor utilizando las predicciones del primero como entrada outer_tree = DecisionTreeRegressor(max_depth=7, min_samples_leaf=3, min_samples_split=4) outer_tree.fit(X_train, predictions_inner) # Hacer predicciones en el conjunto de prueba predictions_outer = outer_tree.predict(X_test) row = [[num_sector_choice, dia_choice, num_op_choice, TMed_choice, Precip_choice]] yhat = outer_tree.predict(row) prediccion = yhat[0] prediccion = round(prediccion, 2) st.markdown( f"<p style='font-size: 60px; text-align: center;'><b><span style='color: #d45d5d;'>{prediccion}€</span></b></p>", unsafe_allow_html=True ) #************FOOTER CUARTA SECCIÓN************* st.markdown( """ <style> .divider { width: 100%; height: 1px; background-color: white; border: none; border-top: 1px dashed white; margin: 20px 0; } </style> """ , unsafe_allow_html=True) st.markdown("<div class='divider'></div>", unsafe_allow_html=True) col1Footer, col2Footer, col3Footer, col4Footer, col5Footer = st.columns(5) with col3Footer: st.title(f" ") st.image("../Imagenes/logo_footer.png", width=270)
interface WorkExperience { company: string title: string location: string dateStart: string dateEnd: string | null descriptions: string[] } interface EducationExperience { school: string location: string programme: string dateStart: string dateEnd: string } interface Skills { type: string items: string[] highlights: string[] } interface TodoList { actionItem: string finished: boolean } export const education: EducationExperience[] = [ { school: 'The Hong Kong Polytechnic University', location: 'Hong Kong', programme: 'BEng (Hons) in Electronic and Information Engineering', dateStart: '2014', dateEnd: '2019', }, { school: 'University of Cincinnati', location: 'Cincinnati, OH, United States', programme: 'Exchange Student at Department of Electrical Engineering and Computer Science', dateStart: 'Jan 2017', dateEnd: 'May 2017', }, ] export const experiences: WorkExperience[] = [ { company: 'OKX', title: 'Engineer II', location: 'Hong Kong', dateStart: 'May 2022', dateEnd: null, descriptions: [ 'Develop account-related system using React, including user onboarding, OAuth connection & security settings', 'Mantain stable OAuth connection with other platforms e.g. TradingView', 'Integrate anti-bot protection to decrease MFA toll fraud', 'Introdce Passkey (FIDO), AppleId as alternative login/register methods', 'Ship top-priority tasks due to local changes in regulatory measures (UK, Turkey)', 'Review project specifications & design technology solutions that meet expectations', 'Refactor & convert legacy codebase to use TypeScript, resulting in increased code maintainability & reduction in bugs', 'Adopt server-side rendering (SSR), resulting in improved performance (core web vitals >70%), better SEO & UX', ], }, { company: 'Silverhorn Investment Advisors Ltd', title: 'Software Engineer', location: 'Hong Kong', dateStart: 'June 2021', dateEnd: 'Mar 2022', descriptions: [ 'Develop internal system that integrates with centralized data management using React & NestJS', 'Manage a team of 4-5 developers/interns', 'Cooperate with data management team to ensure proper integration & data security', 'Develop automated PDF statement generation', 'Applications planning, development, deployment', ], }, { company: 'Midland Realty', title: 'Analyst Programmer', location: 'Hong Kong', dateStart: 'June 2019', dateEnd: 'June 2021', descriptions: [ 'Migrate legacy Windows app to web for CRUD listings using React & NodeJS', 'Work closely with UI/UX designers to deliver quality IT solutions', 'Cooperate with vendor by combining both sides of projects', 'Involve in system/applications planning, development, deployment', ], }, { company: 'Right Tech Ltd', title: 'Programmer', location: 'Hong Kong', dateStart: 'June 2018', dateEnd: 'May 2019', descriptions: [ 'Develop an all-in-one portal for customers using React & NodeJS', 'Launch iOS & Android app for a restaurant that can read NFC using React Native', 'Expand Smart-packaging system to different industries with NFC', 'Develop Windows applications to connect NFC chips with Web App database using C#', 'Implement on-site & remote support to production line system', ], }, ] export const skills: Skills[] = [ { type: 'Frontend', items: [ 'React', 'Javascript', 'Typescript', 'CSS/Less', 'TailwindCSS', 'Mobx', 'Redux', 'React Native', 'Jest', ], highlights: [ 'Migrate from Javascript to Typescript', 'Server Side Rendering (SSR)', 'Web vital/SEO optimization', 'Maintain cocorporate npm packages', ], }, { type: 'Backend', items: ['NodeJS', 'ExpressJS', 'GraphQL', 'MongoDB'], highlights: [ // 'Design and build RESTful & GraphQL API using Nodejs framework', // 'Perform testing using Selenium for automation', ], }, { type: 'DevOps', items: ['Docker', 'Kong', 'Jenkins', 'GitLab Runner', 'AWS', 'Azure'], highlights: [ 'Deploy API gateway with OAuth2.0 using Kong', 'Manage services using Docker and Kubernetes', 'CI/CD tools: auto deploy changes using Jenkins, Github Actions, Gitlab Runner with the help of SCM', ], }, { type: 'Others', items: ['Solidity', 'Ether.js'], highlights: ['Launch a couple of NFT website including smart contract'], }, ] export const certificates: string[] = [ 'AWS Associate Certified Developer (Issued Jun 2021 · Expires Jun 2024)', ] export const spokenLanguages = 'Native in Cantonese, fluent in English & Mandarin' export const social = [ { website: 'LinkedIn', url: 'https://www.linkedin.com/in/calvinlee26/' }, { website: 'X', url: 'https://twitter.com/cally_dev/' }, { website: 'GitHub', url: 'https://github.com/callyberz/' }, ] export const todoList: TodoList[] = [ { actionItem: 'Find out problems in life/work', finished: false, }, { actionItem: 'Blogging using markdown', finished: true, }, { actionItem: 'Supabase', finished: true, }, { actionItem: 'Vercel AI SDK', finished: false, }, { actionItem: 'Ship 1st subscription-based project', finished: false, }, ] export const projects = [ { name: 'Mindful Exercises', description: 'A website that provides mindfulness exercises. (~HeadSpace)', url: '', github: 'https://github.com/callyberz/mindful', }, { name: 'YouTube Playback Speed Tracker', description: 'A Chrome extension that tracks your YouTube playback speed.', github: 'https://github.com/callyberz/speed-checker', }, { name: 'Education Centre All-in-one System', description: 'Easily manage students/courses/homework records for an education center with 3 branches and 300+ students enrolled.', }, { name: 'NFT minting website', description: 'Launched multiple of websites that allows users to mint NFTs.', }, { name: 'Real-time listings scraper', description: 'Actively monitor second-hand car listings based on specific criteria and send push notifications to Telegram. (testing purpose only)', }, { name: 'Custom ESLint rules', description: 'Use AST parser to define self-used ESLint rule for much better warning/error prompt', }, { name: 'Tree distribution in Hong Kong', description: 'Plot tree distribution for 18 districts in Hong Kong by D3js', }, ] export const highlights = [ 'Software Engineer', 'Web Development', 'Full-stack Development', 'ReactJS', 'TypeScript', 'JavaScript', 'NodeJS', ] export const summary = 'Experienced Software Engineer adept in TypeScript, shipping customer-centric solutions. 5+ years of expertise in web development & product enhancement. Seeking frontend/backend/full-stack roles to innovate.'
import { Component, OnInit, ViewChild, ElementRef} from '@angular/core'; import { Constants } from 'src/app/config/constants'; import { iItem, iFullItem } from 'src/app/models/items'; import { ItemsService } from 'src/app/services/items.service'; import { Router, ActivatedRoute } from '@angular/router'; import { Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged } from 'rxjs'; import { LoadingService } from 'src/app/services/loading.service'; import { HelpersService } from 'src/app/services/helpers.service'; import { MatDialog, MatDialogConfig } from "@angular/material/dialog"; import { DialogComponent } from '../../dialog/dialog.component'; import { iPageParams } from 'src/app/models/pageParams'; @Component({ selector: 'app-workspace-items', templateUrl: './workspace-items.component.html', styleUrls: ['./workspace-items.component.scss'] }) export class WorkspaceItemsComponent implements OnInit { constructor(private itemService: ItemsService, public constants: Constants, private router: Router, private route: ActivatedRoute, private el: ElementRef, public loadingService:LoadingService, public helpersService:HelpersService, private dialog: MatDialog) {} itemsPageParams:iPageParams = { sort: '', order: '', search: '', currentPage: 1, onPage: 50, totalPages: 1, totalCount: 0 } items = <iItem[]>[]; currentItem = <iFullItem>{}; editItemId = 0; newItem = 0; noticeMessage: string = ''; searchInput: string = ''; searchInputChanged: Subject<string> = new Subject<string>(); //новый товар addNewItem():void { this.newItem = 1; this.editItemId = 0; this.currentItemInit(); this.helpersService.routeParams(this.route, {'addNewItem': 1}); } //удаление товара deleteItem(delItemId:number):void { const dialogConfig = new MatDialogConfig(); dialogConfig.width = '350px'; dialogConfig.data = { description: 'Подтверждаете удаление товара?', title: 'Удаление' }; const dialogRef = this.dialog.open(DialogComponent, dialogConfig); dialogRef.afterClosed().subscribe((confirmed: boolean) => { if(confirmed){ this.itemService.deleteItemById(delItemId).subscribe({ next: (data:any) => { window.scrollTo(0, 0); if(this.helpersService.isCustomError(data)){ return; } this.noticeMessage = 'Товар удалён'; this.editItemId = 0; this.newItem = 0; this.getItemsList(1, false); this.helpersService.routeParams(this.route); } }) } }); } //закрытие формы редактирования/создания товара cancel():void { this.editItemId = 0; this.newItem = 0; this.helpersService.routeParams(this.route); } //загрузка фотографии onChange(event: any):void { this.clearErrors(); this.itemService.uploadFileToServer(event.target.files[0]).subscribe({ next: (data:any) => { if(this.helpersService.isCustomError(data)){ return; } this.currentItem.newPhotoList.push(data.files); this.el.nativeElement.querySelector('#iFile').value = ''; } }); } //удаление фото deleteImg(photo:string, type:string):void { if(type == 'current'){ this.currentItem.photoList = this.currentItem.photoList.filter(function(f:any) { return f !== photo }); return; } this.currentItem.newPhotoList = this.currentItem.newPhotoList.filter(function(f:any) { return f !== photo }); this.itemService.deleteTempPhoto(photo).subscribe({ next: (data:any) => { this.helpersService.isCustomError(data); } }); } //сохранение нового/редактируемого товара saveItem():void { this.clearErrors(); this.itemService.saveItem(this.currentItem).subscribe({ next: (data:any) => { window.scrollTo(0, 0); if(this.helpersService.isCustomError(data)){ return; } this.noticeMessage = 'Товар сохранён'; this.editItemId = 0; this.newItem = 0; this.helpersService.routeParams(this.route); this.getItemsList(1, false); } }); } //загрузка карточки товара для редактирования editItem(itemId:number):void { this.clearErrors(); this.itemService.getItemById(itemId).subscribe({ next: (data:any) => { window.scrollTo(0, 0); if(this.helpersService.isCustomError(data)){ return; } this.currentItem = data.item; if(this.currentItem.costs){ this.currentItem.costs = this.helpersService.price(this.currentItem.costs); } this.editItemId = this.currentItem.id; this.helpersService.routeParams(this.route, {'editItemId': this.editItemId}); } }) } //поля таблицы товаров tableFields:Array<any> = [ { title: 'Фото', sort: 'photoList', order: 'ASC', active: false, width: 5}, { title: 'Tип', sort: 'type', order: 'ASC', active: false, width: 10 }, { title: 'Артикул поставщика', sort: 'articul', order: 'ASC', active: false, width: 20}, { title: 'Бренд', sort: 'brand', order: 'ASC', active: false, width: 5 }, { title: 'Размер', sort: 'size', order: 'ASC', active: false, width: 5 }, { title: 'Наименование', sort: 'title', order: 'ASC', active: false, width: 20 }, { title: 'Артикул WB', sort: 'articulWB', order: 'ASC', active: false, width: 10 }, { title: 'chrt_id', sort: 'chrtId', order: 'ASC', active: false, width: 10 }, { title: 'Штрихкод', sort: 'barcode', order: 'ASC', active: false, width: 10 }, { title: 'Цена', sort: 'costs', order: 'ASC', active: false, width: 5 }, ]; //смена сортировки changeSort(sort:string):void { let order = 'ASC'; this.tableFields = this.tableFields.map((obj:any) => { if(obj.sort == sort){ if(obj.active && obj.order == 'ASC'){ order = 'DESC'; } return { ...obj, active: true, order: order }; } return { ...obj, active: false, order: order } }); this.itemsPageParams.sort = sort; this.itemsPageParams.order = order; this.getItemsList(); } //выбор страницы changePage(page:number, position = 'top'):void { this.helpersService.routeParams(this.route, {'page': page}); this.getItemsList(page); if(position == 'bottom'){ window.scrollTo(0, 0); } } //загрузка списка товаров getItemsList(page:number = 1, clear:boolean = true):void { if(clear){ this.clearErrors(); } this.itemsPageParams.currentPage = page; this.itemService.getItemsList(this.itemsPageParams).subscribe({ next: (data:any) => { this.items = data.items; this.items = this.items.map((obj:any) => { return {...obj, costs: this.helpersService.price(obj.costs) } }); this.itemsPageParams.totalPages = data.totalPages; this.itemsPageParams.totalCount = data.totalCount; } }) } //очистка текущего элемента currentItemInit():void { this.currentItem = { id: 0, articul: '', articulWb: '', title: '', shortTitle: '', brand: '', type: '', color: '', size: '', barcode: '', chrtId: 0, costs: 0, photo: '', photoList: [], newPhotoList: [],stickerSize: '', stickerContains: '', stickerManufacturer: '', stickerCountry: '', stickerAddress: ''}; } //очистка ошибок clearErrors():void{ this.helpersService.isCustomError(); this.noticeMessage = ''; } ngOnInit():void { this.currentItemInit(); if(!this.newItem && !this.editItemId){ this.changeSort('brand'); } //проверка гет параметров this.route.queryParams.subscribe((params:any) => { if(params.addNewItem){ this.newItem = 1; } if(params.editItemId){ this.editItemId = params.editItemId; this.editItem(this.editItemId); } if(params.page){ this.changePage(params.page); } } ); //поиск по товарам this.searchInputChanged.pipe( debounceTime(700), distinctUntilChanged() ).subscribe( searchText => { if(searchText.length >= 2){ this.itemsPageParams.search = searchText; } else{ this.itemsPageParams.search = ''; } this.getItemsList(); } ); } }
# TYPE SYSTEM # Int, Float, String, Boolean, ID type Pizza{ id: Int! name: String! origin: String ingredients: [Ingredient] # creado el 14-01-2020 } # ININCIO CREADO EL 14-01-2020 type Ingredient{ id: Int! name: String! calories: String } # FIN CREADO EL 14-01-2020 # INICIO CREADO EL 20-01-2020 input PizzaInput{ name: String! origin: String ingredientIds: [Int] #estoy enviando arreglo de enteros, en este caso el id } input UpdatePizzaInput{ id: Int! name: String! origin: String ingredientIds: [Int] } # Mutation type Mutation{ createPizza (pizza: PizzaInput): Pizza updatePizza (pizza: UpdatePizzaInput): Pizza deletePizza (id:Int): Pizza } # FIN CREADO EL 20-01-2020 # Definir el Schema type Query{ pizzas (name: String): [Pizza] pizzaId (id: Int): [Pizza] }
import { Filter } from '@nestjs-query/core' import { UseInterceptors } from '@nestjs/common' import { Args, Context, Int, Mutation, Query, Resolver } from '@nestjs/graphql' import { DiscountManufacturerFilterArgs, DiscountManufacturerInputType, CreateDiscountManufacturerInput, DeleteDiscountManufacturerInput, UpdateDiscountManufacturerInput } from '@vg/api-gateway/modules/discountManufacturer/dto/discountManufacturer.args' import { DiscountManufacturerDto } from '@vg/api-gateway/modules/discountManufacturer/dto/discountManufacturer.dto' import { HookInterceptor } from '@vg/common/interceptors/hook.interceptor' import { GqlContext } from '@vg/core' import { setRpcContext } from '@vg/core/helpers/set-grpc-context.helpers' import { AuthorizerFilter, AuthorizerInterceptor, HookTypes, MutationHookArgs, OperationGroup } from '@vg/query-graphql' import { BaseUniqueFilterArgs } from '@vg/repository/dtos/base-arg.dto' import { Public, Resource } from 'nest-keycloak-connect' @Resolver(() => DiscountManufacturerDto) @Resource('DiscountManufacturer') @UseInterceptors(AuthorizerInterceptor(DiscountManufacturerDto)) export class DiscountManufacturerResolver { @Query(() => DiscountManufacturerDto, { nullable: true }) @Public() async discountManufacturer( @Context() context: GqlContext, @Args() args: BaseUniqueFilterArgs, @AuthorizerFilter({ operationGroup: OperationGroup.READ, many: false }) authFilter: Filter<DiscountManufacturerDto> ): Promise<DiscountManufacturerDto> { const grpcContext = setRpcContext(context) const result = await context.rpc.discount.svc .discountManufacturer( { id: args.id }, grpcContext ) .toPromise() return result.data } @Query(() => [DiscountManufacturerDto]) @Public() async discountManufacturers( @Context() context: GqlContext, @Args() args: DiscountManufacturerFilterArgs ): Promise<DiscountManufacturerDto[]> { const grpcContext = setRpcContext(context) const categories = await context.rpc.discount.svc .discountManufacturers( { filter: args?.filter ? JSON.stringify(args.filter) : null, // @ts-ignore paging: args?.paging, // @ts-ignore sorting: args?.sorting }, grpcContext ) .toPromise() return categories.discountManufacturers ?? [] } @Query(() => Int) @Public() async discountManufacturersTotal( @Context() context: GqlContext, @Args() args: DiscountManufacturerFilterArgs ): Promise<number> { const grpcContext = setRpcContext(context) const result = await context.rpc.discount.svc .discountManufacturersTotal( { filter: args?.filter ? JSON.stringify(args.filter) : null, paging: undefined, sorting: undefined }, grpcContext ) .toPromise() return result.totalCount ?? 0 } @Public() @Mutation(() => DiscountManufacturerDto, { nullable: true }) @UseInterceptors( HookInterceptor(HookTypes.BEFORE_CREATE_ONE, DiscountManufacturerInputType) ) async createDiscountManufacturer( @Context() context: GqlContext, @MutationHookArgs() { input }: CreateDiscountManufacturerInput ): Promise<DiscountManufacturerDto> { const grpcContext = setRpcContext(context) return await context.rpc.discount.svc // @ts-ignore .createDiscountManufacturer( // @ts-ignore { data: input?.discountManufacturer }, grpcContext ) .toPromise() } @Mutation(() => DiscountManufacturerDto, { nullable: true }) @Public() async updateDiscountManufacturer( @Context() context: GqlContext, @Args() { input }: UpdateDiscountManufacturerInput ): Promise<DiscountManufacturerDto> { const grpcContext = setRpcContext(context) return await context.rpc.discount.svc .updateDiscountManufacturer( { // @ts-ignore id: input.id, // @ts-ignore data: input.update }, grpcContext ) .toPromise() } @Mutation(() => DiscountManufacturerDto, { nullable: true }) @Public() async deleteDiscountManufacturer( @Context() context: GqlContext, @Args() { input }: DeleteDiscountManufacturerInput ): Promise<DiscountManufacturerDto> { const grpcContext = setRpcContext(context) return await context.rpc.discount.svc .deleteDiscountManufacturer( { // @ts-ignore id: input.id }, grpcContext ) .toPromise() } }
<?php require 'token_generator.php'; require 'priaid_client.php'; class Demo { private $config; private $diagnosisClient; function __construct() { $this->config = parse_ini_file("config.ini"); } private function checkRequiredParameters() { $pass = true; if (!isset($this->config['username'])) { $pass = false; print "You didn't set username in config.ini"; } if (!isset($this->config['password'])) { $pass = false; print "You didn't set password in config.ini"; } if (!isset($this->config['authServiceUrl'])) { $pass = false; print "You didn't set authServiceUrl in config.ini"; } if (!isset($this->config['healthServiceUrl'])) { $pass = false; print "You didn't set healthserviceUrl in config.ini"; } return $pass; } public function simulate() { if (!$this->checkRequiredParameters()) return; $tokenGenerator = new TokenGenerator($this->config['username'], $this->config['password'], $this->config['authServiceUrl']); $token = $tokenGenerator->loadToken(); if (!isset($token)) exit(); $this->diagnosisClient = new DiagnosisClient($token, $this->config['healthServiceUrl'], 'en-gb'); $bodyLocations = $this->diagnosisClient->loadBodyLocations(); if (!isset($bodyLocations)) exit(); $this->printSimpleObject($bodyLocations); } private function printSimpleObject($object) { array_map(function ($var) { echo "<br><input type='radio' value='", $var['ID'], "' name='body_loc'> ", $var['Name'], "<br>"; }, $object); } } $demo = new Demo(); $demo->simulate(); ?>
import {createAsyncThunk, createSlice} from '@reduxjs/toolkit'; import * as apiInterface from '../apiInterface'; import { NotificationData, NotificationResponse } from './NotificationResponse'; export type NotifListState = { notification: NotificationResponse | null; loadingNotifications: boolean; notificationError: boolean; }; const initialState: NotifListState = { notification: null, loadingNotifications: false, notificationError: false, }; export const fetchNotifications = createAsyncThunk< {notification: NotificationResponse | null}, {requestBody: any, uri: any} >('fetchNotifications', async ({requestBody, uri}) => { const response = await apiInterface.fetchNotifications(requestBody, uri); if (response.kind == 'success') { return { notification: response.body ?? null, }; } else { throw 'Error fetching customers'; } }); const GetNotificationSlice = createSlice({ name: 'GetNotification', initialState: initialState, reducers: {}, extraReducers: builder => { builder .addCase(fetchNotifications.pending, state => { state.loadingNotifications = true; state.notificationError = false; state.notification = initialState.notification; }) .addCase(fetchNotifications.fulfilled, (state, action) => { state.notification = initialState.notification; state.notification = action.payload.notification; state.notificationError = false; state.loadingNotifications = false; }) .addCase(fetchNotifications.rejected, state => { state.notificationError = true; state.loadingNotifications = false; state.notification = initialState.notification; }); }, }); export default GetNotificationSlice.reducer;
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN" "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd" [ <!ENTITY GRAM "GRAM5" > <!ENTITY % xinclude SYSTEM "../../xinclude.mod"> %xinclude; ]> <section> <title>Configuration File</title> <para> For the fake LRM, there's not much to configure: a path to a file where the LRM should write its job files. For real LRMs, there are other things which might belong there: paths to LRM-specific executables such as <command>qsub</command>, tuning parameters fo the LRM adapter script such as the number of available cores per execution node, or the host to contact when using a remote submit protocol between GRAM the the LRM. The configuation parameters used by the LRM adapters included in &GRAM; are described in <olink targetdoc="gram5Admin" targetptr="gram5-configuring-lrm"/>. </para> <para> The LRM adapter configuration files consist of attribute="value" pairs, which comment lines beginning with the <literal>#</literal> character. For the example fake LRM, the configuration file looks like this: <programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="globus-fake.conf" parse="text"/></programlisting> </para> <section> <title>Parsing the Configuration File</title> <para>The Globus Toolkit contains API functions for parsing files in the format used by the LRM configuration files. In Perl, use the <classname>Globus::Core::Config</classname> class. In C/C++, use the <function>globus_common_get_attribute_from_config_file()</function> function. </para> <section> <title>Perl API</title> <para>The <classname>Globus::Core::Config</classname> API is quite simple. The <function>new()</function> constructor parses the configuration file and returns an object containing the attribute=value pairs. The <function>get_attribute()</function> method returns the value of the named attribute. These functions are used in <olink targetptr="gram5-LRM-Adapter-Perl-Config">the fake LRM Perl Module</olink>. </para> </section> <!-- Perl API --> <section> <title>C/C++ API</title> <para>The <function>globus_common_get_attribute_from_config_file()</function> function will load the configuration file and return the value of the attribute passed to it. This function is ued in the SEG module below. Note that this function returns a pointer to a copy of the string value in the location pointed to by the <parameter>value</parameter> parameter. The caller must free this value. </para> </section> <!-- C/C++ API --> </section> <!-- Parsing the Configuration File --> </section> <!-- LRM Adapter Configuration File -->
package IVIRadio.AdditionalService import IVIRadio.AdditionalService.AdditionalServiceTypes.* from "AdditionalService.fidl" import IVIRadio.Types.Types.* from "Types.fidl" import IVIRadio.AdditionalService.AdditionalServiceTypesOptions.* from "AdditionalService.fidl" <** @description : Tuner generic and project independent interface for additional services. This interface provides functions to request data services and to configure them. Other services like announcements can also be configured. @author : EGMG_Tuner **> interface AdditionalService { version { major 2 minor 0 } <** @description : Function to request data from one or many stations for a specific data service. It is possible to configure the request by the DataServiceOption parameter. **> method requestDataService { in { <** @description : Parameter selects the requested data service. **> AdditionalServiceTypes.DataService dataService <** @description : Parameter is a list of stations for which the data is requested. **> StationSelectors selectors <** @description : Parameter for unified options **> AdditionalServiceTypesOptions.UnifiedServiceOption unifiedOptions <** @description : Parameter to configure the requested data service **> AdditionalServiceTypesOptions.DataServiceOption serviceOptions <** @description : An optional handle for identifying the request. **> UInt32 handle } out { <** @description : The handle of the corresponding request. **> UInt32 handleOut <** @description : The result of the request. **> Feedback feedback } } method requestSubscribedServiceOptions { in { <** @description : For which data service are the options requested **> AdditionalServiceTypes.DataService dataservice <** @description : An optional handle for identifying the request **> UInt32 handle } out { <** @description : The handle of the corresponding request **> UInt32 handleOut <** @description : The result of the request **> Feedback feedback } } <** @description : abort a currently active transmission of data **> method abort { in { <** @description : data service a current transmission of data want to be stopeed for **> AdditionalServiceTypes.DataService dataService <** @description : array of station selectors which are providing the currently transmitted data **> StationSelectors stationSelectors <** @description : unified options describing the request **> AdditionalServiceTypesOptions.UnifiedServiceOption unifiedOptions <** @description : specific parameter describing the data request **> AdditionalServiceTypesOptions.DataServiceOption dataServiceOption <** @description : An optional handle for identifying the request. **> UInt32 handle } out { <** @description : The handle of the corresponding request. **> UInt32 handleOut <** @description : The result of the request. **> Feedback feedback } } <** @description : Broadcast to return the requested data **> broadcast Data { out { <** @description : Parameter for which stations the data is responsed **> StationSelectors stationSelectors <** @description : Parameter for which data service the data was requested **> AdditionalServiceTypes.DataService dataService <** @description : Parameters to identify the request **> AdditionalServiceTypesOptions.UnifiedServiceOption unifiedOptions <** @description : Parameters to identify the request **> AdditionalServiceTypesOptions.DataServiceOption selectOptions <** @description : Parameter describs the return format **> AdditionalServiceTypes.DataFormat format <** @description : Parameter describs the return type. **> AdditionalServiceTypes.DataType type <** @description : Parameter is a specific struct depending which data is responsed. **> AdditionalServiceTypes.Data data <** @description : The handle of the corresponding selectComponent request **> UInt32 handleOut <** @description : Execution state of the job. if successful finished EC_OK **> ErrorCodes errorCode } } <** @description : Broadcast to provide information about the currently incoming announcement **> broadcast Announcement { out { <** @description : list of station selectors for that the announcements were configured **> StationSelectors stationSelectors <** @description : configuratios of the announcement configured in the request **> AdditionalServiceTypes.AnnouncementConfigurations announcementConfigurations <** @description : states of the announcement configured in that request **> AdditionalServiceTypes.arrayAnnouncementStates announcementStates <** @description : handle to identify the correct destination of a announcement broadcast **> UInt32 handleOut <** @description : execution state of the job. if successful finished EC_OK **> ErrorCodes errorCode } } <** @description : Broadcast to signalize that the announcement is finished **> broadcast AnnouncementFinished { out { <** @description : information describing the finishing announcement **> AdditionalServiceTypes.Announcement announcement <** @description : handle to identify the destination of the broadcast **> UInt32 handleOut <** @description : execution state of the job. if successful finished EC_OK **> ErrorCodes errorCode } } <** @description : Broadcast to return the subscribed service options **> broadcast SubscribedServiceOptions { out { <** @description : The data service for the request **> AdditionalServiceTypes.DataService dataService <** @description : Array contains arrays of station selectors for which the data service options of the matching array ServiceOptions are valid **> arrayStationSelectors stationSelectors <** @description : Configurations matching to station selectors of the arrayStationSelectors **> AdditionalServiceTypesOptions.UnifiedServiceOptions unifiedOptions <** @description : Configurations matching to station selectors of the arrayStationSelectors **> AdditionalServiceTypesOptions.DataServiceOptions selectOptions <** @description : The handle of the corresponding selectComponent request **> UInt32 handleOut <** @description : execution state of the job. if successful finished EC_OK **> ErrorCodes errorCode } } } <** @author : MGEG_Tuner **> typeCollection AdditionalServiceTypesOptions { version { major 2 minor 0 } <** @description : Structure for options which are selectable for all data services **> struct UnifiedServiceOption { <** @description : Request type **> UpdateType requestType <** @description : Object ID. **> UInt32 objectID } array UnifiedServiceOptions of UnifiedServiceOption <** @description : Array for data service options **> array DataServiceOptions of DataServiceOption <** @description : Union for the selection of a data service. Depending on the data service another structure is used. **> union DataServiceOption { <** @description : Parameter for default type if no specific options are available **> No_Options DSO_NO_OPTION <** @description : Parameter for subtitle options. **> Subtitle_Options DSO_SUBTITLE <** @description : Parameter for teletext options. **> Teletext_Options DSO_TELETEXT <** @description : Parameter for EPG options **> EPG_Options DSO_EPG <** @description : Parameter for journaline options. **> Journaline_Options DSO_JOURNALINE <** @description : Parameter for Announcement options. **> Announcement_Options DSO_ANNOUNCEMENT <** @description : Parameter for EWS options. **> EWS_Options DSO_EWS <** @description : parameter for image options **> Image_Options DSO_IMAGE } <** @description : image options **> struct Image_Options { <** @description : describes the image type of the transmitted image **> AdditionalServiceTypes.ImageType imageType <** @description : describes the data service of the transmitted servcie **> AdditionalServiceTypes.ImageService imageService <** @description : describes the width of the requested image **> UInt32 width <** @description : type describes the height **> UInt32 heigth } <** @description : Default options **> struct No_Options { } <** @description : Journaline options **> struct Journaline_Options { <** @description : Entry object is requested **> Boolean Entry_Object } <** @description : Subtitle options **> struct Subtitle_Options { <** @description : Possible/requested languages **> AdditionalServiceTypes.Languages Languages } <** @description : Teletext options **> struct Teletext_Options { <** @description : Entry object is requested **> Boolean Entry_Page <** @description : Sub page with number x is requested **> UInt32 Sub_Page } <** @description : EWS options **> struct EWS_Options { <** @description : Type of the emergency warning. **> AdditionalServiceTypes.EWSType Type <** @description : Affected area of the emergency warning. **> AdditionalServiceTypes.EWSAffectedArea Affected_Area } <** @description : EPG options **> struct EPG_Options { <** @description : Start time to filter the epg data packet that is requested **> DateTime Start_Date_Time <** @description : End time to filter the returned epg data **> DateTime End_Date_Time <** @description : Genre to filter the returned epg data **> String Genre <** @description : Count of events which are requested from a start time **> UInt32 Count_Events } <** @description : Options for announcements **> struct Announcement_Options { <** @description : Announcement configuration **> AdditionalServiceTypes.AnnouncementConfigurations Type_Configurations } } <** @author : MGEG_Tuner **> typeCollection AdditionalServiceTypes { version { major 2 minor 0 } enumeration AnnouncementState { <** @description : describes if the notified announcement is available **> NotAvailable Available Active } <** @description : array of announcement states **> array AnnouncementStates of AnnouncementState array arrayAnnouncementStates of AnnouncementStates <** @description : Union for the return value of the data broadcast. **> union Data { <** @description : Data is returned as string (link). **> String stringData <** @description : Data is returned as bytebuffer. **> ByteBuffer byteBufferData } <** @description : Enumeration for the data return formats. **> enumeration DataFormat { <** @description : Format XML **> DF_XML <** @description : Format HTML **> DF_HTML <** @description : Format picture **> DF_PICTURE <** @description : Format binary (RAW) **> DF_RAW } <** @description : Enumeration for the data return types. **> enumeration DataType { <** @description : Data type string. **> DT_STRING <** @description : Data type stream. **> DT_STREAM <** @description : Data type byte buffer. **> DT_BYTEBUFFER } <** @description : Affected area of the emergency warning. **> enumeration EWSAffectedArea { EAA_UNKNOWN EAA_NATIONALWIDE EAA_WIDEAREA EAA_REGION EAA_LOCAL EAA_POINT } <** @description : Type of the emergency warning. **> enumeration EWSType { ET_UNKNOWN ET_EMERGENCY_WARNING ET_EARTHQUAKE_WARNING ET_TIDAL_WAVE_WARNING ET_WEATHER_WARNING ET_ROAD_TRAFFIC ET_PERSONAL_CALL ET_EVENT_ANNOUNCEMENT ET_CAS_SERVICE_MESSAGE ET_TEST_SIGNAL } <** @description : enumeration for different image types **> enumeration ImageService { <** @description : type signalizes a categorized slideshow image **> IS_CATEGORIZED_SLIDESHOW <** @description : type signalizes a slideshow image **> IS_SLIDESHOW <** @description : type signalizes an album cover image **> IS_ALBUM_COVER <** @description : type signalizes a station logo image **> IS_STATION_LOGO } enumeration ImageType { <** @description : image type indicates a front view of the booklet **> IT_BOOKLET_FRONT <** @description : image type indicates a back view of the booklet **> IT_BOOKLET_BACK <** @description : image type indicates a view of the interpret **> IT_INTERPRET } <** @description : Struct for languages **> struct Language { String Name } <** @description : Array of languages **> array Languages of Language <** @description : Enumeration for data services. **> enumeration DataService { <** @description : No specific type, should cause an error. **> DS_NO_SERVICE <** @description : <font color="#0f0f0f">Subtitle service</font> **> DS_SUBTITLE <** @description : Teletext service. **> DS_TELETEXT <** @description : EPG service. **> DS_EPG <** @description : image service **> DS_IMAGE <** @description : TMC service. **> DS_TMC <** @description : TPEG service. **> DS_TPEG <** @description : Journaline service. **> DS_JOURNALINE <** @description : Announcement service. **> DS_ANNOUNCEMENT <** @description : EWS service **> DS_EWS } <** @description : Enumeration of announcement types. **> enumeration AnnouncementType { <** @description : Alarm announcement **> AT_ALARM <** @description : Road traffic announcement **> AT_ROAD_TRAFFIC <** @description : Transport flash announcement **> AT_TRANSPORT_FLASH <** @description : warning service announcement **> AT_WARNING_SERVICE <** @description : News announcement **> AT_NEWS <** @description : Area weather announcement **> AT_AREA_WEATHER <** @description : Event announcement **> AT_EVENT <** @description : Special event announcement **> AT_SEPECIAL_EVENT <** @description : Program information announcement **> AT_PROGRAM_INFORMATION <** @description : Sport announcement **> AT_SPORT_REPORT <** @description : Financial report announcement **> AT_FINANCIAL_REPORT } <** @description : Structure for the current announcement with information about channel and type. **> struct Announcement { <** @description : Station which provides the announcement. **> StationSelector stationSelector <** @description : information about the announcement type. **> AnnouncementType type } <** @description : Structure for announcement types. For every type of announcement the availability is given. The user can activate or deactivate each type and he can change the priorities for every type **> struct AnnouncementConfiguration { <** @description : announcement types. **> AnnouncementType type <** @description : activation of announcement type **> Activation active <** @description : priority for the type. **> UInt32 priority } <** @description : Array type for announcement configuration **> array AnnouncementConfigurations of AnnouncementConfiguration }
import React, { useEffect, useState, useContext } from 'react' import styles from "./NewForum.module.scss" import { Navigate } from 'react-router-dom'; import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css"; import { UserContext } from '../../../../../utils/Context/UserContext/UserContext'; import axios from 'axios'; import TextField from '@mui/material/TextField'; import Button from '@mui/material/Button'; const NewForum = ({ handleOpenAlert, changeAlertValues }) => { const {user, ready, cookies} = useContext(UserContext); const [forum, setForum] = useState({ title: '', description: '', author: '', }) const [idForum, setIdForum] = useState(null); const [forumPosted, setForumPosted] = useState(false); useEffect(() => { setForum(prev => ({...prev, author: user?._id})) }, [user]) if(ready === "yes") { if(!user){ handleOpenAlert() changeAlertValues("error", "Vous n'êtes pas connecté") return <Navigate replace to="/"/> } } const handleAddForum = () => { try { if(forum.title === '' || forum.description === '') { handleOpenAlert() changeAlertValues('warning', "Il manque des informations pour ajouter le forum") } else { axios .post('/forum', forum, {headers: {jwt: cookies.token}}) .then((res) => setIdForum(res.data._id)) .then(() => handleOpenAlert()) .then(() => changeAlertValues('success', 'Article ajouté')) .then(() => {setForumPosted(true)}) .catch((e) => changeAlertValues('error', e)) } } catch (err) { //handleOpenAlert() //changeAlertValues('error', err) console.log(err) } } return ( <> {forumPosted ? <Navigate to={`/forum`} /> : <></>} <div className={styles.container}> <div className={styles.wrapper}> <h2>Ajouter un forum</h2> <div className={styles.preview}> <TextField required label="Titre du forum" sx={{width: '100%'}} value={forum.title} onChange={e => setForum(prevValues => ({...prevValues, title: e.target.value}) )} /> </div> <div className={styles.preview}> <TextField required label="Description du forum" sx={{width: '100%'}} value={forum.description} onChange={e => setForum(prevValues => ({...prevValues, description: e.target.value}) )} /> </div> <div className={styles.button_submit}> <Button variant="contained" color='primary' onClick={handleAddForum}>Ajouter le forum</Button> </div> </div> </div> </> ) } export default NewForum;
import { ErrorLongitudInvalida } from 'src/dominio/errores/error-longitud-invalida'; import { ErrorTipoIncorrecto } from 'src/dominio/errores/error-tipo-incorrecto'; import { ErrorValorRequerido } from 'src/dominio/errores/error-valor-requerido'; const NUMERO_MINIMO_CARACTERES_CLAVE = 4; const TIPO: string[] = ['ADMIN', 'CLIENTE']; export class Usuario { readonly #nombre: string; readonly #clave: string; readonly #tipo: string; constructor(nombre: string, clave: string, tipo: string) { this.validarCampo(nombre, 'Nombre'); this.validarTamanoClave(clave); this.validarTipoUsuario(tipo); this.#nombre = nombre; this.#clave = clave; this.#tipo = tipo; } private validarTamanoClave(clave: string) { this.validarCampo(clave, 'Clave'); if (clave.length < NUMERO_MINIMO_CARACTERES_CLAVE) { throw new ErrorLongitudInvalida( `El tamaño mínimo de la clave debe ser ${NUMERO_MINIMO_CARACTERES_CLAVE}`, ); } } private validarCampo(campoAValidar: string, nombreCampo: string) { if (!campoAValidar) { throw new ErrorValorRequerido( `El campo ${nombreCampo} esta vacio, es requerido`, ); } } private validarTipoUsuario(tipo: string) { if (!TIPO.includes(tipo)) { throw new ErrorTipoIncorrecto( `El tipo de Usuario debe ser: ${TIPO.toString()}.`, ); } } get nombre(): string { return this.#nombre; } get clave(): string { return this.#clave; } get tipo(): string { return this.#tipo; } }
import React from "react"; import style from "./style.module.css"; import Table from "react-bootstrap/Table"; import { useSelector, useDispatch } from "react-redux"; import {remove} from '../../redux/features/cartSlice' import ClearIcon from '@mui/icons-material/Clear'; import { IconButton } from "@mui/material"; const Cart = () => { const {cart} = useSelector((state) => state); const dispatch = useDispatch() console.log("cart page: ",cart); function handleClick(id){ dispatch(remove(id)) console.log(clicked) } return ( <div className={style.container}> <Table striped bordered hover size="sm"> <thead> <tr> <th>Image</th> <th>Product Title</th> <th>Price</th> <th>Action</th> </tr> </thead> <tbody> {cart.length==0 ? <p className="text-center text-info mt-4">Cart is empty! Please add products to cart</p> : cart.map((product) => { return ( <tr key={product.id}> <td><img src={product.image} alt={product.title} width='50px' height='auto'/></td> <td>{product.title}</td> <td>{product.price}</td> <td> <IconButton color="error" onClick={()=>handleClick(product.id)}><ClearIcon /></IconButton> </td> </tr> ); })} </tbody> </Table> </div> ); }; export default Cart;
import { connect } from "react-redux"; import { useEffect, useState } from "react"; import { check_autenticated, load_user, reset_password_confirm, refresh, } from "redux/actions/auth/auth"; import "styles/home.css"; import { Navigate, useNavigate, useParams } from "react-router-dom"; import { HomeImg, Logo } from "components/img/Images"; const ResetPasswordConfirm = ({ reset_password_confirm, isAuthenticated, loading, check_autenticated, refresh, load_user, }) => { const params = useParams(); const uid = params.uid; const token = params.token; useEffect(() => { isAuthenticated ? ( <></> ) : ( <> {check_autenticated()} {refresh()} {load_user()} </> ); }, [isAuthenticated, check_autenticated, refresh, load_user]); const [formData, setFormData] = useState({ new_password: "", re_new_password: "", }); const { new_password, re_new_password } = formData; const onChange = (e) => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmit = (e) => { e.preventDefault(); reset_password_confirm(uid, token, new_password, re_new_password); navigate("/"); }; const navigate = useNavigate(); if (isAuthenticated) { return <Navigate to="/Dashboard" />; } return ( <div style={{ backgroundImage: `url(${HomeImg})` }} className=" w-screen bg-cover bg-center h-screen flex justify-center items-center "> <div className=" w-96 h-[450px] bg-transparent border rounded-lg border-gray-600 flex flex-col justify-center px-6 py-12 lg:px-8"> <div className="sm:mx-auto sm:w-full sm:max-w-sm"> <img className="mx-auto h-24 w-auto" src={Logo} alt="Your Company" /> </div> <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm"> <form onSubmit={(e) => { onSubmit(e); }} className="space-y-6 content__form" action="#" method="POST"> <div className="content__inputs"> <label> <input id="new_password" name="new_password" type="password" value={new_password} onChange={(e) => onChange(e)} required className="rounded-md h-9" /> <span>New Password</span> </label> <label> <input id="re_new_password" name="re_new_password" type="password" value={re_new_password} onChange={(e) => onChange(e)} required className="rounded-md h-9" /> <span>Repeat New Password</span> </label> </div> <div> <button type="submit" className="bg-gradient-to-br from-purple-400 to-yellow-400 w-full text-black px-2 py-1.5 font-bold rounded-md hover:opacity-80"> Change Password </button> </div> </form> </div> </div> </div> ); }; const mapStateToProps = (state) => ({ isAuthenticated: state.auth.isAuthenticated, loading: state.auth.loading, }); export default connect(mapStateToProps, { reset_password_confirm, check_autenticated, refresh, load_user, })(ResetPasswordConfirm);
import React from 'react' import ReactDOM from 'react-dom/client' import App from './App.tsx' import './index.css' import { createBrowserRouter, Navigate, RouterProvider } from 'react-router-dom'; import Login from './routes/Login/index.tsx'; import Error from './routes/Error/index.tsx'; import AuthContextProvider from './context/AuthContext.tsx'; import Cashier from './routes/MainMenuOutlet/Cashier'; import Client from './routes/MainMenuOutlet/Client'; import Employee from './routes/MainMenuOutlet/Employee'; import Product from './routes/MainMenuOutlet/Product'; import Report from './routes/MainMenuOutlet/Report'; import CreateClient from './routes/MainMenuOutlet/CreateClient/index.tsx'; const browserRouter = createBrowserRouter([ { path: '/login', element: <Login />, }, { path: '/', element: <App />, errorElement: <Error />, children: [ { path: '/', element: <Navigate to="/caixa" />, }, { path: '/caixa', element: <Cashier />, }, { path: '/cliente', children: [ { index: true, element: <Client />, }, { path: 'criar', element: <CreateClient />, }, ], }, { path: '/funcionario', children: [ { index: true, element: <Employee />, }, ], }, { path: '/produto', children: [ { index: true, element: <Product />, }, ], }, { path: '/relatorio', children: [ { index: true, element: <Report />, }, ], } ] }, ]); ReactDOM.createRoot(document.getElementById('root')!).render( // <React.StrictMode> <AuthContextProvider> <RouterProvider router={browserRouter} /> </AuthContextProvider> // </React.StrictMode>, )