text
stringlengths
184
4.48M
#!/usr/bin/python3 """Defines a class Rectangle that inherits from BaseGeometry""" BaseGeometry = __import__('7-base_geometry').BaseGeometry class Rectangle(BaseGeometry): """Represents Rectangle class""" def __init__(self, width, height): """Initializes the object attributes""" super().integer_validator("width", width) self.__width = width super().integer_validator("height", height) self.__height = height def area(self): """Returns an area of a rectangle""" return self.__width * self.__height def __str__(self): """Returns a string representation of an object""" return "[Rectangle] {}/{}".format(self.__width, self.__height)
import React from 'react'; import { FeaturedMovie } from '@/components/featured-movie'; import { Categories } from '@/components/categories'; import Movies from '@/mocks/movies'; import Genres from '@/mocks/genres'; import { MoviesSection } from '@/components/movies-section'; function HomeContainer({ selectedCategory }) { return ( <div> <FeaturedMovie movie={Movies.results[0]}></FeaturedMovie> <Categories categories={Genres.genres.slice(0, 5)}></Categories> {selectedCategory.movies.length > 0 && ( <MoviesSection title={selectedCategory.title} movies={selectedCategory.movies} /> )} <MoviesSection title="Popular Films" movies={Movies.results.slice(1, 7)} /> <MoviesSection title="Your favorites" movies={Movies.results.slice(7, 13)} /> </div> ); } export default HomeContainer;
# FraudShield: Anomaly Detection Pipeline [![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Python Version](https://img.shields.io/badge/Python-3.10%2B-blue.svg)](https://www.python.org/downloads/) [![Build Status](https://img.shields.io/travis/muditbhargava66/FraudShield.svg)](https://travis-ci.org/muditbhargava66/FraudShield) [![Coverage Status](https://img.shields.io/coveralls/github/muditbhargava66/FraudShield.svg)](https://coveralls.io/github/muditbhargava66/FraudShield) FraudShield is an advanced anomaly detection pipeline designed to identify and prevent fraudulent activities within large datasets. By leveraging cutting-edge machine learning techniques, FraudShield ensures the integrity and security of financial transactions. ## Key Features - Ingestion of large-scale transaction data from various sources - Data cleaning and preprocessing using pandas and scikit-learn - Advanced feature engineering techniques to extract relevant fraud indicators - Training and evaluation of state-of-the-art machine learning models (Random Forest, XGBoost) - Comprehensive model evaluation using multiple metrics (accuracy, precision, recall, F1 score, AUC) - Seamless integration with SQL databases for data storage and retrieval - Modular and scalable architecture for easy maintenance and extension - Robust monitoring and alerting mechanisms for real-time fraud detection - User-friendly interfaces for data exploration, model training, and results interpretation ## Installation 1. Clone the repository: ``` git clone https://github.com/muditbhargava66/FraudShield.git cd FraudShield ``` 2. Install the required dependencies: ``` pip install -r requirements.txt ``` 3. Set up the SQL database: - Create a new database for FraudShield. - Update the database connection details in the configuration file (`conf/database.ini`). - Run the SQL scripts in the `src/sql` directory to create the required tables and indexes. 4. Configure Apache Airflow: - Set up Airflow by following the official documentation: [Apache Airflow Documentation](https://airflow.apache.org/docs/apache-airflow/stable/start.html) - Update the Airflow configuration file (`airflow.cfg`) with the required settings. - Initialize the Airflow database and create an admin user. 5. Compile the C++ modules: ``` cd src/data_cleaning g++ -O3 -o data_cleaning data_cleaning.cpp cd ../feature_engineering g++ -O3 -o feature_engineering feature_engineering.cpp ``` ## Usage ### Part 1 1. Run the data ingestion script: ``` python src/data_ingestion/data_ingestion.py ``` 2. Run the data preprocessing script: ``` python src/data_preprocessing/data_preprocessing.py --input_data /path/to/ingested_data.csv --train_data /path/to/preprocessed_data.npy --test_data /path/to/test_data.npy ``` 3. Train the machine learning models: ``` python src/model_training/train_models.py --preprocessed_data /path/to/preprocessed_data.npy --output_dir /path/to/models/ ``` 4. Evaluate the trained models: ``` python src/model_evaluation/evaluation.py --model_path /path/to/trained_model.pkl --test_data /path/to/test_data.npy --output_path /path/to/evaluation_report.csv ``` ### Part 2 1. Start the Airflow webserver and scheduler: ``` airflow webserver --port 8080 airflow scheduler ``` 2. Access the Airflow web interface by navigating to `http://localhost:8080` in your web browser. 3. Enable the FraudShield DAG (Directed Acyclic Graph) in the Airflow web interface. 4. Trigger the DAG manually or wait for the scheduled run according to the configured schedule interval. 5. Monitor the pipeline execution in the Airflow web interface and check the logs for any errors or issues. ## Configuration The FraudShield pipeline can be configured using the following files: - `conf/database.ini`: Database connection settings. - `conf/airflow.cfg`: Airflow configuration settings. - `conf/pipeline.yaml`: Pipeline parameters and settings. Modify these configuration files according to your specific requirements and environment setup. ## Documentation Detailed documentation for FraudShield can be found in the `docs` directory: - `docs/project_overview.md`: High-level overview of the FraudShield project. - `docs/data_dictionary.md`: Description of the data fields and their characteristics. - `docs/model_architecture.md`: Explanation of the machine learning models used in FraudShield. - `docs/cpp_modules.md`: Documentation for the C++ modules used for data cleaning and feature engineering. - `docs/sql_schema.md`: Description of the SQL database schema and data retrieval process. - `docs/setup_instructions.md`: Step-by-step instructions for setting up FraudShield. ## Model Evaluation Results The trained models were evaluated on a separate test dataset using various performance metrics. Here are the evaluation results for the Random Forest and XGBoost models: ### Random Forest Model ![Random Forest Confusion Matrix](data/plots/confusion_matrix_rf.png) | Metric | Value | |------------|----------------------| | Accuracy | 0.95 | | Precision | 0.9333333333333333 | | Recall | 0.9545454545454546 | | F1 Score | 0.9438202247191011 | | AUC | 0.9864549512987013 | ### XGBoost Model ![XGBoost Confusion Matrix](data/plots/confusion_matrix_xg.png) | Metric | Value | |------------|----------------------| | Accuracy | 0.965 | | Precision | 0.9550561797752809 | | Recall | 0.9659090909090909 | | F1 Score | 0.96045197740113 | | AUC | 0.991984577922078 | The confusion matrices provide a visual representation of the models' performance in terms of true positives, true negatives, false positives, and false negatives. The evaluation metrics demonstrate the high accuracy and effectiveness of both models in detecting fraudulent transactions. ## Contributing Contributions to FraudShield are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request. Make sure to follow the contribution guidelines outlined in [CONTRIBUTING.md](CONTRIBUTING.md). ## License FraudShield is released under the [MIT License](LICENSE). Feel free to use, modify, and distribute the code as per the terms of the license. ## Contact For any questions, suggestions, or feedback, please contact the FraudShield team at [muditbhargava66](muditbhargava66). ---
import { useCtx } from "../../contexts/context"; import { backMusicIcon, loopIcon, nextMusicIcon, pauseIcon, randomIcon, reproducirIcon, } from "../../public/Svgs"; import { useEffect, useState } from "react"; const Reproductor = () => { const [audio, setAudio] = useState(null); const [paused, setPaused] = useState(true); const { reproductor } = useCtx(); useEffect(() => { setAudio(new Audio(reproductor ? reproductor : "")); audio && audio.play(); audio && setPaused(false); }, [reproductor]); useEffect(() => { audio && audio.play(); }, [audio]); useEffect(() => { document.addEventListener( "play", function (e) { var audios = document.getElementsByTagName("audio"); for (var i = 0, len = audios.length; i < len; i++) { if (audios[i] != e.target) { audios[i].pause(); } } }, true ); return () => { document.addEventListener( "play", function (e) { var audios = document.getElementsByTagName("audio"); for (var i = 0, len = audios.length; i < len; i++) { if (audios[i] != e.target) { audios[i].pause(); } } }, true ); }; }, []); // reproducir const reproducir = () => { audio?.play(); setPaused(false); }; // pausar const pause = () => { audio?.pause(); setPaused(true); }; return ( <div className="absolute text-white z-50 bottom-0 px-5 h-20 flex items-center border-t border-[#3a3a3a] bg-[#181818] w-full"> <div className="mx-auto"> <div> <button className="mr-4" onClick={() => { audio?.play(); }} > {randomIcon} </button> <button onClick={() => { audio?.play(); }} > {backMusicIcon} </button> {paused ? ( <button className="bg-white mx-5 text-black rounded-full p-2" onClick={() => reproducir()} > {reproducirIcon} </button> ) : ( <button className="bg-white mx-5 text-black rounded-full p-2" onClick={() => pause()} > {pauseIcon} </button> )} <button onClick={() => { audio?.play(); }} > {nextMusicIcon} </button> <button className="ml-4" onClick={() => {}}> {loopIcon} </button> </div> </div> </div> ); }; export default Reproductor;
#!/usr/bin/env python # # (C) Copyright (2012-2015) Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from builtins import range from future import standard_library standard_library.install_aliases() import sys import argparse PYTHON_VERSION = sys.version_info[:3] PY2 = (PYTHON_VERSION[0] == 2) if PY2: if PYTHON_VERSION < (2, 7, 9): raise Exception('Must use Python 2.7.9 or later') elif PYTHON_VERSION < (3, 4): raise Exception('Must use Python 3.4 or later') import hpOneView as hpov def acceptEULA(con): # See if we need to accept the EULA before we try to log in con.get_eula_status() try: if con.get_eula_status() is True: print('EULA display needed') con.set_eula('no') except Exception as e: print('EXCEPTION:') print(e) def login(con, credential): # Login with givin credentials try: con.login(credential) except: print('Login failed') def del_all_network_sets(net): netsets = net.get_networksets() for netset in netsets: print('Deleting Network Set:', netset['name']) net.delete_networkset(netset) def del_network_set_by_name(net, name): found = False netsets = net.get_networksets() for netset in netsets: print(netset['name'],'==', name) if netset['name'] == name: found = True print('Deleting Network Set:', name) net.delete_networkset(netset) if not found: print('Error, could not locate Network Set:', name) sys.exit() def main(): parser = argparse.ArgumentParser(add_help=True, formatter_class=argparse.RawTextHelpFormatter, description=''' Delete individual or ALL Network Sets Usage: ''') parser.add_argument('-a', dest='host', required=True, help=''' HP OneView Appliance hostname or IP address''') parser.add_argument('-u', dest='user', required=False, default='Administrator', help=''' HP OneView Username''') parser.add_argument('-p', dest='passwd', required=True, help=''' HP OneView Password''') parser.add_argument('-c', dest='cert', required=False, help=''' Trusted SSL Certificate Bundle in PEM (Base64 Encoded DER) Format''') parser.add_argument('-y', dest='proxy', required=False, help=''' Proxy (host:port format''') parser.add_argument('-j', dest='domain', required=False, default='Local', help=''' HP OneView Authorized Login Domain''') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-d', dest='delete_all', action='store_true', help=''' Delete ALL Network-sets''') group.add_argument('-n', dest='name', help=''' Name of the Network-set to delete''') args = parser.parse_args() credential = {'authLoginDomain': args.domain.upper(), 'userName': args.user, 'password': args.passwd} con = hpov.connection(args.host) net = hpov.networking(con) if args.proxy: con.set_proxy(args.proxy.split(':')[0], args.proxy.split(':')[1]) if args.cert: con.set_trusted_ssl_bundle(args.cert) login(con, credential) acceptEULA(con) if args.delete_all: del_all_network_sets(net) sys.exit() del_network_set_by_name(net, args.name) if __name__ == '__main__': sys.exit(main()) # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
import 'package:ecommerce/models/cart_order_model.dart'; import 'package:ecommerce/models/product_item_model.dart'; import 'package:ecommerce/services/cart_services.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; part 'product_details_state.dart'; class ProductDetailsCubit extends Cubit<ProductDetailsState> { ProductDetailsCubit() : super(ProductDetailsInitial()); ProductSize? size; CartServicesImpl cartServices = CartServicesImpl(); final firebaseAuth = FirebaseAuth.instance; int quantity = 1; void getProductDetails(String elementId) async { try { emit(ProductDetailsLoading()); final ProductItemModel product = dummyProducts.firstWhere((element) => element.id == elementId); await Future.delayed(const Duration(seconds: 1)); emit(ProductDetailsLoaded(product: product)); } catch (e) { emit(ProductDetailsError(error: e.toString())); } } void sizeChanged(ProductSize value) { size = value; emit(SizeChanged(value: value)); } void incrementCounter() async { quantity++; await Future.delayed(const Duration(milliseconds: 500)); emit(QuantityChanged(quantity: quantity)); } void decrementCounter() async { if (quantity > 1) quantity--; await Future.delayed(const Duration(milliseconds: 500)); emit(QuantityChanged(quantity: quantity)); } void addToCart(ProductItemModel product) async { try { if (size == null) { throw Exception("Please select a size"); } emit(AddingToCart()); final order = CartOrdersModel( id: DateTime.now().toIso8601String(), product: product, totalPrice: quantity * product.price, quantity: quantity, size: size!, ); cartServices.setCartProducts(firebaseAuth.currentUser!.uid, order); emit(AddedToCart()); } catch (e) { emit(ErrorAddingToCart(error: e.toString())); } } // void getFromCart() async { // try { // emit(GetFromCartLoading()); // await Future.delayed(const Duration(seconds: 1)); // emit(GetFromCartLoaded(cartOrders: dummyCartOrders)); // } catch (e) { // emit(GetFromCartError(error: e.toString())); // } // } // moved to cart cubit , it was have call in hometabview and FavoritesPage }
import React,{useRef,useEffect,useContext} from 'react' import { ImCancelCircle } from 'react-icons/im' import { SelectedContext } from '../Contexts/SelectedContext' import { validateEmail } from '../functions/emailValidation' import positionCheck from '../functions/positionChecker' const Modal1 = (props) => { const { text1, text2, inputText1, inputText2, selectedColor, selectedPosition, selectedSize, buttonText, popupImage, setText1, setText2, setinputText1, setinputText2, setbuttonText, setImageURL } = useContext(SelectedContext) const close = useRef() const validate = useRef() function popUpShower() { close.current.style.display = 'block' setTimeout(() => { close.current.style.opacity = 1 }, 300) } useEffect(() => { setText1('Sign Up') setText2('Join new adventure') setinputText1('Enter fullname') setinputText2('Enter your email') setbuttonText('Sign up') setImageURL('https://thumbsnap.com/i/BZktJYoK.png') popUpShower() }, []); const popUpCloser = () => { console.log('not working in here :)') } const formHandler = (e) => { e.preventDefault() let fullName = document.getElementById('fullname').value.trim() let email = document.getElementById('email').value.trim() if (fullName.length < 2 || !validateEmail(email)) { validate.current.style.backgroundColor = 'red' validate.current.innerText = 'Invalid Info' validate.current.classList.add('animate-pulse') }else{ validate.current.style.backgroundColor = 'lightgreen' validate.current.innerText = 'Done!' validate.current.classList.remove('animate-pulse') } setTimeout(() => { let name = document.getElementById('fullname'), mail=document.getElementById('email') validate.current.style.backgroundColor = '' validate.current.innerText = buttonText validate.current.classList.remove('animate-pulse') name.value='', mail.value='' }, 2000) } let newColor function colorCheck() { switch (selectedColor) { case 'bg-[#F37C34]': newColor = { button: `bg-[#F37C34]`, inputFocus: `focus:outline-[#F37C34]`, inputIcon:`hover:text-[#F37C34]`, } break case 'bg-[#7D4AEA]': newColor = { button: `bg-[#7D4AEA]`, inputFocus: `focus:outline-[#7D4AEA]`, inputIcon:`hover:text-[#7D4AEA]`, } break case 'bg-black': newColor = { button: `bg-black`, inputFocus: `focus:outline-black`, inputIcon:`hover:text-black`, } break case 'bg-blue-400': newColor = { button: `bg-blue-400`, inputFocus: `focus:outline-blue-400`, inputIcon:`hover:text-blue-400`, } break case 'bg-[#777777]': newColor = { button: `bg-[#777777]`, inputFocus: `focus:outline-[#777777]`, inputIcon:`hover:text-[#777777]`, } break default: newColor = { button: `bg-[#7D4AEA]`, inputFocus: `focus:outline-[#7D4AEA]`, inputIcon:`hover:text-[#7D4AEA]`, } break } } colorCheck() function sizeCheck() { if (selectedSize == 'small') return {height:'300px',width: '500px'} if (selectedSize == 'large') return {height:'450px',width: '800px'} else return {height:'350px',width: '600px'} } return ( <div ref={close} style={positionCheck(selectedPosition)} className="hidden opacity-0 cursor-default transition-opacity duration-300 "> <div style={sizeCheck()} className="flex rounded-xl overflow-hidden w-full h-full shadow-2xl"> <div className={`flex flex-col justify-around bg-white w-1/2 p-6`}> <div className={` ${selectedSize == 'small' && 'text-2xl'} ${selectedSize == 'large' && 'text-4xl'} text-3xl break-words font-bold`}> {text1} </div> <div className={` ${selectedSize == 'small' && 'text-base '} ${selectedSize == 'large' && 'text-2xl -mt-7'} break-words text-xl font-medium`}> {text2} </div> <form onSubmit={formHandler} className="flex flex-col gap-4 "> <div className="border-2 rounded-md text-sm"> <input id="fullname" className={` ${newColor.inputFocus} p-2 w-full placeholder:text-black`} type="text" placeholder={inputText1} /> </div> <div className="border-2 rounded-md text-sm"> <input id="email" className={` ${newColor.inputFocus} p-2 w-full placeholder:text-black`} type="text" placeholder={inputText2} /> </div> <button ref={validate} className={`active:scale-95 hover:brightness-125 text-sm transition-all flex items-center justify-center ${newColor.button} text-white px-2 py-2.5 rounded-lg`}> {buttonText} </button> </form> <div className="flex w-full justify-between text-xs"> <div className="cursor-pointer transition-all hover:underline">Forgot password</div> <div className="cursor-pointer transition-all hover:underline">Log In</div> </div> </div> <div style={{backgroundImage:`url(${popupImage.src ? popupImage.src : popupImage})`}} className="bg-no-repeat bg-center bg-cover w-1/2 relative"> <ImCancelCircle onClick={popUpCloser} className="scale-150 hover:scale-[1.58] cursor-pointer absolute top-6 right-6 text-gray-600 transition-all"/> </div> </div> </div> ) } export default Modal1
local addonName = "Deposit Bank" local InterfaceOptionsFrame_OpenToCategory = InterfaceOptionsFrame_OpenToFrame local queryItems local PanelDescriptionText = [[ |cff00ff00Deposit Items from Inventory to Bank with just One click.|r By default the following ItemType will be Deposit to Bank: Gem Recipe Book Reagent Trade Goods (restricted) Trade Goods are restricted by: Elemental Cloth Leather Metal & Stone Cooking Herb Enchanting Jewelcrafting Parts Materials Other There is also a Blacklist and a Whitelist feature to restrict which Items are allowed to Deposit and which not. Whitelisted Items will alwasy Deposited by DepositBank even if the Item is on Blacklist. This means Whitelisted Items got first priority.|r ]] local defaults = { itemBlacklist = { --[6217] = true, -- Copper Rod --[6338] = true, -- Silver Rod --[11128] = true, -- Golden Rod --[11144] = true, -- Truesilver Rod --[16206] = true, -- Arcanite Rod --[25843] = true, -- Fel Iron Rod --[25844] = true, -- Adamantite Rod --[25845] = true, -- Eternium Rod -- Enchanting Rods [6218] = true, -- Runed Copper Rod [6339] = true, -- Runed Silver Rod [11130] = true, -- Runed Golden Rod [11145] = true, -- Runed Truesilver Rod [16207] = true, -- Runed Arcanite Rod [22461] = true, -- Runed Fel Iron Rod [22462] = true, -- Runed Adamantite Rod [22463] = true, -- Runed Eternium Rod [6948] = true, -- Hearthstone [20815] = true, -- Jeweler's Kit }, itemWhitelist = { } } local function GameTooltip_Hide() GameTooltip:Hide() end local Panel = CreateFrame('Frame', addonName, InterfaceOptionsFramePanelContainer) Panel.name = addonName Panel:Hide() Panel:RegisterEvent('PLAYER_LOGIN') Panel:SetScript('OnEvent', function() fubaDepositBankDB = fubaDepositBankDB or defaults for key, value in next, defaults do if(fubaDepositBankDB[key] == nil) then fubaDepositBankDB[key] = value end end end) Panel:SetScript('OnShow', function(self) local Title = self:CreateFontString(nil, nil, 'GameFontNormalLarge') Title:SetPoint('TOPLEFT', 16, -16) Title:SetText('DepositBank by fuba') local Description = self:CreateFontString(nil, nil, 'GameFontHighlightSmall') Description:SetPoint('TOPLEFT', Title, 'BOTTOMLEFT', 0, -8) Description:SetPoint('RIGHT', -32, 0) Description:SetJustifyH('LEFT') Description:SetText(PanelDescriptionText) self.Description = Description self:SetScript('OnShow', nil) end) local containerBackdrop = { bgFile = [[Interface\ChatFrame\ChatFrameBackground]], tile = true, tileSize = 16, edgeFile = [[Interface\Tooltips\UI-Tooltip-Border]], edgeSize = 16, insets = {left = 4, right = 4, top = 4, bottom = 4} } local BlacklistPanel = CreateFrame('Frame', "FDB_BlackList", Panel) BlacklistPanel.name = 'Item Blacklist' BlacklistPanel.parent = addonName BlacklistPanel:Hide() local WhitelistPanel = CreateFrame('Frame', "FDB_WhiteList", Panel) WhitelistPanel.name = 'Item Whitelist' WhitelistPanel.parent = addonName WhitelistPanel:Hide() function BlacklistPanel:default() table.wipe(fubaDepositBankDB.itemBlacklist) for item in next, defaults.itemBlacklist do fubaDepositBankDB.itemBlacklist[item] = true end BlacklistPanel:UpdateList() end function WhitelistPanel:default() table.wipe(fubaDepositBankDB.itemWhitelist) for item in next, defaults.itemWhitelist do fubaDepositBankDB.itemWhitelist[item] = true end WhitelistPanel:UpdateList() end local BLitems = {} local WLitems = {} StaticPopupDialogs.FUBA_DEPOSITBANK_BLACKLISTITEM_REMOVE = { text = 'Are you sure you want to delete\n|T%s:16|t%s\nfrom the Blacklist?', button1 = 'Yes', button2 = 'No', OnAccept = function(data) fubaDepositBankDB.itemBlacklist[data.itemID] = nil BLitems[data.itemID] = nil data.button:Hide() BlacklistPanel:UpdateList() end, timeout = 0, hideOnEscape = true, preferredIndex = 3, -- Avoid some taint } StaticPopupDialogs.FUBA_DEPOSITBANK_WHITELISTITEM_REMOVE = { text = 'Are you sure you want to delete\n|T%s:16|t%s\nfrom the Whitelist?', button1 = 'Yes', button2 = 'No', OnAccept = function(data) fubaDepositBankDB.itemWhitelist[data.itemID] = nil WLitems[data.itemID] = nil data.button:Hide() WhitelistPanel:UpdateList() end, timeout = 0, hideOnEscape = true, preferredIndex = 3, -- Avoid some taint } BlacklistPanel:SetScript('OnShow', function(self) for item in next, fubaDepositBankDB.itemBlacklist do GameTooltip:SetHyperlink("item:"..item..":0:0:0:0:0:0:0"); end local Title = self:CreateFontString(nil, nil, 'GameFontHighlight') Title:SetPoint('TOPLEFT', 20, -20) Title:SetText('Item(s) Ignored from Deposit to Bank') local Description = CreateFrame('Button', nil, self) Description:SetPoint('LEFT', Title, 'RIGHT') Description:SetNormalTexture([[Interface\GossipFrame\ActiveQuestIcon]]) Description:SetSize(16, 16) Description:SetScript('OnLeave', GameTooltip_Hide) Description:SetScript('OnEnter', function(self) GameTooltip:SetOwner(self, 'ANCHOR_TOPLEFT') GameTooltip:AddLine('Easily add more items to filter by\ngrabbing one from your inventory\nand dropping it into the box below.\n\nJust as easily you remove an existing\nitem by right-clicking on it.\n\n|cffff0000Attention!|r\nWhitelist got first Priority.', 1, 1, 1) GameTooltip:Show() end) local Items = CreateFrame('Frame', nil, self) Items:SetPoint('TOPLEFT', Title, 'BOTTOMLEFT', -12, -8) Items:SetPoint('BOTTOMRIGHT', -8, 8) Items:SetBackdrop(containerBackdrop) Items:SetBackdropColor(0, 0, 0, 1/2) Items:EnableMouse(true) local Boundaries = CreateFrame('Frame', nil, Items) Boundaries:SetPoint('TOPLEFT', 8, -8) Boundaries:SetPoint('BOTTOMRIGHT', -8, 8) local function ItemOnClick(self, button) if(button == 'RightButton') then local _, link, _, _, _, _, _, _, _, texture = GetItemInfo(self.itemID) local dialog = StaticPopup_Show('FUBA_DEPOSITBANK_BLACKLISTITEM_REMOVE', texture, link) dialog.data = { itemID = self.itemID, questID = self.questID, button = self } end end local function ItemOnEnter(self) GameTooltip:SetOwner(self, 'ANCHOR_TOPLEFT') GameTooltip:SetHyperlink(format("item:%d:0:0:0:0:0:0:0", self.itemID)) GameTooltip:AddLine(' ') GameTooltip:AddLine('Right-click to remove from list', 0, 1, 0) GameTooltip:Show() end self.UpdateList = function() local index = 1 local width = Boundaries:GetWidth() local cols = math.floor((width > 0 and width or 591) / 36) for item in next, fubaDepositBankDB.itemBlacklist do local Button = BLitems[item] if(not Button) then Button = CreateFrame('Button', nil, Items) Button:SetSize(34, 34) Button:RegisterForClicks('AnyUp') local Texture = Button:CreateTexture() Texture:SetAllPoints() Button.Texture = Texture Button:SetScript('OnClick', ItemOnClick) Button:SetScript('OnEnter', ItemOnEnter) Button:SetScript('OnLeave', GameTooltip_Hide) BLitems[item] = Button end local _, _, _, _, _, _, _, _, _, textureFile = GetItemInfo(item) if(textureFile) then Button.Texture:SetTexture(textureFile) elseif(not queryItems) then self:RegisterEvent('GET_ITEM_INFO_RECEIVED') queryItems = true end Button:ClearAllPoints() Button:SetPoint('TOPLEFT', Boundaries, (index - 1) % cols * 36, math.floor((index - 1) / cols) * -36) Button.itemID = item index = index + 1 end if(not queryItems) then self:UnregisterEvent('GET_ITEM_INFO_RECEIVED') end end self:UpdateList() Items:SetScript('OnMouseUp', function() if(CursorHasItem()) then local _, itemID = GetCursorInfo() if(not fubaDepositBankDB.itemBlacklist[itemID]) then fubaDepositBankDB.itemBlacklist[itemID] = true ClearCursor() self:UpdateList() return end end end) self:SetScript('OnShow', nil) end) BlacklistPanel:HookScript('OnUpdate', function(self) self:UpdateList() end) WhitelistPanel:SetScript('OnShow', function(self) for item in next, fubaDepositBankDB.itemBlacklist do GameTooltip:SetHyperlink("item:"..item..":0:0:0:0:0:0:0"); end local Title = self:CreateFontString(nil, nil, 'GameFontHighlight') Title:SetPoint('TOPLEFT', 20, -20) Title:SetText('Item(s) Forced to Deposit to Bank') local Description = CreateFrame('Button', nil, self) Description:SetPoint('LEFT', Title, 'RIGHT') Description:SetNormalTexture([[Interface\GossipFrame\ActiveQuestIcon]]) Description:SetSize(16, 16) Description:SetScript('OnLeave', GameTooltip_Hide) Description:SetScript('OnEnter', function(self) GameTooltip:SetOwner(self, 'ANCHOR_TOPLEFT') GameTooltip:AddLine('Easily add more items to filter by\ngrabbing one from your inventory\nand dropping it into the box below.\n\nJust as easily you remove an existing\nitem by right-clicking on it.', 1, 1, 1) GameTooltip:Show() end) local Items = CreateFrame('Frame', nil, self) Items:SetPoint('TOPLEFT', Title, 'BOTTOMLEFT', -12, -8) Items:SetPoint('BOTTOMRIGHT', -8, 8) Items:SetBackdrop(containerBackdrop) Items:SetBackdropColor(0, 0, 0, 1/2) Items:EnableMouse(true) local Boundaries = CreateFrame('Frame', nil, Items) Boundaries:SetPoint('TOPLEFT', 8, -8) Boundaries:SetPoint('BOTTOMRIGHT', -8, 8) local function ItemOnClick(self, button) if(button == 'RightButton') then local _, link, _, _, _, _, _, _, _, texture = GetItemInfo(self.itemID) local dialog = StaticPopup_Show('FUBA_DEPOSITBANK_WHITELISTITEM_REMOVE', texture, link) dialog.data = { itemID = self.itemID, questID = self.questID, button = self } end end local function ItemOnEnter(self) GameTooltip:SetOwner(self, 'ANCHOR_TOPLEFT') GameTooltip:SetHyperlink(format("item:%d:0:0:0:0:0:0:0", self.itemID)) GameTooltip:AddLine(' ') GameTooltip:AddLine('Right-click to remove from list', 0, 1, 0) GameTooltip:Show() end self.UpdateList = function() local index = 1 local width = Boundaries:GetWidth() local cols = math.floor((width > 0 and width or 591) / 36) for item in next, fubaDepositBankDB.itemWhitelist do local Button = WLitems[item] if(not Button) then Button = CreateFrame('Button', nil, Items) Button:SetSize(34, 34) Button:RegisterForClicks('AnyUp') local Texture = Button:CreateTexture() Texture:SetAllPoints() Button.Texture = Texture Button:SetScript('OnClick', ItemOnClick) Button:SetScript('OnEnter', ItemOnEnter) Button:SetScript('OnLeave', GameTooltip_Hide) WLitems[item] = Button end local _, _, _, _, _, _, _, _, _, textureFile = GetItemInfo(item) if(textureFile) then Button.Texture:SetTexture(textureFile) elseif(not queryItems) then self:RegisterEvent('GET_ITEM_INFO_RECEIVED') queryItems = true end Button:ClearAllPoints() Button:SetPoint('TOPLEFT', Boundaries, (index - 1) % cols * 36, math.floor((index - 1) / cols) * -36) Button.itemID = item index = index + 1 end if(not queryItems) then self:UnregisterEvent('GET_ITEM_INFO_RECEIVED') end end self:UpdateList() Items:SetScript('OnMouseUp', function() if(CursorHasItem()) then local _, itemID = GetCursorInfo() if(not fubaDepositBankDB.itemWhitelist[itemID]) then fubaDepositBankDB.itemWhitelist[itemID] = true ClearCursor() self:UpdateList() return end end end) self:SetScript('OnShow', nil) end) WhitelistPanel:HookScript('OnUpdate', function(self) self:UpdateList() end) BlacklistPanel:HookScript('OnEvent', function(self, event) if(event == 'GET_ITEM_INFO_RECEIVED') then self:UpdateList() queryItems = false end end) WhitelistPanel:HookScript('OnEvent', function(self, event) if(event == 'GET_ITEM_INFO_RECEIVED') then self:UpdateList() queryItems = false end end) InterfaceOptions_AddCategory(Panel) InterfaceOptions_AddCategory(WhitelistPanel) InterfaceOptions_AddCategory(BlacklistPanel) _G['SLASH_' .. addonName .. 1] = '/fdb' _G['SLASH_' .. addonName .. 2] = '/fubadepositbank' SlashCmdList[addonName] = function() -- On first load IOF doesn't select the right category or panel, this is a dirty fix InterfaceOptionsFrame_OpenToCategory(addonName) InterfaceOptionsFrame_OpenToCategory(addonName) end _G['SLASH_' .. addonName .. 'Blacklist' .. 1] = '/fdbb' _G['SLASH_' .. addonName .. 'Blacklist' .. 2] = '/fubadepositbankblacklist' SlashCmdList[addonName .. 'Blacklist'] = function() -- On first load IOF doesn't select the right category or panel, this is a dirty fix InterfaceOptionsFrame_OpenToCategory(BlacklistPanel.name) InterfaceOptionsFrame_OpenToCategory(BlacklistPanel.name) end _G['SLASH_' .. addonName .. 'Whitelist' .. 1] = '/fdbw' _G['SLASH_' .. addonName .. 'Whitelist' .. 2] = '/fubadepositbankwhitelist' SlashCmdList[addonName .. 'Whitelist'] = function() -- On first load IOF doesn't select the right category or panel, this is a dirty fix InterfaceOptionsFrame_OpenToCategory(WhitelistPanel.name) InterfaceOptionsFrame_OpenToCategory(WhitelistPanel.name) end
const { v4: uuidv4 } = require("uuid"); const { socketModule } = require("../../app.js"); const Teacher = require("../../models/teacherSchema.js"); const Student = require("../../models/studentSchema.js"); function attendance_Polling_WS() { const { attendanceWss } = socketModule; attendanceWss.on("connection", (ws) => { ws.on("message", async (message) => { try { const { id, cid } = JSON.parse(message); const teacher = await Teacher.findById(id); if (!teacher) { ws.send(JSON.stringify({ error: "Invalid teacher", status: 400 })); ws.close(400, "Invalid teacher"); return; } const classObj = teacher.classes.find((c) => c._id.toString() === cid); if (!classObj) { ws.send(JSON.stringify({ error: "Invalid class", status: 400 })); ws.close(400, "Invalid class"); return; } // Define a function to poll for changes to the teacher document let prevLength = 0; const pollTeacherChanges = async (ws) => { const teacher = await Teacher.findById(id); const classRecent = teacher.classes.find( (c) => c._id.toString() === cid ); const recentAttendance = classRecent.recentAttendance.slice(-1)[0]; if (!recentAttendance) return; else { const students = await Promise.all( recentAttendance.students.map(async (student) => { const studentObj = await Student.findById(student.studentId); return { studentId: studentObj._id, name: studentObj.name, srn: studentObj.srn, }; }) ); if (prevLength !== students.length) { attendanceWss.clients.forEach((client) => { if (client.readyState === ws.OPEN) { client.send(JSON.stringify(students)); } }); } prevLength = students.length; } }; const pollInterval = setInterval(() => pollTeacherChanges(ws), 2000); ws.on("close", () => { clearInterval(pollInterval); }); } catch (err) { ws.send(JSON.stringify({ error: "Invalid data", status: 400 })); ws.close(400, "Invalid data"); return; } }); }); } function generateQR_WS() { const { qrCodeWss } = socketModule; let intervalId = null; // Declare a flag to track if save is currently in progress let isSaving = false; // Declare a queue to store pending save operations const saveQueue = []; qrCodeWss.on("connection", (ws, req) => { ws.send("connected"); ws.on("message", async (message) => { try { const { id, cid } = JSON.parse(message); const teacher = await Teacher.findById(id); if (!teacher) { ws.send(JSON.stringify({ error: "Invalid teacher", status: 400 })); ws.close(400, "Invalid teacher"); return; } const classObj = teacher.classes.find((c) => c._id.toString() === cid); if (!classObj) { ws.send(JSON.stringify({ error: "Invalid class", status: 400 })); ws.close(400, "Invalid class"); return; } classObj.recentAttendance.push({ date: Date.now(), students: [], }); await teacher.save(); async function generateQR(ws) { if (isSaving) { saveQueue.push(ws); // If save is already in progress, add ws to the queue return; } isSaving = true; // Set the flag to indicate that save is in progress try { qrCodeWss.clients.forEach((client) => { if (client.readyState === ws.OPEN) { const QrCode = uuidv4(); client.send(QrCode); classObj.tempQR.push({ qr: QrCode, time: Date.now(), }); } }); await teacher.save(); // Call save() for any pending items in the queue if (saveQueue.length > 0) { await Promise.all( saveQueue.map((ws) => ws.send("Qr generation starts!")) ); saveQueue.length = 0; } } catch (error) { // Handle save error } finally { isSaving = false; // Reset the flag after save is completed } } ws.send("Qr generation starts!"); intervalId = setInterval(() => { generateQR(ws); }, 1000); ws.on("close", async () => { clearInterval(intervalId); classObj.tempQR = []; await teacher.save(); isSaving = false; // Reset the flag after WebSocket connection is closed }); } catch (error) { ws.send(JSON.stringify({ error: "Invalid data", status: 400 })); ws.close(400, "Invalid data"); return; } }); }); } generateQR_WS(); attendance_Polling_WS();
module Notes (component) where import Prelude hiding (div) import Affjax (Error, printError) import Affjax.RequestBody (RequestBody(..)) import Affjax.ResponseFormat (json) import Affjax.Web (Response, delete, post, put) import Affjax.Web (get) as Affjax import Control.Alt ((<|>)) import Control.Monad.Error.Class (throwError) import Control.Monad.Except (ExceptT(..), runExceptT, withExceptT) import Control.Monad.RWS (get, gets, modify_) import Control.Monad.Trans.Class (lift) import Data.Argonaut.Core (Json, jsonEmptyObject) import Data.Argonaut.Decode (class DecodeJson, JsonDecodeError, decodeJson, (.:)) import Data.Argonaut.Encode (class EncodeJson, encodeJson, (:=), (~>)) import Data.Array (index, length, mapWithIndex, null, snoc) import Data.Bifunctor (lmap) import Data.Either (Either, either) import Data.Generic.Rep (class Generic) import Data.Int (floor, toNumber) import Data.Lens (Lens', lens, lens', (.~), (^.)) import Data.Maybe (Maybe, maybe) import Data.Newtype (unwrap, wrap) import Data.Show.Generic (genericShow) import Data.String (Pattern(Pattern), split) as Str import Data.Tuple (Tuple(..)) import Effect.Aff (Aff) import Effect.Aff.Class (liftAff) import Effect.Class (liftEffect) import Effect.Class.Console (log, logShow) import Foreign.Object (Object) import Halogen (Component, ComponentHTML, HalogenM, defaultEval, getRef, mkComponent, mkEval, put) as H import Halogen.HTML (HTML, button, div, h1, h2, header, i, input, li, nav, section, span, text, textarea, ul) import Halogen.HTML.Events (onBlur, onClick, onValueChange) import Halogen.HTML.Properties (ref, value) import Halogen.HTML.Properties as Properties import Utils (class_) import Web.DOM (Element) import Web.DOM.Element (getBoundingClientRect, getElementsByClassName) import Web.DOM.HTMLCollection (item) import Web.HTML (window) import Web.HTML.HTMLElement (focus, fromElement) as HTMLElement import Web.HTML.HTMLInputElement (fromElement) as InputElement import Web.HTML.HTMLInputElement (select) import Web.HTML.Window (innerHeight, scroll) type NoOutput = Void type NoteAppM = H.HalogenM State Action () NoOutput Aff type ErrorNoteAppM = ExceptT FatalError NoteAppM type State = { notes :: Array Note , editingState :: EditingState } data EditingState = None | EditingNoteTitle Int | EditingNoteContent Int data Note = NewNote { content :: NoteContent } | ServerNote { content :: NoteContent , storageId :: StorageId } derive instance noteGenericInstance :: Generic Note _ instance noteShowInstance :: Show Note where show = genericShow _content :: Lens' Note NoteContent _content = lens' $ (\note -> Tuple (getContent note) (setContent note)) getContent :: Note -> NoteContent getContent (NewNote n) = n.content getContent (ServerNote n) = n.content setContent :: Note -> NoteContent -> Note setContent (NewNote _) newContent = NewNote { content: newContent } setContent (ServerNote n) newContent = ServerNote (n { content = newContent }) _title :: Lens' Note String _title = _content <<< (lens _.title $ _ { title = _ }) _noteContent :: Lens' Note String _noteContent = _content <<< (lens _.noteContent $ _ { noteContent = _ }) instance noteDecodeJsonInstance :: DecodeJson Note where decodeJson :: Json -> Either JsonDecodeError Note decodeJson json = do dec <- decodeJson json content <- dec .: "content" title <- content .: "title" noteContent <- content .: "noteContent" either (const $ pure $ NewNote { content: { title: title, noteContent: noteContent } }) (decodeServerNote title noteContent) (dec .: "storageId") where decodeServerNote :: String -> String -> Object Json -> Either JsonDecodeError Note decodeServerNote title noteContent storageIdObj = do version <- storageIdObj .: "version" id <- storageIdObj .: "id" pure $ ServerNote { content: { title: title, noteContent: noteContent } , storageId: { version: version, id: id }} instance noteEncodeJson :: EncodeJson Note where encodeJson :: Note -> Json encodeJson (NewNote { content: { title, noteContent } }) = encodeContentObj title noteContent encodeJson (ServerNote { content: { title, noteContent }, storageId: { version, id }}) = cont ~> storage ~> jsonEmptyObject where cont :: Tuple String Json cont = "content" := encodeContentObj title noteContent storage :: Tuple String Json storage = "storageId" := encodeStorageIdObj id version encodeContentObj :: String -> String -> Json encodeContentObj title noteContent = "title" := title ~> "noteContent" := noteContent ~> jsonEmptyObject encodeStorageIdObj :: String -> String -> Json encodeStorageIdObj id version = "id" := id ~> "version" := version ~> jsonEmptyObject type NoteId = Maybe { version :: String, id :: String } -- ^ The Nothing value represents the id of the NewNote type NoteContent = { noteContent :: String, title :: String } type StorageId = { version :: String, id :: String } data Action = Initialize | CreateNewNote | EditNoteTitle Int | NoteTitleChanged Int String | NoteContentChanged Int String | EditDone | EditNoteContent Int | DeleteNote StorageId component :: forall q i. H.Component q i NoOutput Aff component = H.mkComponent { initialState , render , eval: H.mkEval $ H.defaultEval { handleAction = handleAction , initialize = pure Initialize } } initialState :: forall i. i -> State initialState = const { notes: [], editingState: None } newNote :: Note newNote = NewNote { content: { title: "What's your new title?", noteContent: "What's your new content?" } } render :: forall m. State -> H.ComponentHTML Action () m render { notes, editingState } = div [] [ if (null notes) then noNotesDiv else ul [ class_ "list-group" ] (mapWithIndex (noteRender editingState) notes) , section [ class_ "row" ] [ button [ class_ "btn btn-primary", onClick (const CreateNewNote) ] [ text "+" ] ] ] noNotesDiv :: forall w i. HTML w i noNotesDiv = div [ class_ "row" ] [ text "There are no notes to display" ] noteRender :: forall w. EditingState -> Int -> Note -> HTML w Action noteRender editingState idx note = li [ class_ "row list-group-item" ] $ [ div [ class_ "col", ref (wrap $ "note-" <> show idx) ] $ [ noteTitleRender editingState idx note , noteContentRender editingState idx note ] <> noteFooterRender note ] noteFooterRender :: forall w. Note -> Array (HTML w Action) noteFooterRender (NewNote _) = [] noteFooterRender (ServerNote { storageId }) = [ section [ class_ "row my-2 justify-content-center" ] [ button [ class_ "btn btn-sm btn-outline-danger", onClick (const $ DeleteNote storageId) ] [ i [ class_ "bi bi-trash" ] [] ] ] ] noteContentRender :: forall w. EditingState -> Int -> Note -> HTML w Action noteContentRender editingState idx note = section [ class_ "row my-2" ] [ contentRender editingState ] where contentRender (EditingNoteContent editIdx) | editIdx == idx = textarea [ class_ "form-control content-input", onBlur (const EditDone), onValueChange $ NoteContentChanged idx, value (note ^. _noteContent) ] contentRender _ = div [ onClick (const $ EditNoteContent idx) ] [ text (note ^. _noteContent) ] noteTitleRender :: forall w. EditingState -> Int -> Note -> HTML w Action noteTitleRender editingState idx note = header [ class_ "row my-2" ] [ contentRender editingState ] where contentRender (EditingNoteTitle editIdx) | editIdx == idx = input [ class_ "form-control fs-2 lh-2 title-input", onBlur (const EditDone), onValueChange $ NoteTitleChanged idx, value (note ^. _title)] contentRender _ = h2 [ onClick (const $ EditNoteTitle idx) ] [ text (note ^. _title) ] handleAction :: Action -> NoteAppM Unit handleAction action = handleError $ case action of Initialize -> refreshNotes CreateNewNote -> do st <- get H.put st { notes = snoc st.notes (NewNote { content: { title: "What's your new title?", noteContent: "What's your new title?" } }) , editingState = EditingNoteTitle (length st.notes)} goInput (length st.notes) EditNoteTitle idx -> do modify_ \st -> st { editingState = EditingNoteTitle idx } goInput idx EditNoteContent idx -> do modify_ \st -> st { editingState = EditingNoteContent idx } goInput idx NoteTitleChanged idx newTitle -> updateNoteWithSaveAndRefreshNotes idx _title newTitle NoteContentChanged idx newContent -> updateNoteWithSaveAndRefreshNotes idx _noteContent newContent EditDone -> modify_ \st -> st { editingState = None } DeleteNote storageId -> do deleteNote storageId refreshNotes handleError :: ErrorNoteAppM Unit -> NoteAppM Unit handleError m = do res <- runExceptT m either logShow pure res updateNoteWithSaveAndRefreshNotes :: forall a. Int -> Lens' Note a -> a -> ErrorNoteAppM Unit updateNoteWithSaveAndRefreshNotes idx lens_ newVal = do oldNotes <- gets _.notes let modifiedNote = index (snoc oldNotes newNote) idx >>= ((lens_ .~ newVal) >>> pure) maybe (throwError $ CustomFatalError "Unable to modify note at index ") writeAndRefreshThenStopEditing modifiedNote where writeAndRefreshThenStopEditing :: Note -> ErrorNoteAppM Unit writeAndRefreshThenStopEditing note = do resp <- writeToServer note if unwrap resp.status >= 300 || unwrap resp.status < 200 then throwError $ CustomFatalError $ "Wrong status response for post note: " <> show resp.status else refreshNotes lift $ modify_ \st -> st { editingState = None } goInput :: Int -> ErrorNoteAppM Unit goInput idx = do noteElem <- getRef $ "note-" <> show idx scrollTo noteElem titleElem <- focusTitle noteElem maybe (throwError $ CustomFatalError $ "unable to get input element from title element") (liftEffect <<< select) $ InputElement.fromElement titleElem scrollTo :: Element -> ErrorNoteAppM Unit scrollTo e = do w <- liftEffect window rect <- liftEffect $ getBoundingClientRect e liftEffect $ log $ "client rect: " <> show rect.y let elemMiddle = floor $ rect.y + rect.height / toNumber 2 vh <- liftEffect $ innerHeight w liftEffect $ log $ "scrolling to " <> show (elemMiddle - vh / 2) liftEffect $ scroll 0 (max 0 (elemMiddle - vh / 2)) w refreshNotes :: ErrorNoteAppM Unit refreshNotes = do newNotes <- getNotes lift $ modify_ \st -> st { notes = newNotes } getNotes :: ErrorNoteAppM (Array Note) getNotes = do jsonResponse <- withExceptT toFatalError $ ExceptT $ liftAff $ Affjax.get json "/api/note" (_.body >>> decodeJson >>> lmap toFatalError >>> pure >>> ExceptT) jsonResponse deleteNote :: StorageId -> ErrorNoteAppM Unit deleteNote { id } = do jsonResponse <- withExceptT toFatalError $ ExceptT $ liftAff $ delete json ("/api/note/" <> id) if unwrap jsonResponse.status < 200 || unwrap jsonResponse.status >= 300 then (throwError $ CustomFatalError $ "Wrong status code when deleting note " <> id <> ": " <> show jsonResponse.status) else pure unit isCreate :: Note -> Boolean isCreate (NewNote _) = true isCreate (ServerNote _) = false writeToServer :: Note -> ErrorNoteAppM (Response Json) writeToServer note = withExceptT toFatalError $ ExceptT $ liftAff $ writeFunc json "/api/note" ((pure <<< Json <<< encodeJson) note) where writeFunc = if isCreate note then post else put data FatalError = DecodeError JsonDecodeError | NetworkError Error | CustomFatalError String instance fatalErrorShowInstance :: Show FatalError where show (DecodeError err) = "DecodeError: " <> show err show (NetworkError err) = "NetworkError: " <> printError err show (CustomFatalError err) = "CustomError: " <> err instance fatalErrorSemigroupInstance :: Semigroup FatalError where append _ last = last instance jsonDecodeErrorToFatalErrorInstance :: ToFatalError JsonDecodeError where toFatalError = DecodeError instance affjaxErrorToFatalErrorInstance :: ToFatalError Error where toFatalError = NetworkError class ToFatalError a where toFatalError :: a -> FatalError getRef :: String -> ErrorNoteAppM Element getRef refStr = do ref <- lift $ H.getRef (wrap refStr) maybe (throwError $ CustomFatalError $ "cannot get ref " <> refStr) pure ref focusTitle :: Element -> ErrorNoteAppM Element focusTitle noteElem = do title <- (getElementByClassName "title-input" noteElem) <|> (getElementByClassName "content-input" noteElem) focusElement title pure title getElementByClassName :: String -> Element -> ErrorNoteAppM Element getElementByClassName className element = do title <- liftEffect $ getElementsByClassName className element >>= item 0 maybe (throwError $ CustomFatalError $ "unable to get note title") pure title focusElement :: Element -> ErrorNoteAppM Unit focusElement elem = maybe (throwError $ CustomFatalError $ "cannot convert element to HTML element") liftEffect $ (HTMLElement.fromElement elem >>= (pure <<< HTMLElement.focus))
import express, { request } from 'express'; import querystring from 'querystring'; import fetch from 'node-fetch'; require('dotenv').config(); // initialize app const app = express(); const port = 3000; // get environment variables const client_id = process.env.CLIENT_ID; const client_secret = process.env.CLIENT_SECRET; const redirect_uri = process.env.REDIRECT_URI || `http://localhost:${port}/callback` app.get("/", (req, res) => { res.send(` <p>Hello world!</p> <a href="/login">Go to login</a> `); }); app.get("/login", (req, res) => { // Request Spotify app authorization from user res.redirect( 'https://accounts.spotify.com/authorize?' + querystring.stringify({ response_type: 'code', client_id, scope: ``, redirect_uri, state: Math.random() }) ); }) app.get("/callback", async (req, res) => { // Request refresh and access tokens const code = req.query.code || null const state = req.query.state || null // Make request to Spotify for access token const response = await fetch('https://accounts.spotify.com/api/token', { method: 'POST', headers: { 'Authorization': 'Basic ' + Buffer.from(client_id + ":" + client_secret).toString('base64'), 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams( Object.entries({ grant_type: 'authorization_code', code, redirect_uri, }) .map(([ key, value ]) => key + '=' + value) .join('&') ) }).then(async response => { // Verify access token data received try { const data = await response.json(); console.log(data); return data; } catch(error) { console.log("Error!"); console.error(error) } }).then(async data => { // Use access token to request data from Spotify const { access_token } = data; const id = `1klALx0u4AavZNEvC4LrTL`; const albumData = await fetch(`https://api.spotify.com/v1/albums/${id}`, { headers: { 'Authorization': 'Bearer ' + access_token } }); console.log(await albumData.json()); }); }) app.listen(port, () => { console.log(`App listening at http://localhost:${port}`) })
package events; import audio.PlayerManager; import events.util.EventObject; import bot.Bot; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent; import java.awt.*; import java.net.MalformedURLException; import java.net.URL; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Random; // Handler for whenever a user joins a voice channel or disconnects from a channel. public class VoiceStateUpdate extends EventObject { private Guild guild; @Override public String getName() { return "VoiceStateUpdate"; } @Override public String getAction() { return "a voice channel"; } @Override public Guild getGuild() { return guild; } // Determines what set of events to execute. public void onGuildVoiceUpdate(GuildVoiceUpdateEvent event) { guild = event.getGuild(); if (event.getMember().getUser().isBot()) return; // Voice update handler. if (event.getOldValue() == null && event.getVoiceState().inAudioChannel()) joinHandler(event); if (event.getNewValue() == null) leaveHandler(event); } // When someone joins a voice channel, their associated join sound is played. private void joinHandler(GuildVoiceUpdateEvent event) { VoiceChannel channelJoined = Objects.requireNonNull(event.getChannelJoined()).asVoiceChannel(); if (!guild.getAudioManager().isConnected()) guild.getAudioManager().openAudioConnection(channelJoined); Random rand = new Random(); int randomInt = rand.nextInt(1000); URL url; try { // Ultra-rare if (randomInt < 1) { Bot.defaultChannels.get(event.getGuild()).sendMessageEmbeds(new EmbedBuilder() .setColor(Color.CYAN) .addField("ULTRA-RARE STATUS ACHIEVED!", event.getMember().getAsMention() + " HAS SUCCESSFULLY ACHIEVED ULTRA-RARE STATUS!", false) .build()) .queue(); url = new URL(Bot.aws.getObjectUrl(guild.getId() + "-joinsounds", "ultraRare.ogg")); PlayerManager.getInstance().getMusicManager(guild).audioPlayer.setVolume(75); String tableName = guild.getId() + "-ultrarare"; if (Bot.aws.getItem(tableName, "MemberID", event.getMember().getId()).isEmpty()) { List<String> keys = new ArrayList<>(); List<String> keyVals = new ArrayList<>(); keys.add("MemberID"); keyVals.add(event.getMember().getId()); keys.add("Amount"); keyVals.add("1"); keys.add("Last Obtained"); keyVals.add(Bot.getLocalDate().format(DateTimeFormatter.ofPattern("M-d-y"))); Bot.aws.addTableItem(tableName, keys, keyVals); } else { int updatedVal = Integer.parseInt(Bot.aws.getItem(tableName, "MemberID", event.getMember().getId()).get("Amount").s()) + 1; Bot.aws.updateTableItem(tableName, "MemberID", event.getMember().getId(), "Amount", Integer.toString(updatedVal)); Bot.aws.updateTableItem(tableName, "MemberID", event.getMember().getId(), "Last Obtained", Bot.getLocalDate().format(DateTimeFormatter.ofPattern("M-d-y"))); } tableName = "SoundByteServerList"; Bot.aws.updateTableItem(tableName, "ServerID", guild.getId(), "Current Ultra", event.getMember().getId()); } // Rare else if (randomInt < 50) { url = new URL(Bot.aws.getObjectUrl(guild.getId() + "-joinsounds", "rare.ogg")); PlayerManager.getInstance().getMusicManager(guild).audioPlayer.setVolume(60); } // Default else { if (Bot.aws.verifyObject(guild.getId() + "-joinsounds", event.getMember().getId() + ".ogg")) url = new URL(Bot.aws.getObjectUrl(guild.getId() + "-joinsounds", event.getMember().getId() + ".ogg")); else url = new URL(Bot.aws.getObjectUrl(guild.getId() + "-joinsounds", "default.ogg")); PlayerManager.getInstance().getMusicManager(guild).audioPlayer.setVolume(60); } } catch (MalformedURLException e) { Bot.log(getLogType(), "Could not properly set URL"); return; } PlayerManager.getInstance() .loadAndPlay(channelJoined, url.toString()); devMessage(getName(),event.getMember().getEffectiveName() + " joined " + getAction() + " played " + url.getFile().replace("/", ""), getGuild()); } // When every human user leaves a voice channel, the bot closes the connection as well. private void leaveHandler(GuildVoiceUpdateEvent event) { VoiceChannel channelLeft; try { channelLeft = Objects.requireNonNull(guild.getAudioManager().getConnectedChannel()).asVoiceChannel(); } catch (NullPointerException e) { devMessage(getName(), event.getMember().getEffectiveName() + " left " + getAction(), getGuild()); return; } final boolean[] isEmpty = {true}; channelLeft.getMembers().forEach(member -> { if (!member.getUser().isBot()) isEmpty[0] = false; }); if (isEmpty[0]) guild.getAudioManager().closeAudioConnection(); devMessage(getName(), event.getMember().getEffectiveName() + " left " + getAction(), getGuild()); } }
//给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现 //在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。 // // // // 示例 1: // // //输入: temperatures = [73,74,75,71,69,72,76,73] //输出: [1,1,4,2,1,1,0,0] // // // 示例 2: // // //输入: temperatures = [30,40,50,60] //输出: [1,1,1,0] // // // 示例 3: // // //输入: temperatures = [30,60,90] //输出: [1,1,0] // // // // 提示: // // // 1 <= temperatures.length <= 10⁵ // 30 <= temperatures[i] <= 100 // // // Related Topics 栈 数组 单调栈 👍 1599 👎 0 package doc //这里边就是判断高温天气呗 如何做呢 // leetcode submit region begin(Prohibit modification and deletion) // O(N^2) for循环变量两次指定是能完成的 但是题目估计要求O(n)来完成呗 func dailyTemperatures(temperatures []int) []int { stack := make([]int, 0) result := make([]int, len(temperatures)) //倒序 逆向思维 for index := len(temperatures) - 1; index >= 0; index-- { for len(stack) > 0 && temperatures[index] >= temperatures[stack[len(stack)-1]] { stack = stack[:len(stack)-1] } if len(stack) > 0 { result[index] = stack[len(stack)-1] - index //存放索引 不存放值 } else { result[index] = 0 } stack = append(stack, index) //最后才是放索引 } return result } //leetcode submit region end(Prohibit modification and deletion)
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { PersonService, Person } from '../person.service'; // Needed to reference PersonService in this file import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-edit', templateUrl: './edit.component.html', styleUrls: ['./edit.component.css'] }) export class EditComponent implements OnInit { person: Person = null; genders = [{long: 'Female', short: 'F'}, {long: 'Male', short: 'M'}]; private editForm: FormGroup; constructor(private personService: PersonService, private router: Router, private formBuilder: FormBuilder, private route: ActivatedRoute) { this.editForm = formBuilder.group({ 'first': ['', [Validators.required, Validators.minLength(2)]], 'last': ['', [Validators.required, Validators.minLength(2)]], 'ssn': ['', [Validators.required, Validators.pattern('^\d{3}-\d{2}-\d{4}$')]], 'birthDate': [''], 'gender': [''] }); } ngOnInit() { this.route.params.subscribe(params => { let id = +params['id']; // (+) converts string 'id' to a number this.personService.getPerson(id).then((person) => { person.birthDate = this.dateFormatter(person.birthDate); this.person = person; }); }); } savePerson() { this.personService.saveUser(this.person).then(() => { this.showPerson(); }); } showPerson() { this.router.navigate(['/show', this.person.id]); } dateFormatter(date) { let year = date.getFullYear(); let month =("0" + (date.getMonth() + 1)).slice(-2) let day = ("0" + (date.getDate())).slice(-2); return year + '-' + month + '-' + day; } }
package tutorials.bendarz; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.List; public class LambdaExample { private int oneSide = 5; // Method showing some of the examples of lambda expressions and more.. public void doExample() { // We will implement this interface SurfaceCalculator surfaceCalculator; /* * Załóżmy, że mamy klasę JustCalculator, która posiada metodę pobierającą co * implementuje interfejs SurfaceCalulator (implementacje kalkulatora liczącego * pole powierzchni prostoąta) i uruchamia ją w ciele metody. Sama nie chce * zajmować się obliczeniami. Załóżmy, że woli korzystać z implementacji, której * metoda przyjmuje jako parametr. */ JustCalculator justCalculator = new JustCalculator(); /* * Instancja klasy JustCalculator zawiera tylko jedną metodę calculate, która * przyjmuję obiekt do implementujący wspomniany powyżej interfejs i uruchamia * obliczenie pola powierzchni. justCalculator.calculate(coś, co policzy nam * pole powierzchni). * */ /* * We can create somewhere in packages of our classes that implement * SurfaceCalculator and use it. Methods of providing implementation in shape of * a class: 1. make a separate file 2. give name 3. define the body 4. define * head of implemented method 5. Implement the body of the method * * If: */ surfaceCalculator = new SurfaceCalculatorImpl(); System.out.println("Surface area of a rectangle by the standard implementing class: " + surfaceCalculator.calculateSurfaceAreaOfARectangle(10, 12)); justCalculator.calculate(surfaceCalculator); /* * Nothing stands in the way to make it in a similar fashion but in this place, * doing only these steps: 2. give name 3. define the body 4. define head of * implemented method 5. Implement the body of the method */ class SurfaceCalculatorImplemented implements SurfaceCalculator { @Override public int calculateSurfaceAreaOfARectangle(int a, int b) { // TODO Auto-generated method stub return a * b; } } SurfaceCalculatorImplemented surfaceCalculatorImplemented = new SurfaceCalculatorImplemented(); System.out.println("Surface area as per the local implementing class: " + surfaceCalculatorImplemented.calculateSurfaceAreaOfARectangle(10, 12)); // The implementation of the interface can be passed on to a method of a class // JustCalculator justCalculator.calculate(surfaceCalculatorImplemented); /* * If the situation does not require of using any of the good that classes * provide, and we care only about passing on (mostly one time only) some simple * code, than we can use lambda expressions. It is much easier and it requires * much less code than the other methods * * There is only one action that has to be made for the same result as before */ surfaceCalculator = (a, b) -> a * b; System.out.println("Surface area of a square defined with lambda expression: " + surfaceCalculator.calculateSurfaceAreaOfARectangle(2, 2)); justCalculator.calculate(surfaceCalculator); // Lambda expressions can have more than one line surfaceCalculator = (a, b) -> { if (a > 100 && b > 100) { System.out.println("Thats a big recrangle..."); } else if (a < 2 && b < 2) { System.out.println("And that is supposed to be a rectangle?"); } Date date = new Date(); System.out.println("Waring! In a while calculating of a rectangle will be taking place " + date); return a * b; }; justCalculator.calculate(surfaceCalculator); /* * If the implemented method has one parameter, we can use it without * parenthesis Like in this situation: */ TextSurrounder textSurrounder = text -> System.out.println("[Left]" + text + "[Right]"); textSurrounder.surroundText("Text to surround"); /* * The scope of lambda expressions is relative to the place, that it was * implemented The next example does not use from the parameters a and b. To * demonstrate this feature calling to a field of a class LambdaExample and a * local field otherSide. * */ int otherSide = 11; surfaceCalculator = (a, b) -> this.oneSide * otherSide; justCalculator.calculate(surfaceCalculator); // Or we can do it even faster justCalculator.calculate((a, b) -> this.oneSide + otherSide); // This is how we can implement a thread Runnable run = () -> System.out.println("A tread written in a lambda..."); (new Thread(run)).start(); // Sorting by the length of a string Comparator<String> comparatorFromLambda = (a, b) -> a.length() > b.length() ? 1 : -1; // Let's see if it works List<String> list = new ArrayList<String>(Arrays.asList("Short", "Medium", "Long String", "Very Long String")); list.sort(comparatorFromLambda); System.out.println("Sorted list: " + list); /* * It is good to remember that lambda expressions are used, when a problem can * be resolved with a code inside a specified method, if there is no reference * to additional methods and fields of a class that implements the interface * */ /* * Task: write an implementation of an interface java.util.Comparator<String>, * that compares Strings in alphabetical order and every third comparison prints * to the console information "Every third comparison..." */ Comparator<String> comparator = new Comparator<String>() { private int count; @Override public int compare(String o1, String o2) { // TODO Auto-generated method stub if (++count % 3 == 0) { System.out.println("Every third comparison..."); } return o1.compareTo(o2); } }; List<String> list2 = new ArrayList<String>(Arrays.asList("Raz", "Dwa", "Trzy", "Cztery", "A nawet pi��")); list2.sort(comparator); System.out.println("Posortowana lista: " + list2); } }
package TestNgBasics; import java.io.IOException; import org.testng.annotations.*; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import com.aventstack.extentreports.reporter.configuration.ChartLocation; import com.aventstack.extentreports.reporter.configuration.Theme; import com.aventstack.extentreports.*; ; public class TEstNG1 extends Reports { /* * Test--> Testcase * @BeforeMethod --It will run before each testcase * @BeforeMethod --It will run after each testcase * @BeforeClass - it will run before all the testcase in that class * @AfterClass - it will run after all the testcase in that class * @BeforeTest --It will run before all the class * @AfterTest --It will run after all the class * @BeforeSuite --It will run before all the test * @AfterSuite --It will run after all the test */ /* * ExtentHtmlReporter --> report location * ExtentTest -- write in that report */ @BeforeSuite(alwaysRun=true) public void BeforeSuite() { StartRport(); System.out.println("Before Suite"); } @AfterMethod(alwaysRun=true) public void af() { System.out.println("After method"); } @Test(priority=10,enabled=true,groups="Sanity") public void Testcase2() { test = extent.createTest("Test Case 1", "PASSED test case"); test.log(Status.INFO, "Launch Browser"); System.out.println("Step 1"); test.log(Status.INFO, "Enter username"); //test.info("Enter username"); System.out.println("Step 2"); test.log(Status.INFO, "Enter password"); //test.log(LogStatus.INFO, "Enter password"); System.out.println("Step 3"); test.log(Status.PASS, "Login done"); try { test.addScreenCaptureFromPath("C:\\Users\\kumar\\git\\FITAPorurSeleniumWeekEnd\\Screenshot\\1716022821780.png"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //test.log(LogStatus.PASS, "Login sucess"); //throw new ArithmeticException("error"); } @Test(priority=20,invocationCount=5,invocationTimeOut=60,groups={"SIT","Regression"}) public void Testcase1() { System.out.println("Step 1"); System.out.println("Step 2"); System.out.println("Step 3"); System.out.println("Step 4"); } @BeforeClass(alwaysRun=true) public void Beforeclass() { System.out.println("Before Class"); } @Test(dependsOnMethods="Testcase2",priority=-1,timeOut=60,groups= {"Sanity","SIT","Regression"}) public void Testcase3() throws InterruptedException { System.out.println("Testcase3"); //Thread.sleep(3000); } @AfterClass(alwaysRun=true) public void aclass() { System.out.println("After Class"); } @BeforeMethod(alwaysRun=true) public void Bf() { System.out.println("Before method"); } @AfterTest(alwaysRun=true) public void AfterTest() { System.out.println("After Test"); } @AfterSuite public void EndReport() { extent.flush(); } }
#ifndef TASKQUEUE_H #define TASKQUEUE_H #include <iostream> #include <boost/function.hpp> #include <QMetaType> #include <SingleWriterSingleReaderLocklessFifo.h> #include <TaskQueueBase.h> #include <Task.h> #include <TaskQueueExecutorThread.h> namespace cpaf { namespace concurrent { template <typename RETURN_TYPE> class TaskQueue : public TaskQueueBase { public: typedef Task<RETURN_TYPE> TaskType; typedef TaskQueueExecutorThread<RETURN_TYPE> ExecutorThread; typedef typename TaskType::JobFunction JobFunction; typedef typename TaskType::ResultReadyFunction ResultReadyFunction; typedef typename TaskType::TaskDoneFunction TaskDoneFunction; explicit TaskQueue(boost::uint32_t queue_size) : m_fifo(queue_size), m_executor_thread(&m_fifo) { qRegisterMetaType<TaskBasePtr>("TaskBasePtr"); // Register type for signal/slot system QObject::connect( &m_executor_thread, SIGNAL(taskDoneSignal(TaskBasePtr)), this, SLOT(taskDoneSlot(TaskBasePtr)) ); m_executor_thread.start(); } ~TaskQueue() { m_executor_thread.stop(); m_executor_thread.wait(); } TaskType push (const JobFunction &job_fun) { boost::shared_ptr<TaskType> task = boost::make_shared<TaskType>(job_fun); m_fifo.push(task); ensureThreadIsRunning(); return *task; } TaskType push (const JobFunction &job_fun, const ResultReadyFunction &res_ready_fun) { boost::shared_ptr<TaskType> task = boost::make_shared<TaskType>(job_fun, res_ready_fun); m_fifo.push(task); ensureThreadIsRunning(); return *task; } TaskType push (const JobFunction &job_fun, const TaskDoneFunction &task_done_fun) { boost::shared_ptr<TaskType> task = boost::make_shared<TaskType>(job_fun, task_done_fun); m_fifo.push(task); ensureThreadIsRunning(); return *task; } void stop() { m_executor_thread.stop(); } private: virtual void doTaskDone( TaskBasePtr task_base) { using namespace std; boost::shared_ptr<TaskType> task = boost::static_pointer_cast<TaskType>(task_base); task->callDoneAndReadyFunctions(); emitTaskDoneSignal(task_base); } void ensureThreadIsRunning() { if (m_executor_thread.aboutToExit()) { std::cout << "THREAD about to exit. So we wait for it." << std::endl; m_executor_thread.wait(); } if (!m_executor_thread.isRunning()) m_executor_thread.start(); } typedef SingleWriterSingleReaderLocklessFifo<boost::shared_ptr<TaskType> > FifoQueue; FifoQueue m_fifo; ExecutorThread m_executor_thread; }; }} //END namespace cpaf::concurrent #endif // TASKQUEUE_H
package org.example.netty.akka import akka.actor.AbstractActor import akka.actor.ActorRef import akka.actor.Props import akka.event.Logging import akka.event.LoggingAdapter import akka.routing.ActorRefRoutee import akka.routing.BroadcastRoutingLogic import akka.routing.Router import io.netty.channel.Channel import org.example.netty.msg.BaseSendMsg import org.example.netty.msg.CreateUserMsg import org.example.netty.msg.MsgRouterMsg import org.example.netty.msg.RemoveUserMsg class BossActorKt : AbstractActor() { private val log: LoggingAdapter = Logging.getLogger(context.system, this) override fun createReceive(): Receive { return receiveBuilder() // 处理字符串类型的消息 .match(String::class.java) { msg: String -> println("bossActor 收到消息: $msg") } // 创建用户 .match(CreateUserMsg::class.java) { msg: CreateUserMsg -> val name = msg.name!! val roomid = msg.roomid!! val channel = msg.channel!! println("bossActor 创建用户处理, 用户:$name, 聊天室:$roomid") // 创建用户UserActor,得到actorRef val userActor = context.actorOf(UserActorKt.createProps(channel), name) // 保存用户名 nameMap[channel] = name actorMap[channel] = userActor // 保存用户和聊天室的映射关系 if(!userToRoomMap.contains(name)){ userToRoomMap[name] = mutableSetOf() } if(!roomToUserMap.contains(roomid)){ roomToUserMap[roomid] = HashSet<String>() roomToUserRouter[roomid] = Router(BroadcastRoutingLogic()); } var router = roomToUserRouter[roomid]!! router = router.addRoutee(ActorRefRoutee(userActor)) roomToUserRouter.remove(roomid) roomToUserRouter[roomid] = router roomToUserMap[roomid]!!.add(name) userToRoomMap[name]!!.add(roomid) // 给用户发送欢迎登录 val baseSendMsg = BaseSendMsg("system", "欢迎登录", msg.channel) userActor.tell(baseSendMsg, sender) println("聊天室:$roomid 人数:${roomToUserMap[roomid]!!.size}") } // 用户发送消息 .match(MsgRouterMsg::class.java) { msg: MsgRouterMsg -> val name = nameMap[msg.channel] val roomid = msg.toRoom println("bossActor 消息路由处理, " + "用户: $name, 聊天室: $roomid, 发送消息: ${msg.msg}") println("router: ${roomToUserRouter[roomid]!!}") val baseSendMsg = BaseSendMsg(name, msg.msg, msg.channel) roomToUserRouter[roomid]!!.route(baseSendMsg, sender) } // 用户退出消息 .match(RemoveUserMsg::class.java) { msg: RemoveUserMsg -> val name = nameMap[msg.channel] println("bossActor 用户退出处理, 用户:$name") nameMap.remove(msg.channel) val userActorRef = actorMap.remove(msg.channel) val rooms = userToRoomMap.remove(name) if (rooms != null) { for(roomId in rooms){ roomToUserMap[roomId]!!.remove(name) var router = roomToUserRouter[roomId]!! router = router.removeRoutee(ActorRefRoutee(userActorRef)) roomToUserRouter[roomId] = router // 发送用户退出消息 val baseSendMsg = BaseSendMsg("system", "用户 $name 退出", msg.channel) router.route(baseSendMsg, sender) println("聊天室:$roomId 人数:${roomToUserMap[roomId]!!.size}") } } } .build() } companion object { private val nameMap: MutableMap<Channel, String> = mutableMapOf() // channel -> name private val actorMap: MutableMap<Channel, ActorRef> = mutableMapOf() // channel -> actorRef private val userToRoomMap: MutableMap<String, MutableSet<String>> = mutableMapOf() // user -> roomIds private val roomToUserMap: MutableMap<String, MutableSet<String>> = mutableMapOf() // roomId -> users private val roomToUserRouter: MutableMap<String, Router> = mutableMapOf() // roomId -> router fun props(): Props { return Props.create { println("bossActor 已创建") BossActor() } } } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.commands = void 0; const utils_1 = require("../utils"); const commands = {}; exports.commands = commands; /** * @typedef {Object} IdlingResourcesOptions * @property {string} classNames - The comma-separated list of idling resources class names. * Each name must be a full-qualified java class name, like `io.appium.espressoserver.lib.MyIdlingResource`. * Each class in the app source must implement a singleton pattern and have a static `getInstance()` * method returning the class instance, which implements `androidx.test.espresso.IdlingResource` * interface. Read * - https://developer.android.com/training/testing/espresso/idling-resource * - https://android.jlelse.eu/integrate-espresso-idling-resources-in-your-app-to-build-flexible-ui-tests-c779e24f5057 * for more details on how to design and use idling resources concept in Espresso. */ /** * Registers one or more idling resources * * @this {import('../driver').EspressoDriver} * @param {IdlingResourcesOptions} opts * @throws {Error} If there was a failure while parsing options or registering * the actual instances */ commands.mobileRegisterIdlingResources = async function mobileRegisterIdlingResources(opts) { return await this.espresso.jwproxy.command('/appium/execute_mobile/register_idling_resources', 'POST', (0, utils_1.requireOptions)(opts, ['classNames'])); }; /** * Unregisters one or more idling resources * * @this {import('../driver').EspressoDriver} * @param {IdlingResourcesOptions} opts * @throws {Error} If there was a failure while parsing options or unregistering * the actual instances */ commands.mobileUnregisterIdlingResources = async function mobileUnregisterIdlingResources(opts) { return await this.espresso.jwproxy.command('/appium/execute_mobile/unregister_idling_resources', 'POST', (0, utils_1.requireOptions)(opts, ['classNames'])); }; /** * Returns a list of currently registered idling resources * or an empty list if no resources have been registered yet. * * @this {import('../driver').EspressoDriver} * @returns {Promise<string[]>} The list of fully qualified class names */ commands.mobileListIdlingResources = async function mobileListIdlingResources() { return /** @type {string[]} */ (await this.espresso.jwproxy.command('/appium/execute_mobile/list_idling_resources', 'GET')); }; /** * Wait for UI thread to be idle. * @this {import('../driver').EspressoDriver} */ commands.mobileWaitForUIThread = async function mobileWaitForUIThread() { return await this.espresso.jwproxy.command('/appium/execute_mobile/ui_thread_sync', 'POST'); }; exports.default = commands; //# sourceMappingURL=idling-resources.js.map
import React, { useState, useEffect, useCallback } from 'react'; import classNames from 'classnames'; import { ObjectSchema } from 'yup'; import { SizeProps, propsToSize } from 'shared/base/utils/sizeUtil'; import { SpaceProps, propsToSpace } from 'shared/base/utils/spaceUtil'; import './textBoxField.scss'; interface Props extends SizeProps, SpaceProps { name: string; value: string | null | undefined; onChange: (value: string) => void; placeholder?: string; schema?: ObjectSchema<any>; fieldPath?: string; size?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 'auto'; type?: string; prepend?: JSX.Element; autofocus?: boolean; className?: string; inline?: boolean; required?: boolean; min?: number; max?: number; disabled?: boolean; onKeyDown?: (e: React.KeyboardEvent<any>) => void; } export const TextBoxField: React.FC<Props> = ({ name, value, type = 'text', onChange, placeholder, schema, fieldPath, size, children, prepend, autofocus, className, inline, min, max, required, disabled, onKeyDown, ...other }) => { value = value == null ? '' : value; const [message, setMessage] = useState(null); useEffect(() => { let canceled = false; if (schema != null && fieldPath != null) schema .validateAt(fieldPath, value) .then(() => { if (!canceled) setMessage(null); return null; }) .catch(x => { if (!canceled) setMessage(x.message); return null; }); return () => { canceled = true; }; }); const onchange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => onChange(e.target.value), [onChange]); const onkeydown = useCallback((e: React.KeyboardEvent<any>) => (onKeyDown ? onKeyDown(e) : undefined), [onKeyDown]); return ( <div className={classNames( `textBoxField form-group `, className, { [`col-md-${size}`]: size != null, ' inline': inline }, propsToSize(other), propsToSpace(other) )}> {children && ( <label htmlFor={name} className="label"> {children} </label> )} <div className={classNames('input-group', { required })}> {prepend && ( <div className="input-group-prepend"> <div className="input-group-text">{prepend}</div> </div> )} <input disabled={disabled} type={type} className={classNames('form-control', { 'is-invalid': message })} id={name} name={name} placeholder={placeholder} onChange={onchange} onKeyDown={onKeyDown ?? onkeydown} value={value} autoFocus={autofocus} min={min} max={max} /> </div> <div className="invalid-feedback">{message}</div> </div> ); };
# Emanuele Palazzetti .notes: These are my notes, hidden by default # Speed up your Django app with Jython and SPDY # evonove.it .fx: opening-slide --- # Django e SPDY # Emanuele Palazzetti # :: evonove.it # Why? --- # Django e SPDY # Emanuele Palazzetti # :: evonove.it ## Sono cambiate le nostre esigenze <p style="text-align: center; margin-top: 20%;"> <img alt="bootstrap" style="display: inline;" src="img/bootstrap.png"> <img alt="angularjs" style="display: inline;" src="file:///home/palazzem/workspaces/slides-django-spdy/slides/img/angularjs.png"> <img alt="emberjs" style="display: inline;" src="file:///home/palazzem/workspaces/slides-django-spdy/slides/img/emberjs.png"> </p> --- # Django e SPDY # Emanuele Palazzetti # :: evonove.it # ...eppure __HTTP__... --- # Si comincia a cucinare # Emanuele Palazzetti # :: evonove.it # Django + SPDY = (?) --- # Primo ingrediente # Emanuele Palazzetti # :: evonove.it <p style="text-align: center; margin-top: 20%;"> <img alt="jetty" style="display: inline;" src="img/jetty.png"> </p> --- # Una buona ricetta ? # Emanuele Palazzetti # :: evonove.it <p style="text-align: center; margin-top: 5%;"> <img alt="pasta" style="display: inline;" src="img/pasta-fruit.jpg"> </p> --- # Jetty web server # Emanuele Palazzetti # :: evonove.it ## Cosa ci offre ? - Web server e `javax.servlet` container - Supporto per Web Sockets - ... diverse integrazioni con molti componenti Java ... - Supporto allo _stato dell'arte_ per __SPDY/2__ e __SPDY/3__ --- # Jetty web server # Emanuele Palazzetti # :: evonove.it # Jetty è un web container __Java__ # <p style="text-align: center"> <i>Obiettivo: eseguire una Django app dentro Jetty ... ?!</i> </p> --- # Secondo ingrediente # Emanuele Palazzetti # :: evonove.it ![jython](img/jython.jpg) --- # Interprete Jython # Emanuele Palazzetti # :: evonove.it ## Jython Versioni attualmente disponibili sono: - `2.5.3 stable` sufficiente per __Django 1.4.5__ - `2.5.4rc1` - `2.7beta1` necessario per __Django 1.5__ --- # La ricetta finale per Django # Emanuele Palazzetti # :: evonove.it # Django + Jython + Jetty + SPDY = (?) <p style="text-align: center"> <i>Bonus track: supporto a SPDY con la funzionalità server push</i> </p> --- # Altri ingredienti ? # Emanuele Palazzetti # :: evonove.it ## Mi sto dimenticando qualcosa? Non ho a disposizione i backend per i vari DATABASE Possiamo utilizzare la Django app `django-jython` (`doj`): - disposizione dei driver zxJDBC per alcuni backend - tool di pacchettizzazione del `WAR` per il deploy --- # Django - settings.py # Emanuele Palazzetti # :: evonove.it ## Configurazione backend di Django: !python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'postgres', 'PASSWORD': '123456', # <-- No way... 'HOST': 'db.example.com', 'PORT': '', } } --- # Django - settings.py # Emanuele Palazzetti # :: evonove.it ## Configurazione backend di Django: !python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'postgres', 'PASSWORD': '123456', # <-- No way... 'HOST': 'db.example.com', 'PORT': '', } } ## Configurazione backend di Django: con `django-jython`: !python DATABASES = { 'default': { 'ENGINE': 'doj.backends.zxjdbc.postgresql', 'NAME': 'mydb', 'USER': 'postgres', 'PASSWORD': '654321', 'HOST': 'db.example.com', 'PORT': '', } } --- # Una ricetta per Django # Emanuele Palazzetti # :: evonove.it ## Riassunto degli ingredienti: - Django 1.4.5 - django-jython - Jython 2.5.3 - Jetty 8.1.10.v20130312 stable - SPDY/3 --- # Django e SPDY: time to test! # Emanuele Palazzetti # :: evonove.it <p style="text-align: center; margin-top: 5%;"> <img alt="before" style="display: inline;" src="img/before_test.jpg"> </p> --- # Django e SPDY: time to test! # Emanuele Palazzetti # :: evonove.it <p style="text-align: center; margin-top: 5%;"> <img alt="after" style="display: inline;" src="img/after_test.jpg"> </p> --- # Esito della ricetta # Emanuele Palazzetti # :: evonove.it # Django + SPDY = __BLAZING FAST!__ --- # Conclusioni # Emanuele Palazzetti # :: evonove.it ## Obiettivi - Django può beneficiare di implementazioni che offrono l'uso di __SPDY__ - Sperimentiamo: _usiamo SPDY se possibile!_ ## Prossimi passi - Utilizzare _Jetty come proxy_ e _Django + WSGI server_ - Disporre di un WSGI server che supporti __nativamente__ SPDY --- # Riferimenti # Emanuele Palazzetti # :: evonove.it <p style="font-size:2em;"> <b>Emanuele Palazzetti</b><br/><br/> e-mail: emanuele.palazzetti@evonove.it<br/> Twitter: @palazzem<br/> Source code: http://forge.evonove.it/django-spdy </p>
import 'package:flutter/material.dart'; import 'package:todoapp_flutter_axum/pallete.dart'; class RaisedButton extends StatelessWidget { final VoidCallback onPressed; final Color color; final String text; /// It's a button can used in sign type senarios. const RaisedButton({super.key, required this.onPressed, this.color= Pallete.whiteColor, this.text = '',}); @override Widget build(BuildContext context){ return Container( decoration: BoxDecoration( color: color, borderRadius: BorderRadius.circular(7), ), child: ElevatedButton( onPressed: onPressed, style: ElevatedButton.styleFrom( fixedSize: const Size(395, 55), backgroundColor: Colors.transparent, shadowColor: Colors.transparent, ), child: Text( text, style: const TextStyle( fontWeight: FontWeight.w600, fontSize: 17, ), ), ), ); } }
import { Frete } from "src/fretes/fretes.entity" export const translatorMessages = { 'app.of':{ en:'of', pt:'de', }, 'app.date':{ en:'Date', pt:'Data', }, 'app.day':{ en:'Day', pt:'Dia', }, 'app.month':{ en:'Month', pt:'Mês', }, 'app.months.Jan':{ en:'January', pt:'Janeiro', }, 'app.months.Feb':{ en:'February', pt:'Fevereiro', }, 'app.months.Mar':{ en:'March', pt:'Março', }, 'app.months.Apr':{ en:'April', pt:'Abril', }, 'app.months.May':{ en:'May', pt:'Maio', }, 'app.months.Jun':{ en:'June', pt:'Junho', }, 'app.months.Jul':{ en:'July', pt:'Julho', }, 'app.months.Aug':{ en:'August', pt:'Agosto', }, 'app.months.Sep':{ en:'September', pt:'Setembro', }, 'app.months.Oct':{ en:'October', pt:'Outubro', }, 'app.months.Nov':{ en:'November', pt:'Novembro', }, 'app.months.Dec':{ en:'December', pt:'Dezembro', }, 'app.days.Sun':{ en:'Sunday', pt:'Domingo', }, 'app.days.Mon':{ en:'Monday', pt:'Segunda-feira', }, 'app.days.Tue':{ en:'Tuesday', pt:'Terça-feira', }, 'app.days.Wed':{ en:'Wednesday', pt:'Quarta-feira', }, 'app.days.Thu':{ en:'Thursday', pt:'Quinta-feira', }, 'app.days.Fri':{ en:'Friday', pt:'Sexta-feira', }, 'app.days.Sat':{ en:'Saturday', pt:'Sabado', }, } export const dateMonthDayYearWrited = (date:string) => { let [day, month, dayNumber, year] = new Date(date).toDateString().split(' ') return `${translatorMessages['app.days.' + day]['pt']} - ${translatorMessages['app.day']['pt']} ${dayNumber} ${translatorMessages['app.of']['pt']} ${translatorMessages['app.months.'+ month]['pt']} ${translatorMessages['app.of']['pt']} ${year}` } export const dateMonthYearWrited = (date:string) => { let [day, month, dayNumber, year] = new Date(date).toDateString().split(' ') if(new Date(date).toDateString() == 'Invalid Date'){ console.log("Invalid: ", date); return '' } return `${date.split('/')[0]}/${year} - ${translatorMessages['app.months.'+ month]['pt']}` // return `${date.split('/')[0]}/${year} - ${new Intl.DateTimeFormat('pt-br', {month:'long'}).format(new Date(date))}` } export const getAllDaysInMonth = (month, year) => { const getNumberOfDay = (n) =>{ return Number(new Intl.DateTimeFormat('pt-br', {day:"2-digit"}).format(new Date(year, month, n))) } const getMonthString = (day) =>{ return `${month}/${day}/${year}` } let dayCount = 0 let selectedDay = getNumberOfDay(dayCount) let daysOfTheMonth = [] while(selectedDay != 1){ selectedDay = getNumberOfDay(dayCount) daysOfTheMonth.push(getMonthString(selectedDay)) dayCount-- } return daysOfTheMonth } export const dateFrequency = <Type extends {date: Date}>(data: Type[]) => data .map(item=>item.date.toLocaleDateString()) .reduce(function(prev, cur) { prev[cur] = (prev[cur] || 0) + 1; return prev; }, {})
'use client' import Footer from "@/app/components/Footer"; import NavBar from "@/app/components/navBar"; import { cardsVariants, introVariants } from "@/app/utils/motions"; import { Box, ChakraProvider, Flex, theme,Text,useColorModeValue, Grid, GridItem, Link, UnorderedList, ListItem, Divider, OrderedList } from "@chakra-ui/react"; import { motion } from "framer-motion"; export default function Quarter5CC(){ return ( <ChakraProvider cssVarsRoot={undefined} theme={theme}> <NavBar></NavBar> <Box mb="100px"> <Flex direction={"column"}> <motion.nav variants={introVariants} initial="hidden" whileInView="show" > <Text align="center" fontSize={["20px", "25px", "25px"]} textColor={useColorModeValue("blue.600", "blue.200")} fontWeight="bold" > Developing Multi-Cloud Apps <br/>using CDK for Terraform <br></br> Quarter V </Text> </motion.nav> <motion.nav variants={cardsVariants} initial="hidden" whileInView="show"> <Flex mx="30px"> <Grid templateColumns="repeat(10, 1fr)"> <GridItem colEnd={[3,2]} textAlign="left"> {" "} <Text mt="40px" fontSize={"2xl"} fontWeight={"bold"} > {" "} Description </Text> </GridItem> <GridItem colStart={[2,3]} colEnd={11}> <Text borderRadius={"12px"} boxShadow="dark-lg" align={["justify"]} my="20px" p="20px" > Terraform lets you use the same workflow to manage multiple providers and handle cross-cloud dependencies. This simplifies management and orchestration for large-scale, multi-cloud infrastructures. <br/> Cloud Development Kit for Terraform (CDKTF) allows you to use familiar programming languages to define and provision infrastructure. This gives you access to the entire Terraform ecosystem without learning HashiCorp Configuration Language (HCL) and lets you leverage the power of your existing toolchain for testing, dependency management, etc. </Text> </GridItem> </Grid> </Flex> </motion.nav> <motion.nav variants={cardsVariants} initial="hidden" whileInView="show"> <Flex mx="30px"> <Grid templateColumns="repeat(10, 1fr)"> <GridItem colEnd={[3,2]} textAlign="left"> <Text mt="40px" fontSize={"2xl"} fontWeight={"bold"} > {" "} Terraform{" "} </Text> </GridItem> <GridItem colStart={[2,3]} colEnd={11}> <Text borderRadius={"12px"} boxShadow="dark-lg" align={["justify"]} my="20px" p="20px" ml="20px" > {" "} CDK for Terraform <Divider/> <Link textColor={"blue.500"} target="_blank" href="https://developer.hashicorp.com/terraform/cdktf" > https://developer.hashicorp.com/terraform/cdktf </Link> </Text> </GridItem> </Grid> </Flex> </motion.nav> </Flex> </Box> <Footer></Footer> </ChakraProvider> ); }
--- title: "常见网络攻击" description: "常见网络攻击" --- ## xss ### 什么是XSS攻击 cross-site scripting(跨站脚本攻击),简称XSS,是一种代码注入攻击。攻击者通过在目标网站上注入恶意脚本,使之在用户的浏览器上运行。利用这些恶意脚本,攻击者可获取用户的敏感信息如Cookie、SessionID等,进而危害数据安全。 xss攻击的的本质就是网站没有对恶意代码进行过滤,但恶意代码与正常代码混合在一起时,浏览器没办法分辨那些是恶意代码,从而执行了恶意代码 ### 常见的XSS攻击类型 * 存储型:攻击者的恶意代码会被上传到服务器,保存在数据库中,例如留言,评论等公共区域,当其他用户访问存储有恶意代码的页面就会自动执行恶意代码 * 反射型:攻击者通过特定方式来诱惑受害者去访问一个包含恶意代码的url,当受害者点击恶意链接url的时候,恶意代码会直接在受害者的主机的浏览器上执行。 * DOM型:服务器端经常使用列如document.boby.innerHtml等函数动态生成html页面,如果这些函数在引用某些变量时没有进行过滤或检查,就会产生DOM型的XSS #### 攻击步骤 存储型: 1. 攻击者将恶意代码提交至服务器 2. 用户打开目标网站,服务端将恶意代码从数据库中取出拼接在html中返回给浏览器 3. 用户浏览器收到响应后解析执行,恶意代码也在这时被执行 4. 恶意代码窃取用户的信息发到攻击者网站或者冒充用户做攻击者的目标行为 反射型: 1. 攻击者构造特殊的URL其中就包涵了恶意代码 2. ⽤户打开带有恶意代码的 URL 时,⽹站服务器将恶意代码从 URL 中取出,拼接在 HTML 中返回给浏览器 3. 用户浏览器收到响应后解析执行,恶意代码也在这时被执行 4. 恶意代码窃取用户的信息发到攻击者网站或者冒充用户做攻击者的目标行为 DOM型: 1. 攻击者构造特殊的URL其中就包涵了恶意代码 2. 用户打开带有恶意代码的 URL 3. JavaScript 取出 URL 中的恶意代码并执⾏浏览器得到响应后解析执行 4. 恶意代码窃取用户的信息发到攻击者网站或者冒充用户做攻击者的目标行为 注意: 存储型和反射型利用了后端漏洞,DOM型利用了前端漏洞,但本质都是因为浏览器无法识别恶意代码才会出现的问题 ### 防御XSS攻击 1. 转义HTML, 如果不得不拼接 HTML,得对需要插入到 HTML 中的代码做好充分的转义 2. 在cookie中设置HttpOnly属性,js脚本将无法读取到cookie信息 3. 使用 CSP ,其本质是建立一个白名单,告诉浏览器哪些外部资源可以加载和执行,从而防止恶意代码的注入攻击 ## CSRF ### 什么是CSRF攻击 CSRF(Cross Site Request Forgery),即跨站请求伪造攻击,攻击者诱导用户进入一个第三方的网站,该网站就可以向被攻击网站发送跨站请求,如果用户在被攻击网站还保留了登录状态,那么攻击者就可以利用这个状态,冒充用户向服务器发出操作 ### 如何防御CSRF攻击 1. 进行同源检测,服务器根据 http 请求头中 origin 或者 referer 信息来判断请求是否为允许访问的站点。当 origin 或者 referer 信息都不存在的时候,直接阻止请求。这种方式的缺点是有些情况下 referer 可以被伪造,同时还会把搜索引擎的链接也给屏蔽 2. 使用TOKEN 进行验证 3. 使用Cookie 进行双重验证,服务器在用户访问网站页面时,向请求域名注入一个Cookie,内容为随机字符串,然后当用户再次向服务器发送请求的时候,从 cookie 中取出这个字符串,添加到 URL 参数中,然后服务器通过对 cookie 中的数据和参数中的数据进行比较,来进行验证。使用这种方式是利用了攻击者只能利用 cookie,但是不能访问获取 cookie 的特点,但使用这种方法容易遭受XSS攻击. ## 总结 XSS: 相当于用户过分信任网站,放任来自浏览器地址栏代表的那个网站代码在自己本地任意执行,如果没有浏览器的安全机制限制,xss代码可以在用户浏览器为所欲为。 CSRF:相当于网站过分信任用户,放任来自所谓通过访问控制机制的代表合法用户的请求执行网站的某个特定功能。
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "hardhat/console.sol"; contract Todos { struct Todo { string text; bool completed; } // an array of 'todo' structurs Todo[] public todos; function create(string memory _text) public { // 3 ways to init struct // - calling like a functionn todos.push(Todo(_text, false)); // key:val mapping todos.push(Todo({text:_text, completed: false})); // init empty struct + update Todo memory todo; todo.text = _text; // todo.complete init to false todos.push(todo); } function update(uint _index, string memory _text) public { Todo storage todo = todos[_index]; todo.text = _text; } }
\section{Рабочий проект} \subsection{Модули, разработанные для реализации интерпретатора} С целью обеспечить логическое разделение кода, во время его написания были разработаны модули, представляющие собой связанные друг с другом исходные файлы на языке C, составляющие функциональность интерпретатора. \begin{figure}[h!t] \center{\includegraphics[width=1\linewidth]{uml_package}} \caption{Диаграмма пакетов интерпретатора} \label{uml_package:image} \end{figure} Эти файлы и их зависимость друг от друга продемонстрированы на рисунке \ref{uml_package:image} в виде UML-диаграммы пакетов \cite{e32}. Перечень модулей представлен в таблице \ref{modules:table}, куда входят их имена, роль в структуре разрабатываемой ПС, а также описания выполняемых ими задач. \begin{xltabular}{\textwidth}{|l|p{4cm}|X|} \caption{Модули интерпретатора\label{modules:table}} \\ \hline \centrow Имя & \centrow Роль & \centrow Задача \\ \hline \thead{1} & \thead{2} & \centrow 3 \\ \hline \endfirsthead \continuecaption{Продолжение таблицы \ref{modules:table}} \thead{1} & \thead{2} & \centrow 3 \\ \hline \finishhead main.c & Главный модуль & Выполняет инициализацию всех остальных модулей, организует работу между ЛА и вычислителем, запускает сборщик мусора, выполняет возвращение в точку до ошибки при её возникновении \\ \hline alloc.c & Модуль работы с регионами & Хранение массивов и строк реализовано через \quotes{регионы}, инструменты для управления которыми помещены в этот модуль \\ \hline objects.c & Модуль внутреннего объектного представления & Содержит функции, позволяющие создавать объекты и манипулировать ими \\ \hline arith.c & Модуль арифметических функций & Реализует примитивные арифметические функции \\ \hline str.c & Модуль работы со строками & Реализует инструменты для создания объектов-строк и манипуляции ими \\ \hline array.c & Модуль работы с массивами & Реализует инструменты для создания объектов-массивов и манипуляции ими \\ \hline symbols.c & Модуль работы с символами & Реализует инструменты для создания объектов-символов и манипуляции ими \\ \hline pair.c & Модуль работы с парами & Реализует инструменты для создания точечных пар и списков и манипуляции ими \\ \hline lexer.c & Лексический анализатор & Реализует все возможности, необходимые для анализа лексем и создания токенов на их основе \\ \hline parser.c & Синтаксический анализатор & Реализует все возможности, необходимые для формирования объектов внутреннего представления на основе токенов \\ \hline eval.c & Модуль вычисления & Вычисляет s-выражения, связывая тем самым примитивные функции языка и объекты внутреннего представления \\ \hline \end{xltabular} \subsection{Спецификация модулей лексического и синтаксического анализаторов} Для более глубокого раскрытия задач ЛА (lexer.c) и СА (parser.c) в таблицах \ref{modinfo_lexer_fields:table} - \ref{modinfo_parser_funcs:table} приведены поля и методы этих модулей с их именами, описаниями и типами входных и выходных данных. \begin{xltabular}{\textwidth}{|l|p{3.5cm}|X|} \caption{Спецификация полей модуля \quotes{lexer.c}\label{modinfo_lexer_fields:table}}\\ \hline \centrow Имя & \centrow Тип & \centrow Описание \\ \hline \thead{1} & \thead{2} & \centrow 3 \\ \hline \endfirsthead \continuecaption{Продолжение таблицы \ref{modinfo_lexer_fields:table}} \thead{1} & \thead{2} & \centrow 3 \\ \hline \finishhead cur\_symbol & char & Символ, считанный последним (текущий символ) \\ \hline token & token\_t & Токен, генерируемый в момент лексического анализа (текущий токен) \\ \hline token\_error & int & Флаг, оповещающий парсер о возникновении ошибки при лексическом разборе. Если произошла ошибка, его значение -- 1, иначе 0 \\ \hline SYMBOL\_BUFFER\_SIZE & Целочисленная символическая константа & Задаёт размер буфера символов \\ \hline symbol\_buffer & char[] & Буфер символов, считанных из стандартного потока ввода. Имеет обратный порядок элементов. Размер буфера задаётся значением \quotes{SYMBOL\_BUFFER\_SIZE} \\ \hline buffer\_write\_pos & int & Текущая позиция записи в буфере символов \\ \hline buffer\_read\_pos & int & Текущая позиция чтения из буфера символов \\ \hline \end{xltabular} \begin{xltabular}{\textwidth}{|l|p{3.2cm}|X|} \caption{Спецификация методов модуля \quotes{lexer.c}\label{modinfo_lexer_funcs:table}}\\ \hline \centrow Имя & \centrow Ввод / вывод & \centrow Описание \\ \hline \thead{1} & \thead{2} & \centrow 3 \\ \hline \endfirsthead \continuecaption{Продолжение таблицы \ref{modinfo_lexer_funcs:table}} \thead{1} & \thead{2} & \centrow 3 \\ \hline \finishhead get\_cur\_char & > void & Считывает символ из потока ввода и помещает его в буфер. Когда буфер заполняется, производится сдвиг позиций чтения и записи \\ \hline unget\_cur\_char & > void & Возвращает позицию чтения назад на единицу и переприсваивает текущий символ \\ \hline is\_whitespace & < char c \linebreak > int & Проверяет является ли символ пробельным (пробел, перенос строки, табуляция) \\ \hline skip\_comment & > void & Пропускает все символы, пока не достигнет переноса строки или конца входного потока \\ \hline skip\_white\_space & > void & Выполняет пропуск при обнаружении пробельного символа или знака комментария, оперируя для этого функциями \quotes{is\_whitespace} \quotes{skip\_comment} \\ \hline is\_digit & < char c \linebreak > int & Проверяет является ли символ \quotes{c} цифрой (от 0 до 9). Если да -- возвращает 1, иначе 0 \\ \hline is\_alpha & < char c \linebreak > int & Проверяет является ли символ \quotes{c} буквой латинского алфавита в верхнем или нижнем регистре. Если да -- возвращает 1, иначе 0 \\ \hline is\_symbol & < char c \linebreak > int & Проверяет является ли символ \quotes{c} разрешённым (+-*/=\_\&|<>). Если да -- возвращает 1, иначе 0 \\ \hline is\_hex\_symbol & < char c \linebreak > int & Проверяет является ли символ \quotes{c} одним из шестнадцатеричных символов от \quotes{a} до \quotes{f} и от \quotes{A} до \quotes{F} \\ \hline is\_delimeter & < char c \linebreak > int & Проверяет является ли символ \quotes{c} разделителем: открывающая и закрывающая скобки, обратная косая черта, двойная кавычка, пробельный символ, конец потока \\ \hline hex\_num & > int & Преобразует шестнадцатеричное число из потока ввода в десятичное и возвращает его \\ \hline get\_float\_num & > void & Принимает целую часть \quotes{int\_num} от вещественного числа и считывает оставшиеся после точки числа. Преобразует имеющиеся данные в число с плавающей точкой в формате целочисленного (int) и возвращает его \\ \hline get\_num & > int & Считывает из потока ввода число в десятичной или шестнадцатеричной системе счисления и приводит его к десятичной. Записывает его в переменную \quotes{cur\_num}, после чего возвращает \\ \hline get\_symbol & < char *cur\_str \linebreak > void & Считывает имя символа из \quotes{cur\_str} и проверяет его на корректность. Если не корректное -- задаёт для \quotes{token\_error} значение 1 и выводит ошибку \\ \hline get\_string & < char *cur\_str \linebreak > void & Считывает строку, обрамлённую двойными кавычками, из \quotes{cur\_str}. Если отсутствует закрывающая кавычка, выводит ошибку и устанавливает значение \quotes{token\_error} в 1\\ \hline get\_comma & > token\_t & Обрабатывает лексему \quotes{,} или \quotes{,@} из входного потока, формирует для неё токен и возвращает его \\ \hline get\_sharp & > token\_t & Обрабатывает лексему \quotes{\#} или \quotes{\# \textbackslash} из входного потока, формирует для неё токен и возвращает его \\ \hline get\_token & > token\_t* & Считывает лексему из потока ввода, формирует на её основе токен и возвращает его, используя для этого все вышеперечисленные функции \end{xltabular} \begin{xltabular}{\textwidth}{|l|p{3.5cm}|X|} \caption{Спецификация полей модуля \quotes{parser.c}\label{modinfo_parser_fields:table}}\\ \hline \centrow Имя & \centrow Тип & \centrow Описание \\ \hline %\thead{1} & \thead{2} & \centrow 3 \\ \hline %\endfirsthead %\continuecaption{Продолжение таблицы \ref{modinfo_parser_fields:table}} %\thead{1} & \thead{2} & \centrow 3 \\ \hline \finishhead token\_error & extern int & Флаг, устанавливаемый лексером для оповещения парсера о возникновении ошибки при лексическом разборе. Если произошла ошибка, его значение -- 1, иначе 0 \\ \hline cur\_token & token\_t & Последний полученный токен (текущий токен) \end{xltabular} \begin{xltabular}{\textwidth}{|l|p{3.2cm}|X|} \caption{Спецификация методов модуля \quotes{parser.c}\label{modinfo_parser_funcs:table}}\\ \hline \centrow Имя & \centrow Ввод / вывод & \centrow Описание \\ \hline \thead{1} & \thead{2} & \centrow 3 \\ \hline \endfirsthead \continuecaption{Продолжение таблицы \ref{modinfo_parser_funcs:table}} \thead{1} & \thead{2} & \centrow 3 \\ \hline \finishhead strupr & < char *str \linebreak > char* & Преобразует строку \quotes{str} в верхний регистр и возвращает её \\ \hline parse\_quote & < char *quote\_sym \linebreak > object\_t & Считывает s-выражение из потока ввода и помещает его как аргумент в вызов функции цитирования или квазицитирования, после чего возвращает полученный объект-список \\ \hline parse\_element & < type\_t type, void *data, tokentype\_t t\_type \linebreak > object\_t & Обрабатывает элемент списка, формирует на его основе объект и возвращает \\ \hline parse\_list & > object\_t & Обрабатывает список, формируя объекты на основе входящих в него токенов, пока не будет достигнута закрывающая скобка. По окончании возвращает указатель на сформированный объект-список \\ \hline parse\_array & > object\_t & Формирует объект-массив на основе входящих в него токенов \\ \hline parse & > object\_t & Считывает токены, составляющие s-выражение, формирует на их основе объект-список и возвращает его \\ \hline \end{xltabular} \subsection{Модульное тестирование разработанного интерпретатора} Для тестирования разработанной программной системы были созданы пакеты модульных и системного тестов. Модульные тесты вызывают функции компонентов интерпретатора с некоторыми параметрами и проверяют полученные на их выходе результаты с ожидаемыми. Этот тип тестов позволяет достаточно детально проверить работу не только какого-либо механизма ПС, но и функций, которые этот механизм формируют \cite{e14}. На каждый модуль системы был разработан собственный пакет тестов, где почти каждая функция проверяется несколькими способами, покрывая проверками все их сценарии работы. Один из них, тест модуля символов (test\_symbols.c), продемонстрирован в виде таблицы \ref{modulet:table}, содержащей наименование тестируемой функции модуля, тестовый случай и ожидаемый результат, а также краткое описание принципа работы теста. \begin{xltabular}{\textwidth}{|p{4cm}|p{4cm}|X|} \caption{Тестовые случаи для модуля \quotes{symbols.c}\label{modulet:table}}\\ \hline \centrow Имя & \centrow Ввод/вывод & \centrow Цель проверки \\ \hline \thead{1} & \thead{2} & \centrow 3 \\ \hline \endfirsthead \continuecaption{Продолжение таблицы \ref{modulet:table}} \thead{1} & \thead{2} & \centrow 3 \\ \hline \finishhead Сравнение двух строк (compare\_str) & < \quotes{abc}, \quotes{abc} \linebreak > 1 \linebreak < \quotes{abc}, \quotes{abc1} \linebreak > 0 & Тестовый случай охватывает варианты с совпадающими и несовпадающими строками, когда на выходе единица и ноль соответственно \\ \hline Создание символа (find\_symbol) & < \quotes{ab} \linebreak > Объект-символ с именем \quotes{ab} \linebreak < \quotes{a} \linebreak > Объект-символ с именем \quotes{a} & Символ с заданным именем отсутствует в таблице символов, потому будет создан. Тестовый случай проверяет, что имя созданного символа соответсвует заданному \\ \hline Тест на поиск символа по пустой строке (поочерёдно для find\_symbol и check\_symbol) & < \quotes{} \linebreak > NULL & Тестовый случай проверяет, что при получении пустой строки, она будет обработана особым образом и будет возвращено значение NULL \\ \hline Строка для поиска символа имеет недопустимую длину (поочерёдно для find\_symbol и check\_symbol) & < Строка длиной 82 символа \linebreak > NULL & Тестовый случай проверяет, что при получении функцией строки, длиной превосходящей допустимую -- более 81 символа, она будет обработана особенным образом и из неё вернётся значение NULL \\ \hline Создание символа по строке максимальной длины (find\_symbol) & < Строка длиной 81 символ \linebreak > Новый символ с заданным именем & Тестовый случай проверяет, что при обработке функцией строки максимальной длины не происходит ошибка неучтённой единицы \\ \hline Поиск символ по строке максимальной длины (check\_symbol) & < Строка длиной 81 символ \linebreak > Найденный по заданному имени символ & Тестовый случай проверяет, что при обработке функцией строки максимальной длины не происходит ошибка неучтённой единицы \\ \hline Регистрация функции (register\_func) & < "TEST", test \linebreak > & Регистрация функции прошла успешно и можно получить её по имени "TEST" и указатель на её тело соответствует переданному -- test. \\ \hline Создание и получение символа (check\_symbol и find\_symbol) & < "f" \linebreak > NULL \linebreak > Новый символ с именем "f" \linebreak > Созданный ранее символ с именем "f" & Проверив с помощью check\_symbol отсутствие символа, он будет создан с применением find\_symbol и проверка проведётся повторно. Тем самым производится контроль за корректностью работы двух функций вместе \\ \hline Разные символы с одинаковым хеш-значением (hash и find\_symbol)& < \quotes{PJ} \quotes{452} "\textbackslash xe4\textbackslash x44\textbackslash x8a" \linebreak > Символы не равны & Хеш-значения, вычисленные на основе строк из параметров, одинаковы, но объекты-символы, сформированные по ним, указывают на разные области памяти \end{xltabular} Вывод в консоль результатов выполнения этих тестов также показан на рисунке \ref{modul_test_res:image}. \begin{figure}[H] \center{\includegraphics[width=1\linewidth]{modul_test_res}} \caption{Вывод в консоль результатов выполнения модульного теста test\_symbols.c} \label{modul_test_res:image} \end{figure} \subsection{Системное тестирование разработанного интерпретатора} Системные же тесты проверяют работу ПС по принципу чёрного ящика, с теми же возможностями, что есть у пользователя. Этот метод подходит для проверки корректности работы интерпретатора в целом \cite{e15}. Суть подхода заключается в запуске передаваемого в виде строки программного кода и сравнения выведенных в консоль результатов его выполнения с эталонными. Для тестирования используется bash-скрипт \quotes{sys\_test}. При его вызове программный код подаётся в двойных кавычках первым аргументом, а эталонный (ожидаемый) результат аналогичным образом вторым аргументом. При совпадении фактического и ожидаемого результата, в поток вывода \cite{e28} попадёт \quotes{OK}, иначе \quotes{FAIL}. Запуск тестового пакета необходимо производить в консольном интерфейсе, запись результатов при этом будет происходить в стандартный поток вывода консоли. Несколько тестов из пакета системного тестирования представлены на рисунке \ref{system_test_code:image}. \begin{figure}[ht] \center{\includegraphics[width=1\linewidth]{system_test_code}} \caption{Часть тестов из пакета системного тестирования} \label{system_test_code:image} \end{figure} Вывод в консоль результатов выполнения этих тестов так же показан на рисунке \ref{system_test_res:image}. \begin{figure}[H] \center{\includegraphics[width=1\linewidth]{system_test_res}} \caption{Вывод в консоль результатов выполнения системных тестов} \label{system_test_res:image} \end{figure} Алгоритм работы тестового пакета: \begin{enumerate} \item Определяем переменные \quotes{IN}, \quotes{OUT}, и \quotes{OUT\_EXP}, используемые для хранения путей к временным файлам для хранения кода, фактических результатов и ожидаемых результатов соответственно. В дальнейшем "IN" будет использоваться для передачи программного кода на выполнение, а \quotes{OUT}" и \quotes{OUT\_EXP} для сравнения результатов; \item Выводим строку \quotes{TEST: \$1}, где \quotes{\$1} — выполняемый программный код; \item Записываем строку выполняемого программного кода в файл, путь к которому задан в переменной \quotes{IN}. Аналогично поступаем с ожидаемым результатом, но берём путь из переменной \quotes{OUT\_EXP}; \item Запускаем интерпретатор, перенаправляя в его поток вввода данные из файла \quotes{IN}, а также перенаправляем поток вывода в \quotes{OUT}; \item Сравниваем данные из файлов \quotes{OUT} и \quotes{OUT\_EXP}, используя встроенную в систему утилиту \quotes{diff} \cite{e24}. Если файлы идентичны, выводим \quotes{OK} -- успешное завершение теста, иначе \quotes{FAIL} -- несоответствие ожидаемого вывода фактическому; \item Выводим пустую строку, создав тем самым перенос строки для визуального разделения результатов тестов. \end{enumerate} \subsection{Пример использования метапрограммирования для сокращения размера исходного кода} Приведу пример программы, написанной на ДЯП, позволяющей сокращать размер исходного кода за счёт использования макросов. Напишу макрос для ветвления, позволяющий выполнять первый исход, если результат условия ложный, иначе второй исход. Для этого реализуем три макроса: Напишу макросы для следующих функций: \begin{itemize} \item if: для выполнения первого исхода при истинном условии и второго иначе, разработаю на основе встроенного в язык оператора ветвления \quotes{cond}; \item not: для инверсии булевых значений \quotes{T} и \quotes{NIL}; \item nif: объединяющий \quotes{if} и \quotes{not} для достижения поставленной цели. \end{itemize} Реализация макросов: \begin{lstlisting}[language=Lisp, frame=none] (defmacro if (test true false) `(cond (,test ,true) (t ,false))) (defmacro not (test) `(if ,test nil t)) (defmacro nif (test true false) `(if (not ,test) ,true ,false)) \end{lstlisting} Пример использования: \begin{lstlisting}[language=Lisp, frame=none] (setq a 0) (nif (> 5 3) (setq a (+ a 1)) (setq a (+ a 2))) \end{lstlisting} Если бы тот же самый пример был написан с применением \quotes{cond}: \begin{lstlisting}[language=Lisp, frame=none] (setq a 0) (cond ((if (> 5 3) nil t) (setq a (+ a 1))) (t (setq a (+ a 2)))) \end{lstlisting} Код, написанный с использованием nif, проще структурно, потому легче для понимания, и его кодовая запись короче. Таким образом, с использованием разработанного макроса \quotes{nif} были достигнуты сокращение кода и его упрощение для чтения. \subsection{Сборка программной системы} Для компиляции созданной ПС были разработаны два файла сборки \quotes{makefile} \cite{e8}, реализующие разные варианты сборки интерпретатора. Первый, расположенный в корневой папке разработанного интерпретатора, компилирует все модули интерпретатора в один готовый к использованию исполняемый файл. Для запуска сборки используется команда \quotes{make build}. В результате в той же папке будет сформирован файл \quotes{cl-inter}. Теперь можно запустить интерпретатор с нужным файлом исходного кода программы, передав путь до него в качестве параметра. Например: \quotes{cl-inter ./script}. Второй, \quotes{test}, предназначен для запуска модульных и системных тестов, при этом, в случае модульного тестирования, в скомпилированный файл входят только необходимые для тестируемого модуля компоненты. Расположен в папке test, где также находятся все файлы тестов. При вызове \quotes{make test} поочерёдно будут собираться и выполняться все разработанные модульные и системный тесты. Исполняемые файлы при этом будут помещены в директорию ОС для временных файлов - \quotes{/tmp} \cite{e25}.
package com.nullbird.hfs.http.proxy; import com.nullbird.hfs.config.Config; import com.nullbird.hfs.config.rules.actions.ReverseProxy; import com.nullbird.hfs.http.HttpRequest; import com.nullbird.hfs.http.HttpResponse; import com.nullbird.hfs.utils.StringUtils; import com.nullbird.hfs.utils.errors.ConfigurationException; import com.nullbird.hfs.utils.errors.ProxyException; import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; import org.apache.hc.client5.http.impl.async.HttpAsyncClients; import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.message.HeaderGroup; import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder; import org.apache.hc.core5.io.CloseMode; import org.apache.hc.core5.reactor.IOReactorConfig; import org.apache.hc.core5.util.Timeout; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; public class ReverseProxyImpl { private final static Logger LOGGER = Logger.getLogger(ReverseProxyImpl.class.getSimpleName()); private ReverseProxy conf; private transient AtomicInteger requestNumber; private transient HttpHost proxyHost; private transient CloseableHttpAsyncClient __proxyClient; public ReverseProxyImpl(ReverseProxy conf) { this.conf = conf; } public void run(HttpRequest request, HttpResponse response) throws ProxyException { try { int requestNumber=0; if (LOGGER.isLoggable(Level.FINE)) { if (this.requestNumber==null) this.requestNumber = new AtomicInteger(); requestNumber = this.requestNumber.getAndIncrement(); } AsyncRequestBuilder proxyRequestBuilder = buildProxyRequest(request); if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null || request.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { proxyRequestBuilder.setEntity(new ReverseProxyEntityProducer(null, request.getBodyStream())); } copyRequestHeaders(request, proxyRequestBuilder); setXForwardedHeaders(request, proxyRequestBuilder); // Execute the request doExecute(request, response, proxyRequestBuilder, requestNumber); } catch (ProxyException e) { throw e; } catch (Exception e) { throw new ProxyException("Proxifying " + request.getUrl(), e); } finally { response.consume(); } } private void doExecute(HttpRequest request, HttpResponse response, AsyncRequestBuilder proxyRequestBuilder, int requestNumber) throws ProxyException { var proxyRequest = proxyRequestBuilder.build(); if (LOGGER.isLoggable(Level.FINE)) { String debugString = request.getUrl() + " >> " + proxyHost.toString(); LOGGER.log(Level.FINE,"Request "+requestNumber+" running " + debugString); } try { HttpResponse asyncResponse = request.getAsyncResponse(response); new ReverseProxyHttpRequest( proxyRequest, new ReverseProxyResponseConsumer(asyncResponse, conf, requestNumber), this, asyncResponse, request.getUrl(), proxyHost.toString()).run(); } catch (Exception e) { throw new ProxyException(e); } } void tryExecute(ReverseProxyHttpRequest request) { final Future<Void> future = this.__proxyClient.execute( request.getRequestProducer(), request.getResponseConsumer(), null); request.getAsyncResponse().setFuture(future); } private void setXForwardedHeaders(HttpRequest request, AsyncRequestBuilder proxyRequestBuilder) { if (conf.isDoForwardIP()) { String forHeaderName = "X-Forwarded-For"; String forHeader = request.getRemoteAddr(); String existingForHeader = request.getHeader(forHeaderName); if (existingForHeader != null) { forHeader = existingForHeader + ", " + forHeader; } addHeaderImpl(forHeaderName, forHeader, proxyRequestBuilder); } String protoHeaderName = "X-Forwarded-Proto"; String protoHeader = request.getScheme(); addHeaderImpl(protoHeaderName, protoHeader, proxyRequestBuilder); } private void copyRequestHeaders(HttpRequest request, AsyncRequestBuilder proxyRequestBuilder) { // Get an Enumeration of all of the header names sent by the client Enumeration<String> enumerationOfHeaderNames = request.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = enumerationOfHeaderNames.nextElement(); copyRequestHeader(request, proxyRequestBuilder, headerName); } } private void addHeaderImpl(String name, String value, AsyncRequestBuilder addTo) { LOGGER.finer("Header added: " + name + ": " + value); addTo.addHeader(name, value); } /** These are the "hop-by-hop" headers that should not be copied. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html * I use an HttpClient HeaderGroup class instead of Set&lt;String&gt; because this * approach does case insensitive lookup faster. */ protected static final HeaderGroup hopByHopHeaders; static { hopByHopHeaders = new HeaderGroup(); String[] headers = new String[] { "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", "TE", "Trailers", "Transfer-Encoding", "Upgrade", "Expect" }; for (String header : headers) { hopByHopHeaders.addHeader(new BasicHeader(header, null)); } } /** * Copy request headers from the servlet client to the proxy request. */ protected void copyRequestHeader(HttpRequest servletRequest, AsyncRequestBuilder proxyRequest, String headerName) { if (hopByHopHeaders.containsHeader(headerName)) return; // TODO This should be handled more efficiently // The EntityProducer seems to handle this. if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) return; Enumeration<String> headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) { //sometimes more than one value String headerValue = headers.nextElement(); addHeaderImpl(headerName, headerValue, proxyRequest); } } private AsyncRequestBuilder buildProxyRequest(HttpRequest request) throws ProxyException { return AsyncRequestBuilder.create(request.getMethod()) .setHttpHost(proxyHost) .setPath(request.getPath()); } public void initialize(Config config) throws ConfigurationException { if (conf.getTarget()==null) throw new ConfigurationException("ReverseProxy action must have a non null 'target' attribute"); try { URL targetURL = new URL(conf.getTarget()); if (StringUtils.containsNonWhitespace(targetURL.getFile()) || targetURL.getRef()!=null || StringUtils.containsNonWhitespace(targetURL.getPath()) || targetURL.getQuery()!=null) { throw new ConfigurationException("ReverseProxy action target must only contain protocol, host and eventually port"); } proxyHost = new HttpHost(targetURL.getProtocol(), targetURL.getHost(), targetURL.getPort()); __proxyClient = createAndStartHttpClient(); } catch (MalformedURLException e) { throw new ConfigurationException("Unable to parse provided target", e); } } protected CloseableHttpAsyncClient createAndStartHttpClient() { // TODO: Set timeouts and other configuration final IOReactorConfig ioReactorConfig = IOReactorConfig.custom() .setSoTimeout(Timeout.ofMilliseconds(conf.getConnectionTimeoutMs())) .build(); PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder.create() .setMaxConnPerRoute(500) .setMaxConnTotal(500) .build(); var client = HttpAsyncClients.custom() .setConnectionManager(connectionManager) .disableRedirectHandling() .setIOReactorConfig(ioReactorConfig) .build(); client.start(); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("New client created " + client); return client; } public void stop() { LOGGER.info("Stopping http client"); __proxyClient.close(CloseMode.GRACEFUL); } public ReverseProxy getConf() { return conf; } }
#include "Grid.h" Grid::Grid() { placement = new int* [10]; for (int i = 0; i < 10; i++) { placement[i] = new int[10]; for (int j = 0; j < 10; j++) { grid[i][j].setSize(Vector2f(25, 25)); //Set color half transparent grid[i][j].setFillColor(UI.GridColor); } } for (int i = 0; i < 100; i++) { shots[i] = NULL; } shot_count = hit = miss = 0; } Grid::~Grid() { for (int i = 0; i < shot_count; i++) { delete shots[i]; } } /* * draw - Updates the grids. * * @param player - Indicator of the team to draw in the desired position. */ void Grid::draw(int player) { int x = (player == 0 ) ? UI.player1->x : UI.player2->x, y = UI.player1->y; // Draws Grid for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { grid[i][j].setPosition(x + j * 30, y + i * 30); game_window->draw(grid[i][j]); } } // Draw Shots Fired for (int i = 0; i < shot_count; i++) { game_window->draw(*shots[i]); } } /* * ColorShip - Colors the position of the ships blue when alive or red when destroyed. * * @param c - New color for the Ship's whom position is given. * @param hitbox - Location of the Ship's cubes. */ void Grid::ColorShip(Color& c, vector<Vector2i>& hitbox) { for (int i = 0; i < hitbox.size(); i++) { if (!~hitbox[i].x) break; if (placement[hitbox[i].y][hitbox[i].x] == 0 && c == UI.GridColor) { grid[hitbox[i].y][hitbox[i].x].setFillColor(c); } else if (placement[hitbox[i].y][hitbox[i].x] != 0 && c == UI.GridColor && UI.mode == game) { grid[hitbox[i].y][hitbox[i].x].setFillColor(c); } else if (placement[hitbox[i].y][hitbox[i].x] != 0 && c == UI.GridColor) { grid[hitbox[i].y][hitbox[i].x].setFillColor(UI.ShipColor); } else if (c != UI.GridColor) { grid[hitbox[i].y][hitbox[i].x].setFillColor(c); } } } /* * CheckValidity - checks if the ships placements are valid to start the game. * * @return 1 if valid, 0 if ships are overlapping, -1 if ships aren't all deployed. */ int Grid::CheckValidity() { int count = 0; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (placement[i][j] == 0) //Empty Cube count++; if (placement[i][j] != 0 && placement[i][j] != -1) // Multiple ships on the same cube. { return 0; } } } if (count == 83) // 17 cubes are occupied. return 1; return 0; // less than 17 cubes are occupied. } /* * resetPlacements - resets the grid placements info. */ void Grid::resetPlacements() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { placement[i][j] = 0; } } } /* * setPlacements - updates the grid placements info. * * @param hitbox - Location of the Ship's cubes. * @param mode - 1 to add, 0 to remove */ void Grid::setPlacements(vector<Vector2i> hitbox, int mode) { for (int i = 0; i < hitbox.size(); i++) { int x = hitbox[i].x, y = hitbox[i].y; if (!~x) { x = 0; break; } if (mode) //add ship hitbox placement[y][x]--; else //remove ship hitbox placement[y][x] = (placement[y][x] + 1 > 0) ? 0 : placement[y][x] + 1; } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { cout << placement[i][j] << " "; } cout << endl; } cout << endl; } /* * HitGrid - adds shots to the grid at the specified location. * * @param pos - Position of cube targeted in the grid. * * @return 1 if target is hit, 0 if missed, -1 if error occured. */ int Grid::HitGrid(Vector2i& pos) { int x = pos.x; int y = pos.y; int gx = grid[y][x].getPosition().x; int gy = grid[y][x].getPosition().y; // Hit Target if (placement[y][x]) { placement[y][x] = -1; shots[shot_count] = new CircleShape; shots[shot_count]->setRadius(8); shots[shot_count]->setPosition(gx + 4, gy + 4); shots[shot_count]->setFillColor(UI.HitColorShots); shots[shot_count]->setOutlineThickness(4); shots[shot_count]->setOutlineColor(UI.Secondary); shot_count++; hit++; // Terminal Updates printf("HIT TARGET --- Misses: %d, Hits: %d\n", miss, hit); return 1; } // Missed Target placement[y][x] = -1; shots[shot_count] = new CircleShape; shots[shot_count]->setRadius(8); shots[shot_count]->setPosition(gx + 4, gy + 4); shots[shot_count]->setFillColor(UI.MissColorShots); shots[shot_count]->setOutlineThickness(4); shots[shot_count]->setOutlineColor(UI.Secondary); shot_count++; miss++; // Terminal Updates printf("MISSED TARGET --- Misses: %d, Hits: %d\n", miss, hit); return 0; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package business; /** * * @author Donna Seidel */ public class Loan { private double loanamt, rate; private int term; private double mopmt; private double[] bbal, intchg, ebal; //arrays private boolean built; public Loan(double a, double r, int t) { //class constructor this.loanamt = a; this.rate = r; this.term = t; this.mopmt = 0; built = false; } public double getAmount() { return this.loanamt; } public int getTerm() { return this.term; } public void buildLoan() { double mRate = (this.rate / 12.0); double denom = Math.pow(1+mRate, this.term) - 1; this.mopmt = (mRate + mRate/denom) * this.loanamt; // instantiate array sizes bbal = new double[term]; intchg = new double[term]; ebal = new double[term]; //calc arrays bbal[0] = this.loanamt; for (int i=0; i < this.term; i++){ if (i > 0){ bbal[i] = ebal[i-1]; } intchg[i] = (bbal[i] * mRate); ebal[i] = (bbal[i] + intchg[i] - this.mopmt); } built = true; } //end of buildLoan public double getMoPmt() { if (!built) { buildLoan(); } return this.mopmt; } public double getBeginBal(int term) { if (term <= 0 || term > this.term) { return -999; } if (!built){ buildLoan(); } return bbal[term-1]; } public double getIntCharged(int term){ if (term <= 0 || term > this.term) { return -999; } if (!built) { buildLoan(); } return intchg[term-1]; } public double getEndBal(int term) { if (term <= 0 || term > this.term){ return -999; } if (!built){ buildLoan(); } return ebal[term-1]; } }
<div class="profile-wrapper" [ngClass]="{ 'my-light-theme': !themeDark, 'my-dark-theme': themeDark }" fxLayoutAlign="center center" > <mat-card class="box" fxLayout="column"> <div class="edit-button" fxLayout="row" fxFlex="100" fxLayoutAlign="space-between center" > <button mat-icon-button (click)="back()"> <mat-icon>arrow_back_ios</mat-icon> </button> <button mat-icon-button (click)="onEditFields()"> <mat-icon>{{ edit ? "done" : "edit" }}</mat-icon> </button> </div> <mat-card-header fxLayout="column" fxLayoutAlign="center center"> <mat-card-title>🧑🏻‍🚀</mat-card-title> <img [src]="avatar" alt="image_profile" /> <input id="image-input" fxLayoutAling="center center" *ngIf="edit" type="file" (change)="change($event)" /> </mat-card-header> <form class="example-form" [formGroup]="entityForm"> <mat-card-content> <div fxLayout="column"> <div> <mat-form-field class="example-full-width" appearance="outline"> <mat-label>Name</mat-label> <input matInput placeholder="" value="" formControlName="inputName" /> </mat-form-field> <mat-form-field class="example-full-width" appearance="outline"> <mat-label>Lastname</mat-label> <input matInput placeholder="" value="" formControlName="inputLastName" /> </mat-form-field> </div> <mat-form-field class="example-full-width" fxFlex="100" appearance="outline" > <mat-label>Email</mat-label> <input matInput placeholder="" value="" formControlName="inputEmail" /> </mat-form-field> <mat-form-field class="example-full-width" fxFlex="100" appearance="outline" > <mat-label>Status</mat-label> <input matInput placeholder="" value="" formControlName="inputStatus" /> </mat-form-field> <span *ngIf="error" class="span">{{ errorMsg }}</span> </div> </mat-card-content> </form> <mat-card-actions fxLayoutAlign="space-between center"> </mat-card-actions> </mat-card> </div>
/** * Learn more about using TypeScript with React Navigation: * https://reactnavigation.org/docs/typescript/ */ import { BottomTabScreenProps } from "@react-navigation/bottom-tabs"; import { CompositeScreenProps, NavigatorScreenParams, } from "@react-navigation/native"; import { NativeStackScreenProps } from "@react-navigation/native-stack"; declare global { namespace ReactNavigation { type RootParamList = RootStackParamList; } } export type RootStackParamList = { Root: NavigatorScreenParams<RootTabParamList> | undefined; Modal: undefined; NotFound: undefined; }; export type RootStackScreenProps<Screen extends keyof RootStackParamList> = NativeStackScreenProps<RootStackParamList, Screen>; export type RootTabParamList = { TabOne: undefined; TabTwo: undefined; TabAccount: undefined; TabSettings: undefined; }; export type RootTabScreenProps<Screen extends keyof RootTabParamList> = CompositeScreenProps< BottomTabScreenProps<RootTabParamList, Screen>, NativeStackScreenProps<RootStackParamList> >; export type AccountFullResponseBody = { id: number; description: string; balanceDescription: string; totalRevenuesDescription: string; totalExpensesDescription: string; balance: number; totalRevenues: number; totalExpenses: number; selectedPeriod: Period; nextMonth: Period; previousMonth: Period; transactions: Array<TransactionBody>; }; export type SimpleAccountResponseBody = { id: string; accountDescription: string; currentBalance: string; accountTypeDescription: string; }; type Period = { description: string; startDate: string; endDate: string; }; export type TransactionBody = { amountDescription: string; amount: number; description: string; dateValue: string; date: string; type: string; id: number; };
La numeración abyad es un sistema de numeración en el que a las 28 letras del alfabeto árabe se les asignan valores numéricos. Se han utilizado en el mundo arabófono desde antes de la numeración arábiga (siglo VIII). En árabe moderno, la palabra abjadīyah significa «alfabeto» en general. En el sistema abyad la primera letra del álfabeto árabe, álif, se utiliza para representar el 1; la segunda letra, bāʼ, se utiliza para representar el 2, etc. Otras letras se utilizan para representar decenas y centenas: yāʼ para 10, kāf para 20, qāf para 100, etc. La palabra abyad en sí (أبجد) deriva de las primeras cuatro letras (a-b-g-d) del alfabeto fenicio, arameo, hebreo y otros alfabetos utilizados para escribir lenguas semíticas. Estos alfabetos tenían solo 22 letras y acababan en tau, que tiene un valor numérico de 400. El sistema abyad árabe continúa en este punto con letras que no se hallan en los otros alfabetos: ṯāʼ = 500, etc. == Orden del abyad == El orden del abyad árabe tiene dos variantes ligeramente distintas. El orden del abyad no es una sencilla continuación histórica del anterio orden alfabético semítico septentrional, que tiene una posición para la letra semk/samek, aunque ninguna letra árabe deriva de esta. La pérdida de semk se compensó doblando la letra šin en dos letras árabes independientes: šin (ش) y sin (ﺱ), que ocupó el antiguo lugar de semk. El orden abyad más común, leído de derecha a izquierda, es: Esta secuencia suele vocalizarse así: abjad hawwaz ḥuṭṭī kalaman saʻfaṣ qarashat thakhadh ḍaẓagh. Otra vocalización común es esta: abujadin hawazin ḥuṭiya kalman saʻfaṣ qurishat thakhudh ḍaẓugh Otra ordenación del abyad (probablemente más antigua, ahora limitada principalmente al Magreb), es: que se puede vocalizar como: abujadin hawazin ḥuṭiya kalman ṣaʻfaḍ qurisat thakhudh ẓaghush Los diccionarios modernos y otras obras de referencia no usan el orden del abyad para ordenar alfabéticamente. Se prefiere el orden del hijāʼī (هجائي), más moderno, en el que las letras se ordenan parcialmente por similaridad en la forma: Otro tipo de ordenación alfabaʼī utilizado hasta hace poco en el Magreb, antes de ser reemplazado por el orden mashrequí: Los diccionarios persas usan un orden ligeramente distinto, en el que و viene antes de ه‍ en lugar de tras ella. == Usos del sistema abyad == Antes de la introducción de los números indoarábigos, los numerales abyad se utilizaban para todos los usos matemáticos. En árabe moderno, se usan principalmente para ordenar guiones, puntos en listas, etc. En español para estos fines se suelen utilizar también letras («a», «b», «c»...) u ocasionalmente números romanos (I, II, III...), mientras que en árabe se ordenan primero «أ», luego «ب», después «ج», etc. y no en el orden del hijāʼī. Los numerales abyad también se utilizan para asignar valores numéricos a palabras árabes en el marco de la numerología. Una frase islámica tan común como بسم الله الرحمن الرحيم bismillāh al-Raḥmān al-Raḥīm («En nombre de Dios, el clemente, el misericordioso»; véase basmala) tiene un valor numérico de 786 (por un valor acumulativo letra por letra de 2+60+40+1+30+30+5+1+30+200+8+40+50+1+30+200+8+10+40). El nombre Alá الله tiene el valor de 66 (1+30+30+5). == Valores de las letras == Algunos de los valores numéricos son diferentes en el orden del abyad alternativo. Cuatro letras persas usan los siguientes valores: == Sistemas similares == Los numerales abyad son equivalentes a los más antiguos numerales hebreos hasta el número 400. El sistema numérico hebreo se conoce como gematría cuando es utilizado en el marco de la cábala y la numerología. Al igual que la numeración abyad, se utiliza actualmente para ordenar puntos en listas, incluyendo los seis primeros días de la semana. Los numerales griegos difieren en varios puntos de los abyad (por ejemplo, en el alfabeto griego no hay equivalente de la letra ṣād) aunque, al igual que los dos anteriores, sigue actualmente en uso para fines similares. == Véase también == Alfabeto fenicio Historia del alfabeto Abyad Gematría Numerología == Referencias == == Enlaces externos == (en inglés) Overview of the abjad numerological system (en inglés) Sufi numerology site (en inglés) Numerical Value of an Arabic Text as per "Abjad" Calculation - www.alavibohra.org
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:provider/provider.dart'; import 'package:sushi_snap/components/category_tile.dart'; import 'package:sushi_snap/components/food_tile.dart'; import 'package:sushi_snap/models/shop.dart'; import 'package:sushi_snap/pages/food_details_page.dart'; import 'package:sushi_snap/theme/colors.dart'; class MenuPage extends StatefulWidget { const MenuPage({super.key}); @override State<MenuPage> createState() => _MenuPageState(); } class _MenuPageState extends State<MenuPage> { // navigate to food item details page void navigateToFoodItemDetails(int index) { // get the food item final shop = context.read<Shop>(); final foodMenu = shop.foodMenu; Navigator.push( context, MaterialPageRoute( builder: (context) => FoodItemDetailsPage( food: foodMenu[index], ), ), ); } @override Widget build(BuildContext context) { // get the food item final shop = context.read<Shop>(); final foodMenu = shop.foodMenu; final categoryList = shop.categoryList; return Container( decoration: const BoxDecoration( gradient: LinearGradient( colors: [Color(0xffeff2f9), Color(0xffedf0f7), Color(0xffe7eaf3)], stops: [0, 0.5, 1], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), child: Scaffold( backgroundColor: Colors.transparent, appBar: AppBar( centerTitle: true, backgroundColor: Colors.transparent, foregroundColor: Colors.grey[800], elevation: 0, leading: const Icon(Icons.menu), title: const Text( 'SUSHI SNAP', style: TextStyle(fontFamily: 'Shikamaru'), ), actions: [ // cart button IconButton( onPressed: () { Navigator.pushNamed(context, '/cartpage'); }, icon: const Icon(Icons.shopping_cart), ), ], ), body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Starting Message Padding( padding: const EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'We Have All', style: GoogleFonts.tauri( fontSize: 30.0, color: Colors.grey[800]), textAlign: TextAlign.start, ), Text( 'The Sushi You Need', style: GoogleFonts.tauri( fontSize: 30.0, color: Colors.grey[800]), textAlign: TextAlign.start, ), ], ), ), // search bar Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 25), decoration: BoxDecoration(boxShadow: [ BoxShadow( color: Colors.grey.shade200, offset: const Offset(8.0, 8.0), blurRadius: 15.0, spreadRadius: 1.0, ), ]), child: TextField( cursorColor: primaryColor, decoration: InputDecoration( filled: true, fillColor: Colors.white, contentPadding: const EdgeInsets.symmetric(horizontal: 25, vertical: 20), focusedBorder: OutlineInputBorder( borderSide: const BorderSide(color: primaryColor, width: 3), borderRadius: BorderRadius.circular(50), ), enabledBorder: OutlineInputBorder( borderSide: const BorderSide(color: Colors.white, width: 3), borderRadius: BorderRadius.circular(50), ), hintText: "Search your food", ), ), ), // categories Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 25.0), child: Text( "Categories", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.grey[800], fontSize: 18, ), ), ), const SizedBox(height: 5.0), // categories SizedBox( height: 80, child: ListView.separated( shrinkWrap: true, // physics: const BouncingScrollPhysics(), padding: const EdgeInsets.symmetric(horizontal: 25.0), itemCount: categoryList.length, scrollDirection: Axis.horizontal, separatorBuilder: (context, index) => const SizedBox(width: 4.5), itemBuilder: (context, index) { return CategoryTile( category: categoryList[index], onTap: () {}, ); }, ), ), ], ), const SizedBox(height: 10), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 25.0), child: Text( "Popular Meals", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.grey[800], fontSize: 18, ), ), ), const SizedBox(height: 5.0), Container( height: 274, child: ListView.separated( padding: EdgeInsets.all(25), scrollDirection: Axis.horizontal, itemCount: foodMenu.length, separatorBuilder: (context, _) => const SizedBox(width: 10), itemBuilder: (context, index) => FoodTile( food: foodMenu[index], onTap: () {}, ), ), ), // Container( // decoration: BoxDecoration( // color: Colors.white, // borderRadius: BorderRadius.circular(20), // boxShadow: [ // BoxShadow( // color: Colors.grey.withOpacity(0.5), // spreadRadius: 3, // blurRadius: 10, // offset: Offset(0, 3), // ) // ], // ), // child: Padding( // padding: EdgeInsets.symmetric(horizontal: 10), // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Container( // alignment: Alignment.center, // child: Image.asset( // "lib/images/food/salmon/salmonSushi.png", // height: 150, // ), // ), // Text( // "Salmon Sushi", // style: TextStyle( // fontSize: 23, // fontWeight: FontWeight.bold, // ), // ), // SizedBox(height: 10), // Row( // mainAxisAlignment: MainAxisAlignment.spaceBetween, // children: [ // Text( // "Salmon+Sushi", // style: TextStyle( // fontSize: 18, // color: Colors.grey, // fontWeight: FontWeight.bold, // ), // ), // Text( // "4.9", // style: TextStyle( // fontSize: 18, // color: Colors.grey, // fontWeight: FontWeight.bold, // ), // ) // ], // ) // ], // ), // ), // ) ], ), // // menu list // Padding( // padding: const EdgeInsets.symmetric(horizontal: 25.0), // child: Text( // "Food Menu", // style: TextStyle( // fontWeight: FontWeight.bold, // color: Colors.grey[800], // fontSize: 18, // ), // ), // ), // const SizedBox(height: 10.0), // Expanded( // child: ListView.builder( // scrollDirection: Axis.horizontal, // itemCount: foodMenu.length, // itemBuilder: (context, index) => FoodTile( // food: foodMenu[index], // onTap: () => navigateToFoodItemDetails(index), // ), // ), // ), // const SizedBox(height: 25.0), // // popular food // Container( // decoration: BoxDecoration( // color: Colors.grey[100], // borderRadius: BorderRadius.circular(20), // ), // margin: const EdgeInsets.only(left: 25, right: 25, bottom: 25), // padding: const EdgeInsets.all(20), // child: Row( // mainAxisAlignment: MainAxisAlignment.spaceBetween, // children: [ // Row( // children: [ // // image // Image.asset('lib/images/salmon_eggs.png', height: 60.0), // const SizedBox(width: 20.0), // // name and price // Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // // name // Text( // "Salmon Eggs", // style: GoogleFonts.dmSerifDisplay( // fontSize: 18.0, // ), // ), // const SizedBox(height: 10.0), // // price // Text( // "\$21.00", // style: TextStyle( // color: Colors.grey[700], // ), // ), // ], // ), // ], // ), // // Heart // const Icon( // Icons.favorite_outline, // color: Colors.grey, // size: 28, // ) // ], // ), // ), ], ), ), ); } }
/** This file is part of ESP32BoardManager esp-idf component (https://github.com/CalinRadoni/ESP32BoardManager) Copyright (C) 2019 by Calin Radoni This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef WiFiConfig_H #define WiFiConfig_H #include "freertos/FreeRTOS.h" #include "esp_wifi.h" #include <string> class WiFiConfig { public: WiFiConfig(void); ~WiFiConfig(); std::string ssid; std::string pass; void Initialize(void); /** * @brief Check validity of data * * For now it only checks: * - 1 <= {@code ssid}.length() <= 31 * - 8 <= {@code pass}.length() <= 63 */ bool CheckData(void); void SetStationConfig(wifi_config_t*); void SetAPConfig(wifi_config_t*); void SetFromStrings(const char* strSSID, const char* strPASS); private: }; #endif
/** * ? Get authorization token */ import axios from "axios"; import { LoggerService } from "../../struct/general/LoggerService"; import { OAuthAccessToken } from "../../types/oauth_access_token"; async function listen() { const logger = new LoggerService("OsuApi"); logger.printInfo("Refreshing server authorization token"); try { let tokens = await axios<OAuthAccessToken>( "https://osu.ppy.sh/oauth/token", { method: "post", timeout: 999999, headers: { "Content-Type": "application/json", }, data: JSON.stringify({ client_id: process.env.OSU_CLIENT_ID, client_secret: process.env.OSU_CLIENT_SECRET, grant_type: "client_credentials", scope: "public", }), } ); // Auto-Refresh token setTimeout(listen, Number(tokens.data.expires_in) * 1000); process.env.OSU_API_ACCESS_TOKEN = tokens.data.access_token; console.log(process.env.OSU_API_ACCESS_TOKEN); logger.printSuccess("Server authorization token refreshed"); return tokens.data; } catch (e: any) { logger.printError("Error during token refresh:\n"); console.error(e); setTimeout(listen, 5000); return null; } } export const generateOsuApiToken = listen;
// Copyright © SixtyFPS GmbH <info@slint-ui.com> // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial import { DemoPalette, Page } from "common.slint"; import { HomePage } from "./home_page.slint"; import { InkLevel, InkPage } from "./ink_page.slint"; import { SettingsPage } from "./settings_page.slint"; import { PrinterQueue } from "./printer_queue.slint"; // re-export for the native code export { PrinterQueue } import "./fonts/NotoSans-Regular.ttf"; import "./fonts/NotoSans-Bold.ttf"; component SideBarIcon inherits Rectangle { in-out property <bool> active; callback activate; GridLayout { padding: 0px; @children } TouchArea { clicked => { root.activate(); } } } export component MainWindow inherits Window { callback quit(); width: 320px; height: 240px; title: "Slint printer demo"; background: DemoPalette.main-background; default-font-family: "Noto Sans"; default-font-size: DemoPalette.base-font-size; /// Note that this property is overwritten in the .cpp and .rs code. /// The data is only in this file so it looks good in the viewer in property <[InkLevel]> ink-levels: [ {color: #0ff, level: 60%}, {color: #ff0, level: 80%}, {color: #f0f, level: 70%}, {color: #000, level: 30%}, ]; out property<int> active-page: 0; HorizontalLayout { padding: 10px; padding-left: 37px; main-view := Rectangle { height: 100%; border-radius: 20px; background: DemoPalette.page-background-color; Rectangle { clip: true; x: main-view.border-radius / 2; y: main-view.border-radius / 2; width: main-view.width - main-view.border-radius; height: main-view.height - main-view.border-radius; home-page := HomePage { y: root.active-page == 0 ? 0 : root.active-page < 0 ? - self.height - 1px : parent.height + 1px; animate y { duration: 125ms; easing: ease; } } SettingsPage { y: root.active-page == 1 ? 0 : root.active-page < 1 ? - self.height - 1px : parent.height + 1px; animate y { duration: 125ms; easing: ease; } } InkPage { y: root.active-page == 2 ? 0 : root.active-page < 2 ? - self.height - 1px : parent.height + 1px; animate y { duration: 125ms; easing: ease; } ink-levels <=> root.ink-levels; page-visible: root.active-page == 2; } } } } sidebar := Rectangle { width: 7px; x: 5px; function icon-y(index: int) -> length { return 40px // top padding + index * 38px; } Image { x:0; source: @image-url("images/page_selection.svg"); y: sidebar.icon-y(root.active-page) - self.width / 2; animate y { duration: 125ms; } width: main-view.x - sidebar.x + 1px; height: 1.75 * self.width; colorize: DemoPalette.page-background-color; } for page-icon[idx] in [ @image-url("images/home.svg"), @image-url("images/settings.svg"), @image-url("images/ink.svg"), ] : SideBarIcon { y: sidebar.icon-y(idx); x: 6px; height: 20px; width: 20px; icon := Image { colorize: (root.active-page == idx) ? DemoPalette.active-page-icon-color : DemoPalette.inactive-page-icon-color; animate colorize { duration: 125ms; } source: page-icon; image-fit: contain; width: 100%; height: 100%; } activate => { root.active-page = idx; } } Rectangle { y: sidebar.icon-y(3); x: 5px; background: #6284FF; height: 2px; width: 20px; } SideBarIcon { y: sidebar.icon-y(4) - 10px; x: 6px; height: 20px; width: 20px; Image { colorize: DemoPalette.night-mode ? #F1FF98 : DemoPalette.inactive-page-icon-color; source: DemoPalette.night-mode ? @image-url("images/moon_full.svg") : @image-url("images/moon.svg"); image-fit: contain; width: 100%; height: 100%; } activate => { DemoPalette.night-mode = !DemoPalette.night-mode; } } } }
<?php namespace common\models; use backend\models\Staff; use common\base\Status; use Symfony\Component\Yaml\Yaml; use Yii; use yii\bootstrap5\Html; use yii\caching\TagDependency; use yii\helpers\ArrayHelper; use yii\web\User; /** * This is the model class for table "{{%language}}". * * @property int $id * @property string $name * @property string $key * @property int $is_default * @property int $status * @property int $created_by * @property int $created_at * @property int $updated_by * @property int $updated_at * * @property-read array $languages * @property-read array $statuses * @property-read string $systemKey * @property User $author */ class Language extends BaseActiveRecord{ const DEFAULT_LANGUAGE = 1; const SESSION_KEY = 'language.current'; public static $alias = 'language'; /** * {@inheritdoc} */ public static function tableName(){ return '{{%language}}'; } /** * {@inheritdoc} */ public function rules(){ return [ [['name', 'key'], 'required'], [['is_default', 'status', 'created_by', 'created_at', 'updated_by', 'updated_at'], 'integer'], [['name', 'key'], 'string', 'max' => 255], [['key'], 'unique'], ]; } /** * {@inheritdoc} */ public function attributeLabels(){ return [ 'name' => Yii::t('common', 'Name'), 'key' => Yii::t('common', 'Source Language'), 'is_default' => Yii::t('common', 'Default Language'), 'status' => Yii::t('common', 'Status'), 'created_by' => Yii::t('common', 'Author'), 'created_at' => Yii::t('common', 'Created at'), 'updated_by' => Yii::t('common', 'Updated By'), 'updated_at' => Yii::t('common', 'Updated At'), ]; } /** * @return array */ public function behaviors(){ $behaviors = parent::behaviors(); unset($behaviors['status'], $behaviors['language']); $behaviors['audit']['module'] = Yii::t('common', 'System'); $behaviors['audit']['category'] = Yii::t('common', 'Language'); return $behaviors; } /** * @return array|mixed */ public function getConfigs(){ $app_path = Yii::getAlias("@common/language.yml"); return Yaml::parseFile($app_path); } /** * @return array */ public function getLanguages(){ $languages = $this->getConfigs(); if (!empty($languages)){ return ArrayHelper::getColumn($languages, 'name', TRUE); } return []; } /** * @return array */ public function getSourceLanguages(){ $languages = $this->getConfigs(); if (!empty($languages)){ return ArrayHelper::getColumn($languages, 'source', TRUE); } return []; } /** * @return \yii\db\ActiveQuery */ public function getAuthor(){ return $this->hasOne(Staff::class, ['id' => 'created_by']); } /** * @return array */ public function getStatuses(){ $statuses = Status::states(); unset($statuses[Status::STATUS_ALL]); return $statuses; } /** * @param bool $insert * * @return bool */ public function beforeSave($insert){ if ($this->is_default){ $this->status = Status::STATUS_ACTIVE; } return parent::beforeSave($insert); } /** * @param bool $insert * @param array $changedAttributes */ public function afterSave($insert, $changedAttributes){ if ($this->is_default){ $condition = ['and', ['is_default' => self::DEFAULT_LANGUAGE], ['!=', 'id', $this->id]]; Language::updateAll(['is_default' => 0], $condition); } TagDependency::invalidate(Yii::$app->cache, [ self::SESSION_KEY . '.list', self::SESSION_KEY . '.default' ]); parent::afterSave($insert, $changedAttributes); } /** * @return mixed|string */ public function getSystemKey(){ if (!empty($this->languages[$this->key])){ return $this->languages[$this->key] . Html::tag('span', $this->key, ['class' => 'badge badge-soft-info ml-2']); } return $this->key; } /** * @param bool $all * * @return array * @throws \Throwable */ public static function listLanguage($all = TRUE){ $languages = self::getDb()->cache(function (){ return self::find()->orderBy(['name' => SORT_ASC])->asArray()->all(); }, 0, new TagDependency([ 'tags' => self::SESSION_KEY . '.list' ])); if (!empty($languages)){ if (empty($all)){ foreach ($languages as $id => &$language){ if (empty($language['status'])){ unset($languages[$id]); } } } return ArrayHelper::map($languages, 'key', 'name'); } return []; } /** * @return mixed|null * @throws \Throwable */ public static function current(){ if (Yii::$app->has('session')){ return Yii::$app->session->get(static::SESSION_KEY, self::default()); } return self::default(); } /** * @return mixed|null * @throws \Throwable */ public static function currentName(){ $current = self::current(); return self::listLanguage(FALSE)[$current] ?? ''; } /** * @return mixed|null * @throws \Throwable */ public static function currentSource(){ $sources = (new static())->getSourceLanguages(); return $sources[static::current()] ?? static::current(); } /** * @param null|string $language * * @return bool * @throws \yii\db\Exception */ public static function setDefault($language = NULL){ if (empty($language)){ Yii::$app->session->remove(static::SESSION_KEY); return TRUE; } if (self::find() ->andWhere(['key' => $language, 'status' => Status::STATUS_ACTIVE]) ->exists()){ Yii::$app->session->set(static::SESSION_KEY, $language); self::storeLang($language); return TRUE; } return FALSE; } /** * @param $language * * @return int * @throws \yii\db\Exception */ private static function storeLang($language){ $user = Yii::$app->user->identity->id ?? NULL; if (!empty($user)){ return Yii::$app->db->createCommand()->upsert(UserLanguage::tableName(), [ 'user_id' => $user, 'language' => $language, ], [ 'language' => $language ])->execute(); } return NULL; } /** * @return mixed|string * @throws \Throwable */ public static function default(){ $default = self::getDb()->cache(function (){ return self::find() ->select(['key']) ->default() ->andWhere(['is_default' => self::DEFAULT_LANGUAGE]) ->scalar(); }, 0, new TagDependency([ 'tags' => self::SESSION_KEY . '.default' ])); if (empty($default)){ return Yii::$app->params['language.default'] ?? Yii::$app->language; } return $default; } /** * @return false|string */ public static function app(){ $language = Yii::$app->language; if ($language == 'zh-CN'){ $custom_language = 'cn'; }elseif ($language == 'zh-TW'){ $custom_language = 'tw'; }else{ $custom_language = $language; } return $custom_language; } }
import { expect } from '@playwright/test'; import os from 'os'; import { testFactory } from './test-utils.js'; const test = testFactory({ root: './fixtures/wromo-component/' }); let devServer; test.beforeEach(async ({ wromo }) => { devServer = await wromo.startDevServer(); }); test.afterEach(async () => { await devServer.stop(); }); test.describe('Wromo component HMR', () => { test('component styles', async ({ page, wromo }) => { await page.goto(wromo.resolveUrl('/')); const hero = page.locator('section'); await expect(hero, 'hero has background: white').toHaveCSS( 'background-color', 'rgb(255, 255, 255)' ); await expect(hero, 'hero has color: black').toHaveCSS('color', 'rgb(0, 0, 0)'); // Edit the Hero component with a new background color await wromo.editFile('./src/components/Hero.wromo', (content) => content.replace('background: white', 'background: rgb(230, 230, 230)') ); await expect(hero, 'background color updated').toHaveCSS( 'background-color', 'rgb(230, 230, 230)' ); }); // TODO: Re-enable this test on windows when #3424 is fixed // https://github.com/Wromo/wromo/issues/3424 const it = os.platform() === 'win32' ? test.skip : test; it('hoisted scripts', async ({ page, wromo }) => { const initialLog = page.waitForEvent( 'console', (message) => message.text() === 'Hello, Wromo!' ); await page.goto(wromo.resolveUrl('/')); await initialLog; const updatedLog = page.waitForEvent( 'console', (message) => message.text() === 'Hello, updated Wromo!' ); // Edit the hoisted script on the page await wromo.editFile('./src/pages/index.wromo', (content) => content.replace('Hello, Wromo!', 'Hello, updated Wromo!') ); await updatedLog; }); });
from django.db import models from django.urls import reverse # Create your models here. class List(models.Model): text = models.TextField(default="") def get_absolute_url(self): return reverse('view_list',args=[self.id]) class Item(models.Model): text = models.TextField(default="") list = models.ForeignKey(List,default=None) def __str__(self): return self.text class Meta: ordering = ('id',) unique_together = ('list', 'text')
from pathlib import Path from typing import Any from jsonargparse import Namespace from lightning.pytorch import LightningModule, Trainer from lightning.pytorch.cli import ( LightningArgumentParser, LightningCLI, SaveConfigCallback, ) from lightning.pytorch.loggers import WandbLogger class CustomSaveConfigCallback(SaveConfigCallback): def __init__( self, parser: LightningArgumentParser, config: Namespace | Any, config_filename: str = "cli_config.yaml", overwrite: bool = False, multifile: bool = False, save_to_log_dir: bool = False, ) -> None: super().__init__( parser, config, config_filename, overwrite, multifile, save_to_log_dir ) def add_arguments_to_parser(self, parser: LightningArgumentParser): parser.link_arguments("trainer.num_training_steps", "model.num_training_steps") def save_config( self, trainer: Trainer, pl_module: LightningModule, stage: str ) -> None: if len(trainer.loggers) > 0 and stage == "fit": wandb_loggers = [ logger for logger in trainer.loggers if isinstance(logger, WandbLogger) ] if len(wandb_loggers) > 0: wandb_logger = wandb_loggers[0] config_path = Path(wandb_logger.experiment.dir) / self.config_filename config_path.write_text( self.parser.dump(self.config, skip_none=False, yaml_comments=True) ) def run(): cli = LightningCLI( subclass_mode_data=True, subclass_mode_model=True, save_config_callback=CustomSaveConfigCallback, ) if __name__ == "__main__": run()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <!-- ontawesome --> <script src="https://kit.fontawesome.com/dc4c242f43.js" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="/assets/css/styles.css"> <title>Portfolio</title> </head> <body id="home"> <header> <!-- ...............Inicio de Navbar --> <nav class="navbar navbar-nav bg-secondary"> <div class="container-fluid"> <!-- ...............Inicio de Logo Argentina Programa --> <div class="col-2"> <a class="navbar-brand" href="https://argentinaprograma.inti.gob.ar/" target="_blank"> <img src="/assets/img/AP-logo.png" alt="Logo Argentina Programa" width="100%"> </a> </div> <!-- ...............Fin de Logo Argentina Programa --> <!-- ...............Inicio de redes sociales y login--> <ul class="list-group list-group-horizontal"> <li class="list-group-item"><a href="https://github.com/mariemelendez88?tab=repositories" target="_blank"><i class="fa-brands fa-github fa-xl text-white"></i></a></li> <li class="list-group-item"><a href="https://www.linkedin.com/in/mariemdeveloper/" target="_blank"><i class="fa-brands fa-linkedin fa-xl text-white"></i></a></li> <li class="list-group-item"> <i class="fa-solid fa-right-to-bracket fa-xl text-white" type="button" data-bs-toggle="modal" data-bs-target="#ModalLogin"></i> </li> </ul> <!-- ...............Fin de redes sociales y login--> </div> </nav> <!-- ...............Fin de Navbar --> <!-- ...............Inicio de Modal para Login --> <div class="modal fade" id="ModalLogin" tabindex="-1" aria-labelledby="ModalLogin" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="exampleModalLabel">Formulario Login</h4> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="mb-3 row"> <label for="staticEmail" class="col-sm-4 col-form-label"><i class="fa-solid fa-envelope"></i>&nbsp;&nbsp;&nbsp;Email: </label> <div class="col-sm-8"> <input type="text" class="form-control" name="email" placeholder="email@dominio.com" required="required"> </div> </div> <div class="mb-3 row"> <label for="inputPassword" class="col-sm-4 col-form-label"><i class="fa-solid fa-lock"></i>&nbsp;&nbsp;&nbsp;Contraseña: </label> <div class="col-sm-8"> <input type="password" class="form-control" name="password" placeholder="********" required="required"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary">Ingresar</button> </div> </div> </div> </div> <!-- ...............Fin de Modal para Login --> </header> <main class="body"> <!-- ..............Inicio Seccion Acerca de Mi --> <section id="acerca-de-mi"> <img src="../assets/img/banner2.png" class="w-100 img-fluid" alt="Imagen de Banner"> <div class="container-fluid text-center card-body row"> <div class="col-2 col-md-1"></div> <div class="col-12 col-md-3"> <img class="rounded-circle img" src="../assets/img/pfp.png" alt="engineer, full stack" title="Marie Melendez"> <h1 class="titulo">Marie Melendez</h1> <h4 class="info">Full Stack Developer Jr.</h4> </div> <div class="col-12 col-md-6 pt-5"> <h2 class="titulo">Acerca de Mi</h2> <h5 class="info"> Ingeniero electricista con más de 10 años de experiencia en la planificación, organización, desarrollo y supervisión de proyectos eléctricos. Ahora en búsqueda laboral de mi primera experiencia como programador, utilizando el aprendizaje y aplicación efectivo del conocimiento en los distintos cursos relacionados al área. </h5> </div> </div> <!-- ..............Fin Seccion Acerca de Mi --> </section> <!-- .............Inicio Experiencia................ --> <section id="experiencia" class="experiencia mt-5"> <div class="container-fluid"> <div class="row"> <div class="titulo-exp"> <h1 class="text-center linea-exp">EXPERIENCIA</h1> </div> <div class="mt-3 mb-2 caja-exp"> <ul> <!--Experiencia 1--> <li class="list-group-item mt-5"> <div class="container row"> <div class="col-4 mt-2 text-center"> <a href="https://gocode.ar/" class="col-3 text-center"> <img src="/assets/img/gocode.png" class="logo-exp" width="70rem"> </a> </div> <div class="col"> <h3>Developer</h3> <h4>(2022-Actual)</h4> <p>Trabajo en equipo para poner en práctica conocimientos de programación.</p> </div> </div> </li> <!--Experiencia 2--> <li class="list-group-item mt-5"> <div class="container row"> <div class="col-4 mt-2 text-center"> <a href="https://www.worley.com/" class="col-3 text-center"> <img src="/assets/img/Worley-logo.png" class="logo-exp" width="70rem"> </a> </div> <div class="col"> <h3>Senior Electrical Engineer</h3> <h4>(2017-Actual)</h4> <p>Planificación, diseño, ejecución y supervisión de proyectos de ingeniería eléctrica.</p> </div> </div> </li> <!--Experiencia 3--> <li class="list-group-item mt-5"> <div class="container row"> <div class="col-4 mt-2 text-center"> <a href="http://www.usb.ve/" class="col-3 text-center"> <img src="/assets/img/USB-logo.png" class="logo-exp" width="70rem"> </a> </div> <div class="col"> <h3>Profesor</h3> <h4>(2013-2017)</h4> <p>Profesor de materias teóricas y prácticas de Ingeniería Eléctrica.</p> </div> </div> </li> </ul> </div> </div> </div> <!-- ..............Fin Experiencia.................. --> </section> <!-- .............Inicio Educacion................ --> <section id="educacion" class="educacion mt-5"> <div class="container-fluid"> <div class="row"> <div class="titulo-edu"> <h1 class="text-center linea-edu">EDUCACIÓN</h1> </div> <div class="mt-3 mb-2 caja-exp"> <ul> <!--Estudio 1--> <li class="list-group-item mt-5"> <div class="container row"> <div class="col-4 mt-2 text-center"> <a href="https://argentinaprograma.inti.gob.ar/" class="col-3 text-center"> <img src="/assets/img/Argentina-Programa.png" class="logo-exp" width="70rem"> </a> </div> <div class="col"> <h3>Full Stack Developer</h3> <h4>(2022-2023)</h4> <p>Programa de Estudio Digital de programación de páginas web incluyendo frontend y backend.</p> </div> </div> </li> <!--ESTUDIO 2--> <li class="list-group-item mt-5"> <div class="container row"> <div class="col-4 mt-2 text-center"> <a href="https://www.usb.ve/" class="col-3 text-center"> <img src="/assets/img/USB-logo.png" class="logo-exp" width="70rem"> </a> </div> <div class="col"> <h3>ingeniero Electricista</h3> <h4>(2006-2013)</h4> <p>Sistemas de Potencia, Máquinas Eléctricas</p> </div> </div> </li> </ul> </div> </div> </div> <!-- ..............Fin Educacion.................. --> </section> <!-- .............Inicio Skills................ --> <section id="skills" class="skills mt-5"> <div class="container-fluid"> <div> <div class="titulo-skill"> <h1 class="text-center linea-skill">SKILLS</h1> </div> </div> </div> <ul class="row"> <!-- ..............FRONTEND --> <div class="col-12 col-md-6 caja-skill mt-3"> <li class="item-skill mt-3"> <h2 class="tit-item-skill mb-3">Frontend</h2> <!-- HTML5 --> <p>HTML5</p> <div class="progress mb-4 " style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-frontend" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 90%">90%</div> </div> <!-- CSS3 --> <p>CSS3</p> <div class="progress mb-4" style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-frontend" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 80%">80%</div> </div> <!-- Angular --> <p>ANGULAR</p> <div class="progress mb-4" style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-frontend" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 75%">75%</div> </div> </li> </div> <!-- ..............BACKEND --> <div class="col-12 col-md-6 caja-skill mt-3"> <li class="item-skill mt-3"> <h2 class="tit-item-skill mb-3">Backend</h2> <!-- Python --> <p>Python</p> <div class="progress mb-4 " style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-backend" role="progressbar" aria-valuenow="88" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 88%">88%</div> </div> <!-- Java --> <p>Java</p> <div class="progress mb-4 " style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-backend" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 50%">50%</div> </div> <!-- Springboot --> <p>Springboot</p> <div class="progress mb-4 " style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-backend" role="progressbar" aria-valuenow="35" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 35%">35%</div> </div> </li> </div> <!-- ..............IDIOMAS --> <div class="col-12 col-md-6 caja-skill mt-3"> <li class="item-skill mt-3"> <h2 class="tit-item-skill mb-3">Idiomas</h2> <!-- Español --> <p>Español</p> <div class="progress mb-4 " style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-idiomas" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 100%">100%</div> </div> <!-- Inglés --> <p>Español</p> <div class="progress mb-4 " style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-idiomas" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 80%">80%</div> </div> </li> </div> <!-- ..............OTROS --> <div class="col-12 col-md-6 caja-skill mt-3"> <li class="item-skill mt-3"> <h2 class="tit-item-skill mb-3">Otros</h2> <!-- Scrum --> <p>Scrum</p> <div class="progress mb-4 " style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-otros" role="progressbar" aria-valuenow="82" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 82%">82%</div> </div> <!-- Planificación --> <p>Planificación</p> <div class="progress mb-4 " style="height: 1.5rem"> <div class="progress-bar progress-bar-striped progress-bar-animated skill-otros" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="height: 1.5rem; width: 80%">80%</div> </div> </li> </div> </ul> <!-- ..............Fin Skills.................. --> </section> <!-- .............Inicio Proyectos................ --> <section id="proyectos" class="proyectos mt-5"> <div class="container-fluid"> <div class="titulo-proy"> <h1 class="text-center linea-proy">PROYECTOS</h1> </div> <div class="row g-4"> <div class="col-12 col-md-4"> <div class="card"> <img src="/assets/img/proyecto-calculator.png" class="card-img-top p-2" alt="interest, calculator"> <div class="card-body"> <h5 class="card-title">Calculadora de interés simple</h5> <p class="card-text">Calculadora de interés simple para computar cálculos sencillos</p> <a href="https://github.com/mariemelendez88/vftvk-Simple-Interest-Calculator.git" target="_blank" class="btn btn-primary">Ver código</a> <a href="https://htmlpreview.github.io/?https://github.com/mariemelendez88/vftvk-Simple-Interest-Calculator/blob/master/index.html" target="_blank" class="btn btn-info">Ver online</a> </div> </div> </div> <div class="col-12 col-md-4"> <div class="card"> <img src="/assets/img/proyecto-maquetaHTML.png" class="card-img-top p-2" alt="interest, calculator"> <div class="card-body"> <h5 class="card-title">Portfolio Front End</h5> <p class="card-text">Maquetado de portfolio utilizando HTML, CSS, Bootstrap y Fontawesome.</p> <a href="https://github.com/mariemelendez88/MaquetaHTML.git" target="_blank" class="btn btn-primary">Ver código</a> <a href="https://htmlpreview.github.io/?https://github.com/mariemelendez88/vftvk-Simple-Interest-Calculator/blob/master/index.html" target="_blank" class="btn btn-info">Ver online</a> </div> </div> </div> <div class="col-12 col-md-4"> <div class="card"> <img src="/assets/img/Proyectos-GoCode.PNG" class="card-img-top p-2" alt="interest, calculator"> <div class="card-body"> <h5 class="card-title">Página web GoCode</h5> <p class="card-text">Pestaña 'Proyectos' que muestra las websites desarrolladas por GoCode.</p> <a href="#" target="_blank" class="btn btn-primary">Ver código</a> <a href="#" target="_blank" class="btn btn-info">Ver online</a> </div> </div> </div> </div> </div> <!-- ..............Fin Proyectos.................. --> </section> <!-- .............Inicio Referencias................ --> <section id="referencias" class="referencias mt-5"> <div class="container-fluid"> <div class="titulo-ref"> <h1 class="text-center linea-ref">REFERENCIAS</h1> </div> <div class="row g-4 text-center"> <div class="col-12 col-lg-4 text-center"> <div class="mt-3 mb-2 caja-ref text-center"> <h3>Juan Perez</h3> <h5>+54 9 11 0000-0000</h5> <h5>juanp@mail.com</h5> </div> </div> <div class="col-12 col-lg-4 text-center"> <div class="mt-3 mb-2 caja-ref text-center"> <h3>Maria Esparza</h3> <h5>+54 9 11 0000-0000</h5> <h5>mariae@mail.com</h5> </div> </div> <div class="col-12 col-lg-4 text-center"> <div class="mt-3 mb-2 caja-ref text-center"> <h3>Francisco Lara</h3> <h5>+54 9 11 0000-0000</h5> <h5>franciscol@mail.com</h5> </div> </div> <div class="col-1"></div> </div> </div> <!-- ..............Fin Referencias.................. --> </section> <!-- .............Inicio Footer............... --> <section id="footer"> <br><br> <div class="container-fluid text-center"> <footer class="footer"> <p> <button type="button" class="caja" data-bs-toggle="modal" data-bs-target="#ModalAcercade"> <a href="../assets/download/CV-Melendez_Marie - Developer-ENG.pdf" download="CV-Melendez_Marie"> <i class="fa-solid fa-download fa-2x"></i> </a> </button> &copy; Copyright, MarieM 2022. All Rights Reserved </p> </footer> </div> </section> </main> <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script> </body> </html>
"use client"; import React, { Component } from "react"; import { Grid, Container } from "semantic-ui-react"; import Particles from "react-tsparticles"; import { loadFull } from "tsparticles"; import JsFileDownloader from "js-file-downloader"; const ytdl = require("ytdl-core"); import { formatTime, formatNumber } from "../utils"; import ErrorMessage from "../components/ErrorMessage"; import Footer from "../components/Footer"; import VideoCard from "../components/VideoCard"; import Form from "../components/Form"; import Loader from "../components/Loader"; import Header from "../components/Header"; import HomeText from "../components/HomeText"; import AudioCard from "../components/AudioCard"; export default class Page extends Component { constructor() { // Prevent defaultProps error const error = console.error; console.error = (...args) => { if (/defaultProps/.test(args[0])) return; error(...args); }; super(); } state = { isParticleLoading: true, videoUrl: "", videoUrlError: false, isSearching: false, videoInfo: null, errorMessage: null, downloadingPercentage: null, isVisible: false, }; componentDidMount() { this.timeout = setTimeout(() => { this.setState({ isVisible: true }); }, 500); } componentWillUnmount() { clearTimeout(this.timeout); } particlesInit = async (engine) => await loadFull(engine); particlesLoaded = () => this.setState({ isParticleLoading: false }); stripYoutubeId = (url) => { url = url.split( /^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/|shorts\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/ ); return url.length > 1 ? url[1] : ""; }; validateYoutubeUrlId = () => { if (!this.state.videoUrl) { this.setState({ videoUrlError: true }); return false; } let videoId = this.stripYoutubeId(this.state.videoUrl); if (!ytdl.validateID(videoId)) { this.setState({ videoUrlError: true }); return false; } this.setState({ videoUrlError: false }); return true; }; onChangeInput = (value) => { this.setState({ videoUrl: value }, () => { if (this.state.videoUrlError) this.validateYoutubeUrlId(); }); }; onSearch = async () => { let videoUrlIdValid = this.validateYoutubeUrlId(); if (!videoUrlIdValid) { return; } let videoId = this.stripYoutubeId(this.state.videoUrl); this.setState({ isSearching: true, errorMessage: null }); await fetch("/api/getInfo", { method: "POST", body: JSON.stringify({ videoId, }), }) .then((res) => res.json()) .then((res) => { if (res.success) { this.setState({ videoInfo: { ...res.details, thumbnail: res.details.thumbnail.thumbnails.length ? res.details.thumbnail.thumbnails.slice(-1)[0].url : "/not_found.jpg", length: res.details.lengthSeconds ? formatTime(res.details.lengthSeconds) : null, viewCount: res.details.viewCount ? formatNumber(res.details.viewCount) : null, formats: res.formats.map((item) => ({ ...item, isDownloading: false, })), }, }); } else { this.setState({ errorMessage: res.error, videoInfo: null }); } }) .catch((err) => { this.setState({ errorMessage: "Internal server errror, please, try again later.", videoInfo: null, }); console.error(err); }) .finally(() => this.setState({ isSearching: false, downloadingPercentage: null }) ); }; onDownload = async (itag, mimeType, quality, contentLength) => { this.setState({ videoInfo: { ...this.state.videoInfo, formats: this.state.videoInfo.formats.map((item) => ({ ...item, isDownloading: item.itag === itag ? true : false, })), }, errorMessage: null, downloadingPercentage: 0, }); const fileName = `${quality}-${this.state.videoInfo.title}.${ mimeType.includes("audio") ? "m4a" : "mp4" }`; const download = new JsFileDownloader({ url: "api/download", method: "POST", body: JSON.stringify({ itag, videoId: this.state.videoInfo.videoId, }), filename: fileName, contentTypeDetermination: "full", autoStart: false, forceDesktopMode: true, process: (event) => { var downloadingPercentage = Math.floor( (event.loaded / contentLength) * 100 ); this.setState({ downloadingPercentage }); }, }); download .start() .then(() => { this.setState({ downloadingPercentage: 100 }); setTimeout(() => this.setState({ downloadingPercentage: null }), 2000); }) .catch((err) => { if (err.request.status == 429) { this.setState({ errorMessage: "Numerous downloads in a short time, please wait for 10 seconds and then try again.", }); } else { this.setState({ errorMessage: "Error occurred while downloading video, please, try again later.", }); } this.setState({ downloadingPercentage: null }); }) .finally(() => { this.setState({ videoInfo: { ...this.state.videoInfo, formats: this.state.videoInfo.formats.map((item) => ({ ...item, isDownloading: false, })), }, }); }); }; render() { return ( <> <Header /> <Particles id="tsparticles" init={this.particlesInit} loaded={this.particlesLoaded} url="/particles.json" /> {this.state.isParticleLoading ? ( <Loader /> ) : ( <Container style={{ opacity: this.state.isVisible ? 1 : 0, transition: "opacity 0.5s ease-in-out", }} > <Grid verticalAlign="middle" textAlign="center" stackable> <Form isSearching={this.state.isSearching} videoUrlError={this.state.videoUrlError} onChangeInput={this.onChangeInput} onSearch={this.onSearch} /> <ErrorMessage errorMessage={this.state.errorMessage} active={Boolean(this.state.errorMessage)} /> <AudioCard videoInfo={this.state.videoInfo} active={Boolean(this.state.videoInfo)} downloadingPercentage={this.state.downloadingPercentage} onDownload={this.onDownload} onMp3={true}/> <HomeText /> <Footer /> </Grid> </Container> )} </> ); } }
function gain_mat=bem_gainmat(Rq_bemgrid,Xfer,Verbose) %BEM_GAINMAT - Computes the EEG/MEG forward/gain matrix associated with a set of grid points % function gain_mat=bem_gain(Rq_bemgrid,Xfer, Verbose) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EEG/MEG BEM 3-D GRID FORWARD GAIN CALCULATION UTILITY % % This function computes the EEG/MEG forward matrix (kernel) associated with a set of % grid points. % % INPUTS (Required): % Rq_bemgrid: a structure of specific source locations (Nx3 array) % % Xfer: a structure variable return from bem_transfer % Xfer.basis_opt: string --- constant bem or linear bem % Xfer.test_opt: string -- collocation, glerkin % Xfer.mode: mode type % Xfer.geometry: geometry matrix % Xfer.nodes: nodes matrix % Xfer.cdv: conductivity vector % Xfer.Te: the EEG transfermation matrix % Xfer.Tm: the MEG transformation matrix % Xfer.Te_ISA: the EEG transfermation matrix with ISA % Xfer.Tm_ISA: the MEG transformation matrix with ISA % Xfer.eegsensor: eegsensor % Xfer.R_eeg: R_eeg % Xfer.P_sens: P_sens % Xfer.R_meg: the MEG sensor locations, no_sensor by 3 % Xfer.O_meg: the MEG sensor orientations, no_sensor by 3 % % OUTPUTS: Complete set of output parameters are stored in user specified % "*.mat" file defined by "bem_gaingrid_mfname.mat" % gain_matrix.eeg: the eeg gain matrix (N_eeg_sensor by 3*N_dip) % EEG unit: uV/nAm % gain_matrix.meg: the meg gain matrix (N_meg_sensor by 3*N_dip) % MEG unit: fT/nAm % % Other Notes: 3x3 MEG kernel is dotted with sensor orientation to generate more compact % 1x3 kernel % % By M.X. Huang, PhD, March 2004 % % % scale_meg=0.1; % scaling factor converting MEG fields into fT by nAm dipole: 1e-7(mu_0/4pi) x 1e-9 (nAm) x 1e15(fT) scale_eeg=0.001; % scaling factor converting EEG into uV by nAm dipole: 1e-9 (nAm) x 1e6 (uV) if Xfer.ISA==0 if Xfer.mode==1 Te_save = Xfer.Te; Tm_save = []; % Dummy value for kernel routine elseif Xfer.mode==2 Tm_save = Xfer.Tm; Te_save = []; % Dummy value for kernel routine else Tm_save = Xfer.Tm; Te_save = Xfer.Te; end elseif Xfer.ISA==1 if Xfer.mode==1 Te_save = Xfer.Te_ISA; Tm_save = []; elseif Xfer.mode==2 Tm_save = Xfer.Tm_ISA; Te_save = []; else Tm_save = Xfer.Tm_ISA; Te_save = Xfer.Te_ISA; end else if Verbose sprintf('Invalid ISA option chosen!!!') end end % clear Xfer.Te Xfer.Tm Xfer.Te_ISA Xfer.Tm_ISA % %%%% THIS PART DETERMINES DIMENSION PARAMETERS AND DIVIDES THE INPUT DIPOLE SET INTO A SET OF BLOCKS %%%% % if Xfer.mode==1 %EEG only Meeg = size(Xfer.R_eeg,1); % Number of Sensors S = []; R_meg = []; O_meg = []; elseif Xfer.mode==2 %MEG only Mmeg = size(Xfer.R_meg,1); Xfer.R_eeg = []; Xfer.P_wts = []; else Meeg = size(Xfer.R_eeg,1); % Number of Sensors Mmeg = size(Xfer.R_meg,1); % Number of Sensors end % P = size(Rq_bemgrid,1); % Number of Dipole Locations % BLK_SIZE = 50; % Maximum Number of dipoles to process at a single time % Set to prevent overstepping memory bounds in Kernel Calculation blk_tot = floor(P/BLK_SIZE); % Total Number of blocks blk_rem = rem(P,BLK_SIZE); % Residual Number of Dipoles % %%%% THIS PART COMPUTES THE GAIN MATRIX KERNEL (PROCESSING A BLOCK AT A TIME) %%%% % t0 = clock; % Start the clock a tickin... if Verbose hwait = waitbar(0,'Creating the gain matrix for selected sources. . .'); end % if Xfer.mode==1 % EEG Reeg = Xfer.eegsensor(:,2:4); Rmeg = []; Gmeg_grid = []; Geeg_grid = zeros(Meeg,3*P); % Pre-initialize Output for nblk = 1:blk_tot n1 = (nblk-1)*3*BLK_SIZE + 1; % equivalent dipole start index n2 = nblk*3*BLK_SIZE; % equivalent dipole end index n3 = (nblk-1)*BLK_SIZE + 1; % dipole start index n4 = nblk*BLK_SIZE; % dipole end index [Geeg_grid(:,n1:n2) dummy] = bem_kernel(Rq_bemgrid(n3:n4,:),Xfer.basis_opt,Xfer.test_opt,Xfer.geometry,Xfer.nodes,Xfer.cdv,Te_save,Xfer.P_wts,Tm_save,Xfer.R_meg); telap = etime(clock,t0); trem = telap*(P-n4)/n4; if Verbose & ~rem(nblk,10) %bst_message_window('overwrite', sprintf('Completed %.0f of %.0f grid points in %3.2f Sec.',n4,P,telap)) %Expected time to complete: %.2f Sec....',n4,P,telap,trem)) waitbar(nblk/blk_tot, hwait); end end if blk_rem > 0 n1 = blk_tot*3*BLK_SIZE + 1; % equivalent dipole start index (for residual dipoles) n2 = 3*P; % equivalent dipole end index (for residual dipoles) n3 = blk_tot*BLK_SIZE + 1; % dipole start index n4 = P; % dipole end index [Geeg_grid(:,n1:n2) dummy] = bem_kernel(Rq_bemgrid(n3:P,:),Xfer.basis_opt,Xfer.test_opt,Xfer.geometry,Xfer.nodes,Xfer.cdv,Te_save,Xfer.P_wts,Tm_save,Xfer.R_meg); end elseif Xfer.mode==2 % MEG only Reeg = []; Geeg_grid=[]; Gmeg_grid = zeros(Mmeg,3*P); % Pre-initialize Output Gtemp = zeros(Mmeg,3*BLK_SIZE); for nblk = 1:blk_tot n1 = (nblk-1)*3*BLK_SIZE + 1; % equivalent dipole start index n2 = nblk*3*BLK_SIZE; % equivalent dipole end index n3 = (nblk-1)*BLK_SIZE + 1; % dipole start index n4 = nblk*BLK_SIZE; % dipole end index Ptemp = BLK_SIZE; % number dipoles being processed at current time [dummy Gtemp] = bem_kernel(Rq_bemgrid(n3:n4,:),Xfer.basis_opt,Xfer.test_opt,Xfer.geometry,Xfer.nodes,Xfer.cdv,Te_save,Xfer.P_wts,Tm_save,Xfer.R_meg); % for m=1:Mmeg Gmeg_grid(m,n1:n2) = Xfer.O_meg(m,:)*Gtemp(3*m-2:3*m,:); % Apply Sensor Orient to each lead field end % telap = etime(clock,t0); trem = telap*(P-n4)/n4; if Verbose & ~rem(nblk,100) %bst_message_window('overwrite', sprintf('Completed %.0f of %.0f grid points in %3.1f Sec.',n4,P,telap)); %Expected time to complete: %.2f Sec....',n4,P,telap,trem)) waitbar(nblk/blk_tot, hwait); end end if blk_rem > 0 n1 = blk_tot*3*BLK_SIZE + 1; % equivalent dipole start index (for residual dipoles) n2 = 3*P; % equivalent dipole end index (for residual dipoles) n3 = blk_tot*BLK_SIZE + 1; % dipole start index n4 = P; % dipole end index Ptemp = n4-n3+1; % number dipoles being processed at current time Gtemp = zeros(Mmeg,3*Ptemp); [dummy, Gtemp] = bem_kernel(Rq_bemgrid(n3:P,:),Xfer.basis_opt,Xfer.test_opt,Xfer.geometry,Xfer.nodes,Xfer.cdv,Te_save,Xfer.P_wts,Tm_save,Xfer.R_meg); % for m=1:Mmeg Gmeg_grid(m,n1:n2) = Xfer.O_meg(m,:)*Gtemp(3*m-2:3*m,:); % Apply Sensor Orient to each lead field end end elseif Xfer.mode==3 % both EEG and MEG Reeg = Xfer.eegsensor(:,2:4); Geeg_grid = zeros(Meeg,3*P); % Pre-initialize Output Gmeg_grid = zeros(Mmeg,3*P); % Pre-initialize Output Gtemp = zeros(Mmeg,3*BLK_SIZE); for nblk = 1:blk_tot n1 = (nblk-1)*3*BLK_SIZE + 1; % equivalent dipole start index n2 = nblk*3*BLK_SIZE; % equivalent dipole end index n3 = (nblk-1)*BLK_SIZE + 1; % dipole start index n4 = nblk*BLK_SIZE; % dipole end index Ptemp = BLK_SIZE; % number dipoles being processed at current time [Geeg_grid(:,n1:n2) Gtemp] = bem_kernel(Rq_bemgrid(n3:n4,:),Xfer.basis_opt,Xfer.test_opt,Xfer.geometry,Xfer.nodes,Xfer.cdv,Te_save,Xfer.P_wts,Tm_save,Xfer.R_meg); % for m=1:Mmeg Gmeg_grid(m,n1:n2) = Xfer.O_meg(m,:)*Gtemp(3*m-2:3*m,:); % Apply Sensor Orient to each lead field end % telap = etime(clock,t0); trem = telap*(P-n4)/n4; if Verbose & ~rem(nblk,100) %bst_message_window('overwrite', sprintf('Completed %.0f of %.0f grid points in %3.1f Sec.',n4,P,telap)); %Expected time to complete: %.2f Sec....',n4,P,telap,trem)) waitbar(nblk/blk_tot, hwait); end end if blk_rem > 0 n1 = blk_tot*3*BLK_SIZE + 1; % equivalent dipole start index (for residual dipoles) n2 = 3*P; % equivalent dipole end index (for residual dipoles) n3 = blk_tot*BLK_SIZE + 1; % dipole start index n4 = P; % dipole end index Ptemp = n4-n3+1; % number dipoles being processed at current time Gtemp = zeros(Mmeg,3*Ptemp); [Geeg_grid(:,n1:n2), Gtemp] = bem_kernel(Rq_bemgrid(n3:P,:),Xfer.basis_opt,Xfer.test_opt,Xfer.geometry,Xfer.nodes,Xfer.cdv,Te_save,Xfer.P_wts,Tm_save,Xfer.R_meg); % for m=1:Mmeg Gmeg_grid(m,n1:n2) = Xfer.O_meg(m,:)*Gtemp(3*m-2:3*m,:); % Apply Sensor Orient to each lead field end end end clear Gtemp % % If required, apply source orientation % if isstruct(bem_grid_mfname) % if ~isempty(bem_grid_mfname.Orient) % Orientations are actually specified % if Verbose & ~isempty(bem_grid_mfname.Orient) % bst_message_window('Applying source orientation. . .') % isrc = 0; % Gtmp = GBEM_grid; % clear GBEM_grid % for src = 1:size(Gtmp,2)/3 % isrc = isrc + 1; % GBEM_grid(:,src) = Gtmp(:, 3*(isrc-1)+1:3*isrc) * bem_grid_mfname.Orient(:,src); % end % end % end % end telap_fwdgaingrid = etime(clock, t0); if Verbose close(hwait) bst_message_window(sprintf('Total time : %3.1f sec.',telap_fwdgaingrid)) end % %%%% THIS PART STORES THE FINAL RESULTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % gain_mat.eeg=Geeg_grid*scale_eeg; % convert EEG into uV by nAm dipole gain_mat.meg=Gmeg_grid*scale_meg; % convert MEG into fT by nAm dipole clear Geeg_grid Gmeg_grid
// // MockGameManager.swift // paintsplashTests // // Created by admin on 3/4/21. // @testable import paintsplash class MockGameManager: GameManager { var entities = Set<GameEntity>() var renderSystem = MockRenderSystem() var collisionSystem = MockCollisionSystem() var uiEntities = Set<GameEntity>() init() { EventSystem.entityChangeEvents .addEntityEvent.subscribe( listener: { [weak self] event in self?.onAddEntity(event: event) } ) EventSystem.entityChangeEvents .removeEntityEvent.subscribe( listener: { [weak self] event in self?.onRemoveEntity(event: event) } ) EventSystem.entityChangeEvents .addUIEntityEvent.subscribe( listener: { [weak self] event in self?.onAddUIEntity(event: event) } ) EventSystem.entityChangeEvents .removeUIEntityEvent.subscribe( listener: { [weak self] event in self?.onRemoveUIEntity(event: event) } ) } private func onAddEntity(event: AddEntityEvent) { addObject(event.entity) } private func onRemoveEntity(event: RemoveEntityEvent) { removeObject(event.entity) } private func onAddUIEntity(event: AddUIEntityEvent) { uiEntities.insert(event.entity) addObjectToSystems(event.entity) } private func onRemoveUIEntity(event: RemoveUIEntityEvent) { uiEntities.remove(event.entity) removeObjectFromSystems(event.entity) } private func addObjectToSystems(_ object: GameEntity) { renderSystem.addEntity(object) collisionSystem.addEntity(object) } private func removeObjectFromSystems(_ object: GameEntity) { renderSystem.removeEntity(object) collisionSystem.removeEntity(object) } func addObject(_ object: GameEntity) { entities.insert(object) addObjectToSystems(object) } func removeObject(_ object: GameEntity) { entities.remove(object) removeObjectFromSystems(object) } func update(_ deltaTime: Double) { renderSystem.updateEntities(deltaTime) collisionSystem.updateEntities(deltaTime) } }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>reveal.js</title> <link rel="stylesheet" href="dist/reset.css"> <link rel="stylesheet" href="dist/reveal.css"> <link rel="stylesheet" href="dist/theme/black.css"> <!-- Theme used for syntax highlighted code --> <link rel="stylesheet" href="plugin/highlight/monokai.css"> <style> .reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5 { text-transform: none; } </style> </head> <body> <div class="reveal"> <div class="slides"> <section> <h3>Project Corvolt</h3> <p class="stretch"> <img src="img/PXL_20231118_210321479.jpg"> </p> <p> <small>Ken Johnson</small> <br> <small>FVEAA Meeting - March 2024</small> </p> </section> <section> <p> Electrifying a 1963 Chevrolet Corvair 700 Coupe </p> <p class="stretch"> <img src="img/IMG_20190727_090550.jpg"> <small class="fragment" style="float: left; font-size:30px">This one is mine &#x2934;</small> </p> </section> <section> <h3>Conversion Parts</h3> <ul> <li>NetGain HyPer 9 HV AC Motor</li> <li>SME HyPer-Drive X144 Controller & Inverter</li> <li>7 x Tesla Model S 5.3 kWh battery modules</li> <li>SimpBMS from Vero Electric</li> <li>Elcon/TC 1 kW DC-DC Converter</li> <li>Elcon/TC 6.6 kW Onboard Charger</li> </ul> </section> <section> <h3>Motor Install</h3> <p class="stretch"> <img src="img/PXL_20230205_215330500.jpg" width="200"> <img src="img/PXL_20230320_210333675.jpg" width="200"> <img src="img/PXL_20230320_221304283.jpg" width="200"> <img src="img/PXL_20230320_230002872.jpg" width="380"> <img src="img/PXL_20230825_231543425.jpg" width="380"> </p> </section> <section> <h3>Battery Support</h3> <img src="img/PXL_20231125_000030260.jpg" width="380"> <img src="img/PXL_20231125_015547893.MP.jpg" width="380"> <img src="img/PXL_20231125_015541254.jpg" width="380"> <img src="img/PXL_20231023_233612730.jpg" width="380"> </section> <section> <section> <h3>Battery Module Capacity Testing</h3> <p class="stretch"> <!-- First BMS hookup to modules --> <img src="img/PXL_20231007_203857297.jpg"> </p> </section> <section> <h4>Charging</h4> <img src="img/PXL_20231120_021146617.jpg" width="300"> <img src="img/PXL_20240105_043740793.jpg" width="320"> <br> <img src="img/PXL_20240106_203856983.MP.jpg" width="470"> <br> <small class="fragment">232 Ah (Tesla Battery Module, Brand new)</small> <small class="fragment"> / 32 A</small> <small class="fragment" style="color: red;" > = 7.25 hours!</small> </section> <section> <h4>Discharging</h4> <p class="stretch"> <small>via resistive load</small> <img src="img/PXL_20240113_231345095.jpg"> </p> <p> <small class="fragment">Yes, that is a pile of old headlights... </small> <small class="fragment" style="color: red;"> Hot, Smelly & Wasteful! </small> </p> </section> <section> <p class="stretch"> <small style="color: green;">Regenerative </small> <small>discharge between modules</small> <img src="img/PXL_20240216_023750514.jpg"> </p> </section> <section> <h4>Logging Equipment</h4> <img src="img/PXL_20240216_023812326.jpg" style="float: right" width="400"> <ul style="display: block; font-size:28px"> <li>Raspberry Pi 3B with... <ul> <li>MCP2515 SPI CAN Transceiver</li> <li>Two Python scripts</li> <li>MQTT Broker</li> <li>InfluxDB Time Series Database</li> <li>Grafana</li> </ul> </li> <li>VeroBMS (aka SimpBMS) w/ Teensy 3.2</li> <li>100V / 100mA Shunt Resistor</li> <li>UNI-T UT161B Multimeter w/ USB Interface</li> <li>Contactor + Fuse + Disconnect Switch</li> <li>Some wire capable of carrying 40A</li> </ul> <pre style="display: block; font-size:18px"> <code class="hljs html wrap">Raspberry Pi | |---[CAN Bus]---[VeroBMS]---[All Tesla Module BMS Boards] | |---[USB]---[Multimeter]---[Shunt Resistor] | \---[Network]---[MQTT]---[InfluxDB]---[Grafana] </code> </pre> </section> <section> <h4>Data Acquisition and Calculation</h4> <img src="img/Screenshot-grafana.png" style="float: right" width="600"> <img src="img/Screenshot-readings.png" style="float: right" width="600"> <ul style="display: block; font-size:22px"> <li>Total Current and Voltage from each cell in a module under test is recorded to the time series database</li> <li>Averaged over a minute</li> <li>Exported to a Spreadsheet</li> <li>Now we can calculate: <ul> <li>Watts consumed per minute</li> <li>Each module's Amp-hour and Watt-hour rating and State of Health %</li> </ul> </ul> <img src="img/Screenshot-pack-health.png" style="float: left" width="350"> </section> </section> <section> <h3>Pressure Testing</h3> <p class="stretch"> <img src="img/PXL_20240302_223719314.jpg"> </p> </section> <section> <h3>Next Steps</h3> <p class="stretch"> <p> <ul> <li>Finish welding up battery boxes</li> <li>Get the battery boxes mounted into the car</li> <li>Wire up all the things</li> <li>Setup cooling loops for inverter and batteries</li> </ul> </p> <br><br><br><br><br><br> </section> </div> </div> <script src="dist/reveal.js"></script> <script src="plugin/notes/notes.js"></script> <script src="plugin/markdown/markdown.js"></script> <script src="plugin/highlight/highlight.js"></script> <script> Reveal.initialize({ hash: true, transition: 'fade', controlsTutorial: false, plugins: [ RevealMarkdown, RevealHighlight, RevealNotes ] }); </script> </body> </html>
import pytest from django.contrib.auth import get_user_model from django.contrib.auth.base_user import AbstractBaseUser from django.http import HttpResponse from django.urls import reverse from pytest_django.asserts import assertTemplateUsed from ..models import Note @pytest.fixture() def testuser() -> AbstractBaseUser: return get_user_model().objects.create(username='testuser') def test_notes_index_unauthenticated(client) -> None: """User must be logged in to access the page. Unauthenticated user should be redirected to the login page. """ response: HttpResponse = client.get(reverse('notes:notes-index')) assert response.status_code == 302 assert response.url == '/accounts/login/?next=/notes/' def test_notes_index_authenticated(client, testuser) -> None: client.force_login(testuser) response: HttpResponse = client.get(reverse('notes:notes-index')) assert response.status_code == 200 assertTemplateUsed(response, 'notes/index.html') def test_note_create_view_initial_data(client, testuser) -> None: '''Ensure user is set as initial data.''' client.force_login(testuser) response: HttpResponse = client.get(reverse('notes:note-create')) assert response.status_code == 200 assert response.context['form'].initial['user'] == testuser def test_note_detail_view_test_func(client, testuser) -> None: '''Raises Permission denied when user try to access the note of other user.''' user: AbstractBaseUser = get_user_model().objects.create(username='username') note = Note.objects.create(user=user, title='some title', content='some content') client.force_login(testuser) response: HttpResponse = client.get( reverse('notes:note-detail', kwargs={'slug': note.slug}) ) assert response.status_code == 403 def test_note_update_view_test_func(client, testuser) -> None: '''Raises Permission denied when user try to update the note of other user.''' user: AbstractBaseUser = get_user_model().objects.create(username='username') note = Note.objects.create(user=user, title='some title', content='some content') client.force_login(testuser) response: HttpResponse = client.post( reverse('notes:note-update', kwargs={'slug': note.slug}) ) assert response.status_code == 403 def test_note_delete_view_test_func(client, testuser) -> None: '''Raises Permission denied when user try to delete the note of other user.''' user: AbstractBaseUser = get_user_model().objects.create(username='username') note = Note.objects.create(user=user, title='some title', content='some content') client.force_login(testuser) response: HttpResponse = client.delete( reverse('notes:note-delete', kwargs={'slug': note.slug}) ) assert response.status_code == 403
import * as React from "react" import PropTypes from "prop-types" import parse from "html-react-parser" import { getImage } from "gatsby-plugin-image" import ClientBanner from "./ClientBanner" const ClientIntro = ({ banner, title, description, bgImage }) => { const background = getImage(bgImage?.localFile) return ( <section className="px-5 pt-48 pb-16 md:pb-20 lg:pb-48 bg-gradient-to-r from-digi-blue via-digi-sky to-digi-off-white overflow-hidden relative"> <ClientBanner url={banner.url} description={banner.description} logo={banner.logo} /> <div className="container relative z-10"> <div className="md:flex"> <div className="w-full md:w-1/2 2xl:pr-10"> <div className="text-white text-5xl lg:text-7xl font-spirit font-light mb-5"> {title && parse(title)} </div> <div className="text-white font-medium text-2xl leading-9"> {description && parse(description)} </div> </div> </div> </div> {background && ( <div className="opacity-30 md:opacity-100 absolute inset-0 bg-cover bg-right sm:bg-center bg-no-repeat" style={{ backgroundImage: `url(${background?.images?.fallback?.src})`, }} ></div> )} <div className="w-1/2 h-full bg-gradient-to-tr from-transparent via-transparent to-digi-pink/30 absolute top-0 right-0"></div> </section> ) } ClientIntro.propTypes = { banner: PropTypes.object, title: PropTypes.string, description: PropTypes.string, bgImage: PropTypes.object, } ClientIntro.defaultProps = { banner: {}, title: "Lorem Ipsum Title", description: "Lorem Ipsum Description", bgImage: {}, } export default ClientIntro
# imports import os # classes class BCOLOR: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class logger: def __init__(self, log_type): # log type can be 'error', 'warning', 'info', 'debug' self.log_type = log_type def info(self, *args): print(f"{BCOLOR.OKGREEN}{BCOLOR.BOLD}[LOG]{BCOLOR.ENDC} " + " ".join(map(str, args))) def error(self, *args): print(f"{BCOLOR.FAIL}{BCOLOR.BOLD}[ERROR]{BCOLOR.ENDC} " + " ".join(map(str, args))) def warning(self, *args): print(f"{BCOLOR.WARNING}{BCOLOR.BOLD}[WARNING]{BCOLOR.ENDC} " + " ".join(map(str, args))) def debug(self, *args): if self.log_type == 'debug': print(f"{BCOLOR.OKCYAN}{BCOLOR.BOLD}[DEBUG]{BCOLOR.ENDC} " + " ".join(map(str, args))) class Platform: def __init__(self): self.os = os.name clear = 'cls' if os.name == 'nt' else 'clear' # global variables DEBUG = False l = logger('info') if DEBUG: l.log_type = 'debug' l.info('Debug mode enabled') p = Platform() username = None def init(): if not os.name == 'nt': print('This program only works on Windows') exit() # get user name global username username = os.getlogin() l.debug(f'Username: {username}') # check if path exist: ## C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\shortcut_maker if os.path.exists('C:\\Users\\' + username + '\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\shortcut_maker'): l.debug('Path exist') else: l.debug('Path does not exist') # explain to user that path does not exist and ask if they want to create it print('The Start Menu path for this program (Shortcut Maker) does not exist') q = input('do you want to create it? (y/n): ') if q == 'y': os.mkdir('C:\\Users\\' + username + '\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\shortcut_maker') else: print('exiting program') exit() def main(): if not DEBUG: os.system(p.clear) print("Name: ") print("Path: ") print(f"Icon: {BCOLOR.FAIL}{BCOLOR.BOLD}PLANNED{BCOLOR.ENDC}") while True: name = input('what is the name of the new Shortcut: ') if name == "": print("please enter a name") continue else: break if not DEBUG: os.system(p.clear) print("Name: "+name) print("Path: ") print(f"Icon: {BCOLOR.FAIL}{BCOLOR.BOLD}PLANNED{BCOLOR.ENDC}") while True: path = input('what is the path of the new Shortcut: ') if path == "": print("please enter a path") continue else: break if not DEBUG: os.system(p.clear) print("Name: "+name) print("Path: "+path) print(f"Icon: {BCOLOR.FAIL}{BCOLOR.BOLD}PLANNED{BCOLOR.ENDC}") last_check = input('are you sure you want to create this Shortcut? (y/n): ') if last_check == 'y': l.info('Shortcut created') os.system(f'mklink "C:\\Users\\{username}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\shortcut_maker\\{name}" "{path}"') else: l.info('Shortcut not created') if __name__ == '__main__': init() main()
import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:todoey_flutter/models/provider_data.dart'; import 'package:todoey_flutter/models/task.dart'; class MockCallbackFunction extends Mock { call(); } void main() { group('$TaskData', () { late TaskData taskData; final notifyListenerCallback = MockCallbackFunction(); // Your callback function mock setUp(() { taskData = TaskData()..addListener(notifyListenerCallback); reset(notifyListenerCallback); // resets your mock before each test }); test('returns a list of tasks', () { taskData.addTask('task one'); expect(taskData.tasks, isA<List<Task>>()); }); test('adds a task and calls listeners', () { taskData.addTask('task one'); // notify listeners expect(taskData.taskCount, 1); taskData.addTask('task two'); // notify listeners verify(notifyListenerCallback()) .called(2); // verify listener were notified twice }); test('unit tests are independent from each other', () { taskData.addTask('task one'); expect(taskData.taskCount, 1); taskData.addTask('task two'); verify(notifyListenerCallback()).called( 2); // verify listener were notified twice. This only works, if you have reset your mocks }); test('updates a task and calls listeners', () { taskData.addTask('task one'); final task1 = taskData.tasks[0]; expect(task1.isDone, false); taskData.updateTask(task1); expect(task1.isDone, true); verify(notifyListenerCallback()) .called(2); // verify listener were notified twice }); test('removes a task and calls listeners', () { taskData.addTask('task one'); expect(taskData.taskCount, 1); final task1 = taskData.tasks[0]; taskData.deleteTask(task1); expect(taskData.taskCount, 0); verify(notifyListenerCallback()).called(2); }); }); }
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:modal_bottom_sheet/modal_bottom_sheet.dart'; import 'package:smpc/Constants/colors.dart'; import 'package:smpc/Controllers/controllers.dart'; import 'package:smpc/Models/player_model.dart'; import 'package:smpc/Models/team_model.dart'; import 'package:smpc/Services/db_services.dart'; import 'package:smpc/Views/Teams/edit_team_view.dart'; import 'package:smpc/Views/Widgets/widgets.dart'; import '../Players/player_details.dart'; class TeamDetailView extends StatelessWidget { TeamDetailView({Key? key, required this.teamId, this.sportsName}) : super(key: key); final String teamId; final String? sportsName; final TeamsController teamsController = Get.find(); final PlayersController playersController = Get.find(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Team Details')), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15), child: Obx(() { if (teamsController.teams!.any((element) => element.uid == teamId)) { final TeamModel team = teamsController.teams!.firstWhere((element) => element.uid == teamId); return Center( child: Column( children: [ Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox.square( dimension: 150, child: team.logo == null ? const CircleAvatar( backgroundColor: kGreyColor, child: KText(text: 'LOGO', fontWeight: FontWeight.bold, fontSize: 22)) : ClipOval(child: NetImage(imagePath: team.logo!, isUser: true, boxfit: BoxFit.cover)), ), const SizedBox(height: 8), KText(text: team.name!, fontWeight: FontWeight.bold, fontSize: 22), KText(text: sportsName ?? 'Unknown Sports', color: kGreyColor), ], ), const Divider(), ListTile( contentPadding: EdgeInsets.zero, title: const KText(text: 'All Team Players', fontWeight: FontWeight.bold), trailing: const Icon(Icons.edit_note_rounded), onTap: () async { await addTeamPlayer(context, team.playersIds!); }, ), team.playersIds!.isEmpty ? const KText(text: 'There are no player in this team') : ListView.separated( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: team.playersIds!.length, separatorBuilder: (context, index) => const Divider(), itemBuilder: (context, index) { final PlayerModel? player = playersController.players!.any((element) => element.uid == team.playersIds![index]) ? playersController.players! .firstWhere((element) => element.uid == team.playersIds![index]) : null; return player == null ? ListTile(title: KText(text: team.playersIds![index])) : ListTile( contentPadding: EdgeInsets.zero, leading: ListTileNetImage(imageURL: player.image!), title: KText(text: player.name!, fontWeight: FontWeight.bold, fontSize: 17), onTap: () { Get.to(() => PlayerDetailsView(playerId: player.uid!)); }, subtitle: KText(text: 'Roll# ${player.rollNo}')); }, ), ], ), ); } else { return const Center(child: KText(text: 'Team not found')); } })), ), ); } Future<dynamic> addTeamPlayer(BuildContext context, List playerIds) { RxList ids = playerIds.obs; return showCupertinoModalBottomSheet( expand: false, context: context, backgroundColor: kTransparent, builder: (context) => Material( child: CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: const Text('Manage Players'), padding: EdgeInsetsDirectional.zero, trailing: Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () async { Navigator.of(context).pop(); await DBServices().updateTeamPlayer(teamId, ids); }, child: const Text('Update')))), child: SafeArea( // bottom: false, child: Padding( padding: const EdgeInsets.all(8.0), child: Obx(() { if (playersController.players == null) { return const Center(child: CircularProgressIndicator.adaptive()); } else if (playersController.players!.isNotEmpty) { return ListView.separated( physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: playersController.players!.length, separatorBuilder: (context, index) => const Divider(), itemBuilder: (context, index) { final player = playersController.players![index]; return ListTile( contentPadding: EdgeInsets.zero, leading: ListTileNetImage(imageURL: player.image!), title: KText(text: player.name!, fontWeight: FontWeight.bold, fontSize: 17), subtitle: KText(text: 'Roll# ${player.rollNo}'), trailing: Obx(() => Checkbox( checkColor: kWhiteColor, activeColor: kMainColor, // controlAffinity: ListTileControlAffinity.leading, value: ids.map((element) => element).contains(player.uid), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)), onChanged: (value) { ids.contains(player.uid) ? ids.remove(player.uid) : ids.add(player.uid!); })), ); }, ); } else { return const Center( child: Text('There are no player found'), ); } }), ), ), )), ); } }
import { RouteObject, RouterProvider, createBrowserRouter, redirect, } from 'react-router-dom' import { Layout } from './components' import { DashboardPage, ErrorPage, LoginPage, LogoutPage, ProfilePage, StartPage, UsersPage, } from './pages' import { store, userAtom } from './store' import AuthClient from './api/AuthClient' const authRequired = () => { const user = store.get(userAtom) return user ? null : redirect('/login') } const redirectIfUser = () => { const user = store.get(userAtom) return user ? redirect('/profile') : null } const loadCurrentUser = async () => { try { const user = await AuthClient.getCurrentUser() store.set(userAtom, user) } catch (e) { // Ignore } return null } const logoutUser = () => { store.set(userAtom, null) return null } const routes: RouteObject[] = [ { element: <Layout />, errorElement: <ErrorPage />, loader: loadCurrentUser, children: [ { path: '/', element: <StartPage />, }, { path: 'dashboard', element: <DashboardPage />, loader: authRequired, }, { path: 'users', element: <UsersPage />, loader: authRequired, }, { path: 'profile', element: <ProfilePage />, loader: authRequired, }, { path: 'login', element: <LoginPage />, loader: redirectIfUser, }, { path: 'logout', element: <LogoutPage />, loader: logoutUser, }, { path: '*', element: <ErrorPage /> }, ], }, ] const AppRouter = () => <RouterProvider router={createBrowserRouter(routes)} /> export default AppRouter
#pragma once #include "Components/Component.h" #include "Components/Mesh.h" #include "../glm/glm.hpp" #include "../glm/gtc/matrix_transform.hpp" #include "../glm/gtc/type_ptr.hpp" #include "memory" #include "../reactphysics3d/reactphysics3d.h" #include "Physics/PhysicHelper.h" #include "Text.h" namespace amp{ /// This is an AMP default component /// /// With this component you can create convex rigid-bodies /// Use Case: Bottles, balls, chests, ... /// @note In most cases you want to use this component to create dynamic rigid-bodies which can interact with each other and also with DynamicConcaveMesh components /// @attention Make sure to call at first **one** of the following functions before calling other functions of this component (One per Component) /// @see void SetUpFromConvexMesh(), SetUpFromExtraCollissionShape(), SetUpBox(), SetUpSphere(), SetUpCapsule() class DynamicMesh : public Component { public: DynamicMesh() {}; ~DynamicMesh(); DynamicMesh(const DynamicMesh&) = delete; DynamicMesh(DynamicMesh&&) = delete; /// Creates a rigid-body from a existing mesh in your scene /// /// @note Make sure your mesh is in local coordinates in your center /// @note Make sure the mesh you are using is triangulated correctly, otherwise an error could occur /// @note You can use a triangulate or re-mesh modifier (blender 2.83) or similar before exporting the mesh, to prevent errors /// @note Do not scale the created Mesh or the rigid-body, because the collision shape will not be scaled (not supported feature in reactphysics) /// When you want to transform the connected mesh, transform instead this component by calling following functions /// @see applyForceToCenter(), applyForce(), applyTorque(), setTransform() /// @param createdMesh The Mesh connected to the rigid-body and the collision shape you want to use /// @param type Defines if your rigid-body can move, collide, interact or not /// @param mass The mass in kg changes the behavior of the simulated object void SetUpFromConvexMesh(Mesh* createdMesh,PhysicType type, float mass = 15.0f); /// When you want to setup a collision shape from a more complex mesh, you can use a simpler version of the mesh as collision shape instead /// /// @note The created Mesh must already exist /// @note Make sure your collisionShape is in local coordinates in your center /// @note Make sure the collisionShape you are using is triangulated correctly, otherwise an error could occur /// @note You can use a triangulate or re-mesh modifier (blender 2.83) or similar before exporting the mesh, to prevent errors /// @note Make sure the simplerMesh (collisionShape) is fully covering the (actual rendered)createdMesh for best results /// @note Do not scale the created Mesh or the rigid-body, because the collision shape will not be scaled (not supported feature in reactphysics) /// @param createdMesh The actual mesh which becomes displayed and is connected to the rigid-body /// @param collissionShapePath The path to the collision shape you want to use. Example to set the path correct Animation::SetUp() /// @param type Defines if your rigid-body can move, collide, interact or not /// @param mass The mass changes the behavior of the simulated rigid-body void SetUpFromExtraCollissionShape(Component* createdMesh, TEXT collissionShapePath, PhysicType type, float mass = 15.0f); /// Creates a rigid-body in shape of a box /// /// @note You can scale the fitting mesh, but make sure the collision shape has the correct size /// @note Make sure your mesh is in local coordinates centered /// When you want to transform the connected mesh, transform instead this component by calling following functions /// @see applyForceToCenter(), applyForce(), applyTorque(), setTransform() /// @param fittingMesh The Mesh connected to the rigid-body, make sure the box fits your mesh /// @param type Defines if your rigid-body can move, collide, interact or not /// @param mass The mass in kg changes the behavior of the simulated object /// @param deltaToCenter When your Mesh is not at the center in local coordinates, you can set here a translation to center the mesh for correct physic simulation /// @param halfExtents The half size of x, y, z in meters void SetUpBox(Component* fittingMesh, PhysicType type,glm::vec3 halfExtents, float mass = 15.0f, glm::vec3 deltaToCenter = glm::vec3(0,0,0)); /// Creates a rigid-body in shape of a sphere /// /// @param fittingMesh The Mesh connected to the rigid-body, make sure the box fits your mesh /// @param type Defines if your rigid-body can move, collide, interact or not /// @param mass The mass in kg changes the behavior of the simulated object /// @param deltaToCenter When your Mesh is not at the center in local coordinates, you set here a translation to center the mesh for correct physic simulation /// @param radius The radius of the sphere in meters /// @see SetUpBox() for additional behavior information void SetUpSphere(Component* fittingMesh, PhysicType type, float radius, float mass = 15.0f, glm::vec3 deltaToCenter = glm::vec3(0,0,0)); /// Creates a rigid-body in shape of a capsule /// /// @param radius The radius of the cylinder /// @param height The height of the cylinder /// @param fittingMesh The Mesh connected to the rigid-body, make sure the box fits your mesh /// @param type Defines if your rigid-body can move, collide, interact or not /// @param mass The mass in kg changes the behavior of the simulated object /// @param deltaToCenter When your Mesh is not at the center in local coordinates, you set here a translation to center the mesh for correct physic simulation /// @param radius The radius of the sphere in meters /// @see SetUpBox() for additional behavior information void SetUpCapsule(Component* fittingMesh, PhysicType type, float radius, float height, float mass = 15.0f, glm::vec3 deltaToCenter = glm::vec3(0,0,0)); /// @return The location of the rigid-body and the connect glm::vec3 getLocation() override; /// Sets the location of the rigid-body and the connected mesh void setLocation(glm::vec3 newLocation); /// @return The rotation of the rigid-body and the connected mesh glm::quat getRotation(); /// Sets the roatation of the rigid-body and the connected mesh void setRotation(glm::quat newRotation); /// @return The reactphysics collision body rp3d::CollisionBody* getCollissionBody(); /// @return The physic material where you can set physical behavior properties rp3d::Material& getPhysicMaterial(); /// Sets the reactphysics physics material, which changes the rigid-body behavior void setPhysicMaterial(rp3d::Material mat); /// Enables or disables gravity void setGravity(bool isGravity); /// @return True, when gravity enabled, else false. bool isGravity(); /// Activates or deactivates the rigidbody /// /// @note A deactivated rigidbody is ignored in the physic simulation void setActive(bool isActive); /// @return True, if rigid-body is active, else false bool isActive(); /// Set the linear damping factor. This is the ratio of the linear velocity that the body will lose every at seconds of simulation void setDamping(float factor); /// @return The linear damping factor. This is the ratio of the linear velocity that the body will lose every at seconds of simulation float getDamping(); /// Applies a force to the center of your rigid-body void applyForceToCenter(glm::vec3 force); /// Applies a force to specific point inside you rigidbody void applyForce(rp3d::Vector3 force, rp3d::Vector3 point); /// Applies torque to your rigid-body void applyTorque(rp3d::Vector3 torque); /// Sets the transformation of your rigidbody and the connected mesh /// /// @note This transformation is different from the transformation of your component /// @note You want to change this transformation and not the components transformation void setTransform(glm::mat4 transform, bool resetLinearVelocity = true, bool resetAngularVelocity = true); /// @return The transformation of your rigid-body and/btw. the transformation of the connected mesh glm::mat4 getTransform(); /// @param velocity The angular velocity vector of the body void ResetAngularVelocity(glm::vec3 velocity = glm::vec3(0,0,0)); /// @param velocity The linear velocity(current force) vector of the body void ResetLinearVelocity(glm::vec3 velocity = glm::vec3(0,0,0)); /// @return The angular velocity vector of the body glm::vec3 getAngularVelocity(); /// @return The linear velocity(current force) vector of the body glm::vec3 getLinearVelocity(); /// Defines with which rigid-body your rigidbody can interact (collide) with /// /// @param category This is a bit-mask. Each rigid-body can be just in **one** category. So flag just exactly **one** bit inside the mask. /// @param category The default value is 0x0001, so all default rigid-bodies are in the first category /// @param canCollideWith This is also a bit-mask. But you can specify here as many categories as you want to collide with. /// @param canCollideWith Flagging the second and the third bit, would result in that this rigidbody can collide with all rigid-bodies in category 2 or 3. /// @param canCollideWith As long as all rigid-bodies in category 2 and 3 have a flag in their canCollideWith bit-mask of this rigidbody category. (e.g: 1). /// @param canCollideWith The default value is 0xFFFF, so all default rigid-bodies can interact (collide) with each other. /// @attention This function can just be called after your DynamicMesh is setup. void SetCollisionFilter(unsigned short category, unsigned short canCollideWith); protected: virtual void update() override; virtual void OnActivate() override; virtual void OnDeactivate() override; private: void CreateCollisionShapeFromMesh(MeshAttributes* meshAttr, float mass); void CreateRigidBody(Component* createdMesh, PhysicType type, glm::vec3 deltaToCenter); rp3d::RigidBody* rigidBody = nullptr; //have to be self organized rp3d::PolygonVertexArray* polygonVertexArray = nullptr; rp3d::PolygonVertexArray::PolygonFace* polygonFaces = nullptr; rp3d::PolyhedronMesh* polyhedronMesh = nullptr; rp3d::ConvexMeshShape* convexMeshShape = nullptr; rp3d::BoxShape* boxShape = nullptr; rp3d::SphereShape* sphereShape = nullptr; rp3d::CapsuleShape* capsuleShape = nullptr; rp3d::ProxyShape* proxyShape = nullptr; Component* connectedMesh = nullptr; rp3d::Transform previousTransform; glm::vec3 deltaToCenter = glm::vec3(0.0f,0.0f,0.0f); bool isSetUp = false; }; }
import React, { useEffect } from "react"; import Ilogo from "/public/img/main_logo.png"; import { Menus } from "@/lib/constant"; import Link from "next/link"; import { useRouter } from "next/router"; import CustomImage from "../Utility/CustomImage"; function Header() { const router = useRouter(); useEffect(() => { window.addEventListener("scroll", function () { var header = document.querySelector("header"); if (window.pageYOffset > 100) { //@ts-ignore header.classList.add("sticky"); } else { //@ts-ignore header.classList.remove("sticky"); } }); }, []); return ( <div> <header> <button className="navbar-toggler d-xl-none d-inline navbar-menu-button" type="button" data-bs-toggle="offcanvas" data-bs-target="#primaryMenu" > <span className="navbar-toggler-icon"> <i className="iconsax" data-icon="text-align-justify"></i> </span> </button> <Link href="/"> <CustomImage height={500} width={200} src={Ilogo} alt="Ilogo" /> </Link> <nav className="header-nav-middle"> <div className="main-nav navbar navbar-expand-xl navbar-light navbar-sticky"> <div className="offcanvas offcanvas-collapse order-xl-2" id="primaryMenu" > <div className="offcanvas-header navbar-shadow"> <h5 className="mb-0">Back</h5> <button className="btn-close lead" type="button" data-bs-dismiss="offcanvas" aria-label="Close" ></button> </div> <div className="offcanvas-body"> <ul className="navbar-nav"> {Menus.map((data: any) => { const isActive = router.pathname === data.link; return ( <li className={`nav-item ${isActive ? "active" : ""}`}> <Link className="nav-link" href={`${data.link}`}> {data.title} </Link> </li> ); })} </ul> </div> </div> </div> </nav> <a data-cursor="pointer" href="login.html" className="btn btn-theme d-sm-inline-block d-none" > <span>Login Now</span> </a> </header> </div> ); } export default Header;
import { ComponentFixture, TestBed, fakeAsync, tick, } from '@angular/core/testing'; import { ProfileComponent } from './profile.component'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { UserService } from 'src/app/services/user/user.service'; import { BehaviorSubject, ReplaySubject, of } from 'rxjs'; import { Router } from '@angular/router'; import { User } from 'src/model/user'; import { LoggedUser } from 'src/model/token'; describe('ProfileComponent', () => { let component: ProfileComponent; let fixture: ComponentFixture<ProfileComponent>; let mockUserService: Partial<UserService>; let mockRouter: Partial<Router>; beforeEach(() => { mockUserService = { user$: new BehaviorSubject<LoggedUser | null>({ userConnected: { token: 'test-token', user: { id: 'test-id', userName: 'test-username', email: 'test@email.com', passwd: 'test-password', }, }, }), logoutUser: jasmine.createSpy('logoutUser'), }; mockRouter = { navigate: jasmine.createSpy('navigate'), }; TestBed.configureTestingModule({ imports: [HttpClientTestingModule], declarations: [ProfileComponent], providers: [ { provide: UserService, useValue: mockUserService }, { provide: Router, useValue: mockRouter }, ], }); fixture = TestBed.createComponent(ProfileComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should deploy menu when clicked', () => { expect(component.isMenuDeployed).toBeFalse(); component.deployMenu(); expect(component.isMenuDeployed).toBeTrue(); }); it('should log out when clicked', () => { component.handleLogout(); expect(mockUserService.logoutUser).toHaveBeenCalled(); expect(mockRouter.navigate).toHaveBeenCalledWith(['login']); }); it('should navigate to favorites when goToFavorites is called', () => { component.goToFavorites(); expect(mockRouter.navigate).toHaveBeenCalledWith(['favorites']); }); it('should navigate to login when goToLogin is called', () => { component.goToLogin(); expect(mockRouter.navigate).toHaveBeenCalledWith(['login']); }); it('should navigate to create a Post when goToCreatePost is called', () => { component.goToCreatePost(); expect(mockRouter.navigate).toHaveBeenCalledWith(['create']); }); it('Menu should auto close after 3 seconds', fakeAsync(() => { component.deployMenu(); expect(component.isMenuDeployed).toBeTrue(); tick(5100); expect(component.isMenuDeployed).toBeFalse(); })); });
using UnityEngine; using TMPro; using System; using System.Collections; using UnityEngine.InputSystem; public class PlayerControls : MonoBehaviour { #region References /// <summary>Reference to the character controller component</summary> public CharacterController CharCtrl; [SerializeField, Tooltip("Entity Collider")] private BoxCollider entityCollider; [SerializeField] private ChunkManager chunkManager; [SerializeField] private Generator generator; [SerializeField] private EBlockType selectedBlock; /// <summary> /// Reference to the input system class /// </summary> private Controls controls; public Camera PlayerCamera; [SerializeField, Tooltip("The player's game mode")] private Gamemode gamemode; private bool flying; [SerializeField] int moveSpeed; [SerializeField] private float rotationSpeed; private float pitch; private float veloY = 0f; private Vector2 pitchMinMax = new Vector2(-89, 89); /// <summary>Defines if the player can move</summary> bool movementActive = true; [SerializeField] private TMP_Text debugText; private bool showDebugText; [SerializeField] private SelectedCubeLineDrawer cubeDrawer; private bool placeBlock = false; private bool PlaceBlock { get { return placeBlock; } set { placeBlock = value; destroyBlock = false; } } private bool destroyBlock = false; private bool DestroyBlock { get { return destroyBlock; } set { destroyBlock = value; placeBlock = false; } } private float breakCooldown = 0.1f; private float placeCooldown = 0.15f; private float blockCooldownTimer = 0f; #endregion #region Methods private void Awake() { // removes the cursor while playing and locks its position Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; Application.targetFrameRate = -1; QualitySettings.vSyncCount = 0; // Debug.Log($"Round {40f / 16f + 0.01f} to {Mathf.RoundToInt(40f / 16f + 0.01f)}"); // Debug.Log($"Round {24f / 16f + 0.01f} to {Mathf.RoundToInt(24f / 16f + 0.01f)}"); controls = new(); controls.Player.Hotkey1.performed += OnHotkey1; controls.Player.Hotkey2.performed += OnHotkey2; controls.Player.Hotkey3.performed += OnHotkey3; controls.Player.Hotkey4.performed += OnHotkey4; controls.Player.Hotkey5.performed += OnHotkey5; controls.Player.Hotkey6.performed += OnHotkey6; controls.Player.Hotkey7.performed += OnHotkey7; controls.Player.Hotkey8.performed += OnHotkey8; controls.Player.Hotkey9.performed += OnHotkey9; controls.Player.DebugScreen.performed += OnDebugMenuPressed; } // Update is called once per frame void Update() { if (movementActive) { if (Input.GetMouseButtonDown(0)) { DestroyBlock = true; } if (Input.GetMouseButtonDown(1)) { PlaceBlock = true; } if (Input.GetMouseButtonUp(0)) { blockCooldownTimer = 0; DestroyBlock = false; } if (Input.GetMouseButtonUp(1)) { blockCooldownTimer = 0; PlaceBlock = false; } Move(); CameraMove(); RaycastThing(); } } private void RaycastThing() { if (showDebugText) { debugText.text = $"FPS: {(int)(1 / Time.deltaTime)}\n"; debugText.text += $"X: {Math.Round(transform.position.x, 4).ToString().PadRight(6, '0')}\tY: {Math.Round(transform.position.y, 4).ToString().PadRight(6, '0')}\tZ: {Math.Round(transform.position.z, 4).ToString().PadRight(6, '0')}\n"; debugText.text += $"Hilliness: {GameManager.Instance.ChunkBuilder.EvaluateHilliness(transform.position)}\n"; debugText.text += $"World Height: {GameManager.Instance.ChunkBuilder.EvaluateWorldHeight(transform.position, generator.WorldHeightCurve)}\n"; debugText.text += $"Grounded: {CharCtrl.isGrounded}\n"; } if (Physics.Raycast(PlayerCamera.transform.position, PlayerCamera.transform.forward, out RaycastHit hit, 6f)) { Vector3Int blockPos; (float, float, float) normal = (hit.normal.x, hit.normal.y, hit.normal.z); Vector3 point = new(hit.point.x + 0.0001f, hit.point.y - 0.0001f, hit.point.z + 0.0001f); switch (normal) { case (1, 0, 0): blockPos = new(Mathf.FloorToInt(point.x - 1), Mathf.CeilToInt(point.y), Mathf.FloorToInt(point.z)); break; case (0, -1, 0): blockPos = new(Mathf.FloorToInt(point.x), Mathf.CeilToInt(point.y + 1), Mathf.FloorToInt(point.z)); break; case (0, 0, 1): blockPos = new(Mathf.FloorToInt(point.x), Mathf.CeilToInt(point.y), Mathf.FloorToInt(point.z - 1)); break; default: blockPos = new(Mathf.FloorToInt(point.x), Mathf.CeilToInt(point.y), Mathf.FloorToInt(point.z)); break; } if (showDebugText && debugText.gameObject.activeInHierarchy) { debugText.text += $"Looking at\nX:{blockPos.x} Y:{blockPos.y} Z:{blockPos.z}\n"; if (hit.collider.TryGetComponent(out SubChunk targetSubChunk) || hit.collider.transform.parent.TryGetComponent(out targetSubChunk)) { debugText.text += $"{targetSubChunk.GetBlock(blockPos)}\n"; } } cubeDrawer.CubePosition = blockPos; Debug.DrawLine(blockPos, blockPos + Vector3.forward); Debug.DrawLine(blockPos, blockPos + Vector3.right); Debug.DrawLine(blockPos, blockPos + Vector3.down); if (DestroyBlock) { if (blockCooldownTimer <= 0) { blockCooldownTimer = breakCooldown; if (hit.collider.TryGetComponent(out SubChunk targetSubChunk) || hit.collider.transform.parent.TryGetComponent(out targetSubChunk)) { targetSubChunk.RemoveBlockAt(blockPos); } } blockCooldownTimer -= Time.deltaTime; } else if (PlaceBlock) { if (blockCooldownTimer <= 0) { blockCooldownTimer = placeCooldown; switch (normal) { case (1, 0, 0): blockPos.x += 1; break; case (-1, 0, 0): blockPos.x -= 1; break; case (0, 1, 0): blockPos.y += 1; break; case (0, -1, 0): blockPos.y -= 1; break; case (0, 0, 1): blockPos.z += 1; break; case (0, 0, -1): blockPos.z -= 1; break; } Bounds bounds = new Bounds(new(blockPos.x + 0.5f, blockPos.y - 0.5f, blockPos.z + 0.5f), Vector3.one); if (CharCtrl.bounds.Intersects(bounds)) { Debug.Log("Cannot place block here"); return; } Vector2Int chunkPos = ChunkManager.Instance.GetChunkCoordinate(blockPos); SubChunk.AddBlockAt(blockPos, selectedBlock, ChunkManager.Instance.GetChunk(chunkPos).GetComponent<Chunk>()); } blockCooldownTimer -= Time.deltaTime; } } else if (cubeDrawer.CubeEnabled) { cubeDrawer.CubeEnabled = false; } } Bounds placedBlockBounds; private void showplacedaura() { if (placedBlockBounds != null) { Debug.DrawRay(placedBlockBounds.min, Vector3.up * placedBlockBounds.size.y); Debug.DrawRay(placedBlockBounds.min, Vector3.right * placedBlockBounds.size.x); Debug.DrawRay(placedBlockBounds.min, Vector3.forward * placedBlockBounds.size.z); Debug.DrawRay(placedBlockBounds.min + Vector3.right * placedBlockBounds.size.x, Vector3.forward * placedBlockBounds.size.z); Debug.DrawRay(placedBlockBounds.min + Vector3.right * placedBlockBounds.size.x, Vector3.up * placedBlockBounds.size.y); Debug.DrawRay(placedBlockBounds.max, Vector3.down * placedBlockBounds.size.y); Debug.DrawRay(placedBlockBounds.max, Vector3.left * placedBlockBounds.size.x); Debug.DrawRay(placedBlockBounds.max, Vector3.back * placedBlockBounds.size.z); } } /// <summary> /// Player Movement /// </summary> void Move() { Vector3 direction = Input.GetAxis("Horizontal") * transform.right + Input.GetAxis("Vertical") * transform.forward; direction = Vector3.ClampMagnitude(direction, 1) * moveSpeed; if (gamemode == Gamemode.Survival) { Walk(ref direction); } else if (gamemode == Gamemode.Creative) { if (flying) Fly(ref direction); else Walk(ref direction); if (Input.GetKeyDown(KeyCode.F)) { flying = !flying; if (flying) { transform.position = new Vector3(transform.position.x, transform.position.y + .1f, transform.position.x); } else { veloY = 0f; } } } CharCtrl.Move(direction * Time.deltaTime); } private void Walk(ref Vector3 direction) { if (CharCtrl.isGrounded && Input.GetKeyDown(KeyCode.Space)) { veloY = 5.03f; direction.y = veloY; } if (!CharCtrl.isGrounded) { veloY += -9.81f * Time.deltaTime; direction.y = veloY; } else if (veloY < 0f) { veloY = -1f; direction.y = veloY; } } private void Fly(ref Vector3 direction) { direction *= 1.5f; if (Input.GetKey(KeyCode.Space)) { veloY = 6f; direction.y = veloY; } if (CharCtrl.isGrounded) { flying = false; veloY = 0f; } if (Input.GetKey(KeyCode.LeftShift)) { veloY = -3f; direction.y = veloY; } } /// <summary> /// Camera Movement /// </summary> void CameraMove() { transform.Rotate(Input.GetAxis("Mouse X") * rotationSpeed * Vector3.up); pitch += -Input.GetAxis("Mouse Y") * rotationSpeed; pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y); PlayerCamera.transform.localEulerAngles = new Vector3(pitch, 0, 0); } /// <summary>Enables or disables movement</summary> /// <param name="active"></param> public void SetMovementActive(bool active) { movementActive = active; } private void OnHotkey1(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { selectedBlock = EBlockType.Stone; } } private void OnHotkey2(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { selectedBlock = EBlockType.Dirt; } } private void OnHotkey3(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { selectedBlock = EBlockType.Grass; } } private void OnHotkey4(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { selectedBlock = EBlockType.WoodPlanks; } } private void OnHotkey5(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { selectedBlock = EBlockType.WoodLog; } } private void OnHotkey6(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { selectedBlock = EBlockType.Leafes; } } private void OnHotkey7(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { } } private void OnHotkey8(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { } } private void OnHotkey9(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { } } private void OnDebugMenuPressed(InputAction.CallbackContext ctx) { if (ctx.action.WasPerformedThisFrame()) { showDebugText = !showDebugText; if (showDebugText) debugText.gameObject.SetActive(true); else debugText.gameObject.SetActive(false); } } private void OnEnable() { controls.Enable(); } private void OnDisable() { controls.Disable(); } #endregion }
// // WorkoutDetailView.swift // WorkoutSwiftData // // Created by Ivan Voloshchuk on 14/08/23. // import SwiftData import SwiftUI struct WorkoutDetailView: View { @Environment(\.modelContext) private var context @Query(sort: [SortDescriptor(\Exercise.name, order: .forward)], animation: .bouncy) var exercises: [Exercise] @Bindable var workout: Workout @State private var selectedExercises: Set<Exercise> = [] @State private var selectedDay: Day = .Monday var body: some View { VStack { /* If I don't specify explicitly the ID, it won't work */ List(exercises, id: \.self, selection: $selectedExercises) { exercise in Text(exercise.name) } .toolbar { EditButton() } List { Section("Workout day") { Picker("Day", selection: $selectedDay) { ForEach(Day.allCases, id: \.self) { Text($0.rawValue).tag($0) } } } } Button("Confirm") { workout.exercises = Array(selectedExercises) workout.selectedDay = selectedDay } .buttonStyle(PrimaryButton()) .padding(.horizontal, 16) .padding(.bottom, 16) } .onAppear { selectedDay = workout.selectedDay selectedExercises = Set(workout.exercises ?? []) } } } #Preview { /* https://www.hackingwithswift.com/quick-start/swiftdata/how-to-use-swiftdata-in-swiftui-previews */ let config = ModelConfiguration(isStoredInMemoryOnly: true) let container = try! ModelContainer(for: Workout.self, configurations: config) return WorkoutDetailView(workout: Workout.mock().first!) .modelContainer(container) }
/* $Id: messagedialog.hg,v 1.15 2006/06/20 18:46:59 murrayc Exp $ */ /* messagedialog.h * * Copyright (C) 1998-2002 The gtkmm Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <gtkmm/dialog.h> _DEFS(gtkmm,gtk) _PINCLUDE(gtkmm/private/dialog_p.h) namespace Gtk { _CC_INCLUDE(gtk/gtktypebuiltins.h) _WRAP_ENUM(MessageType, GtkMessageType) _WRAP_ENUM(ButtonsType, GtkButtonsType) /** Convenient message window. * * Gtk::MessageDialog presents a dialog with an image representing the type * of message (Error, Question, etc.) alongside some message text. It's * simply a convenience widget; you could construct the equivalent of * Gtk::MessageDialog from Gtk::Dialog without too much effort, but * Gtk::MessageDialog saves typing. * * A MessageDialog looks like this: * @image html messagedialog1.png * * @ingroup Dialogs */ class MessageDialog : public Dialog { _CLASS_GTKOBJECT(MessageDialog, GtkMessageDialog, GTK_MESSAGE_DIALOG, Gtk::Dialog, GtkDialog) _UNMANAGEABLE public: explicit MessageDialog(const Glib::ustring& message, bool use_markup = false, MessageType type = MESSAGE_INFO, ButtonsType buttons = BUTTONS_OK, bool modal = false); MessageDialog(Gtk::Window& parent, const Glib::ustring& message, bool use_markup = false, MessageType type = MESSAGE_INFO, ButtonsType buttons = BUTTONS_OK, bool modal = false); _IGNORE(gtk_message_dialog_new, gtk_message_dialog_new_with_markup) _WRAP_METHOD(void set_image(Widget& image), gtk_message_dialog_set_image) _WRAP_METHOD(Widget* get_image(), gtk_message_dialog_get_image) _WRAP_METHOD(const Widget* get_image() const, gtk_message_dialog_get_image, constversion) _WRAP_METHOD(void set_markup(const Glib::ustring& str), gtk_message_dialog_set_markup, deprecated "Use set_message(string, true).") /** Sets the primary text of the message dialog. * * @param text The message. * @param use_markup Whether @a message contains pango markup. */ void set_message(const Glib::ustring& message, bool use_markup = false); _IGNORE() /** Sets the secondary text of the message dialog. * Note that setting a secondary text makes the primary text become bold, unless you have provided explicit markup. * * @newin2p6. * * @param text The message. * @param use_markup Whether @a message contains pango markup. */ void set_secondary_text(const Glib::ustring& text, bool use_markup = false); _IGNORE(gtk_message_dialog_format_secondary_text, gtk_message_dialog_format_secondary_markup) _WRAP_PROPERTY("message-type", MessageType) _WRAP_PROPERTY("buttons", ButtonsType) _WRAP_PROPERTY("text", Glib::ustring) _WRAP_PROPERTY("use-markup", bool) _WRAP_PROPERTY("secondary-text", Glib::ustring) _WRAP_PROPERTY("secondary-use-markup", bool) _WRAP_PROPERTY("image", Widget*) }; } // namespace Gtk
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* AMateria.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mechane <mechane@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/08/06 11:23:55 by mechane #+# #+# */ /* Updated: 2023/08/07 06:54:54 by mechane ### ########.fr */ /* */ /* ************************************************************************** */ #include "AMateria.hpp" AMateria::AMateria(): type("None") { std::cout << "AMateria Default constructor called" << std::endl; } AMateria::AMateria(std::string const &type) { this->type = type; std::cout << "AMateria constructor called" << std::endl; } AMateria::~AMateria() { std::cout << "AMateria Default destructor called" << std::endl; } AMateria& AMateria::operator=(const AMateria& other) { if (this == &other) return *this; this->type = other.type; return *this; } AMateria::AMateria(const AMateria &other) { *this = other; } const std::string& AMateria::getType() const { return type; } void AMateria::use(ICharacter& target) { std::cout << "AMateria abstractly used on " << target.getName() << std::endl; }
import React, { useState, useEffect, useRef } from 'react'; import uploadImg from '../assets/uploadimg.jpeg'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import './List.css'; const ListePage = () => { const [liste, setListe] = useState([]); const [nom, setNom] = useState(''); const [prenom, setPrenom] = useState(''); const [price, setPrice] = useState(''); const [erreurMessage, setErreurMessage] = useState(''); const inputRef = useRef(null); const [selectedImage, setSelectedImage] = useState(null); useEffect(() => { const savedListe = JSON.parse(localStorage.getItem('liste')) || []; setListe(savedListe); }, []); const ajouterChamp = () => { if (!selectedImage) { setErreurMessage('Please select an image.'); return; } if (!nom || !prenom || !price) { setErreurMessage('Finish all the input fields, please.'); return; } const newItem = { nom, prenom, price, image: selectedImage }; const updatedListe = [newItem, ...liste]; localStorage.setItem('liste', JSON.stringify(updatedListe)); // Save to localStorage setListe(updatedListe); setNom(''); setPrenom(''); setPrice(''); setSelectedImage(null); setErreurMessage(''); }; const supprimerChamp = (index) => { const updatedListe = [...liste]; updatedListe.splice(index, 1); localStorage.setItem('liste', JSON.stringify(updatedListe)); // Update localStorage setListe(updatedListe); }; const handelClick = () => { inputRef.current.click(); }; const handleImageChange = (event) => { const file = event.target.files[0]; setSelectedImage(URL.createObjectURL(file)); }; const sortByPrice = () => { const sortedListe = [...liste].sort((a, b) => b.price - a.price); setListe(sortedListe); }; return ( <div className=""> <div className='header'> <div onClick={handelClick}> <img src={selectedImage ? selectedImage : uploadImg} className='uploudIMG' alt='' /> <input type='file' ref={inputRef} style={{ display: 'none' }} onChange={handleImageChange} /> </div> <div className="inputs"> <div className='input'> <label className="">House code </label> <input type="text" className="" value={prenom} onChange={(e) => setPrenom(e.target.value)} /> </div> <div className='input'> <label className="">price </label> <input type="text" className="" value={price} onChange={(e) => { const inputPrice = e.target.value; if (/^\d*\.?\d*$/.test(inputPrice)) { setPrice(inputPrice); } }} /> </div> <div className='input'> <label className="lable">Adress </label> <input type="text" className="" value={nom} onChange={(e) => setNom(e.target.value)} /> </div> <div> {erreurMessage && <p className="errormsg">{erreurMessage}</p>}</div> </div> <div className=""> <button className="add" onClick={ajouterChamp} > Add </button> <button className="sort" onClick={sortByPrice}>Sort by Price</button> </div> </div> <div className="main"> {liste.length > 0 ? ( <ul> {liste.map((champ, index) => ( <li key={index} className="row" > <p >{index + 1} </p> {champ.image && <img src={champ.image} className='houseimg' alt='' />} <p >{champ.nom}</p> <p >{champ.prenom}</p> <p >{champ.price} $</p> <button className="remove" onClick={() => supprimerChamp(index)} > remove</button> </li> ))} </ul> ) : ( <p>there is no ranked houses please enter one .</p> )} </div> </div> ); }; export default ListePage;
import { useState, useEffect } from 'react' export interface Destination { name: string description: string distance: string travel: string images: { png: string; webp: string } } export interface CrewMember { name: string images: { png: string; webp: string } role: string bio: string } export interface Tech { name: string images: { portrait: string; landscape: string } description: string } interface Data { destinations: Destination[] crew: CrewMember[] technology: Tech[] } function useFetchData(): Data | undefined { const [data, setData] = useState<Data>() useEffect(() => { async function getData(): Promise<void> { const data = await fetch('/data.json') const res = await data.json() setData(res) } getData() return () => {} }, []) return data } export default useFetchData
package t3209; import javax.swing.JFileChooser; import javax.swing.text.BadLocationException; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; /** * Created by DELL on 11/14/2017. */ public class Controller { private View view; private HTMLDocument document; private File currentFile; public static void main(String[] args) { View view = new View(); Controller controller = new Controller(view); view.setController(controller); view.init(); controller.init(); } public Controller(View view) { this.view = view; } public HTMLDocument getDocument() { return document; } public void resetDocument(){ if(document != null) { document.removeUndoableEditListener(view.getUndoListener()); } document = (HTMLDocument) new HTMLEditorKit().createDefaultDocument(); document.addUndoableEditListener(view.getUndoListener()); view.update(); } public void setPlainText(String text){ resetDocument(); StringReader stringReader = new StringReader(text); try { new HTMLEditorKit().read(stringReader, document, 0); } catch (IOException e) { ExceptionHandler.log(e); } catch (BadLocationException e) { ExceptionHandler.log(e); } } public String getPlainText(){ StringWriter stringWriter = new StringWriter(); try { new HTMLEditorKit().write(stringWriter, document, 0, document.getLength()); } catch (IOException e) { ExceptionHandler.log(e); } catch (BadLocationException e) { ExceptionHandler.log(e); } return stringWriter.toString(); } public void createNewDocument(){ view.selectHtmlTab(); resetDocument(); view.setTitle("HTML editor"); view.resetUndo(); currentFile = null; } public void openDocument(){ view.selectHtmlTab(); JFileChooser jFileChooser = new JFileChooser(); jFileChooser.setFileFilter(new HTMLFileFilter()); int chooser = jFileChooser.showOpenDialog(view); if (chooser == JFileChooser.APPROVE_OPTION) { currentFile = jFileChooser.getSelectedFile(); resetDocument(); view.setTitle(currentFile.getName()); try { FileReader fileReader = new FileReader(currentFile); new HTMLEditorKit().read(fileReader, document, 0); view.resetUndo(); } catch (Exception e) { ExceptionHandler.log(e); } } } public void saveDocument(){ if (currentFile == null) saveDocumentAs(); else { view.selectHtmlTab(); view.setTitle(currentFile.getName()); try { FileWriter fileWriter = new FileWriter(currentFile); new HTMLEditorKit().write(fileWriter, document, 0, document.getLength()); } catch (Exception e) { ExceptionHandler.log(e); } } } public void saveDocumentAs(){ view.selectHtmlTab(); JFileChooser jFileChooser = new JFileChooser(); jFileChooser.setFileFilter(new HTMLFileFilter()); int chooser = jFileChooser.showSaveDialog(view); if(chooser == JFileChooser.APPROVE_OPTION){ currentFile = jFileChooser.getSelectedFile(); view.setTitle(currentFile.getName()); try { FileWriter fileWriter = new FileWriter(currentFile); new HTMLEditorKit().write(fileWriter, document, 0, document.getLength()); } catch (IOException e) { ExceptionHandler.log(e); } catch (BadLocationException e) { ExceptionHandler.log(e); } } } public void init(){ createNewDocument(); } public void exit(){ System.exit(0); } }
#!/usr/bin/python3 """ Module containing the State class and an instance Base = declarative_base() """ from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base # Create an instance of the declarative base Base = declarative_base() class State(Base): """ State class to represent the states table """ __tablename__ = 'states' # Define columns id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) name = Column(String(128), nullable=False)
class Student { var name: String = "" get() = field.uppercase() set(value) { if (value.isNotBlank()) { field = value } } } class Employee( var name: String, var surname: String, ) { val fullName1: String get() = "$name $surname" val fullName2: String = "$name $surname" } class Holder { val v1: Int get() = calculate("v1") val v2: Int = calculate("v2") private fun calculate(propertyName: String): Int { println("Calculating $propertyName") return 42 } } fun main() { val user = Student() user.name = "norbert" user.name = "" user.name = " " println(user.name) // NORBERT val employee1 = Employee("Maja", "Markiewicz") println(employee1.fullName1) // Maja Markiewicz println(employee1.fullName2) // Maja Markiewicz employee1.surname = "Moskała" println(employee1.fullName1) // Maja Moskała println(employee1.fullName2) // Maja Markiewicz val h1 = Holder() // Calculating v2 }
import { FC, useEffect, useRef } from 'react'; type Point = { x: number, y: number }; type Vector2D = [number, number]; function pointToLineDistance(p:Point, p1:Point, p2:Point) { // 计算直线向量 P1P2 var vectorP1P2: [number, number] = [p2.x - p1.x, p2.y - p1.y]; // 计算点 C 到直线上某一点的向量表示 P1C var vectorP1C: [number, number] = [p.x - p1.x, p.y - p1.y]; // 计算直线向量 P1P2 的模的平方 var dotP1P2 = dotProduct(vectorP1P2, vectorP1P2); // 计算投影长度 len var len = dotProduct(vectorP1C, vectorP1P2) / dotP1P2; // 计算最短距离的点的坐标 var shortestPoint = { x: p1.x + len * (p2.x - p1.x), y: p1.y + len * (p2.y - p1.y) }; // 计算最短距离 var distance = Math.abs(len); return { distance: distance, shortestPoint: shortestPoint }; } function dotProduct(vec1:Vector2D, vec2:Vector2D) { var dot = 0; for (var i = 0; i < vec1.length; i++) { dot += vec1[i] * vec2[i]; } return dot; } // 示例点和直线 var pointC = { x: 2, y: 3 }; var pointP1 = { x: 1, y: 1 }; var pointP2 = { x: 5, y: 4 }; // 调用函数计算最短距离和最短距离点的坐标 var result = pointToLineDistance(pointC, pointP1, pointP2); console.log("最短距离:", result.distance); console.log("最短距离点坐标:", result.shortestPoint); export const ShortestPoint: FC = () => { const canvasRef = useRef<HTMLCanvasElement>(null); useEffect(() => { const canvas = canvasRef.current! as HTMLCanvasElement; const ctx = canvas.getContext("2d")!; // 定义点和直线的坐标 var pointC = { x: 250, y: 150 }; var pointP1 = { x: 100, y: 100 }; var pointP2 = { x: 300, y: 300 }; const {distance, shortestPoint} = pointToLineDistance(pointC, pointP1, pointP2); const drawPoint = (point:Point, color?:string) => { ctx.beginPath(); ctx.arc(point.x, point.y, 5, 0, 2 * Math.PI); ctx.fillStyle = color || "red"; ctx.fill(); } const drawLine = (point1:Point, point2:Point) => { ctx.beginPath(); ctx.moveTo(point1.x, point1.y); ctx.lineTo(point2.x, point2.y); ctx.stroke(); ctx.closePath(); } drawPoint(pointC, 'blue'); drawPoint(pointP1); drawPoint(pointP2); drawPoint(shortestPoint, 'blue'); drawLine(pointP1, pointP2); drawLine(pointC, shortestPoint); }, []); return (<> <h2>ShortestPoint</h2> <canvas ref={canvasRef} id="myCanvas" width="600" height="600" style={{width: '600px', height: '600px'}}></canvas> </>); };
import { $, component$, useComputed$, useSignal } from "@builder.io/qwik"; import type { DocumentHead } from "@builder.io/qwik-city"; import { routeAction$, routeLoader$, useLocation, useNavigate, } from "@builder.io/qwik-city"; import { AxiosError } from "axios"; import { instance } from "~/axiosInstance"; export const useCreateTodo = routeAction$(async (form, { fail, redirect }) => { try { await instance.post("/todos", { data: { title: form.title, description: form.description, completed: false, }, }); redirect(301, "/"); } catch (e) { if (e instanceof AxiosError) { return fail(500, { status: "error", error: e.response?.data.message }); } } }); export const useEditTodo = routeAction$(async (form, { fail, redirect }) => { try { await instance.put(`/todos/${form.id}`, { data: { ...(form as any).data, }, }); redirect(301, "/"); } catch (e) { if (e instanceof AxiosError) { console.log(JSON.stringify(e.response?.data), "data"); return fail(500, { status: "error", error: e.response?.data.message }); } } }); export const useTodo = routeLoader$<{ id: string; attributes: { title: string; description: string; completed?: boolean; }; } | null>(async (requestEvent) => { const currentTodo = requestEvent.params; if (!currentTodo.id) { return null; } const parsedId = Number.parseInt(currentTodo.id); if (Number.isNaN(parsedId)) { return null; } const todoId = currentTodo.id; const res = await instance.get(`/todos/${todoId}`); return res.data.data as { id: string; attributes: { title: string; description: string; completed?: boolean; }; }; }); const CreateTodo = component$(() => { const newTodo = useCreateTodo(); const editTodo = useEditTodo(); const location = useLocation(); const todo = useTodo(); const todoID = location.params as { id: "new" | number }; const navigate = useNavigate(); const isNew = useComputed$(() => { if (!todoID.id) { navigate("/"); return false; } const parsed = Number.parseInt(todoID.id.toString()); if (Number.isNaN(parsed) && todoID.id === "new") { return true; } return false; }); const title = useSignal(todo.value?.attributes.title ?? ""); const description = useSignal(todo.value?.attributes.description ?? ""); const completed = useSignal(todo.value?.attributes.completed ?? false); const onSubmit = $(async () => { if (isNew.value) { await newTodo.submit({ title: title.value, description: description.value, }); } else { await editTodo.submit({ data: { title: title.value, description: description.value, completed: completed.value, }, id: todo.value?.id, }); } }); return ( <div> <div class="flex flex-col items-center justify-center space-y-4"> <h3 class="my-6">Create a new TODO</h3> <input placeholder="title" name="title" class="w-96 rounded-md border-2 p-1" bind:value={title} /> <textarea name="description" placeholder="description" class="w-96 rounded-md border-2 p-1" bind:value={description} /> {!isNew.value && ( <div> <input type="checkbox" name="completed" bind:checked={completed} /> <span>Mark as completed</span> </div> )} <button onClick$={onSubmit}>{isNew.value ? "Create" : "Update"}</button> </div> </div> ); }); export default CreateTodo; export const head: DocumentHead = { title: "Create a new Todo", };
<?php namespace App; use Illuminate\Contracts\Auth\MustVerifyEmail as IMustVerifyEmail; use Illuminate\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Authenticatable implements IMustVerifyEmail { use MustVerifyEmail, Notifiable, SoftDeletes; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; protected $dates = [ 'accessed_at' ]; public function isAdmin() { return $this->role === 'admin'; } public function posts() { return $this->hasMany('App\Post'); } public function comments() { return $this->hasMany('App\Comment'); } }
module IKUT { export class DetailView extends BaseView { private static TAG: string = "DetailView - "; private parentView: BaseView; private curAlarm: Alarm; private curUser: User; private origstars: number; constructor(options?: Backbone.ViewOptions<Backbone.Model>) { super(options); var self: DetailView = this; self.bDebug = true; //$(window).resize(_.debounce(that.customResize, Setting.getInstance().getResizeTimeout())); } public render(args?: any): any { var self: DetailView = this; if (self.bDebug) console.log(DetailView.TAG + "render()"); // apply template if (args instanceof Alarm) { self.curAlarm = <Alarm>args; self.origstars = self.curAlarm.getStars(); console.log("self.origstars: " + self.origstars); var origFormattedStars = ""; if (self.origstars > 1000000) { origFormattedStars = Math.floor(self.origstars / 1000000) + "M"; } else if (self.origstars > 1000) { origFormattedStars = Math.floor(self.origstars / 1000) + "K"; } else { origFormattedStars = self.origstars.toString(); } var exist: Alarm = Model.getAlarms().findWhere({ cid: self.curAlarm.getcId() }); var stars = Model.getCurUser().getStars(); var formattedStars = ""; if (stars > 1000000) { formattedStars = Math.floor(stars / 1000000) + "M"; } else if (stars > 1000) { formattedStars = Math.floor(stars / 1000) + "K"; } else { formattedStars = stars.toString(); } if (exist) { // Edit existing alarm // apply template var template = _.template(Template.getDetailViewTemplate()); if (self.curAlarm.getType() == ALARM_LIST.DAILY) { // Daily Alarm // detail var template2 = _.template(Template.getDarilyAlarmEditTemplate()); var data2 = { name: self.curAlarm.getName(), } var data = { header: "Daily Alarm Detail", //content: (<Alarm>args).getFormattedTime() + ' - <span class="invisible">' + (<Alarm>args).getFormattedEndTime() + '</span>', content: template2(data2), } } else { // Group Alarm // detail var template5 = _.template(Template.getGroupAlarmEditTemplate()); var data5 = { name: self.curAlarm.getName(), users: Model.getUsers(), curUser: Model.getCurUser(), origstars: self.curAlarm.getStars(), stars: formattedStars, } var data = { header: "Group Alarm Detail", //content: (<Alarm>args).getFormattedTime() + ' - <span class="invisible">' + (<Alarm>args).getFormattedEndTime() + '</span>', content: template5(data5), } } } else { // Create a new alarm // apply template var template = _.template(Template.getDetailViewTemplate()); if (self.curAlarm.getType() == ALARM_LIST.DAILY) { // Daily Alarm // detail var template2 = _.template(Template.getDarilyAlarmEditTemplate2()); var data2 = { name: self.curAlarm.getName(), } var data = { header: "New Dairly Alarm", //content: (<Alarm>args).getFormattedTime() + ' - <span class="invisible">' + (<Alarm>args).getFormattedEndTime() + '</span>', content: template2(data2), } } else { // detail var template5 = _.template(Template.getGroupAlarmEditTemplate2()); var data5 = { name: self.curAlarm.getName(), users: Model.getUsers(), curUser: Model.getCurUser(), origstars: self.curAlarm.getStars(), stars: formattedStars, } var data = { header: "New Group Alarm", //content: (<Alarm>args).getFormattedTime() + ' - <span class="invisible">' + (<Alarm>args).getFormattedEndTime() + '</span>', content: template5(data5), } } } self.$el.html(template(data)); // add time picker $('#time-start').datetimepicker({ format: 'LT', defaultDate: self.curAlarm.getDate(), }); // add datetime picker $('#datetime').datetimepicker({ defaultDate: self.curAlarm.getDate(), }); /* .on("dp.change", function (event) { console.log(event.date); }); */ $('#category').selectpicker({ size: 'false', mobile: true, }); $('#category').selectpicker('val', self.curAlarm.getCategory()); $('#days').selectpicker({ size: 'false', mobile: true, }); $('#participants').selectpicker({ size: 'false', mobile: true, countSelectedText: function (numSelected, numTotal) { return (numSelected == 1) ? "{0} member added" : "{0} members added"; }, }); var cids: Array<string> = self.curAlarm.getUsercIds(); $('#participants').selectpicker('val', cids); // composite days var days: Array<number> = new Array<number>(); if (self.curAlarm.getIsDailyDayOn(DAY_LIST.MONDAY)) { days.push(0); } if (self.curAlarm.getIsDailyDayOn(DAY_LIST.TUESDAY)) { days.push(1); } if (self.curAlarm.getIsDailyDayOn(DAY_LIST.WEDNESDAY)) { days.push(2); } if (self.curAlarm.getIsDailyDayOn(DAY_LIST.THURSDAY)) { days.push(3); } if (self.curAlarm.getIsDailyDayOn(DAY_LIST.FRIDAY)) { days.push(4); } if (self.curAlarm.getIsDailyDayOn(DAY_LIST.SATURDAY)) { days.push(5); } if (self.curAlarm.getIsDailyDayOn(DAY_LIST.SUNDAY)) { days.push(6); } $('#days').selectpicker('val', days); self.addEventListener(); } else if (args instanceof User) { // Render User self.curUser = <User>args; var exist2: User = Model.getUsers().findWhere({ cid: self.curUser.getcId() }); if (exist2) { // Edit existing User // detail var template3 = _.template(Template.getUserEditTemplate()); var data3 = { username: self.curUser.getUsername(), firstname: self.curUser.getFirstname(), lastname: self.curUser.getLastname(), description: self.curUser.getDescription(), created: self.curUser.getFormattedCreatedDate(), } // apply template var template = _.template(Template.getDetailViewTemplate()); var data = { header: "Friend Detail", //content: (<Alarm>args).getFormattedTime() + ' - <span class="invisible">' + (<Alarm>args).getFormattedEndTime() + '</span>', content: template3(data3), } self.$el.html(template(data)); // add recent group alarm var alarms: Alarms = Model.getAlarms().getPastGroupAlarmsForUsers(Model.getCurUser(), self.curUser); if (alarms.models.length > 0) { var recent: Alarm = alarms.models[0]; self.$('#recent').val(recent.getFormattedTime() + " " + recent.getFormattedDate() + " - " + recent.getName()); } else { self.$('#recent').val("No Recent Group Alarm"); } // add event listener self.addEventListener2(); } else { // Add new User var template4 = _.template(Template.getUserAddTemplate()); var data4 = { } // apply template var template = _.template(Template.getDetailViewTemplate()); var data = { header: "Friend Search", //content: (<Alarm>args).getFormattedTime() + ' - <span class="invisible">' + (<Alarm>args).getFormattedEndTime() + '</span>', content: template4(data4), } self.$el.html(template(data)); self.renderNonAddedUsers(); // add event listener self.addEventListener3(); } } return self; } public renderNonAddedUsers(): void { var self: DetailView = this; var users: Users = Model.getNonAddedUsers(); var template = _.template(Template.getUserItemTemplate()); var data = { users: users, } self.$('#userlist').html(template(data)); $('#userlist').btsListFilter('#searchname', { itemChild: 'span', sourceTmpl: '<div class="user-item"><span class="col-xs-10 ">{title}</span><i class="col-xs-2 fa fa-plus-square fa-1x btn-add"></i></div><div class="clear" />', itemEl: '.user-item', emptyNode: function (data) { return '<div class="user-item-none">No Result</div><div class="clear" />'; }, }); } public setParentView(view: BaseView) { var self: DetailView = this; self.parentView = view; } public addEventListener(): void { var self: DetailView = this; self.$('#btn-save').off('click'); self.$('#btn-save').on('click', function () { click1.play(); View.setIsLoading(true); // remove all warnings self.$('.warn').addClass('hidden'); // check valid time. var isError: boolean = false; if (self.$('#datetime').length) { if (self.$('#stars').val() == 0 || self.$('#stars').val() == "" || (Model.getCurUser().getStars() + self.origstars < parseInt(self.$('#stars').val()))) { self.$('.warn-stars').removeClass('hidden'); isError = true; } if (moment(self.$('#datetime').data("date")).valueOf() < moment(new Date()).valueOf()) { self.$('.warn-datetime').removeClass('hidden'); isError = true; } if (self.$('#name').val() == "") { self.$('.warn-name').removeClass('hidden'); isError = true; } if (isError) { View.setIsLoading(false); return; } } var orig: Alarm = Model.getAlarms().findWhere({ cid: self.curAlarm.getcId() }); // set name self.curAlarm.set('name', self.$('#name').val()); orig.set('name', self.$('#name').val()); // set time if (self.$('#datetime').length) { self.curAlarm.set('date', moment(self.$('#datetime').data("date")).format(Setting.getDateTimeFormat1())); orig.set('date', moment(self.$('#datetime').data("date")).format(Setting.getDateTimeFormat1())); } else { //console.log(self.curAlarm.getFormattedTime()); self.curAlarm.set('date', moment(moment(new Date()).format(Setting.getDateFormat()) + " " + self.$('#time-start').data("date")).format(Setting.getDateTimeFormat1())); orig.set('date', moment(moment(new Date()).format(Setting.getDateFormat()) + " " + self.$('#time-start').data("date")).format(Setting.getDateTimeFormat1())); //console.log(self.curAlarm.getFormattedTime()); //console.log($('#time-start').data("date")); } // stars if (self.$('#datetime').length) { self.curAlarm.set('stars', parseInt($('#stars').val())); orig.set('stars', parseInt($('#stars').val())); Model.getCurUser().set('stars', Model.getCurUser().getStars() + self.origstars - parseInt($('#stars').val())); } // category self.curAlarm.set('category', parseInt($('#category option:selected').val())); orig.set('category', parseInt($('#category option:selected').val())); // days self.curAlarm.removeDailyAllDays(); $.each(self.$('#days option:selected'), function (index: number, item: any) { self.curAlarm.addDailyDay(parseInt($(item).val())); orig.addDailyDay(parseInt($(item).val())); }); // participants if (self.$('#participants').length) { self.curAlarm.removeAllUsers(); //self.curAlarm.addUsercId(Model.getCurUser().getcId()); $.each(self.$('#participants option:selected'), function (index: number, item: any) { self.curAlarm.addUsercId($(item).val()); }); } // back to parentview self.parentView.animInactive(); }); self.$('#btn-delete').off('click'); self.$('#btn-delete').on('click', function () { click1.play(); View.setIsLoading(true); var orig: Alarm = Model.getAlarms().findWhere({ cid: self.curAlarm.getcId() }); Model.getAlarms().remove(orig); self.parentView.animInactive(); }); self.$('#btn-create').off('click'); self.$('#btn-create').on('click', function () { click1.play(); View.setIsLoading(true); // remove all warnings self.$('.warn').addClass('hidden'); // check valid time. var isError: boolean = false; if (self.$('#datetime').length) { if (self.$('#stars').val() == 0 || self.$('#stars').val() == "" || (Model.getCurUser().getStars() < parseInt(self.$('#stars').val()))) { self.$('.warn-stars').removeClass('hidden'); isError = true; } if (moment(self.$('#datetime').data("date")).valueOf() < moment(new Date()).valueOf()) { self.$('.warn-datetime').removeClass('hidden'); isError = true; } if (self.$('#name').val() == "") { self.$('.warn-name').removeClass('hidden'); isError = true; } if (isError) { View.setIsLoading(false); return; } } Model.getAlarms().add(self.curAlarm); //var orig: Alarm = self.curAlarm; // set name self.curAlarm.set('name', self.$('#name').val()); //orig.set('name', self.$('#name').val()); // set time if (self.$('#datetime').length) { self.curAlarm.set('date', moment(self.$('#datetime').data("date")).format(Setting.getDateTimeFormat1())); } else { //console.log(self.curAlarm.getFormattedTime()); self.curAlarm.set('date', moment(moment(new Date()).format(Setting.getDateFormat()) + " " + self.$('#time-start').data("date")).format(Setting.getDateTimeFormat1())); //console.log(self.curAlarm.getFormattedTime()); //console.log($('#time-start').data("date")); } //console.log(self.curAlarm.getFormattedTime()); //orig.set('date', moment(moment(new Date()).format(Setting.getDateFormat()) + " " + self.$('#time-start').data("date")).format(Setting.getDateTimeFormat1())); //console.log(self.curAlarm.getFormattedTime()); //console.log($('#time-start').data("date")); // stars if (self.$('#stars').length) { self.curAlarm.set('stars', parseInt($('#stars').val())); Model.getCurUser().set('stars', Model.getCurUser().getStars() - parseInt($('#stars').val())); } else { self.curAlarm.set('stars', 5); } // category self.curAlarm.set('category', parseInt($('#category option:selected').val())); //orig.set('category', parseInt($('#category option:selected').val())); // days self.curAlarm.removeDailyAllDays(); $.each(self.$('#days option:selected'), function (index: number, item: any) { self.curAlarm.addDailyDay(parseInt($(item).val())); //orig.addDailyDay(parseInt($(item).val())); }); // participants if (self.$('#participants').length) { self.curAlarm.removeAllUsers(); //self.curAlarm.addUsercId(Model.getCurUser().getcId()); $.each(self.$('#participants option:selected'), function (index: number, item: any) { self.curAlarm.addUsercId($(item).val()); }); } // back to parentview self.parentView.animInactive(); }); } public addEventListener2(): void { var self: DetailView = this; self.$('#btn-save').off('click'); self.$('#btn-save').on('click', function () { click1.play(); View.setIsLoading(true); self.curUser.set('description', self.$('#description').val()); // back to parentview self.parentView.animInactive(); }); self.$('#btn-delete').off('click'); self.$('#btn-delete').on('click', function () { click1.play(); View.setIsLoading(true); Model.getUsers().remove(self.curUser); Model.getNonAddedUsers().add(self.curUser); self.parentView.animInactive(); }); } public addEventListener3(): void { var self: DetailView = this; self.$('#searchname').off('keydown'); self.$('#searchname').on('keydown', function () { click1.play(); View.setIsLoading(true); setTimeout(function () { if (self.$('#searchname').val() != "") { self.$('#wrapper-userlist').removeClass('hidden'); } else { self.$('#wrapper-userlist').addClass('hidden'); } View.setIsLoading(false); }, 250); }); self.$('.btn-add').off('click'); self.$('.btn-add').on('click', function () { click1.play(); View.setIsLoading(true); var cid = $(this).attr('data-cid'); var user: User = Model.getNonAddedUsers().findWhere({ cid: cid }); user.set("created", moment(new Date()).format(Setting.getDateTimeFormat1())); Model.getNonAddedUsers().remove(user); Model.getUsers().add(user); $('#searchname').val(""); self.$('#wrapper-userlist').addClass('hidden'); self.renderNonAddedUsers(); self.addEventListener3(); // back to parentview self.parentView.animInactive(); }); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{{ getOption('sitename') }}</title> <!-- Fonts --> <link href="{{ url('public/admin/font-awesome/css/font-awesome.min.css')}}" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700" rel='stylesheet' type='text/css'> <!-- Styles --> <link href="{{ url('public/admin/css/bootstrap.min.css')}}" rel="stylesheet"> {{-- <link href="{{ elixir('css/app.css') }}" rel="stylesheet"> --}} <style> body { font-family: 'Lato'; } .fa-btn { margin-right: 6px; } </style> </head> <body id="app-layout"> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <!-- Collapsed Hamburger --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse"> <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Branding Image --> <a class="navbar-brand" href="{{ url('/') }}"> Laravel </a> </div> <div class="collapse navbar-collapse" id="app-navbar-collapse"> <!-- Left Side Of Navbar --> <ul class="nav navbar-nav"> <li><a href="{{ url('/home') }}">Home</a></li> </ul> <!-- Right Side Of Navbar --> <ul class="nav navbar-nav navbar-right"> <!-- Authentication Links --> @if (Auth::guest()) <li><a href="{{ url('/login') }}">Login</a></li> <li><a href="{{ url('/register') }}">Register</a></li> @else <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> {{ Auth::user()->name }} <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li><a href="{{ url('/logout') }}"><i class="fa fa-btn fa-sign-out"></i>Logout</a></li> </ul> </li> @endif </ul> </div> </div> </nav> @yield('content') <!-- JavaScripts --> <script src="{{ url('public/admin/js/jquery.js')}}"></script> <link href="{{ url('public/admin/js/bootstrap.min.js')}}" rel="stylesheet"> {{-- <script src="{{ elixir('js/app.js') }}"></script> --}} </body> </html>
import { PityHistory, PityHistoryEntry } from "../types"; interface PaimonMoeHistoryEntry { type: "weapon" | "character" code: "100" | "200" | "300" | "301" | "302" | "400" id: string time: string pity: number } interface PaimonMoeBanner { total: number legendary: number rare: number pulls: PaimonMoeHistoryEntry[] } interface PaimonMoeHistory { "server": GenshinServer "wish-counter-setting": { firstTime: boolean manualInput: boolean } "wish-counter-character-event"?: PaimonMoeBanner "wish-counter-weapon-event"?: PaimonMoeBanner "wish-counter-standard"?: PaimonMoeBanner "wish-uid": string } enum GenshinServer { "America" = "America", "Europe" = "Europe", "China" = "China", "Asia/TW/HK/MO" = "Asia" } function getFilteredHistory(history: PityHistoryEntry[]): PaimonMoeBanner { const banner: PaimonMoeBanner = { total: history.length, legendary: 0, rare: 0, pulls: [] } //let fiveStarPity = 0 //let fourStarPity = 0 for (const wish of history) { // Increment pity banner.rare++ banner.legendary++ // Create default pull object const pull: PaimonMoeHistoryEntry = { type: wish.item_type.toLowerCase() as "weapon", id: wish.name.toLowerCase().replaceAll(" ", "_").replaceAll("'", ""), time: wish.time, code: wish.gacha_type, pity: 1 } // Check for 4- and 5-star pulls and change values accordingly switch (wish.rank_type) { case "4": // banner.rare++ pull.pity = banner.rare banner.rare = 0 break case "5": // banner.legendary++ pull.pity = banner.legendary banner.legendary = 0 break; } // Add the modified pull to the pulls banner.pulls.push(pull) } return banner } export default async function (history: PityHistory): Promise<{[key: string]: any}> { // Create an object and add some default settings const finalHistory: PaimonMoeHistory = { server: GenshinServer["Asia/TW/HK/MO"], "wish-counter-setting": { firstTime: true, manualInput: false }, "wish-uid": history.uid } // Get proper server (the rest are Asia) if (history.uid) { const startingDigit = history.uid.charAt(0) switch (startingDigit) { case "6": finalHistory.server = GenshinServer.America break; case "7": finalHistory.server = GenshinServer.Europe break; } } // Sort from earliest to latest const sortedHistory = history.history?.sort((a, b) => (a.time > b.time) ? 1 : -1) // Filter banner wishes const eventWishes = sortedHistory.filter(e => e.gacha_type === "400" || e.gacha_type === "301") const weaponWishes = sortedHistory.filter(e => e.gacha_type === "300" || e.gacha_type === "302") const standardWishes = sortedHistory.filter(e => e.gacha_type === "200") // Set the banner wishes if (eventWishes.length) finalHistory["wish-counter-character-event"] = getFilteredHistory(eventWishes) if (weaponWishes.length) finalHistory["wish-counter-weapon-event"] = getFilteredHistory(weaponWishes) if (standardWishes.length) finalHistory["wish-counter-standard"] = getFilteredHistory(standardWishes) // Return the final object return finalHistory }
import React, { useEffect } from "react"; import Route_btn_Container from "./Route_btn_Container"; import { useState } from "react"; import { avatarList } from "../utils/constants"; const HomeMain = () => { const [avatarName, setAvatarName] = useState("Sittu"); useEffect(() => { const name = localStorage.getItem("avatar_name") || "Sittu"; setAvatarName(name); }, []); function clickHandler(e) { let index; do { index = Math.floor(Math.random() * 4); } while (avatarList[index] === avatarName); setAvatarName(avatarList[index]); localStorage.setItem("avatar_name", avatarList[index]); } return ( <div className=" flex flex-col"> <p className="font-founder text-white font-bold text-4xl leading-[2.5rem] tracking-normal"> Hello Mr. <br /> <span className="before:block before:-z-10 before:absolute before:-inset-1 before:-skew-y-3 before:bg-svgColor relative z-20 mr-4 my-2 text-5xl select-none inline-block hover:cursor-pointer" onClick={clickHandler} > {avatarName}, </span> <br /> how may I assist you :){" "} </p> <Route_btn_Container /> </div> ); }; export default HomeMain;
// Global Variables var workflow = document.getElementsByClassName("workflow")[0] var box = document.getElementsByClassName("box")[0] var sliderCountNumber = document.getElementsByClassName("sliderCountNumber")[0]; var sliderIterationDelay = document.getElementsByClassName("sliderIterationDelay")[0]; var sliderCountNumberIndicator = document.getElementsByClassName("sliderCountNumberIndicator")[0]; var sliderIterationDelayIndicator = document.getElementsByClassName("sliderIterationDelayIndicator")[0]; var sortAlgorithm = document.getElementsByClassName("sortAlgorithm")[0]; var buttonStartSort = document.getElementsByClassName("buttonStartSort")[0]; var buttonRandomize = document.getElementsByClassName("buttonRandomize")[0]; var buttonMute = document.getElementsByClassName("buttonMute")[0]; let frequency = 10 // control the hertz of the sorting sound var context = new window.AudioContext(); // allow use of audio to be played var display; // Function for generating random number function getRandomInt(max) { return Math.floor(Math.random() * max); } // Function to dis/able interactables async function setStatusButtonSlides(status) { buttonStartSort.disabled = status; sliderCountNumber.disabled = status; sliderIterationDelay.disabled = status; buttonRandomize.disabled = status; } // Change the number of bars sliderCountNumber.oninput = function() { sliderCountNumberIndicator.innerHTML = "Count of number: " + this.value; display.fill(sliderCountNumber.value) arrayIsSorted = false } // Change the speed of the bars (lower is faster) sliderIterationDelay.oninput = function () { sliderIterationDelayIndicator.innerHTML = "Iteration delay: " + this.value display.iterationDelay = parseInt(this.value) } // The Start button: starts the selected sort algorithm buttonStartSort.addEventListener("click", async function() { if (!display.isSorted) { setStatusButtonSlides(true) switch (sortAlgorithm.value) { case ("bubbleSort"): await display.bubbleSort() break case ("insertionSort"): await display.insertionSort() break case ("selectionSort"): await display.selectionSort() break case ("quickSort"): await display.quickSort() break case ("mergeSort"): await display.mergeSort() break } setStatusButtonSlides(false); } }); // The Randomize button: randomize the bars' positions buttonRandomize.addEventListener("click", async function() { display.fill(sliderCountNumber.value); }); // THe Mute button: silent the audio and change the text from mute <--> unmute buttonMute.addEventListener("click", function() { if (frequency === 10) { frequency = 0; buttonMute.textContent = "Unmute" } else { frequency = 10; buttonMute.textContent = "Mute" } }) // delay function for animation async function delay(delayIter) { return new Promise(resolve => { setTimeout(() => { resolve(1_000) }, delayIter); }) } // Load the bars document.addEventListener("DOMContentLoaded", async function() { display = new Display({ box, maxValue: parseInt(sliderCountNumber.value) }); display.fill(sliderCountNumber.value); })
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../Otras2estilos.css"> <link rel="stylesheet" href="../Menú/Menu.css"> <link rel="icon" href="../IMG/MetoICON.png"> <title>M E T O D O L O G Í A</title> </head> <body> <header class="hero"> <nav class="nav container"> <div class="nav__logo"> <h2 class="nav__title">Metodología</h2> </div > <div class="nav__menu"> <img src="" alt="" class="nav__img"> </div> <!------------Enlace a Pagina Principal--> <div class="INICIO"> <a href="../Metodología de la Investigación/Metodologia.html" class="button"> <img src="../IMG/INICIO.png" alt="Botón"></a> </div> </nav> <section class="hero__container container"> <h1 class="hero__title">Autoconciencia</h1> </section> </header> <!--Fin de Enlance a Pagina Principal--> <!--Barra de Navegación--> <nav class="menu"> <ul class="list"> <li class="list__item list__item--click"> <div class="list__button list__button--click"> <a href="#" class="nav__link">Inicio</a> <img src="../Menú/flecha.svg" class="list__arrow"> </div> <ul class="list__show"> <li class="list__inside"> <a href="../Metodología de la Investigación/Metodologia.html" class="nav__link nav__link--inside">Metodología de la Investigación</a> </li> </ul> </li> <li class="list__item list__item--click"> <div class="list__button list__button--click"> <a href="#" class="nav__link">Primer Parcial</a> <img src="../Menú/flecha.svg" class="list__arrow"> </div> <ul class="list__show"> <li class="list__inside"> <a href="../ImportanciaInvestigacion.html" class="nav__link nav__link--inside">Importancia de la Investigación</a> </li> <li class="list__inside"> <a href="../PensamientoReflexivo.html" class="nav__link nav__link--inside">Pensamiento Reflexivo</a> </li> <li class="list__inside"> <a href="../RobertoSampieri.html" class="nav__link nav__link--inside">Dr.Roberto Sampieri</a> </li> <li class="list__inside"> <a href="../ManuelGalan.html" class="nav__link nav__link--inside">Manuel Galan Amador</a> </ul> </li> <li class="list__item list__item--click"> <div class="list__button list__button--click"> <a href="#" class="nav__link">Segundo Parcial</a> <img src="../Menú/flecha.svg" class="list__arrow"> </div> <ul class="list__show"> <li class="list__inside"> <a href="../Investigación.html" class="nav__link nav__link--inside">Investigación</a> </li> <li class="list__inside"> <a href="../InstrumentosRecolecciónDatos.html" class="nav__link nav__link--inside">Instrumentos de Recolección de Datos</a> </li> <li class="list__inside"> <a href="../WendySuzuki.html" class="nav__link nav__link--inside">Doctora Wendy Suzuki</a> </li> <li class="list__inside"> <a href="../Tesina.html" class="nav__link nav__link--inside">Tesina</a> </li> </ul> </li> <li class="list__item list__item--click"> <div class="list__button list__button--click"> <a href="#" class="nav__link">Tercer Parcial</a> <img src="../Menú/flecha.svg" class="list__arrow"> </div> <ul class="list__show"> <li class="list__inside"> <a href="../TiposHipotesis.html" class="nav__link nav__link--inside">Tipos de Hipótesis </a> </li> </ul> </li> <li class="list__item list__item--click"> <div class="list__button list__button--click"> <a href="#" class="nav__link">Ver Subtemas</a> <img src="../Menú/flecha.svg" class="list__arrow"> </div> <ul class="list__show"> <li class="list__inside"> <a href="../Pensamiento Reflexivo/Autoconciencia.html" class="nav__link nav__link--inside">Autoconciencia</a> </li> <li class="list__inside"> <a href="../Pensamiento Reflexivo/Comunicación.html" class="nav__link nav__link--inside">Comunicación</a> </li> <li class="list__inside"> <a href="../Pensamiento Reflexivo/Decisiones.html" class="nav__link nav__link--inside">Decisiones</a> </li> <li class="list__inside"> <a href="../Pensamiento Reflexivo/Razonamiento.html" class="nav__link nav__link--inside">Razonamiento</a> </li> </ul> </li> </ul> </nav> <script src="../Menú/Menu.js"></script> <!--Fin Barra de Navegación--> <main> <section class="container about"> <h2 class="subtitle">¿Qué es la Autoconciencia?</h2> <p class="about__paragraph">La autoconciencia es un estado de profundo conocimiento y comprensión de uno mismo. Implica estar consciente de nuestros pensamientos, emociones, creencias, motivaciones y acciones, así como de cómo estas variables influyen en nuestro comportamiento y en nuestras interacciones con los demás. La autoconciencia interna nos permite sintonizar con nuestros sentimientos y necesidades, reconocer nuestras fortalezas y debilidades, y tomar decisiones más alineadas con nuestros valores y metas personales. Por otro lado, la autoconciencia externa implica la capacidad de percibir y comprender cómo nos ven los demás, cómo nuestras acciones impactan en ellos y cómo nos comportamos en diferentes contextos sociales. Al desarrollar la autoconciencia, podemos tomar decisiones más informadas, ajustar nuestro comportamiento según sea necesario y cultivar relaciones más saludables y auténticas con los demás. Además, la autoconciencia nos brinda la oportunidad de reconocer y transformar nuestros patrones de pensamiento y comportamiento negativos, permitiéndonos desarrollar un mayor autodominio y bienestar emocional. En definitiva, la autoconciencia es un proceso de autodescubrimiento y autoexploración constante que nos ayuda a comprendernos mejor a nosotros mismos y a vivir una vida más consciente y significativa.</p> <h2 class="subtitle">Caracteristicas de la Autoconciencia</h2> <p class="about__paragraph2"> <ul class="about__list2"> <li><b>Autoobservación</b></li> <li><b>Autoevaluación</b></li> <li><b>Conexión emocional</b></li> <li><b>Autenticidad</b></li> <li><b>Autenticidad</b></li> <li><b>Empatía:</b></li> <li><b>Responsabilidad personal</b></li> </ul> </p> </section> <section class="knowledge"> <div class="knowledge__container container"> <div class="knowledge__texts"> <h2 class="Pvideo">¿Porque es importante ser autoconcientes?</h2> <p class="about__paragraph">La autoconciencia es importante porque nos permite conocernos a nosotros mismos en un nivel profundo, tomar decisiones informadas, gestionar nuestras emociones, mejorar personalmente y construir relaciones saludables. Ser conscientes de nosotros mismos nos capacita para vivir una vida más auténtica, significativa y en armonía con nuestros valores y metas personales.</p> <img src="autoconciencia.png" class="imagen"> </div> </section> <footer class="footer"> <section class="footer__container container"> <nav class="nav naav--footer"> <h2 class="footer__title">Metodología</h2> <h2 class="footer__title2">Josué Reyneri Morales Molina 5090-23-4182</h2> <ul class="nav__link nav__link--footer"> </ul> </nav> <form class="footer__form"> <h2 class="footer__newsletter">Contactanos</h2> <div class="footer__inputs"> <input type="email" placeholder="Email:" class="footer__input"> <input type="submit" value="Registrate" class="footer__submit"> </div> </form> </section> <section class="footer__copy container"> <div class="footer__social"> <a href="https://umg.edu.gt/" class="footer__icons"><img src="https://www.nicepng.com/png/detail/321-3210681_this-escudo-de-la-universidad-mariano-galvez.png" alt="Mi umg" class="footer__img"></a> </div> </section> </footer> </main> </body> </html>
/* $Id: LookAction.java,v 1.3 2012/09/02 11:40:50 kiheru Exp $ */ /*************************************************************************** * (C) Copyright 2003 - Marauroa * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.actions.query; import static games.stendhal.common.constants.Actions.LOOK; import static games.stendhal.common.constants.Actions.NAME; import static games.stendhal.common.constants.Actions.TARGET; import static games.stendhal.common.constants.Actions.TYPE; import games.stendhal.common.NotificationType; import games.stendhal.common.constants.Actions; import games.stendhal.server.actions.ActionListener; import games.stendhal.server.actions.CommandCenter; import games.stendhal.server.actions.admin.AdministrationAction; import games.stendhal.server.core.engine.GameEvent; import games.stendhal.server.entity.Entity; import games.stendhal.server.entity.item.Item; import games.stendhal.server.entity.player.Player; import games.stendhal.server.util.EntityHelper; import marauroa.common.game.Definition; import marauroa.common.game.Definition.DefinitionClass; import marauroa.common.game.RPAction; import marauroa.common.game.RPObject; /** * Processes a look menu action. */ public class LookAction implements ActionListener { public static void register() { CommandCenter.register(LOOK, new LookAction()); } /** * processes the requested action. * * @param player the caller of the action * @param action the action to be performed */ public void onAction(final Player player, final RPAction action) { Entity entity = null; if (action.has(Actions.TARGET_PATH)) { entity = EntityHelper.getEntityFromPath(player, action.getList(Actions.TARGET_PATH)); } else { entity = EntityHelper.entityFromSlot(player, action); if (entity == null) { entity = EntityHelper.entityFromTargetName(action.get(TARGET), player); } } if (entity != null) { if (entity instanceof Player) { if (((Player) entity).isGhost() && (player.getAdminLevel() < AdministrationAction.getLevelForCommand("ghostmode"))) { return; } } if (entity instanceof Item) { Item item = (Item) entity; RPObject base = item.getBaseContainer(); if (base instanceof Player) { Player owner = (Player) base; // Check if looking is allowed if ((player != owner) && isHiddenSlot(owner, item.getContainerSlot().getName())) { return; } } } String name = entity.get(TYPE); if (entity.has(NAME)) { name = entity.get(NAME); } new GameEvent(player.getName(), LOOK, name).raise(); final String text = entity.describe(); if (entity.has(Actions.ACTION) && entity.get(Actions.ACTION).equals(Actions.READ)) { player.sendPrivateText(NotificationType.RESPONSE, text); } else { player.sendPrivateText(text); } player.notifyWorldAboutChanges(); } } /** * Check if a slot is hidden to others than the player itself. * * @param player * @param slotName * @return <code>true</code> if other players should not be able to view * the slot contents, <code>false</code> if it's allowed. */ private boolean isHiddenSlot(Player player, String slotName) { byte flags = player.getRPClass().getDefinition(DefinitionClass.RPSLOT, slotName).getFlags(); return (((flags & Definition.PRIVATE) | (flags & Definition.HIDDEN)) != 0); } }
--- title: Constantes Inteiras categories: [ "Variables" ] subCategories: [ "Constants" ] --- = Integer Constants // OVERVIEW SECTION STARTS [#overview] -- [float] === Descrição Constantes Inteiras são números usados diretamente em um sketch, como 123. Por padrão, esses números são tratados como link:../../data-types/int[int] mas você pode mudar isso com os modificadores U e L (ver abaixo). [%hardbreaks] Normalmente, constantes inteiras são tratadas como inteiros na base 10 (decimais), mas notações especiais (modificadores) podem ser usados para escrever-se números em outras bases. [%hardbreaks] |=== |Base |Exemplo |Modificador |Comentário |10 (decimal) |123 |nenhum | |2 (binário) |B1111011 |prefixo 'B' |funciona apenas com valores 8-bit (0 a 255) caracteres 0 e 1 válidos |8 (octal) |0173 |prefixo "0" |caracteres 0-7 válidos |16 (hexadecimal) |0x7B |prefixo "0x" |caracteres 0-9, A-F, a-f válidos |=== [%hardbreaks] -- // OVERVIEW SECTION ENDS // HOW TO USE SECTION STARTS [#howtouse] -- [float] == Decimal (base 10) Essa é a matemática de senso comum a qual você já está acostumado. Constantes sem prefixos são assumidas como valores decimais. [float] === Código de Exemplo: [source,arduino] ---- n = 101; // o mesmo que 101 decimal ((1 * 10^2) + (0 * 10^1) + 1) ---- [%hardbreaks] [float] == Binário (base 2) Apenas os caracteres 0 e 1 são válidos. [float] === Código de Exemplo: [source,arduino] ---- n = B101; // o mesmo que 5 decimal ((1 * 2^2) + (0 * 2^1) + 1) ---- O modificador binário funciona apenas em bytes (8 bits), ou seja, entre 0 (B0) e 255 (B11111111). Se for conveniente inserir um int (16 bits) em formato binário, você pode fazê-lo com um procedimento em dois passos, como: [source,arduino] ---- meuInt = (B11001100 * 256) + B10101010; // B11001100 é o byte mais significativo ---- [%hardbreaks] [float] == Octal (base 8) Apenas os caracteres 0 a 7 são válidos. Valores octais são indicados pelo prefixo "0" (zero). [float] === Código de Exemplo: [source,arduino] ---- n = 0101; // o mesmo que 65 decimal ((1 * 8^2) + (0 * 8^1) + 1) ---- *Cuidado:* é possível criar um bug difícil de encontrar (acidentalmente), caso seja inserido um zero antes de uma constante, fazendo com que o compilador interprete sua constante como octal. [%hardbreaks] [float] == Hexadecimal (base 16) Os caracteres válidos são 0 a 9 e as letras A a F; A possui valor 10, B é 11, até o F, que é 15. Valores hexadecimais são indicados pelo prefixo "0x". Note que as letras A-F podem ser também iseridas em minúsculo (a-f). [float] === Código de Exemplo: [source,arduino] ---- n = 0x101; // o qmesmo que 257 decimal ((1 * 16^2) + (0 * 16^1) + 1) ---- [%hardbreaks] [float] === Notas e Advertências *Modificadores 'U' e 'L':* Por padrão, uma constante inteira é tratada como int com as mesmas limitações desse tipo de dado. Para especificar uma constante inteira com outro tipo de dado, termine-a com: - um 'u' ou 'U' para forçar a constante para formato unsigned (sem sinal). Exemplo: 33u - um 'l' ou 'L' para forçar a constante para formato long. Exemplo: 100000L - um 'ul' ou 'UL' para forçar a constante para formato unsigned long. Exemplo: 32767ul [%hardbreaks] -- // HOW TO USE SECTION ENDS // SEE ALSO SECTION BEGINS [#see_also] -- [float] === Ver Também [role="language"] -- // SEE ALSO SECTION ENDS
library(dplyr) layoffs <- read.csv("tech_layoffs.csv", stringsAsFactors = FALSE) # A function that takes in a dataset and returns a list of info about it: summary_information <- function(layoffs) { # The list to return summary_info <- list() # Number of companies reported summary_info$unique_companies <- length(unique(layoffs$company)) # Total number of layoffs in the dataset layoffs$total_layoffs <- suppressWarnings(as.numeric(layoffs$total_layoffs)) summary_info$total_layoff <- as.integer( sum(layoffs$total_layoffs, na.rm = TRUE)) # Company layoffs the most and its number max_layoffs <- layoffs %>% group_by(company) %>% summarize(total_layoff_num = sum(total_layoffs)) %>% filter(! is.na(total_layoff_num)) %>% filter(total_layoff_num == max(total_layoff_num)) summary_info$company_name <- max_layoffs$company summary_info$max_company_layoffs <- as.integer(max_layoffs$total_layoff_num) # Most location of the headquarter of the layoff company summary_info$max_headquarter_location <- layoffs %>% group_by(headquarter_location) %>% summarize(headquarter_num = n()) %>% filter(headquarter_num == max(headquarter_num)) %>% pull(headquarter_location) # Percentage of the company status company_status <- layoffs %>% group_by(status) %>% summarize(comp_status = n()) summary_info$private_percent <- round( company_status$comp_status[1] / sum(company_status$comp_status) * 100, digits = 2) # Industry impact the most by layoffs # clean the industry column ind <- list() for (i in as.list(layoffs$industry)) { industries <- unlist(strsplit(i, ", ")) ind <- append(ind, industries[length(industries)]) } ind <- lapply(ind, tolower) ind <- lapply(X = ind, FUN = function(t) gsub("-", "", t)) max_industry <- layoffs %>% mutate(industry_cleaned = ind) %>% group_by(industry_cleaned) %>% summarize(industry_count = n()) %>% filter(industry_count == max(industry_count)) %>% pull(industry_cleaned) summary_info$max_industry <- unlist(max_industry) # return the summary_info return(summary_info) } summary_info <- summary_information(layoffs)
-------------------------------------------------------------------------------- -- Ccsds_Socket_Interface Component Implementation Spec -------------------------------------------------------------------------------- -- Standard Includes: -- Invokee Connector Includes: with Socket; -- The Socket Component is an interface component which connects the rest of the assembly to an outside entity (usually the ground system) via a TCP/IP socket. It spawns an internal task to listen to the socket for incoming data. It also provides an asynchronous receive connector which it services on it's task, sending any data it receives out of the socket. The data send and receive connectors are of a generic buffer type, Com_Packet, so that data of an arbitrary format can be sent via this component. -- package Component.Ccsds_Socket_Interface.Implementation is type Instance is new Ccsds_Socket_Interface.Base_Instance with private; -------------------------------------------------- -- Subprogram for implementation init method: -------------------------------------------------- -- This initialization subprogram connects the component to a TCP socket on the given address and port. overriding procedure Init (Self : in out Instance; Addr : in String := "127.0.0.1"; Port : in Natural := 2_001); -- Public function which closes the TCP socket. not overriding procedure Final (Self : in out Instance); private -- The component class instance record: type Instance is new Ccsds_Socket_Interface.Base_Instance with record Sock : Socket.Instance; Addr : String (1 .. 512); Port : Natural; end record; --------------------------------------- -- Invokee connector primitives: --------------------------------------- -- On this connector the Socket Interface Component receives data and sends it out of the socket. overriding procedure Ccsds_Space_Packet_T_Recv_Async (Self : in out Instance; Arg : in Ccsds_Space_Packet.T); -- This procedure is called when a Ccsds_Space_Packet_T_Recv_Async message is dropped due to a full queue. overriding procedure Ccsds_Space_Packet_T_Recv_Async_Dropped (Self : in out Instance; Arg : in Ccsds_Space_Packet.T) is null; --------------------------------------- -- Invoker connector primitives: --------------------------------------- -- This procedure is called when a Ccsds_Space_Packet_T_Send message is dropped due to a full queue. overriding procedure Ccsds_Space_Packet_T_Send_Dropped (Self : in out Instance; Arg : in Ccsds_Space_Packet.T) is null; -- This procedure is called when a Event_T_Send message is dropped due to a full queue. overriding procedure Event_T_Send_Dropped (Self : in out Instance; Arg : in Event.T) is null; ------------------------------------------------------- -- Definition of subtasks functions for task execution: ------------------------------------------------------- -- This internal task is used to listen on the socket for incoming packets. -- IMPORTANT: This component needs an inner task to run the -- following function as if it were the "cycle" method of -- a normal component. The "cycle" method of this component -- acts in the normal way, blocking on the component -- queue, waiting for messages to send through the socket. -- The special cycle method below should be run on another -- task to block on the socket, waiting for incoming messages -- which it will then send out to the rest of the assembly. overriding procedure Listener (Self : in out Instance); end Component.Ccsds_Socket_Interface.Implementation;
import { NavLink } from "react-router-dom"; import styled from "styled-components"; import { HiOutlineCalendarDays, HiOutlineCog6Tooth, HiOutlineHome, HiOutlineAcademicCap, } from "react-icons/hi2"; import { useToggleMenu } from "../context/ToggleMenuContext"; const NavList = styled.ul` display: flex; flex-direction: column; gap: 0.8rem; `; const StyledNavLink = styled(NavLink)` &:link, &:visited { display: flex; align-items: center; gap: 1.2rem; color: var(--color-grey-600); font-size: 1.6rem; font-weight: 500; padding: 1.2rem; transition: all 0.3s; } /* This works because react-router places the active class on the active NavLink */ &:hover, &:active, &.active:link, &.active:visited { color: var(--color-grey-800); background-color: var(--color-grey-50); border-radius: var(--border-radius-sm); } & svg { width: 2.4rem; height: 2.4rem; color: var(--color-grey-400); transition: all 0.3s; } &:hover svg, &:active svg, &.active:link svg, &.active:visited svg { color: var(--color-brand-600); } `; function MainNav() { const { isMenuOpen } = useToggleMenu(); return ( <nav> <NavList> <li> <StyledNavLink to="/dashboard"> <HiOutlineHome /> {isMenuOpen && <span>Home</span>} </StyledNavLink> </li> <li> <StyledNavLink to="/dashboard"> <HiOutlineCalendarDays /> {isMenuOpen && <span>Dashboard</span>} </StyledNavLink> </li> <li> <StyledNavLink to="/courses"> <HiOutlineAcademicCap /> {isMenuOpen && <span>Courses</span>} </StyledNavLink> </li> <li> <StyledNavLink to="/settings"> <HiOutlineCog6Tooth /> {isMenuOpen && <span>Settings</span>} </StyledNavLink> </li> </NavList> </nav> ); } export default MainNav;
import classNames from 'classnames'; import React, { PureComponent, ReactNode } from 'react'; import { Button, Checkbox, Col, FormControl, Row } from 'react-bootstrap'; import { CompactPicker } from 'react-color'; import { createFormInputId, createFormInputName, getNameFromId } from '../utils'; import { DOMAIN_CONDITION_FORMAT_BACKGROUND_COLOR, DOMAIN_CONDITION_FORMAT_TEXT_COLOR, DOMAIN_CONDITIONAL_FORMAT_PREFIX, DOMAIN_VALIDATOR_BOLD, DOMAIN_VALIDATOR_ITALIC, DOMAIN_VALIDATOR_REMOVE, DOMAIN_VALIDATOR_STRIKETHROUGH, } from '../constants'; import { PropertyValidator } from '../models'; import { PropDescType } from '../PropDescType'; import { LabelHelpTip } from '../../base/LabelHelpTip'; import { Filters } from './Filters'; import { ValidatorModal } from './ValidatorModal'; interface ConditionalFormatOptionsProps { dataType: PropDescType; domainIndex: number; expanded: boolean; index: number; mvEnabled: boolean; onChange: (validator: PropertyValidator, index: number) => void; onDelete: (index: number) => void; onExpand: (index: number) => void; validator: any; validatorIndex: number; } interface ConditionalFormatState { showFillColor: boolean; showTextColor: boolean; } export class ConditionalFormatOptions extends PureComponent<ConditionalFormatOptionsProps, ConditionalFormatState> { constructor(props) { super(props); this.state = { showTextColor: false, showFillColor: false, }; } static isValid = (validator: PropertyValidator): boolean => { return Filters.isValid(validator.get('formatFilter'), DOMAIN_CONDITIONAL_FORMAT_PREFIX); }; onDelete = (): void => { const { onDelete, validatorIndex } = this.props; onDelete(validatorIndex); }; onFieldChange = (evt): void => { const { onChange, validator, validatorIndex } = this.props; let value = evt.target.value; const name = getNameFromId(evt.target.id); if ( name === DOMAIN_VALIDATOR_BOLD || name === DOMAIN_VALIDATOR_STRIKETHROUGH || name === DOMAIN_VALIDATOR_ITALIC ) { value = evt.target.checked; } onChange(validator.set(name, value), validatorIndex); }; onFilterChange = (expression: string): void => { const { validator, validatorIndex, onChange } = this.props; onChange(validator.set('formatFilter', expression), validatorIndex); }; expandValidator = (): void => { const { onExpand, validatorIndex } = this.props; onExpand(validatorIndex); }; firstFilterTooltip = (): ReactNode => { return ( <LabelHelpTip title="First Condition" required={true}> Add a condition to this format rule that will be tested against the value for this field. </LabelHelpTip> ); }; renderDisplayCheckbox = (name: string, label: string, value: boolean): ReactNode => { const { validatorIndex, domainIndex } = this.props; return ( <Row> <Col xs={12} className="domain-validation-display-checkbox-row"> <Checkbox id={createFormInputId(name, domainIndex, validatorIndex)} name={createFormInputName(name)} checked={value} onChange={this.onFieldChange} > {label} </Checkbox> </Col> </Row> ); }; onColorShow = (evt): void => { const { showTextColor, showFillColor } = this.state; let name = getNameFromId(evt.target.id); // If click on caret icon if (!name) { name = getNameFromId(evt.target.parentElement.parentElement.id); } // Strange little border between icon and button if (!name) { name = getNameFromId(evt.target.parentElement.id); } if (name === DOMAIN_CONDITION_FORMAT_TEXT_COLOR) { this.setState(() => ({ showTextColor: !showTextColor, showFillColor: false })); } if (name === DOMAIN_CONDITION_FORMAT_BACKGROUND_COLOR) { this.setState(() => ({ showFillColor: !showFillColor, showTextColor: false })); } }; onColorChange = (color): void => { const { onChange, validator, validatorIndex } = this.props; const { showTextColor } = this.state; const name = showTextColor ? DOMAIN_CONDITION_FORMAT_TEXT_COLOR : DOMAIN_CONDITION_FORMAT_BACKGROUND_COLOR; onChange(validator.set(name, color.hex.substring(1)), validatorIndex); }; renderColorPickers = (): ReactNode => { const { validator, validatorIndex } = this.props; const { showTextColor, showFillColor } = this.state; const textColor = validator.textColor ? '#' + validator.textColor : 'black'; const fillColor = validator.backgroundColor ? '#' + validator.backgroundColor : 'white'; return ( <Row className="domain-validator-color-row"> <Col xs={4}> {this.getColorPickerButton( DOMAIN_CONDITION_FORMAT_TEXT_COLOR, 'Text Color', textColor, showTextColor )} </Col> <Col xs={4}> {this.getColorPickerButton( DOMAIN_CONDITION_FORMAT_BACKGROUND_COLOR, 'Fill Color', fillColor, showFillColor )} </Col> <Col xs={1} /> <Col xs={3}> <FormControl type="text" id={'domain-validator-preview-' + validatorIndex} defaultValue="Preview Text" style={{ fontSize: '12px', width: '100px', color: textColor, backgroundColor: fillColor, fontWeight: validator.bold ? 'bold' : 'normal', fontStyle: validator.italic ? 'italic' : 'normal', textDecoration: validator.strikethrough ? 'line-through' : '', }} /> </Col> </Row> ); }; getColorPickerButton = (name: string, label: string, color: string, showColorPicker: boolean): ReactNode => { const { validatorIndex, domainIndex } = this.props; const iconClassName = classNames('domain-color-caret', 'fa', 'fa-lg', { 'fa-caret-up': showColorPicker, 'fa-caret-down': !showColorPicker, }); return ( <div style={{ width: '100%' }}> <Button id={createFormInputId(name, domainIndex, validatorIndex)} key={createFormInputId(name, domainIndex, validatorIndex)} name={createFormInputName(name)} onClick={this.onColorShow} className="domain-color-picker-btn" > {label} <span className={iconClassName} /> </Button> {showColorPicker && ( <div className="domain-validator-color-popover"> <div className="domain-validator-color-cover" id={createFormInputId(name, domainIndex, validatorIndex)} onClick={this.onColorShow} /> <CompactPicker onChangeComplete={this.onColorChange} color={color} /> </div> )} <div className="domain-color-preview" style={{ backgroundColor: color }} /> </div> ); }; render(): ReactNode { const { validatorIndex, expanded, dataType, validator, mvEnabled, domainIndex } = this.props; // Needs to be able to take string values for between syntax, but keep as date if that is the selected type (issue 39193) const type = dataType.getJsonType() === 'date' ? dataType.getJsonType() : 'string'; return ( <div className="domain-validator-panel" id={'domain-condition-format-' + validatorIndex}> {expanded && ( <div> <Filters validatorIndex={validatorIndex} domainIndex={domainIndex} onChange={this.onFilterChange} type={type} mvEnabled={mvEnabled} expression={validator.formatFilter} prefix={DOMAIN_CONDITIONAL_FORMAT_PREFIX} firstFilterTooltip={this.firstFilterTooltip()} /> <div className="domain-validation-subtitle">Display Options</div> {this.renderDisplayCheckbox(DOMAIN_VALIDATOR_BOLD, 'Bold', validator.bold)} {this.renderDisplayCheckbox(DOMAIN_VALIDATOR_ITALIC, 'Italics', validator.italic)} {this.renderDisplayCheckbox( DOMAIN_VALIDATOR_STRIKETHROUGH, 'Strikethrough', validator.strikethrough )} {this.renderColorPickers()} <Row className="domain-validator-color-row"> <Col xs={12}> <Button className="domain-validation-delete" name={createFormInputName(DOMAIN_VALIDATOR_REMOVE)} id={createFormInputId(DOMAIN_VALIDATOR_REMOVE, domainIndex, validatorIndex)} onClick={this.onDelete} > Remove Formatting </Button> </Col> </Row> </div> )} {!expanded && ( <div> {validator.formatFilter ? Filters.describeExpression(validator.formatFilter, DOMAIN_CONDITIONAL_FORMAT_PREFIX) : 'Missing condition'} <div className="domain-validator-collapse-icon" onClick={this.expandValidator}> <span className="fa fa-pencil" /> </div> </div> )} </div> ); } } export const ConditionalFormatOptionsModal = ValidatorModal(ConditionalFormatOptions);
## Import ```js import { useFocusTrap } from "@prismane/core/hooks"; ``` ## Usage By default, the `useFocusTrap` hook focuses the first focusable element in the container, to which the `ref` is passed. As you can see, in the example below, we pass the `ref` to a `Stack` container, and the first input of the container is focused. ```jsx function Demo() { const ref = useFocusTrap(); return ( <Flex direction="column" gap={fr(2)} w="300px"> <TextField /> <Stack ref={ref}> <TextField placeholder="I should be focused" /> <TextField /> </Stack> </Flex> ); } ``` ### Toggle Hook The functionality of the hook can be toggled, if we pass a `boolean` value as the `isOpen` parameter of the hook. ```jsx function Demo() { const [open, setOpen] = useState(false); const ref = useFocusTrap(open); return ( <Flex direction="column" gap={fr(2)} w="300px"> <TextField /> <Stack ref={ref}> <TextField placeholder="I should be focused" /> <TextField /> </Stack> <Button onClick={() => setOpen(!open)}>Toggle Hook</Button> </Flex> ); } ``` ### Initial Focused Element You can set the initial element that will be focused, by giving it an attribute of `data-initialfocus`. ```jsx function Demo() { const [open, setOpen] = useState(false); const ref = useFocusTrap(open); return ( <Flex direction="column" gap={fr(2)} w="300px"> <TextField /> <Stack ref={ref}> <TextField placeholder="I am the first, but I am not focused" /> <TextField placeholder="I should be focused" data-initialfocus /> </Stack> <Button onClick={() => setOpen(!open)}>Toggle Hook</Button> </Flex> ); } ``` ## API ### Parameters | Name | Type | Description | Default | | -------- | --------- | ---------------------------------- | ------- | | `isOpen` | `boolean` | The boolean that toggles the hook. | `true` | ### Return Value | Name | Type | Description | | ----- | ---------- | --------------------------------------------------------------------------- | | `ref` | `Ref<any>` | The ref that should be passed to the container with the focusable elements. |
# content of test_sample.py from ..questions_settings import Questions from ..retirement_plan import Retirement import pytest import time class TestRetirement: """ Class for test Retirement class Attributes ---------- questions: Question() Question class object retirement: Retirement() Retirement class object Methods ------- get_message(): move to next question check_input(monkeypatch) check user input test_for_replicant(capsys, monkeypatch) test for replicant decision test_for_replicant2(capsys) test for replicant decision test_for_hunan(capsys) test for human decision """ questions = Questions(10) retirement = Retirement() def get_message(self): """move to next question and return user answer Returns: -------- str: user answer """ self.questions.next() return self.questions.answer def check_input(self, monkeypatch): """checking user answer and test input Parameters: ----------- monkeypatch : pytest modify or replace parts of the system under test during a test """ user_input = "a" monkeypatch.setattr("builtins.input", lambda _: user_input) message = self.get_message() assert message == "a" def test_for_replicant(self, capsys, monkeypatch): """checking for replicant Parameters ---------- capsys: CaptureFixture Fixture in pytest that provides a way to capture output generated by a test function monkeypatch : pytest modify or replace parts of the system under test during a test """ start = time.time() for _ in range(10): self.check_input(monkeypatch) end = time.time() self.retirement.calculate(end - start, self.questions.total_points) def test_for_replicant2(self, capsys): """Test for replicant Parameters ---------- capsys: CaptureFixture Fixture in pytest that provides a way to capture output generated by a test function """ self.retirement.human_or_replicant() captured = capsys.readouterr() assert captured.out == "You are Replicant\n" def test_for_human(self, capsys): """Test for human Parameters ---------- capsys: CaptureFixture Fixture in pytest that provides a way to capture output generated by a test function """ self.retirement.calculate(16, 90) self.retirement.human_or_replicant() captured = capsys.readouterr() assert captured.out == "Congratulations you are human!\n"
package com.maxml.bachelorhouse.activity; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.maxml.bachelorhouse.R; import com.maxml.bachelorhouse.fragment.rooms.RoomsFragment; import com.maxml.bachelorhouse.fragment.rooms.StatisticsFragment; import com.maxml.bachelorhouse.util.BachelorConstants; public class RoomsActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rooms); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Rooms"); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); getSupportFragmentManager().beginTransaction().add(R.id.rooms_fragment_container, new RoomsFragment(), BachelorConstants.ROOMS_LIST_FRAGMENT_TAG).commit(); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_exit) { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Closing Project") .setMessage("Are you sure you want to close this project?") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); // if (id == R.id.nav_camera) { // Handle the camera action if (id == R.id.nav_gallery) { getSupportFragmentManager().beginTransaction().replace(R.id.rooms_fragment_container, new RoomsFragment(), BachelorConstants.ROOMS_LIST_FRAGMENT_TAG).commit(); // } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { getSupportFragmentManager().beginTransaction().replace(R.id.rooms_fragment_container, new StatisticsFragment(), BachelorConstants.ROOMS_LIST_FRAGMENT_TAG).commit(); // } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { Intent emailIntent = new Intent(Intent.ACTION_SEND, Uri.fromParts( "mailto:", "abc@gmail.com", null)); emailIntent.setType("text/plain"); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Help : your subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Your comment"); startActivity(Intent.createChooser(emailIntent, "Send email via:")); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
<template> <div> <el-container> <el-header class="homeHeader"> <div class="title">人事劳资管理信息系统</div> <el-dropdown class="userInfo" @command="commandHandler"><!--command是elementui里面的dropdown Events--> <span class="el-dropdown-link"> {{user.name}}<i> <img :src="user.userface" alt=""></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item command="userInfo">个人中心</el-dropdown-item><!--给每个dropitem设置command属性作为标识---> <el-dropdown-item command="setting">设置</el-dropdown-item> <el-dropdown-item divided command="logout">注销登陆</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </el-header> <el-container> <el-aside width="200px"> <el-menu router unique-opened> <el-submenu :index="index+''" v-for="(item,index) in routes" v-if="!item.hidden" :key="index"><!--这个routes就是计算属性里面的routes--><!--this.$router.options.routes拿到的就是router/index.js中的数组 v-if设置当hidden为false时才渲染--> <template slot="title" > <i :class="item.iconCls" style="color: #0aaeff;margin: 5px"></i> <span>{{item.name}}</span> </template> <el-menu-item :index="child.path" v-for="(child,indexj) in item.children" :key="indexj">{{child.name}}</el-menu-item><!--index设置成想要去的路径,它是一个唯一标识--> </el-submenu> </el-menu> </el-aside> <el-main class="main"> <el-breadcrumb style="padding-bottom: 10px" separator-class="el-icon-arrow-right" v-if="this.$router.currentRoute.path !='/home'"> <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item> <el-breadcrumb-item>{{this.$router.currentRoute.name}}</el-breadcrumb-item><!--当前路由对象的name属性--> </el-breadcrumb> <div class="homeWelcome" v-if="this.$router.currentRoute.path =='/home'"> 欢迎使用人事劳资管理信息系统! </div> <router-view /> </el-main> </el-container> </el-container> </div> </template> <script> export default { name: "Home", data(){ return{ user:JSON.parse(window.sessionStorage.getItem('user'))/*因为window....这样得到的是字符串而不是对象,所以用JSON.parse将他转为对象方便操作*/ } }, computed:{ routes(){ return this.$store.state.routes;////this.$store获取到store } }, methods:{ commandHandler(cmd){ if(cmd == 'logout'){/*点击的是注销,做以下处理*/ this.$confirm('此操作将注销登陆, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { this.getRequest('/logout'); window.sessionStorage.removeItem('user')/*清空登陆数据*/ this.$store.commit('initRoutes',[]) this.$router.replace('/')/*跳转到登录页*/ }).catch(() => { this.$message({ type: 'info', message: '操作取消' }); }); } } } } </script> <style scoped> .homeHeader{ background-color: #029dff; display: flex; align-items: center;/*富裕空间(侧轴上的):两边 (垂直居中)*/ justify-content: space-between;/*富裕空间(主轴上的:项目之间 */ padding: 0px 15px;/*防止两边离太久*/ box-sizing: border-box;/*padding在框的里面*/ } .homeHeader .title{ font: 24px "华文行楷"; color: white; } .userInfo{ cursor: pointer; } .el-dropdown-link img{ width: 42px; height: 42px; border-radius: 21px; margin-left: 8px; } .el-dropdown-link{ display: flex; align-items: center; } .homeWelcome{ text-align: center; font: 30px 华文行楷; color: #1295ff; padding-top: 50px; } </style>
import { AUTH_SERVICE, DatabaseModule } from '@app/common'; import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { ClientsModule, Transport } from '@nestjs/microservices'; import * as Joi from 'joi'; import { Post, PostSchema } from './entities/post.entity'; import { PostsController } from './posts.controller'; import { PostsService } from './posts.service'; import { PostsRepository } from './repository/posts.repository'; @Module({ imports: [ DatabaseModule, DatabaseModule.forFeature([{ name: Post.name, schema: PostSchema }]), ConfigModule.forRoot({ isGlobal: true, validationSchema: Joi.object({ MONGODB_URI: Joi.string().required(), PORT: Joi.number().required(), }), envFilePath: './apps/posts/.env', }), ClientsModule.registerAsync([ { name: AUTH_SERVICE, useFactory: (configService: ConfigService) => ({ transport: Transport.TCP, options: { host: configService.get('AUTH_HOST'), port: configService.get('AUTH_PORT'), }, }), inject: [ConfigService], }, ]), ], controllers: [PostsController], providers: [PostsService, PostsRepository], }) export class PostsModule {}
# File: models.py from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Boolean from sqlalchemy.orm import relationship from database import Base class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) username = Column(String, unique=True, index=True) hashed_password = Column(String) blogs = relationship("Blog", back_populates="owner") is_admin = Column(Boolean, default=False) # New field class Blog(Base): __tablename__ = "blogs" id = Column(Integer, primary_key=True, index=True) title = Column(String, index=True) content = Column(String) user_id = Column(Integer, ForeignKey("users.id")) created_at = Column(DateTime) owner = relationship("User", back_populates="blogs")
import * as React from "react"; import Avatar from "@mui/material/Avatar"; import Button from "@mui/material/Button"; import CssBaseline from "@mui/material/CssBaseline"; import TextField from "@mui/material/TextField"; import Box from "@mui/material/Box"; import LockOutlinedIcon from "@mui/icons-material/LockOutlined"; import Typography from "@mui/material/Typography"; import Container from "@mui/material/Container"; import { createTheme, ThemeProvider } from "@mui/material/styles"; import ArrowBackIosNewTwoToneIcon from "@mui/icons-material/ArrowBackIosNewTwoTone"; import Navigation from "../../Navigation/Navigations"; import { useNavigate } from "react-router-dom"; import { useState, useEffect } from "react"; import axios from "axios"; import "./AdminLogin.css"; const theme = createTheme(); export default function AdminLogin() { const navigate = useNavigate(); const [adminData, setAdminData] = useState([]); const [emailId, setEmailId] = useState(""); const [password, setPassword] = useState(""); // const handleSubmit = (event) => { // event.preventDefault(); // const data = new FormData(event.currentTarget); // console.log({ // email: data.get("email"), // password: data.get("password"), // }); // }; const emailChanage = (event) => { setEmailId(event.target.value); }; const passwordChange = (event) => { setPassword(event.target.value); }; const handleSubmit = (e) => { e.preventDefault(); const loginBody = { username: emailId, password: password, }; axios .post("http://localhost:8092/admin-security-login", loginBody) .then((response) => { // console.log(response.data); sessionStorage.setItem("adminLogin", response.data.token); alert("Welcome Admin"); navigate("/admin-news-feed"); }) .catch((error) => { alert("Inavlid credentials."); }); // let found = adminData.find((element) => element.emailId == emailId); // if (found == undefined) { // alert("Invalid Credentials"); // } else { // if (found.emailId == emailId && found.password == password) { // alert("Login Successful"); // localStorage.setItem("admin", JSON.stringify(found)); // navigate("/admin-news-feed"); // } else { // alert("Credentials are not found"); // } // } let found = adminData.find((element) => element.emailId == emailId); localStorage.setItem("admin", JSON.stringify(found)); }; useEffect(() => { axios.get("http://localhost:8086/admins").then((response) => { setAdminData(response.data); }); }, []); return ( <div className="admin-img"> <Navigation /> <ThemeProvider theme={theme}> <Container component="main" maxWidth="xs" className="login-admin"> <CssBaseline /> <Box sx={{ marginTop: 8, display: "flex", flexDirection: "column", alignItems: "center", }} > <Avatar sx={{ m: 1, bgcolor: "secondary.main" }} style={{ backgroundColor: "#AE275F" }} > <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Admin Login </Typography> <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }} > <TextField margin="normal" required fullWidth id="email" label="Email Address" name="email" // autoComplete="email" autoFocus onChange={emailChanage} /> <TextField margin="normal" required fullWidth name="password" label="Password" type="password" id="password" // autoComplete="current-password" onChange={passwordChange} /> <Button type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }} id="btnlogin" style={{ backgroundColor: "#AE275F" }} onClick={handleSubmit} > Sign In </Button> <Button type="submit" halfWidth variant="contained" sx={{ mt: 1, mb: 1 }} id="btnlogin" style={{ backgroundColor: "#AE275F" }} onClick={() => { navigate("/"); }} > <ArrowBackIosNewTwoToneIcon /> Home </Button> </Box> </Box> </Container> </ThemeProvider> <footer className="copyrightfooter"> <p> Copyright &#169; By Axis Batch 9 </p> </footer> </div> ); }
using System.Text; namespace StackOperations; public class Program { static void Main(string[] args) { do { Console.Clear(); Console.WriteLine("Enter a expression to check if it's balanced"); var expression = Console.ReadLine(); if (string.IsNullOrEmpty(expression)) { Console.WriteLine("Expression is null or empty. Please enter a valid expression."); continue; } DisplayResult(expression); Console.WriteLine("Do you want to check another expression? press Y or any other key to exit"); } while (Console.ReadLine().ToUpper() == "Y"); } static void DisplayResult(string expression) { Console.WriteLine($"Cleaning expression: {expression}"); var cleanedExpression = CleanExpression(expression); if (IsExpressionBalanced(cleanedExpression)) { Console.WriteLine($"{expression} is balanced :)"); } else { Console.WriteLine($"{expression} is not balanced :("); } } static string CleanExpression(string expression) { // ++ Boa! Usou uma estrutura de dados sobre a qual não falamos, mas esse um caso de uso perfeito! var validChars = new HashSet<char> { '(', '{', '[', ')', '}', ']' }; var cleanedExpression = new StringBuilder(); foreach(var c in expression) { if(validChars.Contains(c)){ cleanedExpression.Append(c); } } return cleanedExpression.ToString(); } static bool IsExpressionBalanced(string expression) { var stack = new Stack<char>(); HashSet<char> openingChars = new HashSet<char> { '(', '{', '[' }; foreach(var c in expression) { if (openingChars.Contains(c)) { stack.Push(c); } else if(stack.Count == 0 || !PairMatches(stack.Pop(), c)) { return false; } } return stack.Count == 0; } // Por convenção, em dotnet usamos o prefixo `Try...` quando é um método 'inseguro', cujos possíveis erros estão sendo suprimidos // (como é o caso do `int.TryParse("12", out int value)`) e o resultado da operação será devolvido condicionalmente ao sucesso na execução. // O método abaixo não abre a possibilidade de erro e dá uma resposta canônica, e não uma resposta sobre a 'tentativa'. static bool PairMatches(char open, char close) { return (open == '(' && close == ')') || (open == '{' && close == '}') || (open == '[' && close == ']'); } }
<template> <header> <a class="title" href="https://www.baidu.com"> <img src="https://avatars.githubusercontent.com/u/30764933?s=200&v=4" alt="诗词中国🇨🇳" /> <h3>Poetry China</h3> </a> <div class="action"> <div class="item chapter" @click="router.push('poetry')">{{poetryStore.title}}</div> <div class="item dictation"> <i class="iconfont icon-zitiyulan" :class="{active: store.isDictation}" @click="status = !status"> </i> <Transition name="menu-move"> <div class="menu" v-if="status"> <p class="tips">是否开启默写</p> <div class="switch-box"> <Switch v-model:value="store.isDictation" /> <p>默写已{{store.isDictation ? '开启' : '关闭'}}</p> </div> <template v-if="store.isDictation"> <p class="tips">默写模式</p> <div class="selector"> <select> <option :value="0">全部隐藏</option> <option :value="1">显示标点符号</option> </select> </div> </template> </div> </Transition> </div> <div class="item annotate"> <i class="iconfont icon-zhongwenxianshi" :class="{active: store.isAnnotate}" @click="store.handleAnnotateStatus"> </i> </div> <div class="item"> <i class="iconfont icon-youxiyouxiji" @click="router.push('play')"></i> </div> </div> </header> </template> <script setup lang="ts"> import { ref } from 'vue' import { useRouter } from 'vue-router' import { usePoetryStore } from '@/stores/poetry' import { useConfigStore } from '@/stores/config' import Switch from '@/components/swtich/index.vue' const router = useRouter() const store = useConfigStore() const poetryStore = usePoetryStore() const status = ref(false) </script> <style scoped lang="scss"> @import '../../assets/main.scss'; header { display: flex; justify-content: space-between; height: 68px; padding: 20px 30px; .title { display: flex; align-items: center; text-decoration: none; font-size: 32px; img { width: 48px; height: 48px; background-color: #fafafa; margin-right: 12px; } h3 { color: $theme-color; font-weight: 600; } } .action { display: flex; align-items: center; height: 100%; padding: $gap-large; font-size: 18px; box-sizing: border-box; border-radius: $radius-large; background-color: #fff; box-shadow: $shadow-small; .chapter { padding: 6px 12px; margin-right: $gap-middle; } .item { border-radius: $radius-middle; &:hover.chapter, &:hover .iconfont { color: #fff !important; cursor: pointer; background-color: $theme-color-bg-deep; } .iconfont { padding: 2px 4px; margin-left: 6px; color: $text-color; border-radius: $radius-middle; font-size: 22px; &.active { color: $theme-color !important; } } } .dictation { position: relative; .menu { position: absolute; top: 33px; left: 50%; z-index: 88; transform: translateX(-50%); width: 180px; padding: $gap-large; border-radius: $radius-middle; box-sizing: border-box; background-color: #fff; box-shadow: $shadow-large; .tips { font-size: 14px; margin-bottom: $gap-middle; } .switch-box { display: flex; justify-content: space-between; align-items: center; font-size: 12px; margin-bottom: $gap-large; } .selector { select { outline: none; width: 80%; height: 30px; border: none; box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 2.16); } } } } } } .menu-move-enter-active { animation: moveEnter 0.2s; } .menu-move-leave-active { animation: moveLeave 0.2s; } @keyframes moveEnter { 0% { top: 66px; opacity: 0; } 100% { top: 33px; opacity: 1; } } @keyframes moveLeave { 0% { top: 33px; opacity: 1; } 100% { top: 66px; opacity: 0; } } </style>
import { type CurrentDateInterface } from './current-date'; import type { AutoClearableInterval, AutoClearableListeners, AutoClearableListersArgs, AutoClearableStore, AutoClearableTimer, RequireAtLeastOne, } from '../../types'; export type UseTimeHookArgs = Partial<AutoClearableInterval> & Partial<AutoClearableTimer> & Partial<AutoClearableListeners> & Partial<AutoClearableListersArgs> & Partial<AutoClearableStore>; export type UseTimeHookHookListenerArgs = Readonly< Pick<UseTimeHookReturnValue, 'currentDate' | 'ampm' | 'isRunning'> >; export type UseTimeHookListenerCallback = ( args: UseTimeHookHookListenerArgs ) => void; export type UseTimeHookListener = ( callback: UseTimeHookListenerCallback ) => void; export type UseTimeHookReturnValue = { /** * @description * Current date object. * * @example * ```js * console.log(time.currentDate); * ``` */ currentDate: CurrentDateInterface['date']; /** * @description * 'AM' or 'PM' depends on time. * * @example * ```js * console.log(time.ampm); * ``` */ ampm: string; /** * @description * Indicates whether the timer is running or not. * * @example * ```js * console.log(time.isRunning); * ``` */ isRunning: CurrentDateInterface['isRunning']; /** * @description * Start timer. * * @example * ```js * time.start(); * ``` */ start: CurrentDateInterface['start']; /** * @description * Stop timer. * * @example * ```js * time.stop(); * ``` */ stop: CurrentDateInterface['stop']; /** * @description * Listener method that fires on the specified timer event. * * @example * ```js * time.on('update', () => { * console.log('updated!'); * }); * ``` */ on: ( type: Parameters<CurrentDateInterface['on']>[0], listener: UseTimeHookListenerCallback ) => void; }; export type UseTimeHook = ( args?: RequireAtLeastOne<UseTimeHookArgs> ) => Readonly<UseTimeHookReturnValue>;
package common_JDK; import java.util.*; public class Class_5 { public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; } public class main { public void main_1() { java.util.HashMap<String, Double> map = new java.util.HashMap<String, Double>(); ValueComparator bvc = new ValueComparator(map); java.util.TreeMap<String, Double> sorted_map = new java.util.TreeMap<String, Double>(bvc); map.put("A", 99.5); map.put("B", 67.4); map.put("C", 67.4); map.put("D", 67.3); System.out.println("unsorted map: " + map); sorted_map.putAll(map); System.out.println("results: " + sorted_map); } } class ValueComparator implements Comparator<String> { java.util.Map<String, Double> base; public ValueComparator(java.util.Map<String, Double> base) { this.base = base; } public int compare(String a, String b) { if (base.get(a) >= base.get(b)) { return -1; } else { return 1; } } } }
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version } from '@microsoft/sp-core-library'; import { IPropertyPaneConfiguration, PropertyPaneTextField, PropertyPaneCheckbox, PropertyPaneDropdown, IPropertyPaneDropdownOption, PropertyPaneToggle, PropertyPaneLabel, PropertyPaneSlider } from '@microsoft/sp-property-pane'; import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import {SPHttpClient} from '@microsoft/sp-http'; import * as strings from 'MergedCalendarWebPartStrings'; import MergedCalendar from './components/MergedCalendar'; import { IMergedCalendarProps } from './components/IMergedCalendarProps'; export interface IMergedCalendarWebPartProps { description: string; showWeekends: boolean; calSettingsList: string; legendPos: string; legendAlign: string; spCalPageSize: string; spCalParams : {rangeStart: string, rangeEnd: string, pageSize: string}; graphCalParams : {rangeStart: string, rangeEnd: string, pageSize: string}; isListView: boolean; listViewType: string; listViewNavBtns: boolean; listViewLegend: boolean; listViewErrors: boolean; listViewMonthTitle: boolean; listViewViews: boolean; listViewHeight: number; listViewTitle: string; posGrpView: boolean; } export default class MergedCalendarWebPart extends BaseClientSideWebPart<IMergedCalendarWebPartProps> { public render(): void { const element: React.ReactElement<IMergedCalendarProps> = React.createElement( MergedCalendar, { description: this.properties.description, showWeekends: this.properties.showWeekends, context: this.context, calSettingsList: this.properties.calSettingsList, legendPos : this.properties.legendPos, legendAlign: this.properties.legendAlign, dpdOptions : [ { key: 'E1Day', text: '1 Day Cycle' }, // { key: 'E2Day', text: '2 Day Cycle' }, // { key: 'E3Day', text: '3 Day Cycle' }, // { key: 'E4Day', text: '4 Day Cycle' }, { key: 'E5Day', text: '5 Day Cycle' }, // { key: 'E6Day', text: '6 Day Cycle' }, // { key: 'E7Day', text: '7 Day Cycle' }, // { key: 'E8Day', text: '8 Day Cycle' }, // { key: 'E9Day', text: '9 Day Cycle' }, { key: 'E10Day', text: '10 Day Cycle' }, ], spCalParams : this.properties.spCalParams, graphCalParams: this.properties.graphCalParams, spCalPageSize: this.properties.spCalPageSize, isListView: this.properties.isListView, listViewType: this.properties.listViewType, listViewNavBtns: this.properties.listViewNavBtns, listViewLegend: this.properties.listViewLegend, listViewErrors: this.properties.listViewErrors, listViewMonthTitle: this.properties.listViewMonthTitle, listViewViews: this.properties.listViewViews, listViewHeight: this.properties.listViewHeight, listViewTitle: this.properties.listViewTitle, posGrpView: this.properties.posGrpView } ); // spCalParams: {rangeStart: this.properties.spCalParams.rangeStart, rangeEnd: this.properties.spCalParams.rangeEnd, pageSize: this.properties.spCalParams.pageSize}, // graphCalParams: {rangeStart: this.properties.graphCalParams.rangeStart, rangeEnd: this.properties.graphCalParams.rangeEnd, pageSize: this.properties.graphCalParams.pageSize}, ReactDom.render(element, this.domElement); } protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse('1.0'); } // protected get disableReactivePropertyChanges(): boolean { // return true; // } // private validateListName(value: string): string { // if (value === null || value.trim().length === 0) { // return 'Provide a list name'; // } // if (value.length > 40) { // return 'List name should not be longer than 40 characters'; // } // return ''; // } /* Loading Dpd with list names - Start */ private lists: IPropertyPaneDropdownOption[]; private async loadLists(): Promise<IPropertyPaneDropdownOption[]> { let listsTitle : any = []; try { let response = await this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists?$select=Title&$filter=BaseType eq 0 and BaseTemplate eq 100 and Hidden eq false`, SPHttpClient.configurations.v1); if (response.ok) { const results = await response.json(); if(results){ console.log('results', results); results.value.map((result: any)=>{ listsTitle.push({ key: result.Title, text: result.Title }); }); return listsTitle; } } } catch (error) { return error.message; } } protected onPropertyPaneConfigurationStart(): void { if (this.lists) { this.render(); return; } this.context.statusRenderer.displayLoadingIndicator(this.domElement, 'lists'); this.loadLists() .then((listOptions: IPropertyPaneDropdownOption[]): void => { this.lists = listOptions; this.context.propertyPane.refresh(); this.context.statusRenderer.clearLoadingIndicator(this.domElement); this.render(); }); } protected onPropertyPaneFieldChanged(propertyPath: string, oldValue: any, newValue: any): void { if (propertyPath === 'listName' && newValue) { // push new list value super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue); // refresh the item selector control by repainting the property pane this.context.propertyPane.refresh(); // re-render the web part as clearing the loading indicator removes the web part body this.render(); } else { super.onPropertyPaneFieldChanged(propertyPath, oldValue, oldValue); } } /* Loading Dpd with list names - End */ protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: "Settings", groupFields: [ PropertyPaneDropdown('calSettingsList', { label : 'Calendar Settings List', options: this.lists, selectedKey : 'CalendarSettings' }), PropertyPaneCheckbox('showWeekends', { text: "Show Weekends" }), ] }, { groupName: "Legend", groupFields: [ PropertyPaneDropdown('legendPos', { label : 'Position', options: [ {key: 'top', text: 'Top'}, {key: 'bottom', text: 'Bottom'} // {key: 'both', text: 'Both'} ], selectedKey : 'top' }), PropertyPaneDropdown('legendAlign', { label : 'Alignment', options: [ {key: 'horizontal', text: 'Horizontal'}, {key: 'vertical', text: 'Vertical'} ], selectedKey : 'vertical' }), PropertyPaneToggle('posGrpView', { label: 'POS Groups View', onText: 'On', offText: 'Off', checked : false }), ] }, { groupName: 'Events View', groupFields: [ PropertyPaneToggle('isListView', { label: 'List View', onText: 'On', offText: 'Off', checked : false }), PropertyPaneTextField('listViewTitle', { label: 'Title', value: this.properties.listViewTitle, }), PropertyPaneDropdown('listViewType', { label: 'List View Type', disabled: !this.properties.isListView, options: [ {key: 'listDay', text: 'Day List'}, {key: 'listWeek', text: 'Week List'}, {key: 'listMonth', text: 'Month List'} ], selectedKey : this.properties.listViewType }), PropertyPaneLabel('listViewOptions', { text: 'Header & Footer Options', }), PropertyPaneCheckbox('listViewMonthTitle', { text: "Month Name", disabled: !this.properties.isListView, checked: this.properties.listViewMonthTitle }), PropertyPaneCheckbox('listViewNavBtns', { text: "Navigation Buttons (previous, next, today)", disabled: !this.properties.isListView, checked: this.properties.listViewNavBtns }), PropertyPaneCheckbox('listViewLegend', { text: "Legend", disabled: !this.properties.isListView, checked: this.properties.listViewLegend }), PropertyPaneCheckbox('listViewErrors', { text: "Errors", disabled: !this.properties.isListView, checked: this.properties.listViewErrors }), PropertyPaneCheckbox('listViewView', { text: "Views", disabled: !this.properties.isListView, checked: this.properties.listViewViews }), PropertyPaneSlider('listViewHeight', { label: 'Height', min: 200, max: 1000, value: this.properties.listViewHeight, disabled: !this.properties.isListView, step : 10, showValue: true, }) ] }, /* { groupName: "SharePoint Calendars", groupFields: [ /*PropertyPaneDropdown('spCalParams.rangeStart', { label : 'Number of months before today', options: [ {key: '1', text: '1'}, {key: '2', text: '2'}, {key: '3', text: '3'}, {key: '4', text: '4'}, {key: '5', text: '5'}, {key: '6', text: '6'}, ], selectedKey : '3' }), PropertyPaneDropdown('spCalParams.rangeEnd', { label : 'Number of months after today', options: [ {key: '1', text: '1'}, {key: '2', text: '2'}, {key: '3', text: '3'}, {key: '4', text: '4'}, {key: '5', text: '5'}, {key: '6', text: '6'}, {key: '7', text: '7'}, {key: '8', text: '8'}, {key: '9', text: '9'}, {key: '10', text: '10'}, {key: '11', text: '11'}, {key: '12', text: '12'}, ], selectedKey : '6' }), PropertyPaneDropdown('spCalParams.pageSize', { label : 'Number of events', options: [ {key: '500', text: '500'}, {key: '750', text: '750'}, {key: '1250', text: '1250'}, {key: '1500', text: '1500'}, {key: '1750', text: '1750'}, {key: '2250', text: '2250'}, {key: '3000', text: '3000'}, ], selectedKey : '750' }), PropertyPaneDropdown('spCalPageSize', { label : 'Number of events', options: [ {key: '500', text: '500'}, {key: '750', text: '750'}, {key: '1000', text: '1000'}, {key: '1250', text: '1250'}, {key: '1500', text: '1500'}, {key: '1750', text: '1750'}, {key: '2250', text: '2250'}, {key: '3000', text: '3000'}, ], selectedKey : '1000' }), ] }, { groupName: "Graph Calendars", groupFields: [ PropertyPaneDropdown('graphCalParams.rangeStart', { label : 'Number of months before today', options: [ {key: '1', text: '1'}, {key: '2', text: '2'}, {key: '3', text: '3'}, {key: '4', text: '4'}, {key: '5', text: '5'}, {key: '6', text: '6'}, ], selectedKey : '3' }), PropertyPaneDropdown('graphCalParams.rangeEnd', { label : 'Number of months after today', options: [ {key: '1', text: '1'}, {key: '2', text: '2'}, {key: '3', text: '3'}, {key: '4', text: '4'}, {key: '5', text: '5'}, {key: '6', text: '6'}, {key: '7', text: '7'}, {key: '8', text: '8'}, {key: '9', text: '9'}, {key: '10', text: '10'}, {key: '11', text: '11'}, {key: '12', text: '12'}, ], selectedKey : '4' }), PropertyPaneDropdown('graphCalParams.pageSize', { label : 'Number of events', options: [ {key: '50', text: '50'}, {key: '100', text: '100'}, {key: '150', text: '150'}, {key: '200', text: '200'}, {key: '250', text: '250'}, {key: '300', text: '300'}, {key: '350', text: '350'}, ], selectedKey : '100' }), ] } */ ] } ] }; } }
import React, { useState, useContext } from "react"; import { Box, Text, Divider, FormControl, FormLabel, Input, Textarea, Button, FormErrorMessage, InputGroup, InputRightAddon, useToast, List, ListItem, Tag, TagLabel, TagCloseButton } from "@chakra-ui/react"; import { useForm } from "react-hook-form"; import { MyContext } from '../contexts/MyContext'; import axios from "axios"; function OpenTicket() { const { rootState, logoutUser } = useContext(MyContext); const { isAuth, theUser } = rootState; const { handleSubmit, register, formState: { errors }, } = useForm(); const removeFile = (indexToRemove) => { setSelectedFiles((prevFiles) => prevFiles.filter((_, idx) => idx !== indexToRemove)); }; const onSubmit = async (values) => { const formData = new FormData(); // Anexar campos do chamado formData.append('title', values.title); formData.append('description', values.description); // Se houver arquivos selecionados, adicione-os ao formData if (selectedFiles.length) { // Mudando de values.file para selectedFiles selectedFiles.forEach(file => { formData.append('files[]', file); }); } // Anexar informações do usuário formData.append('user_id', theUser.id); formData.append('email', theUser.email); formData.append('department_id', theUser.department_id); formData.append('status', 'aberto'); try { const response = await axios.post(`${import.meta.env.VITE_REACT_APP_URL}/lrv-chamados-api/public/api/chamados`, formData, { headers: { 'Content-Type': 'multipart/form-data', }, }); if (response.data.success) { // Handle success } } catch (error) { // Handle error } }; const [selectedFiles, setSelectedFiles] = useState([]); const handleFileChange = (event) => { const files = event.target.files; if (files.length) { setSelectedFiles(Array.from(files)); // Armazenando os objetos File diretamente } }; return ( <Box w="100%" maxW="500px" borderWidth="1px" borderRadius="lg" p="6" overflow="hidden"> <Text fontSize="2xl">Abertura de chamado</Text> <Divider my="4" /> <form style={{display: 'flex', flexDirection: 'column', gap: "10px"}} onSubmit={handleSubmit(onSubmit)}> <FormControl w="100%" isInvalid={errors.title} mb="4"> <FormLabel htmlFor="title">Título do chamado</FormLabel> <Input id="title" {...register("title", { required: "Este campo é obrigatório", })} /> <FormErrorMessage> {errors.title && errors.title.message} </FormErrorMessage> </FormControl> <FormControl w="100%" isInvalid={errors.description} mb="4"> <FormLabel htmlFor="description">Descrição</FormLabel> <Textarea id="description" {...register("description", { required: "Este campo é obrigatório", })} /> <FormErrorMessage> {errors.description && errors.description.message} </FormErrorMessage> </FormControl> <FormControl w="100%" isInvalid={errors.file} mb="4"> <FormLabel htmlFor="file">Anexar arquivos</FormLabel> <InputGroup> <Input id="file" type="file" multiple // permite múltiplos arquivos {...register("file")} style={{ display: "none" }} onChange={handleFileChange} /> <Input placeholder="Nenhum arquivo escolhido" value={selectedFiles.length ? `${selectedFiles.length} arquivos selecionados` : ""} isReadOnly pr="4.5rem" /> <InputRightAddon> <label htmlFor="file"> <Button as="span" colorScheme="blue" size="sm"> Escolher arquivos </Button> </label> </InputRightAddon> </InputGroup> {selectedFiles.length > 0 && ( <Box mt={2} display="flex" flexWrap="wrap" gap="2"> {selectedFiles.map((file, idx) => ( <Tag key={idx} borderRadius="full" variant="solid" colorScheme="blue" size="md"> <TagLabel>{file.name}</TagLabel> <TagCloseButton onClick={() => removeFile(idx)} /> </Tag> ))} </Box> )} <FormErrorMessage> {errors.file && errors.file.message} </FormErrorMessage> </FormControl> <Button colorScheme="blue" type="submit" mt="4"> Salvar chamado </Button> </form> </Box> ); } export default OpenTicket;
// // NSImage+SatusBar.swift // IGR Software // // Created by Vitalii Parovishnyk on 29.06.2023. // Copyright © 2023 IGR Soft. All rights reserved. // import AppKit extension NSImage { /// Provides an appropriate icon for the status bar based on the triggered status. /// /// This method returns one of two possible icons based on the triggered status: /// - If triggered, it will return an alert icon. /// - Otherwise, it will return a default menu icon. /// /// - Parameter triggered: A Boolean flag indicating if the status bar icon should be in the alert state. Default is `false`. /// /// - Returns: An `NSImage` instance representing the appropriate icon for the status bar. Returns `nil` if the named image resource is not found. static func statusBarIcon(triggered: Bool = false) -> NSImage? { if triggered { NSImage(named: "MenuIconAlert") } else { NSImage(named: "MenuIcon") } } }
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; void showShareAlert(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Partager sur :'), content: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ IconButton( icon: Icon(Icons.facebook), onPressed: () { // Logique de partage sur Facebook }, ), IconButton( onPressed: () { // Logique de partage sur Instagram }, icon: SvgPicture.asset( 'assets/icons/instagram.svg', // Chemin vers le fichier SVG de l'icône Instagram width: 24, height: 24, ), ), IconButton( onPressed: () { // Logique de partage sur Twitter }, icon: SvgPicture.asset( 'assets/icons/twitter.svg', // Chemin vers le fichier SVG de l'icône Twitter width: 24, height: 24, ), ), ], ), ); }, ); } void showCommentAlert(BuildContext context) { TextEditingController commentController = TextEditingController(); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Commenter'), content: TextField( controller: commentController, decoration: InputDecoration( hintText: 'Saisissez votre commentaire', ), ), actions: [ ElevatedButton( onPressed: () { // Récupérer le commentaire et l'envoyer String comment = commentController.text; // Faire quelque chose avec le commentaire (envoi, affichage, etc.) Navigator.pop(context); // Fermer la boîte de dialogue }, child: Text('Envoyer'), ), ], ); }, ); } void showUploadPhotoDialog(BuildContext context) { TextEditingController nameController = TextEditingController(); TextEditingController lastNameController = TextEditingController(); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Télécharger une photo'), content: Column( mainAxisSize: MainAxisSize.min, children: [ Text('Voulez-vous télécharger une photo ?'), SizedBox(height: 16), TextField( controller: nameController, decoration: InputDecoration( labelText: 'Nom', ), ), SizedBox(height: 8), TextField( controller: lastNameController, decoration: InputDecoration( labelText: 'Prénom', ), ), ], ), actions: [ TextButton( onPressed: () { // Logique pour joindre une image avec les noms et prénoms String name = nameController.text; String lastName = lastNameController.text; // Faites quelque chose avec les noms et prénoms... Navigator.pop(context); // Fermer l'alerte }, child: Text('Joindre une image'), ), TextButton( onPressed: () { Navigator.pop(context); // Fermer l'alerte }, child: Text('Annuler'), ), ], ); }, ); }
# Занятие 2 <!-- ### Вопросы по дз Обсуждаем 10 мин общие вопроыс из тг по установке среды, вопросы по туру go. Обсуждаем ### О слайсах и мапах #### Слайсы и память (подсветим некоторые моменты) Слайс - один из объектов который, как правило, помещается в стек. Это происходит если на этапе компилляции неизвестен размер слайса. ``` Пример из slice_example ``` --> Как может утекать память, как работают слайсы. Насколько растет слайс - Undocumented feature. ``` Пример из slice_cut ``` ![утчка](./data/slice.png) #### Кратко про мапы Говорить особо ничего, map - одна из основных структур в программировании. Не знаешь что делать - возьми хешмап. Существует такая вещь как пустая структура, она не занимает памяти в go. Множества в go принято делать через мапу со значениями в виде пустых структур ``` numbers := []int{0,1,2,0,4,6} uniqueNumbers := make(map[string]struct{},len(numbers)) for _,v:=range numbers{ uniqueNumbers[v] = struct{}{} } fmt.Println(len(uniqueNumbers)) // 5 _, okZero := uniqueNumbers[0] fmt.Println(okZero) // true _, okTen := uniqueNumbers[10] fmt.Println(okTen) // false ``` #### Передача по значению Такие типы как map и slice сами по себе маленькие, они лишь указывают на внутреннее хранилище самих данных. В функции их обычно передают не по указателю, даже если требуется внести изменения в элементы. Исключение - функция, которой необходимо изменить размер слайса (почему - упражнение на дом) ### Методы и интерфейсы Для удобства у структуры можно определить методы. Тема из ООП. Методы могут быть на структуру или на поинтер на структуру, в зависимости от этого данные структуры копируются или не копируются. Под капотом ресивер метода по сути передается как первый аргумент метода. ### Что такое ООП Классы Объекты Objects are instances of a class created with specifically defined data. Objects can correspond to real-world objects or an abstract entity. When class is defined initially, the description is the only object that is defined. Методы Аттрибуты Энкапсуляция Абстракция Наследование Полиморфизм -> дак тайпинг Duck typing: If it walks like a duck and it quacks like a duck, then it must be a duck ### Интерфейсы в go Интерфейс описывает любой объект с заданным набором методов. Структуры могут реализовать интерфейс неявно: если есть метод с тем же названием и сигнатурой - он реализует метод интерфейса. Если структура реализует интерфейс с поинтер ресивером, саму структуру нельзя использовать где требуется этот интерфейс, требуется использовать указатель на нее. Интерфейс по сути представляет собой структуру с двумя полями: указатель на тип данных и указатель на данные. Это хорошо описано в a tour of go, не будем сейчас это рассматривать. ### Три аспекта разработки кода Интерфейсы тупят #### Git С git все очень просто. Git это система версионирования которая делает снепшоты файлов в определенный момент. Каждый следующий снепшот не сохраняет все данные, а только разницу с предыдущим. Это называется коммит. Все коммиты распологаются в ветках, у проекта есть одна или несколько основных веток. Будем рассматривать сейчас проект с одной основной веткой master. Когда несколько человек работают над одним проектом, трудно всем сразу вносить изменения в мастера. Поэтому можно отделить свою ветку от основной и вести разработку там. В это время мастер может меняться, но это не затригвает работу в отдельной ветке. В какой-то момент работа в отдельной ветке достигает некоторого логического завершения и ее необходимо слить с основной веткой. Это называется мерж. Большая часть мержа происходит автоматически, но если за время между отделением ветки от мастера и ее слиянием в одном и том же месте произошли изменения и в ветке, и в мастере, происходит мерж конфликт. При мерж конфликте необходимо руками указать финальную версию проблемных файлов и завершить мерж. Это удобно делать в IDE. В Git, как правило, есть удаленный сервер куда пишут все участники проекта, каждый может качать оттуда и писать туда. В общем состояние просто синхронизируется между сервером и клиентом (участником проекта) при определенных командах. Нельзя просто всем писать в мастер - будет хаос. Поэтому мерж делается на стороне сервера обычно через UI через Pull Request. Как правило, существуют политики на PR: должны пройти тесты; определенное количество человек должны сделать ревью кода и поставить аппрув; должен отработать линтер. Часть файлов, лежащих в проекте git, не требуется версионировать - готовые сборки, конфиги IDE и тп. Файлы можно игнорировать через .gitignore В Git главное понимать сценарии работы и что происходит. Как именно это сделать - легко гуглится, лучший источник - stackoverflow. Помимо основных описанных выше сценариев в git много других возможностей: удаление прошлого коммита; создание и переход в новую ветку одной командой; временное сохранение изменений без коммита; перенос части изменений; выкачивание только части репозитория и многое другое. Представьте что вы хотите сделать с git и напишите это в гугле - вы получите ответ как. Примерный процесс работы с git на псевдокоде ``` git config ... - сконфигурировать свою почту и имя git clone ... - скачать репо git checkout -b user/branchname - создать ветку и переключиться на нее ... вносятся изменения в файлы проекта git add ... - выбрать файлы, которые будут добавлены в стейдж (файлы в стейдже будут сохранены в коммит) git commit -m "commit name" - сделать коммит из застейдженных файлов git pull origin master - скачать актуальную версию мастера с сервера и смерджить ее со своей. Тут могут появиться конфликты - их надо разрешить. git push origin HEAD - запушить свою ветку на сервер ... в UI сервера делается PR, при необходимости внести изменния они добавляются также через push и потом PR завершается. ``` https://education.github.com/git-cheat-sheet-education.pdf
<div> <h4 id="subtitle">{{ !productId ? 'Novo' : isView ? 'Visualizar' : 'Editar' }}</h4> <h1>Produto</h1> </div> <mat-card class="loading-container"> <div class="loading" *ngIf="isLoading"> <mat-spinner></mat-spinner> </div> <form [formGroup]="form" (submit)="register()"> <mat-grid-list cols="4" rowHeight="100px" gutterSize="16px"> <mat-grid-tile colspan="1"> <mat-form-field class="full-width form-group" > <mat-label>Nome</mat-label> <input type="text" formControlName="nome" matInput required /> <mat-hint *ngIf="getErrors('nome') !== ''" class="input-errors">{{ getErrors('nome') }}</mat-hint> </mat-form-field> </mat-grid-tile> <mat-grid-tile colspan="1"> <mat-form-field class="full-width form-group" > <mat-label>Valor</mat-label> <span matPrefix>R$ &nbsp;</span> <input type="number" formControlName="valor" matInput required /> <mat-hint *ngIf="getErrors('valor') !== ''" class="input-errors">{{ getErrors('valor', 'valor') }}</mat-hint> </mat-form-field> </mat-grid-tile> <mat-grid-tile colspan="1"> <mat-form-field class="full-width form-group"> <mat-label>Tamanho produto</mat-label> <mat-select formControlName="tamanho" required> <mat-option *ngFor="let tamanho of tamanhosProduto" [value]="tamanho.value"> {{tamanho.label}} </mat-option> </mat-select> <mat-hint *ngIf="getErrors('tamanho') !== ''" class="input-errors">{{ getErrors('tamanho') }}</mat-hint> </mat-form-field> </mat-grid-tile> <mat-grid-tile colspan="1"> <mat-form-field class="full-width form-group" > <mat-label>Quantidade fatias</mat-label> <input type="number" formControlName="qtdFatias" matInput required /> <mat-hint *ngIf="getErrors('qtdFatias') !== ''" class="input-errors">{{ getErrors('qtdFatias', 'quantidade de fatias') }}</mat-hint> </mat-form-field> </mat-grid-tile> </mat-grid-list> <mat-form-field class="full-width form-group" > <mat-label>Descrição</mat-label> <textarea formControlName="descricao" matInput rows="4"></textarea> <mat-hint *ngIf="getErrors('descricao') !== ''" class="input-errors">{{ getErrors('descricao', 'descrição') }}</mat-hint> </mat-form-field> <div class="d-flex justify-end"> <button mat-stroked-button color="primary" type="reset" (click)="goBack()">Voltar</button> <button mat-raised-button color="primary" class="ml-4" type="submit" *ngIf="!isView"> Salvar </button> </div> </form> </mat-card>
<div *ngIf="authenticated"> <mat-toolbar>My Top Rated Trips</mat-toolbar> <mat-grid-list cols='3'> <mat-grid-tile *ngFor="let trip of favoriteTrips"> <mat-card> <mat-card-header> <mat-card-title> <h4>{{trip.data.title}}</h4> </mat-card-title> </mat-card-header> <img mat-card-image src="{{trip.data.imageUrl}}" alt="{{trip.data.title}}"> <mat-card-actions> <button mat-button mat-raised-button class="detailsButton" [routerLink]="['/trip/'+trip.key]"><i class="material-icons">visibility</i>Trip Details</button> <button mat-button mat-raised-button class="editButton" [routerLink]="['/edit-trip/'+trip.key]"><i class="material-icons">mode_edit</i>Edit Trip</button> </mat-card-actions> </mat-card> </mat-grid-tile> </mat-grid-list> <mat-toolbar>Upcoming Trips</mat-toolbar> <mat-grid-list cols='3'> <mat-grid-tile *ngFor="let trip of upcomingTrips"> <mat-card> <mat-card-header> <mat-card-title> <h4>{{trip.data.title}}</h4> </mat-card-title> </mat-card-header> <img mat-card-image src="{{trip.data.imageUrl}}" alt="{{trip.data.title}}"> <mat-card-content> <p></p> </mat-card-content> <mat-card-actions> <button mat-button mat-raised-button [routerLink]="['/trip/'+trip.key]"> Trip Details</button> <button mat-button mat-raised-button [routerLink]="['/edit-trip/'+trip.key]"> Edit Trip</button> </mat-card-actions> </mat-card> </mat-grid-tile> </mat-grid-list> </div> <div *ngIf="!authenticated"> <h1>You are not authenticated!</h1> </div>
import React from 'react'; import '../../css/signup.css'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; import { TextField, Button, Select, MenuItem, OutlinedInput, InputLabel } from '@material-ui/core'; import { country_list } from '../../helpers/variables'; import { ToastContainer, toast } from 'react-toastify'; const Signup = () => { const [signupInfo, setsignupInfo] = React.useState({ name: '', email: '', cellphone: '', country: '', password: '', }); const [password2, setPassword2] = React.useState(''); const [user, setUser] = React.useState([]); const [block, setBlock] = React.useState(true); let navigate = useNavigate(); /* Checking if the user is logged in, if it is, it redirects to the home page. */ React.useEffect(()=>{ const token = localStorage.getItem('token'); if (token) { navigate('/', { replace: true }); } },[]) /** * It saves the signup information in the state. */ const saveSignupInfo = (e) =>{ setsignupInfo({ ...signupInfo,[e.target.name]:e.target.value }) if(signupInfo.name.length !== 0 && signupInfo.email.length !== 0 && signupInfo.cellphone.length !== 0 && signupInfo.country.length !== 0 && signupInfo.password.length !== 0 && password2.length !== 0){ setBlock(false); }else{ setBlock(true); } } /** * If the name, email, cellphone, country, password, and password2 fields are not empty, then the * button is not disabled */ const handleChange = () =>{ if(signupInfo.name.length !== 0 && signupInfo.email.length !== 0 && signupInfo.cellphone.length !== 0 && signupInfo.country.length !== 0 && signupInfo.password.length !== 0 && password2.length !== 0){ setBlock(false); }else{ setBlock(true); } } /** * If the password and password2 fields don't match, display an error message and block the user from * signing up */ const compare = () =>{ if(signupInfo.password !== password2){ toast.error("Passwords don't match"); setBlock(true); }else{ setBlock(false); } } /** * A function that is called when the user clicks the submit button. It sends the information to the * server and if the server accepts the information, it will send back a response. If the response is * successful, it will alert the user that the registration was successful and will redirect the user * to the login page. If the response is not successful, it will alert the user that the registration * was not successful. */ const onSubmit = () =>{ console.log(signupInfo); axios.post('http://localhost:4000/api/client/signup',signupInfo) .then(({data}) =>{ setUser(data); alert('Register sucessfull, now you can Log in'); navigate('/', { replace: true }); window.location.reload(true); }) .catch(({response}) =>{ toast.error(response.data); }); } React.useEffect(()=>{ console.log(password2) },[password2]); return ( <div className="sign"> <ToastContainer autoClose={2000}/> <section class="signup flex-center"> <h1 className='title'>Sign up</h1> <form action="" method="GET" className='inputs'> <figure class="input"> <TextField id="outlined-basic" label="Full Name" variant="outlined" type="text" value={signupInfo.name} onChange={saveSignupInfo} size="small" name='name' className='select'/> </figure> <figure class="input"> <TextField id="outlined-basic" label="Email" variant="outlined" type="text" value={signupInfo.email} onChange={saveSignupInfo} size="small" name='email' className='select'/> </figure> <figure class="input"> <TextField id="outlined-basic" label="Cellphone" variant="outlined" type="text" value={signupInfo.cellphone} onChange={saveSignupInfo} size="small" name='cellphone' className='select'/> </figure> <figure class="input"> <InputLabel id="demo-simple-select-label">Country</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" value={signupInfo.country} label="Country" input={<OutlinedInput label="Name" />} onChange={saveSignupInfo} name='country' className='select' > {country_list.map((obj, index)=>( <MenuItem value={country_list[index]}>{country_list[index]}</MenuItem> ))} </Select> </figure> <figure class="input"> <TextField id="outlined-basic" label="Password" variant="outlined" type="password" value={signupInfo.password} onChange={saveSignupInfo} size="small" name='password' className='select'/> </figure> <figure class="input"> <TextField id="outlined-basic" label="Confirm password" variant="outlined" type="password" value={password2} onChange={(e)=>{setPassword2(e.target.value); handleChange()}} onBlur={compare} size="small" name='password2' className='select'/> </figure> </form> <Button disabled={block} onClick={onSubmit} variant="contained" className='submit' color='primary'>Submit</Button> <div class="readyto flex-center terms"> <p>All rights reserved</p> <p>HotelPosadaReal.com 2022</p> </div> </section> </div> ) } export default Signup;
<?php namespace App\Transformers; use App\Models\Transaction; use League\Fractal\TransformerAbstract; class TransactionTransformer extends TransformerAbstract { /** * A Fractal transformer. * * @return array */ public function transform(Transaction $transaction) { return [ 'identifier'=>(int)$transaction->id, 'quantity'=>(int)$transaction->quantity, 'buyer'=>(int)$transaction->buyer_id, 'product'=>(int)$transaction->product_id, 'creationDate'=>(string)$transaction->created_at, 'lastChange'=>(string)$transaction->updated_at, 'deleteDate'=>isset($transaction->deleted_at)? (string) $transaction->deleted_at:null, 'links'=>[ [ 'rel'=>'self', 'href'=>route('transactions.show',$transaction->id), ], [ 'rel'=>'transaction.categories', 'href'=>route('transactions.categories.index',$transaction->id), ], [ 'rel'=>'transaction.seller', 'href'=>route('transactions.sellers.index',$transaction->id), ], [ 'rel'=>'buyer', 'href'=>route('buyers.show',$transaction->buyer_id), ], [ 'rel'=>'product', 'href'=>route('products.show',$transaction->product_id), ], ] ]; } public static function originalAttribute($index){ $attributes = [ 'identifier'=>'id', 'quantity'=>'quantity', 'buyer'=>'buyer_id', 'product'=>'product_id', 'creationDate'=>'created_at', 'lastChange'=>'updated_at', 'deleteDate'=>'deleted_at' ]; return isset($attributes[$index])? $attributes[$index] :null; } public static function transformedAttribute($index){ $attributes = [ 'id'=>'identifier', 'quantity'=>'quantity', 'buyer_id'=>'buyer', 'product_id'=>'product', 'created_at'=> 'creationDate', 'updated_at'=>'lastChange', 'deleted_at'=>'deleteDate' ]; return isset($attributes[$index])? $attributes[$index] :null; } }
// 현재 물품 const items = { milk: 1, egg: 2, kimchi: 6, }; // 장보기 목록 만들기 const createShoppingList = (currentItems, neededItems) => { const shoppingList = {}; Object.entries(neededItems).forEach(([neededItem, neededItemCount]) => { if (!currentItems[neededItem]) { shoppingList[neededItem] = neededItemCount; } else if (currentItems[neededItem] - neededItemCount < 0) { shoppingList[neededItem] = neededItemCount - currentItems[neededItem]; } }); return shoppingList; }; // 냉장고 확인하기 const checkRefrigerator = () => { return items; }; // 목록에 있는 것 구입하기 const buyItems = (shoppingList) => { Object.entries(shoppingList).forEach(([purchaseItem, purchaseItemCount]) => { if (!items[purchaseItem]) items[purchaseItem] = 0; items[purchaseItem] += purchaseItemCount; delete shoppingList[purchaseItem]; }); }; // 장보기 const shopping = () => { const currentItems = checkRefrigerator(); const neededItems = { milk: 1, cheese: 3, kimchi: 1, }; console.log("------------------------------------------"); console.log(" "); console.log("현재 냉장고에 들어 있는 물품 >", currentItems); console.log("필요한 물품들 >", neededItems); console.log(" "); const shoppingList = createShoppingList(currentItems, neededItems); console.log("------------------------------------------"); console.log(" "); console.log("사야할 물품 목록 >", shoppingList); console.log(" "); console.log("------------------------------------------"); buyItems(shoppingList); console.log(" "); console.log("장보기 완료!"); console.log("냉장고 물품 확인하기 >", checkRefrigerator()); console.log(" "); console.log("------------------------------------------"); }; shopping();