text
stringlengths
184
4.48M
#include <algorithm> #include <iostream> #include <ctime> #include <fstream> #include <sstream> #include "Plant.hpp" #include "Player.hpp" #include "Map.hpp" #include "Game.hpp" #include "Land.hpp" using namespace std; void Game::start(CoinPlant &coinPlant,HornPlant &hornPlant,BombPlant &bombPlant,HealPlant &healPlant) { while (!gameEnd_) { round(); }//while if (winned_) { cout << "Congratulations! You have killed all zombies!" << endl; }//if else if(bombUsed_) { cout << "\n\nYou lose the game since you cannot use that many bomb plants!" << endl; } else { cout<<"\n\nOh no... You have no plant on the map"<<endl; }//else system("pause"); system("cls"); }//Game::start void Game::read_txt(const std::string &fileName,CoinPlant &coinPlant,HornPlant &hornPlant,BombPlant &bombPlant,HealPlant &healPlant) { ifstream File(fileName); char plantType, dollarSign; std::string plantName; int cost, hp; int coinVisits, coinReward; int hornDamage; int healPoints; for (int i = 0; i < 4; ++i) { File >> plantType >> plantName >> dollarSign >> cost >> hp; if (plantType == 'C') { File >> coinVisits >> coinReward; coinPlant.set_properties(plantName, cost, hp, coinVisits, coinReward); } else if (plantType == 'S') { File >> hornDamage; hornPlant.set_properties(plantName, cost, hp, hornDamage); } else if (plantType == 'B') { hornDamage = 100; bombPlant.set_properties(plantName, cost, hp, hp); } else if (plantType == 'H') { File >> healPoints; healPlant.set_properties(plantName, cost, hp, healPoints); } } } void Game::read_game_settings() { string input; numLands_=8; numZombies_=3; cout << "-----------------------------" << endl; cout << "| Plants vs. Zombies |" << endl; cout << "-----------------------------" << endl; cout << "Number of lands on the map (1-10, default: 8)...>"; getline(cin,input); if(!input.empty()) { istringstream iss(input); iss>>numLands_; } cout << "Number of zombies on the map (1-10, default: 3)...>"; getline(cin,input); if(!input.empty()) { istringstream iss(input); iss>>numZombies_; } cout << "Plants vs. Zombies Rule:\n\n"; cout << "How to win:\n"; cout << " (1) All zombies are dead.\n"; cout << " (2) At least one plant is live.\n"; cout << " (3) The number of dead bomb plants cannot exceed the number of zombies.\n\n"; cout << "How to lose:\n"; cout << " All plants are dead.\n"; system("pause"); system("cls"); srand(time(NULL)); player_.earn_money(150); map_ = Map(numLands_,0); for(int i=0;i<numZombies_;++i) { map_.add_zombie(new Zombie(i,rand() % numLands_)); } map_.move_player_to(rand() % numLands_); } void Game::move_player() { int place = map_.get_player_position(); place = (place + (rand() % 6 + 1)) % numLands_; map_.move_player_to(place); if (map_.get_plant_on(place)) { display(); map_.get_plant_on(place)->visit(player_, map_.get_all_zombies(), map_.get_all_plants()); }//if } void Game::move_zombies() { std::vector<Zombie*> allZombies = map_.get_all_zombies(); for (const auto& zombie : allZombies) { //Move zombie to new position int place = zombie->get_position(); place = (place + (rand() % 3 + 1)) % numLands_; map_.move_zombie_to(zombie->get_id(),place); display(); cout<<"Zombie ["<< zombie->get_id() << "] moves to land "<<place<<"."<<endl; Plant *plantWithZombie = map_.get_plant_on(zombie->get_position()); if (plantWithZombie) { // Plant attacks zombie if (plantWithZombie->is_offensive()) { std::cout << plantWithZombie->attack(zombie) << '\n'; if (zombie->get_health() <= 0) { std::cout << "Zombie is killed!" << std::endl; }//if }//if // Zombie attacks plant if (zombie->get_health() > 0 && plantWithZombie->get_health() > 0) { zombie->attack(plantWithZombie); }//if if (plantWithZombie->get_health() <= 0) { std::cout << "Plant " << plantWithZombie->get_type_name() << " is dead!" << std::endl; }//if }//if map_.remove_dead_plants(); system("pause"); } //std::cerr << "asdfasf\n"; //system("pause"); map_.remove_dead_zombies(); } void Game::display() const { system("cls"); map_.display(numZombies_); cout << "------------------------------------------------\n" << "Zombie information:" << endl; std::vector<Zombie*> allZombies = map_.get_all_zombies(); sort(allZombies.begin(), allZombies.end(), [](Zombie *a, Zombie *b) { return a->get_id() < b->get_id(); }); for (const auto& zombie : allZombies) { string zombieStats = zombie->get_stats(); cout << zombieStats << endl; } }//Game::display_zombies_stats void Game::round() { string input; display(); if(player_.get_money() > 0 && map_.get_plant_on(map_.get_player_position()) == nullptr) { cout<<"[0] "<<CoinPlant::get_info()<<endl; cout<<"[1] "<<HornPlant::get_info()<<endl; cout<<"[2] "<<BombPlant::get_info()<<endl; cout<<"[3] "<<HealPlant::get_info()<<endl; cout<<endl; int choice=lastChoice_; cout<<"player $"<<player_.get_money()<<": Enter your choice (4 to give up, default: " << lastChoice_ << ")...>"; getline(cin,input); if(!input.empty()) { istringstream iss(input); iss>>choice; if (choice < 0 || choice > 3) { choice = 4; } lastChoice_ = choice; } int place = map_.get_player_position(); Plant* plantPtr=nullptr; switch (choice) { case 0: plantPtr = new CoinPlant(); map_.add_plant(plantPtr); player_.buy(*plantPtr); cout<<"You have planted "<<CoinPlant::get_name()<<" at land "<<place<<" !"<<endl; break; case 1: plantPtr= new HornPlant(); map_.add_plant(plantPtr); player_.buy(*plantPtr); cout<<"You have planted "<<HornPlant::get_name()<<" at land "<<place<<" !"<<endl; break; case 2: plantPtr= new BombPlant(); map_.add_plant(plantPtr); player_.buy(*plantPtr); cout<<"You have planted "<<BombPlant::get_name()<<" at land "<<place<<" !"<<endl; break; case 3: plantPtr= new HealPlant(); map_.add_plant(plantPtr); player_.buy(*plantPtr); cout<<"You have planted "<<HealPlant::get_name()<<" at land "<<place<<" !"<<endl; break; case 4: cout<<"You give up!"<<endl; break; } system("pause"); } else if (map_.get_plant_on(map_.get_player_position()) == nullptr) { cout<<"You do not have enough money to plant anything!"<<endl; system("pause"); } int numPlants = map_.get_all_plants().size(); int numZombies = map_.get_all_zombies().size(); if(numPlants ==0) { gameEnd_ = true; winned_ = false; bombUsed_ = false; return; }//if else if(numZombies == 0) { gameEnd_ = true; winned_ = true; bombUsed_ = false; return; }//else if // system("pause"); move_zombies(); move_player(); numPlants = map_.get_all_plants().size(); if(numPlants == 0) { gameEnd_=1; winned_ = false; bombUsed_ = false; return; } else if(BombPlant::get_dead_bomb_cnt()>(numZombies_/2)) { gameEnd_ = true; winned_ = false; bombUsed_ = true; return; } // system("pause"); system("cls"); };
import 'package:badges/badges.dart'; import 'package:ff_navigation_bar/ff_navigation_bar.dart'; import 'package:ff_navigation_bar/ff_navigation_bar_item.dart'; import 'package:ff_navigation_bar/ff_navigation_bar_theme.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:pharmaaccess/components/drawer/app_drawer.dart'; import 'package:pharmaaccess/pages/index.dart'; import 'package:pharmaaccess/widgets/bottombar/button.dart'; import 'package:pharmaaccess/widgets/title_widget.dart'; class MainScreen extends StatefulWidget { @override _MainScreenState createState() => _MainScreenState(); } class _MainScreenState extends State<MainScreen> with TickerProviderStateMixin<MainScreen> { int _page = 0; PageController _controller = PageController(initialPage: 0); ScrollController _scrollController = new ScrollController(); bool _isPageViewAnimating = false; int _animateTo = 0; final _scaffoldKey = GlobalKey<ScaffoldState>(); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, endDrawer: AppDrawer(), body: SafeArea( top: false, child: NestedScrollView( controller: _scrollController, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( primary: true, centerTitle: true, title: TitleWidget(), backgroundColor: Colors.white, leading: Padding( padding: const EdgeInsets.all(10.0), child: Badge( showBadge: true, borderRadius: 0, position: BadgePosition.topRight(top: -2, right: 2), badgeColor: Colors.white, badgeContent: Text( '3', style: TextStyle(fontSize: 12), ), child: IconButton( color: Colors.black87, padding: EdgeInsets.all(0), icon: SvgPicture.asset( 'assets/images/icon_notification.svg', color: Colors.black87), tooltip: 'Notifications', onPressed: () {/* ... */}, ), ), ), actions: <Widget>[ IconButton( color: Colors.black87, icon: const Icon(Icons.mic), tooltip: 'Voice', onPressed: () {/* ... */}, ), ], ), ]; }, body: PageView( onPageChanged: (int page) { if (_isPageViewAnimating && page != _animateTo) return; setState(() { _isPageViewAnimating = false; _animateTo = page; _page = page; }); }, controller: _controller, children: <Widget>[ HomePage(), BrandPage(), HomePage(), BrandPage(), ], ), ), ), bottomNavigationBar: FFNavigationBar( theme: FFNavigationBarTheme( barBackgroundColor: Colors.white, selectedItemBorderColor: Colors.yellow, selectedItemBackgroundColor: Colors.green, selectedItemIconColor: Colors.white, selectedItemLabelColor: Colors.black, ), selectedIndex: _page, onSelectTab: (index) { setState(() { _page = index; }); }, items: [ FFNavigationBarItem( iconData: Icons.calendar_today, label: 'Schedule', ), FFNavigationBarItem( iconData: Icons.people, label: 'Contacts', ), FFNavigationBarItem( iconData: Icons.attach_money, label: 'Bills', ), FFNavigationBarItem( iconData: Icons.note, label: 'Notes', ), FFNavigationBarItem( iconData: Icons.settings, label: 'Settings', ), ], ), ); } Widget bottomMenuButtonBuilder(BarButton destination) { switch (destination.title) { case "Search": { return IconButton( splashColor: Colors.white70, color: Colors.white, padding: EdgeInsets.all(0), icon: const Icon(Icons.search), tooltip: 'Search', onPressed: () {}, ); } break; case "More": { return IconButton( splashColor: Colors.white70, color: Colors.white, padding: EdgeInsets.all(0), icon: const Icon(Icons.more_horiz), tooltip: 'Search', onPressed: () { _scaffoldKey.currentState.openEndDrawer(); }, ); } break; case "Club": { return Container( width: 24, height: 24, child: SvgPicture.asset('assets/images/icon_club.svg', color: Colors.white, width: 24), ); } break; case "Brands": { return SizedBox( width: 24, height: 24, child: SvgPicture.asset('assets/images/icon_brand.svg', color: Colors.white, width: 24), ); } break; default: return Icon(destination.icon, color: Colors.white); } } }
import * as THREE from "three"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // Hintergrundfarbe des Renderers auf weiss setzen renderer.setClearColor(0xfefefe); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 1000 ); const orbit = new OrbitControls(camera, renderer.domElement); camera.position.set(0, 8, 14); orbit.update(); const gridHelper = new THREE.GridHelper(10, 10); scene.add(gridHelper); const axesHelper = new THREE.AxesHelper(2); scene.add(axesHelper); // Laden der Daten aus der Datei fetch("data.csv") .then((response) => response.text()) .then((data) => { const lines = data.split("\n").slice(1); // Erste Zeile überspringen (Header) lines.forEach((line) => { const [id, x1, y1, z1, x2, y2, z2] = line.split(",").map(Number); const startPoint = new THREE.Vector3(x1, y1, z1); const endPoint = new THREE.Vector3(x2, y2, z2); const direction = endPoint.clone().sub(startPoint); const arrowHelper = new THREE.ArrowHelper( direction.normalize(), startPoint, direction.length(), 0xffa500 ); scene.add(arrowHelper); }); }) .catch((error) => { console.error("Error loading the file:", error); }); function animate() { requestAnimationFrame(animate); // Aktualisieren der OrbitControls in der Animationsschleife orbit.update(); renderer.render(scene, camera); } // Reagieren auf Größenänderungen des Fensters window.addEventListener("resize", () => { const width = window.innerWidth; const height = window.innerHeight; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); // Aufrufen der resize Methode von OrbitControls orbit.handleResize(); }); animate();
import { useState, useEffect } from 'react' import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd' import { cropLabel } from 'handleLabel' import { ReactComponent as DeleteIcon } from 'assets/svg/delete.svg' import { ReactComponent as RefreshIcon } from 'assets/svg/refresh.svg' import { ReactComponent as CheckmarkIcon } from 'assets/svg/checkmark.svg' import { EventTimeDisplay } from './event-time-display' import { useResponsiveSizes } from 'hooks' import moment from 'moment' const defaultEvents = [ { isDefault: false, isWork: true, type: 'Work', options: [ { taskId: 'qwertyuiop', value: 'Make Presentation' }, { taskId: 'asdfghjkl1', value: 'Work Report' }, { taskId: 'zxcvbnm234', value: 'Email Customers' }, ], selectedOptionTaskId: 'qwertyuiop', startTime: moment('2023-02-22 09:00:00'), endTime: moment('2023-02-22 11:00:00'), }, { isDefault: false, isWork: true, type: 'Work', options: [ { taskId: 'qwertyuiop', value: 'Make Presentation' }, { taskId: 'asdfghjkl1', value: 'Work Report' }, { taskId: 'zxcvbnm234', value: 'Email Customers' }, ], selectedOptionTaskId: 'asdfghjkl1', startTime: moment('2023-02-22 11:00:00'), endTime: moment('2023-02-22 13:00:00'), }, { isDefault: false, isWork: true, type: 'Work', options: [ { taskId: 'qwertyuiop', value: 'Make Presentation' }, { taskId: 'asdfghjkl1', value: 'Work Report' }, { taskId: 'zxcvbnm234', value: 'Email Customers' }, ], selectedOptionTaskId: 'zxcvbnm234', startTime: moment('2023-02-22 13:00:00'), endTime: moment('2023-02-22 15:00:00'), }, ] export const EventsContainer = ({ eventsClosed, setEventsClosed, promptsClosed, }) => { const [events, setEvents] = useState([]) const [eventTypeLength, setEventTypeLength] = useState(24) const [eventTypeWidth, setEventTypeWidth] = useState('50px') const { sizes } = useResponsiveSizes() useEffect(() => { if (sizes.smallPhone) { setEventTypeLength(20) setEventTypeWidth('44px') } else { setEventTypeLength(24) setEventTypeWidth('50px') } }, [sizes]) /* connect events to Firebase */ useEffect(() => { setEvents(defaultEvents) }, []) const onDragEnd = async (result) => { const { destination, source, draggableId } = result if (!destination) { return } if ( destination.droppableId === source.droppableId && destination.index === source.index ) { return } const newEvents = Array.from(events) const [removed] = newEvents.splice(source.index, 1) newEvents.splice(destination.index, 0, removed) setEvents(newEvents) } const getEventContent = (event, index) => { if (sizes.tabLand) { return ( <div className='task__details'> <p className='board-task__name' style={{ paddingBottom: '0.3rem', marginLeft: '10px' }} > {cropLabel(event.type, eventTypeLength)} </p> <div style={{ display: 'inline-block', paddingBottom: '0.3rem', marginLeft: '5px', }} > <EventTimeDisplay isStart={true} time={event.startTime} setEvents={setEvents} eventIndex={index} /> </div> <div style={{ display: 'inline-block', paddingBottom: '0.3rem', }} > <EventTimeDisplay isStart={false} time={event.endTime} setEvents={setEvents} eventIndex={index} /> </div> <div style={{ display: 'inline-block', paddingBottom: '0.3rem', marginLeft: '10px', marginRight: '10px', }} > <select value={event.selectedOptionTaskId} className={'select-preference text-color__none'} onChange={(e) => { const newEvents = [...events] newEvents[index].selectedOptionTaskId = e.target.value setEvents(newEvents) }} > {event.options.map((option) => ( <option value={option.taskId} style={{ color: '#222222' }}> {cropLabel(option.value, 24)} </option> ))} </select> </div> </div> ) } else { return ( <> <p className='board-task__name' style={{ marginLeft: '10px', width: eventTypeWidth, }} > {cropLabel(event.type, eventTypeLength)} </p> <div style={{ display: 'flex', flexGrow: 1 }} /> <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', }} > <div style={{ display: 'inline-block', marginLeft: '10px', }} > <EventTimeDisplay isStart={true} time={event.startTime} setEvents={setEvents} eventIndex={index} /> </div> <div style={{ display: 'inline-block', }} > <EventTimeDisplay isStart={false} time={event.endTime} setEvents={setEvents} eventIndex={index} /> </div> <div style={{ display: 'inline-block', marginLeft: '10px', marginRight: '10px', }} > <select value={event.selectedOptionTaskId} className={'select-preference text-color__none'} onChange={(e) => { const newEvents = [...events] newEvents[index].selectedOptionTaskId = e.target.value setEvents(newEvents) }} > {event.options.map((option) => ( <option value={option.taskId} style={{ color: '#222222' }}> {cropLabel(option.value, eventTypeLength)} </option> ))} </select> </div> </div> <div style={{ display: 'flex', flexGrow: 1 }} /> </> ) } } return ( <div className='events__container'> <div className='events__header-container'> {!(promptsClosed && !eventsClosed) && ( <i class={`arrow-lg ${eventsClosed ? 'up' : 'down'}`} onClick={() => setEventsClosed(!eventsClosed)} /> )} </div> <div className={`events__body-container${ eventsClosed ? '--closed' : promptsClosed ? '--extended' : '' }`} > <div style={{ width: '90%' }}> <DragDropContext onDragEnd={(result) => onDragEnd(result)}> <Droppable droppableId='events'> {(provided) => ( <div ref={provided.innerRef} {...provided.droppableProps}> {events.map((event, index) => ( <Draggable draggableId={index.toString()} index={index}> {(provided) => ( <div className='board-task-schedule' {...provided.dragHandleProps} {...provided.draggableProps} ref={provided.innerRef} > {getEventContent(event, index)} <RefreshIcon style={{ minWidth: '16px', minHeight: '16px', paddingLeft: '3px', paddingRight: '3px', cursor: 'pointer', }} /> <DeleteIcon style={{ minWidth: '16px', minHeight: '16px', paddingLeft: '3px', paddingRight: '3px', marginRight: '3px', cursor: 'pointer', }} onClick={() => { const newEvents = [...events] newEvents.splice(index, 1) setEvents(newEvents) }} /> </div> )} </Draggable> ))} {provided.placeholder} </div> )} </Droppable> </DragDropContext> </div> </div> <div className='events__footer-container'> <button className='action action__add-project' style={{ marginRight: '5px', display: 'flex', alignItems: 'center' }} type='submit' disabled={events.length === 0} > <CheckmarkIcon width='14' height='14' /> <span style={{ marginLeft: '5px' }}>Accept</span> </button> <button className='action action__add-project' style={{ marginLeft: '5px', display: 'flex', alignItems: 'center' }} type='submit' disabled={events.length === 0} > <RefreshIcon width='14' height='14' /> <span style={{ marginLeft: '5px' }}>Refresh</span> </button> </div> </div> ) }
class ActionsController < ApplicationController before_action :require_login! layout false, only: :frame def dispatch_action callback_uuid = Action.find(params[:action_id]).dispatch(params[:uuid]) if callback_uuid.present? redirect_to action_frame_path, notice: { state: "dispatched", callback_uuid: callback_uuid } else redirect_to action_frame_path end end def force_dispatch force_data = {} params.each_key do |key| if key.starts_with? "force_" force_data[key.to_s.sub("force_", "").to_sym] = params[key] end end callback_uuid = Action.find(params[:action_id]).dispatch(params[:uuid], force_data) if callback_uuid.present? redirect_to action_edit_path, notice: { state: "dispatched", callback_uuid: callback_uuid } else redirect_to action_edit_path end end def action_status dispatch = Dispatch.find(params[:callback_uuid]) render json: { success: true, name: dispatch.name, executed: dispatch.executed, error: dispatch.error } end def frame @action = Action.find params[:action_id] @enabled = @action.enabled? params[:uuid] create_dispatch_data render :plugin_frame if @action.plugin? render :dispatched_frame if @action.dispatched? end def toggle action_datum = ActionDatum::find_or_create_by(consumer_id: params[:uuid], action_id: params[:action_id]) return unless action_datum.action.plugin? action_datum.toggle redirect_to action_frame_path end def edit if notice == "reset" @toast_title = "Data reset" @toast_body = "Data for this consumer and action has been reset to default" elsif notice == "save" @toast_title = "Data saved" @toast_body = "Data saved for this consumer and action" end @action_datum = ActionDatum::find_or_create_by consumer_id: params[:uuid], action_id: params[:action_id] @action = @action_datum.action @formatted_json = JSON.pretty_generate(JSON.parse(@action_datum.get_data), indent: " ") return redirect_to consumer_path unless @action.editable create_dispatch_data end def update action_datum = ActionDatum::find_or_create_by consumer_id: params[:uuid], action_id: params[:action_id] success = action_datum.set_data params[:data] redirect_to action_edit_path, notice: success ? "save" : { message: "invalid_json", override_data: params[:data] } end def reset action_datum = ActionDatum::find_or_create_by consumer_id: params[:uuid], action_id: params[:action_id] action_datum.update data: nil redirect_to action_edit_path, notice: "reset" end private def create_dispatch_data @dispatch_data = { turbo_method: :post, controller: "tippy", tippy_placement: "bottom" } @dispatch_button_name = "Dispatch" if (notice.present? && notice["state"] == "dispatched") @dispatch_button_name = "Sent" @dispatch_data[:controller] = "tippy action-status" @dispatch_data[:callback_uuid] = notice["callback_uuid"] end end end
package ru.skillfactory.Ex28.io; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import ru.skillfactory.Ex28.model.Statistics; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class XlsWriter { private static final Logger logger = Logger.getLogger(XlsWriter.class.getName()); private XlsWriter(){} public static void wrtStatisticsXls(List<Statistics> statisticsList, String pathToWrt) throws IOException { logger.log(Level.INFO,"Writing to the " + pathToWrt + " file - started!"); XSSFWorkbook statisticsXxssfWorkbook = new XSSFWorkbook(); XSSFSheet statisticsXssfSheet = statisticsXxssfWorkbook.createSheet("Statistics"); //setting up fonts Font headerFont = statisticsXxssfWorkbook.createFont(); headerFont.setBold(true); headerFont.setFontHeightInPoints((short) 14); CellStyle headerStyle = statisticsXxssfWorkbook.createCellStyle(); headerStyle.setFont(headerFont); // headerStyle.setFillBackgroundColor( ); // end of setting up fonts int rowNum = 0; Row headerRow = statisticsXssfSheet.createRow(rowNum++); Cell profileHeaderCell = headerRow.createCell(0); profileHeaderCell.setCellValue("Study Profile"); profileHeaderCell.setCellStyle(headerStyle); Cell averageSocoreHeaderCell = headerRow.createCell(1); averageSocoreHeaderCell.setCellValue("Average ScoreMark"); averageSocoreHeaderCell.setCellStyle(headerStyle); Cell numberOfStudentsHeaderCell = headerRow.createCell(2); numberOfStudentsHeaderCell.setCellValue("Number of Students"); numberOfStudentsHeaderCell.setCellStyle(headerStyle); Cell numberOfUniverisitiesHeaderCell = headerRow.createCell(3); numberOfUniverisitiesHeaderCell.setCellValue("Number of Universities"); numberOfUniverisitiesHeaderCell.setCellStyle(headerStyle); Cell universityHeaderCell = headerRow.createCell(4); universityHeaderCell.setCellValue("University"); //set header style universityHeaderCell.setCellStyle(headerStyle); for (Statistics statistics:statisticsList) { Row rowData = statisticsXssfSheet.createRow(rowNum++); Cell studyProfileCell = rowData.createCell(0); studyProfileCell.setCellValue(statistics.getStudyProfile().getStudyProfileRus()); Cell avgScoreCell = rowData.createCell(1); avgScoreCell.setCellValue(statistics.getAvgExamScore()); Cell numberOfStudentsCell = rowData.createCell(2); numberOfStudentsCell.setCellValue(statistics.getNumberOfStudents()); Cell numberOfUniversitiesCell = rowData.createCell(3); numberOfUniversitiesCell.setCellValue(statistics.getNameOfUniversity()); Cell universityNameCell = rowData.createCell(4); universityNameCell.setCellValue(statistics.getNameOfUniversity()); } try (FileOutputStream fileOutputStream = new FileOutputStream(pathToWrt)) { statisticsXxssfWorkbook.write(fileOutputStream); } catch(IOException e) { logger.log(Level.SEVERE, "Writing to " + pathToWrt + " file failed ",e); return; }logger.log(Level.INFO,"Write to the " + pathToWrt + " file was successful"); } }
import React from 'react'; import { connect } from 'react-redux'; import ProFile from './ProFile'; import { getUserProfile, updateStatus, getStatus } from './../../../redux/postREDUCER'; import { useLocation, useNavigate, useParams} from "react-router-dom"; // import { withAuthRedirect } from '../../../hoc/withAuthRedirect'; import { compose } from 'redux'; class ProfileContainer extends React.Component { componentDidMount() { let userId = this.props.router.params.userId; if (!userId) { userId = this.props.authorizedUserId; // if(!userId) { // this.props.history.push('/login'); // } } this.props.getUserProfile(userId); this.props.getStatus(userId); } render() { return ( < ProFile {...this.props} profile={this.props.profile} status={this.props.status} updateStatus={this.props.updateStatus} /> ); } } // let AuthRedirectComponent = withAuthRedirect(ProfileContainer); let mapStateToProps = (state) => { return { profile: state.postPAGE.profile, authorizedUserId: state.auth.id, isAuth: state.auth.isAuth, nameFromAPI: state.postPAGE.nameFromAPI, status: state.postPAGE.status }; }; function withRouter(Component) { function ComponentWithRouterProp(props) { let location = useLocation(); let navigate = useNavigate(); let params = useParams(); return (<Component {...props} router={{ location, navigate, params }} /> ); } return ComponentWithRouterProp; } export default compose( connect(mapStateToProps, { getUserProfile, getStatus, updateStatus }), withRouter, // withAuthRedirect )(ProfileContainer)
let user_score = 0; let bot_score = 0; const choices = document.querySelectorAll(".choice"); const message = document.querySelector("#msg"); const userScore = document.querySelector("#user-score"); const botScore = document.querySelector("#bot-score"); const draw = () => { message.innerText = "Game is Draw"; message.style.backgroundColor = "#081b31"; }; const showWinner = (userWin) => { if (userWin) { user_score++; userScore.innerText = user_score; message.innerText = "You win!"; message.style.backgroundColor = "green"; console.log("winner is player"); } else { bot_score++; botScore.innerText = bot_score; message.innerText = "Bot wins!"; message.style.backgroundColor = "red"; } }; const generate_botChoices = () => { const value = ["rock", "paper", "scissor"]; //Generate bot choice randomly const randomNum = Math.floor(Math.random() * 3); return value[randomNum]; }; const game = (userChoice) => { const botChoice = generate_botChoices(); if (userChoice === botChoice) { //draw condition draw(); } else { let userWin = true; if (userChoice === "rock") { //bot choice must be scissors to win game by user userWin = botChoice === "paper" ? false : true; } else if (userChoice === "paper") { //bot choice must be rock so that user can win userWin = botChoice === "scissor" ? false : true; } else { //for user have siccsors condn bot choice must be paper to win userWin = botChoice === "rock" ? true : false; } showWinner(userWin); } }; choices.forEach((choice) => { choice.addEventListener("click", () => { const userChoice = choice.getAttribute("id"); game(userChoice); }); });
<template> <div v-if="showSponsors" :key="showSponsors"> <div class="px-4 sm:px-6 lg:px-8"> <div class="sm:flex sm:items-center"> <div class="sm:flex-auto"> <h1 class="text-xl font-semibold text-gray-900">Sponsoren</h1> <p class="mt-2 text-sm text-gray-700"> Liste aller Sponsoren </p> </div> <div class="mt-4 sm:mt-0 sm:ml-16 sm:flex-none"> <button type="button" class="inline-flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 sm:w-auto" @click=" newSponsor = true;editSponsor = false;showSponsors = false; "> Neuer Sponsor </button> </div> </div> <div class="mt-8 flex flex-col"> <div class="-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div class="inline-block min-w-full py-2 align-middle"> <div class="overflow-hidden shadow-sm ring-1 ring-black ring-opacity-5"> <table class="min-w-full divide-y divide-gray-300"> <thead class="bg-gray-50"> <tr> <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 lg:pl-8"> Logo </th> <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 lg:pl-8"> Name </th> <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 lg:pl-8"> Link </th> <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 lg:pl-8"> Active </th> </tr> </thead> <tbody class="divide-y divide-gray-200 bg-white"> <tr v-for="sponsor in sponsors" :key="sponsor.id"> <td class="w-32 whitespace-nowrap px-3 py-4 text-sm text-gray-500 text-center"> <div class="flex flex-col items-center"> <img :src='"/storage/" + sponsor.image' class="max-h-8" /> </div> </td> <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500 text-center"> {{ sponsor.name }} </td> <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500 text-left"> <a :href="sponsor.link" target="_blank">{{ sponsor.link }}</a> </td> <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500"> <span v-if="sponsor.active == 1" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"> Aktiv </span> <span v-if="sponsor.active == 0" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"> Inaktiv </span> </td> <td class="flex flex-col relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6 lg:pr-8"> <a href="#" class="text-indigo-600 hover:text-indigo-900" @click="setEditID(sponsor.id)">Bearbeiten<span class="sr-only">, {{ sponsor.name }}</span></a> <a href="#" class="text-red-600 hover:text-red-900" @click="openDeleteModal(sponsor.id)">Löschen<span class="sr-only">, {{ sponsor.name }}</span></a> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div v-if="newSponsor" :key="newSponsor"> <button type="button" class="inline-flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 sm:w-auto" @click="newSponsor = false;editSponsor=false;showSponsors=true"> Zurück </button> <NewSponsorForm @close_create="closeCreate"></NewSponsorForm> </div> <div v-if="editSponsor" :key="editSponsor"> <button type="button" class="inline-flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 sm:w-auto" @click="newSponsor = false;editSponsor=false;showSponsors=true"> Zurück </button> <EditSponsorForm @close_edit="closeEdit" :sponsor_id="editSponsorId"></EditSponsorForm> </div> <DeleteSponsorModal :show="deleteModal" @close="deleteModal=false;toDeleteId=-1;" @deleted="deleteModal=false;toDeleteId=-1;getSponsors()" :sponsor_id="toDeleteId"></DeleteSponsorModal> </template> <script> import NewSponsorForm from '../Sponsors/NewSponsorForm.vue'; import EditEventForm from '../Events/EditEventForm.vue'; import DeleteSponsorModal from '../Sponsors/DeleteSponsorModal.vue'; export default { data() { return { editSponsorId: null, newSponsor: false, editSponsor: false, showSponsors: true, toDeleteId: -1, deleteModal: false, sponsors: [], }; }, created() { this.getSponsors(); }, methods: { getSponsors() { let vm = this; axios.get("/admin/api/sponsors") .then(response => { vm.sponsors = response.data; }). catch(error => { console.log(error); }); }, closeCreate() { this.newSponsor = false; this.showSponsors = true; this.getSponsors(); }, closeEdit() { this.editSponsor = false; this.showSponsors = true; this.getSponsors(); }, setEditID(id) { this.editSponsorId = id; this.editSponsor = true; this.showSponsors = false; }, openDeleteModal(id) { this.toDeleteId = id; this.deleteModal=true; }, }, components: { NewSponsorForm, EditEventForm, DeleteSponsorModal } } </script>
module Lib.MatrixParser where import Prelude (pure, show, ($), (<$>), (<<<)) import Network.HTTP.Affjax as Affjax import Control.Monad.Aff.Class (class MonadAff) import Data.Traversable as TRV import Data.Maybe (Maybe(..)) import Data.Argonaut.Core as Arg import Data.Either (Either(..)) import Network.RemoteData as RD import Control.Monad.Eff.Exception as E import Data.Int as Int import Data.Array import Data.Tuple.Nested as TupleN import Data.StrMap as SM import Lib.MiscFFI import Lib.Types as T toPackageIdxTsReports :: forall e m. MonadAff (ajax :: Affjax.AJAX | e) m => Either String Arg.Json -> m (RD.RemoteData E.Error T.PackageIdxTsReports) toPackageIdxTsReports (Right a) = case Arg.toObject a of Just obj -> let pkgName = case SM.lookup "pkgname" obj of Just pkgN -> case Arg.toString pkgN of Just pn -> pn Nothing -> "package is not String" Nothing -> "package name does not exist" idxState = case SM.lookup "idxstate" obj of Just idx -> case Arg.toNumber idx of Just idxts -> Int.round idxts Nothing -> 0 Nothing -> 0 hcVersions = case SM.lookup "hcversions" obj of Just arr -> case Arg.toArray arr of Just arrHc -> toString <$> arrHc Nothing -> [] Nothing -> [] pkgVersions = case SM.lookup "pkgversions" obj of Just pkgObj -> case Arg.toObject pkgObj of Just ob -> toCellReportSummary <$> ob Nothing -> SM.empty Nothing -> SM.empty in pure $ RD.Success { pkgname : pkgName , idxstate : idxState , hcversions : hcVersions , pkgversions : pkgVersions } Nothing -> pure (RD.Failure (E.error "Json is not an object")) toPackageIdxTsReports (Left e) = pure (RD.Failure (E.error e)) toCellReportSummary :: Arg.Json -> Array T.CellReportSummary toCellReportSummary json = case Arg.toArray json of Just arr -> cellReport <$> arr Nothing -> [] cellReport :: Arg.Json -> T.CellReportSummary cellReport jobj= case Arg.toObject jobj of Just obj -> let reporttype = case SM.lookup "t" obj of Just typeR -> case Arg.toString typeR of Just tr -> tr Nothing -> "type is not String" Nothing -> "type does not exist" bjle = case SM.lookup "bjle" obj of Just buildJle -> case Arg.toNumber buildJle of Just bj -> Int.round bj Nothing -> 0 Nothing -> 0 perr = case SM.lookup "perr" obj of Just planErr -> case Arg.toBoolean planErr of Just a -> true Nothing -> false Nothing -> false bok = case SM.lookup "bok" obj of Just buildOk -> case Arg.toNumber buildOk of Just bo -> Int.round bo Nothing -> 0 Nothing -> 0 bfail = case SM.lookup "bfail" obj of Just buildFail -> case Arg.toNumber buildFail of Just bf -> Int.round bf Nothing -> 0 Nothing -> 0 bdfail = case SM.lookup "bdfail" obj of Just buildDFail -> case Arg.toNumber buildDFail of Just bd -> Int.round bd Nothing -> 0 Nothing -> 0 in { crsT : reporttype , crsBjle : bjle , crsPerr : perr , crsBok : bok , crsBfail : bfail , crsBdfail : bdfail } Nothing -> { crsT : "na" , crsBjle : 0 , crsPerr : false , crsBok : 0 , crsBfail : 0 , crsBdfail : 0 } toCellReportDetail :: forall e m. MonadAff (ajax :: Affjax.AJAX | e) m => Either String Arg.Json -> m (RD.RemoteData E.Error T.CellReportDetail) toCellReportDetail (Right a) = case Arg.toObject a of Just obj -> let pkgName = case SM.lookup "pkgname" obj of Just pkgN -> case Arg.toString pkgN of Just pn -> pn Nothing -> "package is not String" Nothing -> "package name does not exist" pkgVersion = case SM.lookup "pkgversion" obj of Just pkgver -> case Arg.toString pkgver of Just pv -> pv Nothing -> "package is not String" Nothing -> "package name does not exist" idxState = case SM.lookup "idxstate" obj of Just idx -> case Arg.toNumber idx of Just idxts -> Int.round idxts Nothing -> 0 Nothing -> 0 hcVersion = case SM.lookup "hcversion" obj of Just hcver -> case Arg.toString hcver of Just hc -> hc Nothing -> "hcversion is not String" Nothing -> "hcversion does not exist" reportType = case SM.lookup "type" obj of Just reportT -> case Arg.toString reportT of Just rt -> rt Nothing -> "report type is not String" Nothing -> "report type does not exist" solverError = case SM.lookup "solver_err" obj of Just solverE -> case Arg.toString solverE of Just se -> se Nothing -> "solver is not String" Nothing -> "na" unitsHistory = case SM.lookup "units" obj of Just unitsH -> case Arg.toArray unitsH of Just units -> toArrayMap <$> units Nothing -> [] Nothing -> [] in pure $ RD.Success { pkgname : pkgName , pkgversion : pkgVersion , idxstate : idxState , hcversion : hcVersion , reporttype : reportType , solverE : solverError , units : unitsHistory } Nothing -> pure (RD.Failure (E.error "Json is not an object")) toCellReportDetail (Left e) = pure (RD.Failure (E.error e)) toPackageHistories :: forall e m. MonadAff (ajax :: Affjax.AJAX | e) m => Either String Arg.Json -> m (RD.RemoteData E.Error T.PackageHistories) toPackageHistories (Right a) = case Arg.toArray a of Just arr -> pure (RD.Success (toTuple4 <$> arr)) Nothing -> pure (RD.Failure (E.error "json is not array")) toPackageHistories (Left e) = pure (RD.Failure (E.error e)) toTuple4 :: Arg.Json -> T.PackageHistory toTuple4 json = case Arg.toArray json of Just arr -> let pkgIdx = case index arr 0 of Just idx -> case Arg.toNumber idx of Just pi -> Int.round pi Nothing -> 0 Nothing -> 0 verName = case index arr 1 of Just vname -> case Arg.toString vname of Just a -> a Nothing -> "na" Nothing -> "na" revision = case index arr 2 of Just rev -> case Arg.toNumber rev of Just r -> Int.round r Nothing -> 0 Nothing -> 0 userName = case index arr 3 of Just uname -> case Arg.toString uname of Just a -> a Nothing -> "na" Nothing -> "na" in TupleN.tuple4 pkgIdx verName revision userName Nothing -> TupleN.tuple4 0 "na" 0 "na" toUnitIdInfo :: forall e m. MonadAff (ajax :: Affjax.AJAX | e) m => Either String Arg.Json -> m (RD.RemoteData E.Error T.UnitIdInfo) toUnitIdInfo (Right a) = case Arg.toObject a of Just obj -> let unitId = case SM.lookup "id" obj of Just uid -> case Arg.toString uid of Just ui -> ui Nothing -> "unit id is not String" Nothing -> "unit id does not exist" hcVersion = case SM.lookup "hcver" obj of Just hcver -> case Arg.toString hcver of Just hc -> hc Nothing -> "hcversion is not String" Nothing -> "hcversion does not exist" pkgName = case SM.lookup "pkgname" obj of Just pkgN -> case Arg.toString pkgN of Just pn -> pn Nothing -> "package is not String" Nothing -> "package name does not exist" pkgVersion = case SM.lookup "pkgver" obj of Just pkgVer -> case Arg.toString pkgVer of Just pv -> pv Nothing -> "package is not String" Nothing -> "package name does not exist" status = case SM.lookup "status" obj of Just stat -> case Arg.toString stat of Just st -> st Nothing -> "status is not String" Nothing -> "status name does not exist" logMsg = case SM.lookup "logmsg" obj of Just logm -> case Arg.toString logm of Just lm -> lm Nothing -> "log message is not String" Nothing -> "log message name does not exist" libDeps = case SM.lookup "lib_deps" obj of Just libD -> case Arg.toObject libD of Just ld -> toArrayString <$> ld Nothing -> SM.empty Nothing -> SM.empty exeDeps = case SM.lookup "exe_deps" obj of Just exeD -> case Arg.toObject exeD of Just ed -> toArrayString <$> ed Nothing -> SM.empty Nothing -> SM.empty in pure $ RD.Success { uiiId : unitId , uiiHcVer : hcVersion , uiiPkgname : pkgName , uiiPkgver : pkgVersion , uiiStatus : status , uiiLogmsg : logMsg , uiiLibDeps : libDeps , uiiExeDeps : exeDeps } Nothing -> pure (RD.Failure (E.error "Json is not object")) toUnitIdInfo (Left e) = pure (RD.Failure (E.error e)) toUnitIdInfoDeps :: forall e m. MonadAff (ajax :: Affjax.AJAX | e) m => Either String Arg.Json -> m (RD.RemoteData E.Error T.UnitIdInfoDeps) toUnitIdInfoDeps (Right a) = case Arg.toObject a of Just obj -> pure (RD.Success (toUnitIdInfoDep <$> obj)) Nothing -> pure (RD.Failure (E.error "Json is not object")) toUnitIdInfoDeps (Left e) = pure (RD.Failure (E.error e)) toUnitIdInfoDep :: Arg.Json -> T.UnitIdInfoDep toUnitIdInfoDep a = case Arg.toObject a of Just obj -> let pkgName = case SM.lookup "pkgname" obj of Just pkgN -> case Arg.toString pkgN of Just pn -> pn Nothing -> "package is not String" Nothing -> "package name does not exist" pkgVersion = case SM.lookup "pkgver" obj of Just pkgVer -> case Arg.toString pkgVer of Just pv -> pv Nothing -> "package is not String" Nothing -> "package name does not exist" status = case SM.lookup "status" obj of Just stat -> case Arg.toString stat of Just st -> st Nothing -> "status is not String" Nothing -> "status name does not exist" libDeps = case SM.lookup "lib_deps" obj of Just libD -> case Arg.toObject libD of Just ld -> toArrayString <$> ld Nothing -> SM.empty Nothing -> SM.empty exeDeps = case SM.lookup "exe_deps" obj of Just exeD -> case Arg.toObject exeD of Just ed -> toArrayString <$> ed Nothing -> SM.empty Nothing -> SM.empty in { pkgname : pkgName , pkgver : pkgVersion , status : status , lib_deps : libDeps , exe_deps : exeDeps } Nothing -> T.unitIdInfoDepEmpty toUser :: forall e m. MonadAff (ajax :: Affjax.AJAX | e) m => Either String Arg.Json -> m (RD.RemoteData E.Error T.User) toUser (Right json) = case Arg.toObject json of Just obj -> let usrName = case SM.lookup "name" obj of Just pkgN -> case Arg.toString pkgN of Just pn -> pn Nothing -> "user is not String" Nothing -> "user name does not exist" usrPackages = case SM.lookup "packages" obj of Just pkgVer -> case Arg.toArray pkgVer of Just pv -> toString <$> pv Nothing -> [] Nothing -> [] in pure $ RD.Success { name : usrName, packages : usrPackages} Nothing -> pure $ RD.Failure (E.error "failed to parse User") toUser (Left e) = pure $ RD.Failure (E.error "failed to parse User") toString :: Arg.Json -> String toString json = case Arg.toString json of Just arr -> arr Nothing -> "na" toArrayString :: Arg.Json -> Array String toArrayString json = case Arg.toArray json of Just arr -> toString <$> arr Nothing -> [] toArrayMap :: Arg.Json -> SM.StrMap String toArrayMap json = case Arg.toObject json of Just obj -> toString <$> obj Nothing -> SM.empty toPackageQueue :: forall e m. MonadAff (ajax :: Affjax.AJAX | e) m => Either String Arg.Json -> m (RD.RemoteData E.Error (Array T.PackageQueue)) toPackageQueue (Right a) = case Arg.toArray a of Just arr -> pure (RD.Success (toObjectQueue <$> arr)) Nothing -> pure (RD.Failure (E.error "Json is not Array")) toPackageQueue (Left e) = pure (RD.Failure (E.error e)) toSpecificPackageQueue :: forall e m. MonadAff (ajax :: Affjax.AJAX | e) m => Either String Arg.Json -> m (RD.RemoteData E.Error T.PackageQueue) toSpecificPackageQueue (Right a) = pure (RD.Success (toObjectQueue a)) toSpecificPackageQueue (Left e) = pure (RD.Failure (E.error e)) toObjectQueue :: Arg.Json -> T.PackageQueue toObjectQueue json = case Arg.toObject json of Just obj -> let prio = case SM.lookup "priority" obj of Just pr -> case Arg.toNumber pr of Just p -> Int.round p Nothing -> 0 Nothing -> 0 mod = case SM.lookup "modified" obj of Just pkgName -> case Arg.toString pkgName of Just pkgName' -> pkgName' Nothing -> "package is not String" Nothing -> "package name does not exist" pkg = case SM.lookup "pkgname" obj of Just pkgName -> case Arg.toString pkgName of Just pkgName' -> pkgName' Nothing -> "package is not String" Nothing -> "package name does not exist" idx = case SM.lookup "idxstate" obj of Just idx -> case Arg.toNumber idx of Just idxts -> Int.round idxts Nothing -> 0 Nothing -> 0 in { priority : prio , modified : mod , pkgname : pkg , idxstate : idx } Nothing -> { priority : 0 , modified : "" , pkgname : "" , idxstate : 0 }
<script setup lang="ts"> import { getCategoryTicketCount, getSortedCategories } from '..'; import { getCategoryTicketsRoute } from 'domains/tickets'; import { categoryStore } from '..'; import Category from '../types'; import { PropType } from 'vue'; import Ticket from '../../tickets/types'; const props = defineProps({ categories: { type: Array as PropType<Category[]> } }); const deleteCategory = async (categoryId: number) => { await categoryStore.actions.delete(categoryId); }; const categories = categoryStore.actions.getAll(); </script> <template> <div class="header-wrapper"> <h2>All categories</h2> <router-link style="color: white;" :to="{name: 'categories.create'}" > Create a new category </router-link> </div> <div class="category-list"> <div v-for="category in getSortedCategories()" :key="category.id" class="category-item"> <router-link :to="getCategoryTicketsRoute(category.id)" class="category-link"> <div style="display: flex; justify-content: space-between;"> <div class="category-title">{{ category.title }}</div> <router-link :to="{name: 'categories.edit', params: {id: category.id}}"> edit </router-link> <button @click="deleteCategory(category.id)" class="delete-button"> delete </button> </div> <div class="category-ticket-count">{{ getCategoryTicketCount(category) }} Tickets</div> </router-link> </div> </div> </template> <style scoped> @import 'style/categories-overview.css'; </style>
import { readFileSync, readdirSync, existsSync, unlinkSync, writeFileSync, } from "fs"; export const getFileNames = (dir: string) => { return readdirSync(dir, "utf-8"); }; export const readTableOrTables = async <Src extends string | string[]>( src: Src ): Promise<Src extends string ? string[][] : string[][][]> => { if ( typeof src === "string" && src[src.length - 1] !== "/" && src[src.length - 1] !== "\\" ) { const file = readFileSync(src as string, { encoding: "utf-8" }); return parseCsv(file) as any; } else if ( typeof src === "string" && (src[src.length - 1] === "/" || src[src.length - 1] === "\\") ) { const fileNames = await getFileNames(src as string); const files: string[] = []; for (const name of fileNames) { const file = readFileSync(src + name, { encoding: "utf-8", }); if (file) { files.push(file); } else { console.log("empty file: " + name); } } return files.map((csv) => parseCsv(csv)) as any; } else if (Array.isArray(src)) { const files: string[] = []; for (const name of src) { const file = readFileSync(name, { encoding: "utf-8" }); if (file) { files.push(file); } else { console.log("empty file: " + name); } } return files.map((csv) => parseCsv(csv)) as any; } throw new Error("unknown src " + src); }; export const writeCsv = async (rows: string[][], path: string) => { if (existsSync(path)) { unlinkSync(path); } const fileContent = rows.map((row) => row.join(",") + "\n").join(""); console.log("writing: " + path); writeFileSync(path, fileContent, { encoding: "utf-8" }); }; export const parseCsv = (csv: string) => { if (!csv) return; const rows: string[][] = []; for (const line of csv.split("\n")) { if (!line.includes(",")) { if (!rows.length) { // omit headers continue; } // omit footers break; } let col = ""; let isEscaping = false; const row: string[] = []; const appendSb = () => { row.push( col .replace(/\s+/g, " ") .replace(/"([^"]*)"/g, (_, s) => `"${s.trim()}"`) .trim() .toLowerCase() ); col = ""; isEscaping = false; }; for (let i = 0; i < line.length; i++) { const char = line[i]; if (char === "," && !isEscaping) { appendSb(); continue; } if (char === '"') { isEscaping = !isEscaping; } col += char; if (i === line.length - 1) { appendSb(); } } rows.push(row); } // delete columns without data if (rows.length > 1) { const includedCols = Array(rows[0].length).fill(false); for (let i = 0; i < rows[0].length; i++) { for (let j = 1; j < rows.length; j++) { if (rows[j][i]) { includedCols[i] = true; break; } } } return rows.map((r) => r.filter((c, i) => includedCols[i])); } };
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:mangerpanel/consts/constants.dart'; import 'package:mangerpanel/inner_screens/add_prod.dart'; import 'package:mangerpanel/inner_screens/all_products.dart'; import 'package:mangerpanel/responsive.dart'; import 'package:mangerpanel/services/global_method.dart'; import 'package:mangerpanel/services/utils.dart'; import 'package:mangerpanel/widgets/buttons.dart'; import 'package:mangerpanel/widgets/header.dart'; import 'package:mangerpanel/widgets/products_widget.dart'; import 'package:mangerpanel/widgets/text_widget.dart'; import 'package:provider/provider.dart'; import '../controllers/MenuController.dart'; import '../widgets/grid_products.dart'; import '../widgets/orders_list.dart'; import '../widgets/orders_widget.dart'; class DashboardScreen extends StatelessWidget { const DashboardScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { Size size = Utils(context).getScreenSize; Color color = Utils(context).color; return SafeArea( child: SingleChildScrollView( controller: ScrollController(), padding: const EdgeInsets.all(defaultPadding), child: Column( children: [ Header( fct: () { context.read<MenuController>().controlDashboarkMenu(); }, title: 'Dashboard', ), const SizedBox( height: 20, ), TextWidget( text: 'Latest Products', color: color, ), const SizedBox( height: 15, ), Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ ButtonsWidget( onPressed: () { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const AllProductsScreen())); }, text: 'View All', icon: Icons.store, backgroundColor: Colors.blue), const Spacer(), ButtonsWidget( onPressed: () { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const UploadProductForm(), ), ); }, text: 'Add product', icon: Icons.add, backgroundColor: Colors.blue), ], ), ), const SizedBox( height: 15, ), const SizedBox(height: defaultPadding), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( // flex: 5, child: Column( children: [ Responsive( mobile: ProductGridWidget( crossAxisCount: size.width < 650 ? 2 : 4, childAspectRatio: size.width < 650 && size.width > 350 ? 1.1 : 0.8, ), desktop: ProductGridWidget( childAspectRatio: size.width < 1400 ? 0.8 : 1.05, ), ), OrdersList(), ], ), ), ], ) ], ), ), ); } }
/* Given a 0-indexed string s, permute s to get a new string t such that: All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i]. The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j]. Return the resulting string. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels. Example 1: Input: s = "lEetcOde" Output: "lEOtcede" Explanation: 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places. Example 2: Input: s = "lYmpH" Output: "lYmpH" Explanation: There are no vowels in s (all characters in s are consonants), so we return "lYmpH". Constraints: - 1 <= s.length <= 105 - s consists only of letters of the English alphabet in uppercase and lowercase. */ #include <string> #include <map> #include <vector> class Solution { public: std::string sortVowels(std::string s) { std::map<char, int> vowel_map{ {'a', 0}, {'e', 0}, {'i', 0}, {'o', 0}, {'u', 0}, {'A', 0}, {'E', 0}, {'I', 0}, {'O', 0}, {'U', 0}, }; std::vector<int> iterators; for (int i = 0; i < s.size(); ++i) { if (vowel_map.contains(s[i])) { vowel_map[s[i]] += 1; iterators.push_back(i); } } int itr{}; for (auto [key, value] : vowel_map) { while (value > 0) { s[iterators[itr]] = key; --value; ++itr; } } return s; } };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create New</title> <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3' crossorigin='anonymous'> <link rel='stylesheet' type='text/css' href="{{ url_for('static', filename='style.css') }}"> </head> <body> <!-- PAGE CONTAINER --> <div class="container d-flex justify-content-between"> <!-- REGISTRATION FORM --> <div class="container" id="register"> <h1>Register</h1> <form action="/users/create" method="POST"> <!-- FIRST NAME AND VALIDATION --> <div class="form-group mb-4"> <label for="">First Name:</label> <input name="first_name" type="text" class="form-control"> {% with messages = get_flashed_messages(category_filter="first_name") %} {% if messages %} <div class="form-group alert alert-warning" role="alert"> <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} {% endwith %} </div> <!-- LAST NAME AND VALIDATION --> <div class="form-group mb-4"> <label for="">Last Name:</label> <input name="last_name" type="text" class="form-control"> {% with messages = get_flashed_messages(category_filter="last_name") %} {% if messages %} <div class="form-group alert alert-warning" role="alert"> <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} {% endwith %} </div> <!-- EMAIL AND VALIDATION --> <div class="form-group mb-4"> <label for="">Email:</label> <input name="email" type="email" class="form-control" placeholder="name@example.com"> {% with messages = get_flashed_messages(category_filter="email") %} {% if messages %} <div class="form-group alert alert-warning" role="alert"> <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} {% endwith %} </div> <!-- PASSWORD AND VALIDATION --> <div class="form-group mb-4"> <label for="">Password:</label> <input name="password" type="password" class="form-control"> <small>Must be 8 characters with at least 1 letter, 1 number, and 1 special character (!@#$%^&_-*?)</small> {% with messages = get_flashed_messages(category_filter="password") %} {% if messages %} <div class="form-group alert alert-warning" role="alert"> <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} {% endwith %} </div> <!-- CONFIRM PASSWORD AND VALIDATION --> <div class="form-group mb-4"> <label for="">Confirm Password:</label> <input name="confirm_password" type="password" class="form-control"> {% with messages = get_flashed_messages(category_filter="confirm") %} {% if messages %} <div class="form-group alert alert-warning" role="alert"> <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} {% endwith %} </div> <button type="submit" class="btn btn-primary">Register</button> </form> </div> <!-- LOGIN FORM --> <div class="container" id="login"> <h1>Login</h1> <form action="/users/login" method="POST"> <div class="form-group mb-4"> <label for="">Email:</label> <input name="email" type="email" class="form-control"> </div> <div class="form-group mb-4"> <label for="">Password:</label> <input name="password" type="password" class="form-control"> {% with messages = get_flashed_messages(category_filter="login") %} <!-- LOGIN VALIDATION --> {% if messages %} <div class="form-group alert alert-warning" role="alert"> <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} {% endwith %} </div> <button type="submit" class="btn btn-primary">Login</button> </form> </div> </div> <!-- Bootstrap JS Link --> <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js' integrity='sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p' crossorigin='anonymous'></script> </body> </html>
<template> <!-- input --> <div v-if="selectedItem" class="flex justify-center items-center w-screen h-screen bg-black bg-opacity-50" > <div class="bg-gray-800 border-gray-700 border-2 rounded select-none text-white p-2" > <h1>{{ selectedItem.name }}</h1> <input ref="input" v-model="input" class="w-[10rem] bg-gray-700 border-gray-600 border-2 rounded px-2 py-1 outline-none" :placeholder="selectedItem.name" > </div> </div> <!-- menu --> <div v-else-if="menu && !selectedItem" > <div class="fixed left-3 top-3 text-white select-none" > <div class="bg-gray-800 border-gray-700 border-2 rounded w-[17.5rem] py-2 text-center" > <h1 class="text-lg" > {{ getTitle() }} </h1> <h1 v-if="menu.subtitle" class="text-gray-400 italic" > {{ menu.subtitle }} </h1> <div class="flex flex-col mt-2" > <div v-for="item in getVisibleItems()" :key="item.id" class="flex flex-row justify-around items-center" :style="getStyle(item)" > <icon v-if="item.leftIcon" :icon="item.leftIcon" /> <div v-if="item.type == 'select'" class="flex flex-row items-center gap-3" > <icon icon="arrow-left" /> <h1> {{ typeof item.selectedOption == 'string' ? item.selectedOption : item.selectedOption?.name }} </h1> <icon icon="arrow-right" /> </div> <h1 v-else > {{ item.name }} </h1> <icon v-if="item.rightIcon" :icon="item.rightIcon" /> </div> </div> </div> <!-- preview image --> <div v-if="menu && menu.selected && menu.selected.type == 'select' && menu.selected.selectedOption && typeof menu.selected.selectedOption == 'object' && menu.selected.selectedOption.imgSrc" class="max-w-full p-5 m-auto bg-gray-800 border-gray-700 rounded border-2 mt-3 flex flex-col items-center" > <h1>Vorschau: {{ menu.selected.selectedOption.name }}</h1> <img class="max-w-[50%]" :src="menu.selected.selectedOption.imgSrc" > </div> </div> <!-- keys --> <div class="fixed right-3 top-3 text-white select-none bg-gray-800 border-gray-700 border-2 rounded p-2" > <div v-for="(item, index) in keyControls" :key="index" class="flex justify-between items-center gap-5" > <h1>{{ item.key }}</h1> <h1 class="text-gray-400 italic" > {{ item.text }} </h1> </div> </div> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' import { IMenu, IMenuItem } from './Types' const MAX_ITEMS = 20 const EMITS = { SELECT: 'select', HOVER: 'hover', CHANGESELECTION: 'changeselection', CHANGESITE: 'changesite' } const KEYS = { ArrowLeft: 37, ArrowRight: 39, ArrowUp: 38, ArrowDown: 40, Enter: 13, PageUp: 33, PageDown: 34 } export default defineComponent({ data() { return { menu: undefined as IMenu | undefined, selectedItem: undefined as IMenuItem | undefined, input: undefined as string | undefined, page: 0, keyControls: [ { key: 'Pfeil hoch', text: 'Letztes item (hoch)' }, { key: 'Pfeil runter', text: 'Nächstes item (runter)' }, { key: 'Pfeil links', text: 'Letzte option (links)' }, { key: 'Pfeil rechts', text: 'Nächste option (rechts)' }, { key: 'Enter', text: 'Item auswählen' }, { key: 'Seite hoch', text: 'Letzte Seite' }, { key: 'Seite runter', text: 'Nächste Seite' } ] } }, mounted() { if ('alt' in window) //@ts-expect-error alt isn't available in plain html types window.alt.on('keyup', this.handleKeyEvent) else window.addEventListener('keyup', this.handleKeyEvent) }, unmounted() { if ('alt' in window) //@ts-expect-error alt isn't available in plain html types window.alt.off('keyup', this.handleKeyEvent) else window.removeEventListener('keyup', this.handleKeyEvent) }, methods: { openMenu(menu: IMenu) { this.menu = menu // set default options for select items for (let i=0; i<this.menu.items.length; i++) { const item = this.menu.items[i] item.id = i if (item.type != 'select') continue if (!item.selectOptions) { console.error(`Item ${item} is of type select but has no selectOptions!`) continue } item.selectedOption = item.selectOptions[0] } menu.selected = menu.items[0] }, getPages() { return !this.menu ? 0 : Math.round(this.menu.items.length / MAX_ITEMS) }, getTitle() { return !this.menu ? '' : this.menu.items.length <= MAX_ITEMS ? this.menu.title : `${this.menu.title} (${this.page + 1}/${this.getPages()})` }, getVisibleItems(): IMenuItem[] { if (!this.menu || this.menu.items.length == 0) return [] if (this.menu.items.length <= MAX_ITEMS) return this.menu.items const r = [] as IMenuItem[] for (let i=0; i<MAX_ITEMS; i++) { const index = i + this.page * MAX_ITEMS if (index >= this.menu.items.length) break r.push(this.menu.items[index]) } return r }, getStyle(item: IMenuItem) { return this.menu?.selected == item ? `background: ${this.menu.highlightColor || '#64748b'};` : '' }, handleKeyEvent(ev: KeyboardEvent | number) { if (!this.menu || !this.menu.selected) return const keyCode = typeof ev == 'number' ? ev : ev.keyCode // item won't be null due to check for menu // if there is a menu, there will always be a selected item const item = this.menu.selected as NonNullable<IMenuItem> switch (keyCode) { case KEYS.ArrowLeft: { if (item.type != 'select' || !item.selectedOption || !item.selectOptions) break const crntIndex = item.selectOptions.indexOf(item.selectedOption) if (crntIndex == 0) break item.selectedOption = item.selectOptions[crntIndex - 1] this.emit( EMITS.CHANGESELECTION, 'left', crntIndex - 1, item.name, typeof item.selectedOption == 'string' ? item.selectedOption : item.selectedOption?.name ) break } case KEYS.ArrowRight: { if (item.type != 'select' || !item.selectedOption || !item.selectOptions) break const crntIndex = item.selectOptions.indexOf(item.selectedOption) if (crntIndex == item.selectOptions.length - 1) break item.selectedOption = item.selectOptions[crntIndex + 1] this.emit( EMITS.CHANGESELECTION, 'right', crntIndex + 1, item.name, typeof item.selectedOption == 'string' ? item.selectedOption : item.selectedOption?.name ) break } case KEYS.ArrowUp: { const visibleItems = this.getVisibleItems() const firstItemOnPage = visibleItems[0] if (this.menu.selected == firstItemOnPage) break this.menu.selected = visibleItems[visibleItems.indexOf(this.menu.selected) - 1] this.emit( EMITS.HOVER, this.menu.selected.name ) break } case KEYS.ArrowDown: { const visibleItems = this.getVisibleItems() const lastItemOnPage = visibleItems[visibleItems.length - 1] if (this.menu.selected == lastItemOnPage) break this.menu.selected = visibleItems[visibleItems.indexOf(this.menu.selected) + 1] this.emit( EMITS.HOVER, this.menu.selected.name ) break } case KEYS.Enter: { this.handleSelect(this.menu.selected) break } case KEYS.PageUp: { if (this.getPages() < 2 || this.page == this.getPages() - 1) return this.page++ this.menu.selected = this.getVisibleItems()[0] this.emit(EMITS.CHANGESITE, 'up', this.page) break } case KEYS.PageDown: { if (this.getPages() < 2 || this.page == 0) return this.page-- this.menu.selected = this.getVisibleItems()[this.getVisibleItems().length - 1] this.emit(EMITS.CHANGESITE, 'down', this.page) break } } }, emit(eventName: string, ...args: unknown[]) { if ('alt' in window) { // @ts-expect-error alt isn't available in plain html types window.alt?.emit(eventName, ...args) } else { console.log(`[EMIT] ${eventName}: ${args.join(',')}`) } }, handleSelect(item: IMenuItem) { switch (item.type) { case 'button': this.emit(EMITS.SELECT, item.name) break case 'select': this.emit( EMITS.SELECT, item.name, typeof item.selectedOption == 'string' ? item.selectedOption : item.selectedOption?.name ) break case 'input': if (this.selectedItem) { this.handleInputSubmit() } else { this.selectedItem = item this.$nextTick(() => { // @ts-expect-error vue doesn't recognice refs this.$refs['input'].focus() }) } break } }, handleInputSubmit() { this.emit(EMITS.SELECT, this.selectedItem?.name, this.input) this.selectedItem = undefined this.input = undefined } }, }) </script>
package com.example.oop2.Models; import com.example.oop2.MovieTheatreApplication; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.stage.Modality; import javafx.stage.Stage; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; /** * Utility class for managing scenes * You can use changeScene and closeWindow to manage scenes */ public class SceneHelper { /** * The SceneHelper class */ private static final SceneHelper sh = new SceneHelper(); /** * The application's current user */ private static User aCurrentUser = null; /** * The id of the room currently being edited */ private static int aCurrentRoomID = -1; /** * The id of the movie currently being edited */ private static int aCurrentMovie = -1; /** * The id of the showtime currently being edited */ private static int aCurrentShowtime = -1; /** * changeScene changes to the desired scene by passing the destination, an ActionEvent and a title * @param destination String holding the destination view * @param pEvent Determines the source of the event * @param title String that holds the title of the scene * */ public static void changeScene(String destination, ActionEvent pEvent, String title) throws IOException { FXMLLoader fxmlLoader = new FXMLLoader(MovieTheatreApplication.class.getResource(destination)); Scene nextScene = new Scene(fxmlLoader.load()); Stage nextStage = new Stage(); nextStage.setScene(nextScene); nextStage.setTitle(title); nextStage.initModality(Modality.WINDOW_MODAL); nextStage.initOwner(((Node) pEvent.getSource()).getScene().getWindow()); nextStage.showAndWait(); } /** * closeWindow closes the current window using a node to get the current scene * @param node Gets a node from the scene to then close the scene the node is from * */ public static void closeWindow(Node node) { Stage stage = (Stage) node.getScene().getWindow(); stage.close(); } public static boolean checkWithUser(String message) { Alert alert = new Alert(Alert.AlertType.WARNING, message); ButtonType buttonTypeExit = new ButtonType("Continue"); ButtonType buttonTypeCancel = new ButtonType("Cancel"); alert.getButtonTypes().setAll(buttonTypeExit, buttonTypeCancel); AtomicBoolean returnValue = new AtomicBoolean(false); alert.showAndWait().ifPresent(buttonType -> { if (buttonType == buttonTypeExit) { alert.close(); returnValue.set(true); } }); return returnValue.get(); } public static void errorMessage(String message) { Alert alert = new Alert(Alert.AlertType.WARNING, "Warning"); alert.setContentText(message); alert.showAndWait(); } /** * Sets the current user * * @param pCurrentUser the logged-in user */ public static void setCurrentUser(User pCurrentUser) { aCurrentUser = pCurrentUser; } /** * Gets the current user * * @return the logged-in user */ public static User getCurrentUser() { return aCurrentUser; } /** * Sets the edited room ID * * @param pCurrentRoomID the ID of the room being edited */ public static void setCurrentRoomID(int pCurrentRoomID) { aCurrentRoomID = pCurrentRoomID; } /** * Gets the ID of the room being edited * * @return the ID of the current room being edited */ public static int getCurrentRoomID() { return aCurrentRoomID; } /** * Sets the current movie ID * * @param pCurrentMovie the ID of the movie being edited */ public static void setCurrentMovie(int pCurrentMovie) { aCurrentMovie = pCurrentMovie; } /** * Gets the current movie ID * * @return the ID of the movie being edited */ public static int getCurrentMovie() { return aCurrentMovie; } /** * Sets the current showtime ID * * @param pCurrentShowtime the ID of the showtime being edited */ public static void setCurrentShowtime(int pCurrentShowtime) { aCurrentShowtime = pCurrentShowtime; } /** * Gets the current showtime ID * * @return the ID of the showtime being edited */ public static int getCurrentShowtime() { return aCurrentShowtime; } }
/* 450. Delete Node in a BST Medium Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Example 1: Input: root = [5,3,6,2,4,null,7], key = 3 Output: [5,4,6,2,null,null,7] Explanation: Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted. Example 2: Input: root = [5,3,6,2,4,null,7], key = 0 Output: [5,3,6,2,4,null,7] Explanation: The tree does not contain a node with value = 0. Example 3: Input: root = [], key = 0 Output: [] Constraints: The number of nodes in the tree is in the range [0, 104]. -105 <= Node.val <= 105 Each node has a unique value. root is a valid binary search tree. -105 <= key <= 105 Follow up: Could you solve it with time complexity O(height of tree)? */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode deleteNode(TreeNode root, int key) { if (root == null) { return null; } if (root.val == key) { // 1. 待删除节点恰好是末端节点,两个子节点都为空 if (root.left == null && root.right == null) { return null; } // 2. 待删除节点只有一个非空子节点,那么要让子节点接替自己的位置。 if (root.left == null) { return root.right; } if (root.right == null) { return root.left; } // 3. 待删除节点有两个子节点,为了不破坏 BST 的性质, // 必须找到左子树中最大的那个节点或者右子树中最小的那个节点来接替自己。 // 使用右子树中最小的子节点来替代待删除节点 // 找到右子树的最小节点 TreeNode minNode = getMinNode(root.right); root.val = minNode.val; // 转而去删除 minNode root.right = deleteNode(root.right, minNode.val); } if (root.val > key) { root.left = deleteNode(root.left, key); } if (root.val < key) { root.right = deleteNode(root.right, key); } return root; } private TreeNode getMinNode(TreeNode node) { while (node.left != null) { node = node.left; } return node; } }
<template> <div id="myTable" @contextmenu="stopDefault"> <a-table class="albumTable" size="small" :showHeader="showHeader" :columns="props.columns" :data-source="data" :pagination=pagination :rowClassName="(record, index) => (index % 2 === 0 ? 'table-striped' : null)" :customRow=customRow @change="handleTableChange" /> </div> </template> <script setup> import { $axios } from '@/request/axios'; import { computed, h, nextTick, onMounted,ref,watch } from 'vue'; import { useStore } from 'vuex'; import timeFormat from '@/utils/timeFormat'; const props = defineProps({ columns:Array, dataSource:Array, pagination:[Object,Boolean], virtual:{ validator(value){ if(value.listHeight == undefined || value.itemSize == undefined){ throw Error("error arguments for virtual"); } return true; }, default(rawProps) { return { listHeight: 0 , itemSize : 0} } }, showHeader:{ type:Boolean, default:true, }, id:{ type:Number, required:false }, user:{ type:Boolean, default:false, }, bufferRange:{ type:Number, default:0, }, }); const emit = defineEmits(['handlePlaySong','handleTableChange']) const store = useStore(); const customRow = (record) => { return { style:{ height: props.virtual ? props.virtual.itemSize + 'px' : null, }, onDblclick: (event) => { if(typeof props.id === 'number'){ handlePlaySong(record.key,record.index,props.id); }else{ handlePlaySong(record.key,record.index); } }, oncontextmenu:async (event)=>{ const {data:res} = await $axios({ method:'get', url:`/api/comment/music?id=${record.key}&limit=1` }) const {data:{songs:song}} = await $axios({ method:'get', url:`/api/song/detail?ids=${record.key}` }) store.commit('changeTableMenu',{ show:true, x:event.pageX, y:event.pageY, commentCount:res.total, song:{ id:song[0].id, name:song[0].name, singer:song[0].ar, dt:timeFormat(song[0].dt), fee:song[0].fee, noCopyrightRcmd:song[0].noCopyrightRcmd, mv:song[0].mv, }, user:props.user, }) } }; } const handlePlaySong = (songId,index,id)=>{ emit('handlePlaySong',songId,index,id); } const handleTableChange = (pagination,filters, sorter, { currentDataSource })=>{ emit('handleTableChange',pagination,filters,sorter,{ currentDataSource }); } const stopDefault = (e)=>{ e.preventDefault(); } const scrollTop = props.virtual.listHeight ? ref(0) : null; const start = props.virtual.listHeight ? computed(()=>parseInt(scrollTop.value / props.virtual.itemSize)) : null; const visibleCount = props.virtual.listHeight ? computed(()=>Math.ceil(props.virtual.listHeight / props.virtual.itemSize)) : null; const end = props.virtual.listHeight ? computed(()=> start.value + visibleCount.value) : null; const placeholderWrapper = props.virtual.listHeight ? document.createElement('div') : null; const aboveCount = props.virtual.listHeight ? computed(()=>Math.min(props.bufferRange,start.value)) : null; const belowCount = props.virtual.listHeight ? computed(()=>Math.min(props.bufferRange,props.dataSource.length-end.value)) : null; const data = computed(()=>{ if(props.virtual.listHeight){ const startRange = start.value - aboveCount.value; const endRange = end.value + belowCount.value; return props.dataSource.slice(startRange,endRange); }else{ return props.dataSource } }); onMounted(()=>{ if(props.virtual.listHeight){ const parentNode = document.querySelector('.ant-table-content'); const table = document.querySelector('.ant-table-content table'); const tbody = document.querySelector('.ant-table-content table .ant-table-tbody'); const myTable = document.querySelector('#myTable'); parentNode.appendChild(placeholderWrapper); parentNode.style.position = 'relative'; table.style.position = 'absolute'; const toTop = myTable.offsetTop+tbody.offsetTop; window.addEventListener('scroll', (e)=>{ if(e.target.scrollTop > toTop){ scrollTop.value = e.target.scrollTop - toTop; table.style.transform = `translateY(${scrollTop.value - scrollTop.value % props.virtual.itemSize - (aboveCount.value * props.virtual.itemSize)}px)`; } },true) } }) watch([()=>props.dataSource,()=>props.virtual.itemSize],props.virtual.listHeight ? ()=>{ placeholderWrapper.style.height = props.dataSource.length * props.virtual.itemSize + 'px'; } : ()=>{},{ immediate:true }) </script> <style lang="less" scoped> @import '@/assets/theme.less'; #myTable{ position: relative; .albumTable{ :deep(.ant-table){ background-color: transparent; } :deep(.ant-table-content){ table{ table-layout: fixed !important; } .slash{ margin: 0 4px; } .likeIcon{ cursor: pointer; &.liked:hover{ color: #d73535 !important; } } .album,.song,.singer{ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .downloadIcon{ cursor: pointer; } .album{ cursor: pointer; color: #999; &:hover{ color: #b1b9b9; } mark { background-color: transparent; color: #7ab9e6; } } .song{ display: flex; align-items: center; justify-content:left; .vipIcon,mvIcon,noCopyrightIcon{ margin-left: 1px; } mark { background-color: transparent; color: #7ab9e6; } } .singer{ cursor: pointer; color: #999; .singerName{ transition: none; } .singerName:hover{ color: #b1b9b9; } mark { background-color: transparent; color: #7ab9e6; } } .dt{ color: #999; } .likeIcon:hover,.downloadIcon:hover{ color: #949494; } .ant-table-cell{ background-color: transparent; border-bottom: 0; padding-top: 6px; padding-bottom: 6px; color: @black-font-color; font-size: 13px; transition: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .table-striped td { background-color: #2f2f2f; } tr:hover .ant-table-cell{ background-color: #373737; } tr td:first-child{ padding-left: 13px; text-align: center; font-size: 13px; color: #666; } tr td:nth-child(2),td:nth-child(3){ font-size: 15px; color: #666; padding-left: 2px; } .ant-table-thead .ant-table-cell{ color: #666; &::before{ visibility: hidden; } } } } } </style>
/* * Copyright 2023 StarTree Inc * * Licensed under the StarTree Community License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at http://www.startree.ai/legal/startree-community-license * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, * either express or implied. * * See the License for the specific language governing permissions and limitations under * the License. */ import { act, renderHook } from "@testing-library/react-hooks"; import axios from "axios"; import { ActionStatus } from "../actions.interfaces"; import type { AnomalyStats } from "../dto/anomaly.interfaces"; import { AnomalyFeedbackType } from "../dto/anomaly.interfaces"; import { useGetAnomaly, useGetAnomalyStats, useUpdateAnomalyFeedback, } from "./anomaly.actions"; const mockAnomaly = { id: 1, }; const mockAnomalyStats = { totalCount: 12, countWithFeedback: 4, feedbackStats: { ANOMALY: 3, ANOMALY_EXPECTED: 0, NOT_ANOMALY: 1, ANOMALY_NEW_TREND: 0, NO_FEEDBACK: 0, }, } as AnomalyStats; jest.mock("axios"); const mockedAxios = axios as jest.Mocked<typeof axios>; describe("Anomaly Actions", () => { describe("useGetAnomaly", () => { it("should return initial default values", () => { const { result } = renderHook(() => useGetAnomaly()); expect(result.current.anomaly).toBeNull(); expect(result.current.getAnomaly).toBeDefined(); expect(result.current.status).toEqual(ActionStatus.Initial); expect(result.current.errorMessages).toEqual([]); }); it("should update data appropriately when making a successful REST call", async () => { mockedAxios.get.mockResolvedValueOnce({ data: mockAnomaly }); const { result, waitFor } = renderHook(() => useGetAnomaly()); await act(async () => { const promise = result.current.getAnomaly(1); // Wait for state update await waitFor( () => result.current.status === ActionStatus.Initial ); // When REST call is in progress expect(result.current.anomaly).toBeNull(); expect(result.current.getAnomaly).toBeDefined(); expect(result.current.status).toEqual(ActionStatus.Working); expect(result.current.errorMessages).toEqual([]); return promise.then(() => { // When REST call is completed expect(result.current.anomaly).toEqual(mockAnomaly); expect(result.current.getAnomaly).toBeDefined(); expect(result.current.status).toEqual(ActionStatus.Done); expect(result.current.errorMessages).toEqual([]); }); }); }); }); describe("useGetAnomalyStats", () => { it("should return initial default values", () => { const { result } = renderHook(() => useGetAnomalyStats()); expect(result.current.anomalyStats).toBeNull(); expect(result.current.getAnomalyStats).toBeDefined(); expect(result.current.status).toEqual(ActionStatus.Initial); expect(result.current.errorMessages).toEqual([]); }); it("should update data appropriately when making a successful REST call", async () => { mockedAxios.get.mockResolvedValueOnce({ data: mockAnomalyStats }); const { result, waitFor } = renderHook(() => useGetAnomalyStats()); await act(async () => { const promise = result.current.getAnomalyStats({ startTime: 1, endTime: 2, }); // Wait for state update await waitFor( () => result.current.status === ActionStatus.Initial ); // When REST call is in progress expect(result.current.anomalyStats).toBeNull(); expect(result.current.getAnomalyStats).toBeDefined(); expect(result.current.status).toEqual(ActionStatus.Working); expect(result.current.errorMessages).toEqual([]); return promise.then(() => { // When REST call is completed expect(result.current.anomalyStats).toEqual( mockAnomalyStats ); expect(result.current.getAnomalyStats).toBeDefined(); expect(result.current.status).toEqual(ActionStatus.Done); expect(result.current.errorMessages).toEqual([]); }); }); }); }); describe("useUpdateAnomalyFeedback", () => { it("should return initial default values", () => { const { result } = renderHook(() => useUpdateAnomalyFeedback()); expect(result.current.anomalyFeedback).toBeNull(); expect(result.current.updateAnomalyFeedback).toBeDefined(); expect(result.current.status).toEqual(ActionStatus.Initial); expect(result.current.errorMessages).toEqual([]); }); it("should update data appropriately when making a successful REST call", async () => { mockedAxios.post.mockResolvedValueOnce({ data: mockAnomalyStats }); const { result, waitFor } = renderHook(() => useUpdateAnomalyFeedback() ); await act(async () => { const promise = result.current.updateAnomalyFeedback(1, { type: "ANOMALY" as AnomalyFeedbackType, comment: "hello world", }); // Wait for state update await waitFor( () => result.current.status === ActionStatus.Initial ); // When REST call is in progress expect(result.current.anomalyFeedback).toBeNull(); expect(result.current.updateAnomalyFeedback).toBeDefined(); expect(result.current.status).toEqual(ActionStatus.Working); expect(result.current.errorMessages).toEqual([]); return promise.then(() => { // When REST call is completed expect(result.current.anomalyFeedback).toEqual( mockAnomalyStats ); expect(result.current.updateAnomalyFeedback).toBeDefined(); expect(result.current.status).toEqual(ActionStatus.Done); expect(result.current.errorMessages).toEqual([]); }); }); }); }); });
package org.idp.server.configuration; import java.util.*; import java.util.stream.Collectors; import org.idp.server.basic.json.JsonReadable; import org.idp.server.type.ciba.BackchannelTokenDeliveryMode; import org.idp.server.type.extension.RegisteredRedirectUris; import org.idp.server.type.oauth.*; /** ClientConfiguration */ public class ClientConfiguration implements JsonReadable { String clientId; String clientSecret; List<String> redirectUris = new ArrayList<>(); String tokenEndpointAuthMethod; List<String> grantTypes = new ArrayList<>(); List<String> responseTypes = new ArrayList<>(); String clientName = ""; String clientUri = ""; String logoUri = ""; String scope; String contacts = ""; String tosUri = ""; String policyUri = ""; String jwksUri; String jwks; String softwareId = ""; String softwareVersion = ""; List<String> requestUris = new ArrayList<>(); String backchannelTokenDeliveryMode = ""; String backchannelClientNotificationEndpoint = ""; String backchannelAuthenticationRequestSigningAlg = ""; Boolean backchannelUserCodeParameter; String applicationType = "web"; String idTokenEncryptedResponseAlg; String idTokenEncryptedResponseEnc; List<String> authorizationDetailsTypes = new ArrayList<>(); String tlsClientAuthSubjectDn; String tlsClientAuthSanDns; String tlsClientAuthSanUri; String tlsClientAuthSanIp; String tlsClientAuthSanEmail; boolean tlsClientCertificateBoundAccessTokens = false; String authorizationSignedResponseAlg; String authorizationEncryptedResponseAlg; String authorizationEncryptedResponseEnc; // extension boolean supportedJar; String issuer; public ClientConfiguration() {} public ClientId clientId() { return new ClientId(clientId); } public String clientIdValue() { return clientId; } public String clientSecretValue() { return clientSecret; } public ClientSecret clientSecret() { return new ClientSecret(clientSecret); } public List<String> redirectUris() { return redirectUris; } public boolean hasRedirectUri() { return !redirectUris.isEmpty(); } public boolean isMultiRegisteredRedirectUri() { return redirectUris.size() >= 2; } public RedirectUri getFirstRedirectUri() { return new RedirectUri(redirectUris.get(0)); } public RegisteredRedirectUris registeredRedirectUris() { return new RegisteredRedirectUris(redirectUris); } public String tokenEndpointAuthMethod() { return tokenEndpointAuthMethod; } public List<String> grantTypes() { return grantTypes; } public List<String> responseTypes() { return responseTypes; } public String clientName() { return clientName; } public String clientUri() { return clientUri; } public String logoUri() { return logoUri; } public String scope() { return scope; } public String contacts() { return contacts; } public String tosUri() { return tosUri; } public String policyUri() { return policyUri; } public String jwksUri() { return jwksUri; } public String jwks() { return jwks; } public String softwareId() { return softwareId; } public String softwareVersion() { return softwareVersion; } public List<String> scopes() { if (Objects.isNull(scope)) { return List.of(); } return Arrays.stream(scope.split(" ")).toList(); } public Set<String> filteredScope(String spacedScopes) { if (Objects.isNull(spacedScopes) || spacedScopes.isEmpty()) { return Set.of(); } List<String> scopes = Arrays.stream(spacedScopes.split(" ")).toList(); return scopes.stream().filter(scope -> scopes().contains(scope)).collect(Collectors.toSet()); } public Set<String> filteredScope(List<String> scopes) { return scopes.stream().filter(scope -> scopes().contains(scope)).collect(Collectors.toSet()); } public boolean isSupportedJar() { return supportedJar; } public boolean isRegisteredRequestUri(String requestUri) { return requestUris.contains(requestUri); } public boolean isRegisteredRedirectUri(String redirectUri) { return redirectUris.contains(redirectUri); } public TokenIssuer tokenIssuer() { return new TokenIssuer(issuer); } public boolean isSupportedResponseType(ResponseType responseType) { return responseTypes.contains(responseType.value()); } public boolean matchClientSecret(String that) { return clientSecret.equals(that); } public ClientAuthenticationType clientAuthenticationType() { return ClientAuthenticationType.valueOf(tokenEndpointAuthMethod); } public BackchannelTokenDeliveryMode backchannelTokenDeliveryMode() { return BackchannelTokenDeliveryMode.of(backchannelTokenDeliveryMode); } public boolean hasBackchannelTokenDeliveryMode() { return backchannelTokenDeliveryMode().isDefined(); } public String backchannelClientNotificationEndpoint() { return backchannelClientNotificationEndpoint; } public boolean hasBackchannelClientNotificationEndpoint() { return !backchannelClientNotificationEndpoint.isEmpty(); } public String backchannelAuthenticationRequestSigningAlg() { return backchannelAuthenticationRequestSigningAlg; } public boolean hasBackchannelAuthenticationRequestSigningAlg() { return !backchannelAuthenticationRequestSigningAlg.isEmpty(); } public Boolean backchannelUserCodeParameter() { return backchannelUserCodeParameter; } public boolean hasBackchannelUserCodeParameter() { return Objects.nonNull(backchannelUserCodeParameter); } public boolean isSupportedGrantType(GrantType grantType) { return grantTypes.contains(grantType.value()); } public boolean isWebApplication() { return applicationType.equals("web"); } public String idTokenEncryptedResponseAlg() { return idTokenEncryptedResponseAlg; } public String idTokenEncryptedResponseEnc() { return idTokenEncryptedResponseEnc; } public boolean hasEncryptedIdTokenMeta() { return Objects.nonNull(idTokenEncryptedResponseAlg) && Objects.nonNull(idTokenEncryptedResponseEnc); } public List<String> authorizationDetailsTypes() { return authorizationDetailsTypes; } public boolean isAuthorizedAuthorizationDetailsType(String type) { return authorizationDetailsTypes.contains(type); } public String tlsClientAuthSubjectDn() { return tlsClientAuthSubjectDn; } public String tlsClientAuthSanDns() { return tlsClientAuthSanDns; } public String tlsClientAuthSanUri() { return tlsClientAuthSanUri; } public String tlsClientAuthSanIp() { return tlsClientAuthSanIp; } public String tlsClientAuthSanEmail() { return tlsClientAuthSanEmail; } public boolean isTlsClientCertificateBoundAccessTokens() { return tlsClientCertificateBoundAccessTokens; } public String authorizationSignedResponseAlg() { return authorizationSignedResponseAlg; } public boolean hasAuthorizationSignedResponseAlg() { return Objects.nonNull(authorizationSignedResponseAlg); } public String authorizationEncryptedResponseAlg() { return authorizationEncryptedResponseAlg; } public String authorizationEncryptedResponseEnc() { return authorizationEncryptedResponseEnc; } public boolean hasEncryptedAuthorizationResponseMeta() { return Objects.nonNull(idTokenEncryptedResponseAlg) && Objects.nonNull(idTokenEncryptedResponseEnc); } }
import { InMemoryCameraRepository } from 'src/tests/repositories/in-memory-camera-repository'; import { CameraService } from './camera.service'; const photoPathMock = 'file:///path/test' function initializeCameraServiceWithCustomPath(): CameraService { const cameraRepository = new InMemoryCameraRepository() cameraRepository.setPhotoPath(photoPathMock) const cameraService = new CameraService(cameraRepository) return cameraService } describe('CameraService', () => { let cameraService: CameraService; beforeEach(() => { cameraService = initializeCameraServiceWithCustomPath() }); it('should open camera and get photo', () => { const photo = cameraService.openCamera() expect(photo).toBeTruthy() }); it('should get the correct photo path', async () => { const photo = await cameraService.openCamera() expect(photo.path).toEqual(photoPathMock) }) });
using World.Application; using World.Infrastructure; using Serilog; // require serialog and serialog.aspNetCore using Microsoft.Extensions.DependencyInjection; using World.Presentation; using World.Persistence; using MediatR; using World.Application.Behaviors; using Serilog.Settings.Configuration; using Microsoft.OpenApi.Models; using World.WebApi.config; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.Extensions.Options; using Swashbuckle.AspNetCore.SwaggerGen; using World.WebApi.middleware; using Microsoft.Extensions.Configuration; using World.WebApi.filters; using Asp.Versioning.ApiExplorer; using FluentValidation; var builder = WebApplication.CreateBuilder(args); /********************* Add Dependency Injection *****************/ builder.Services .AddApplication() .AddAuthorization() .AddInfrastructure() .AddPresentation() .AddPersistant(builder.Configuration); /*****************************************************************/ /***************** Log Config *************************************/ var options = new ConfigurationReaderOptions(ApplicationAssembly.Instance, typeof(Program).Assembly); // builder.Host.UseSerilog(); builder.Host.UseSerilog((context, configuration) => { configuration .ReadFrom .Configuration(context.Configuration, options); }); /******************* Authentication and Autherization *****************/ // Configure own cors policy builder.Services.AddCors(o => o.AddPolicy("AllowMyOrigin", builder => { builder.WithOrigins(@"http://localhost:4201", "*"); builder.SetIsOriginAllowed((host) => true); builder.AllowCredentials(); builder.AllowAnyMethod(); builder.AllowAnyHeader(); })); builder.Services.AddMvc(option => { option.EnableEndpointRouting = true; option.Filters.Add(new AuthorizationTokenFilter(builder.Configuration)); // Add roles permission validator option.Filters.Add(new RolePermissionFilter()); // Add Exception filter option.Filters.Add(new CustomExceptionFilter()); }); /************************************************************************/ /************************************************************************/ // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>(); builder.Services.AddSwaggerGen(o => o.OperationFilter<SwaggerDefaultValues>()); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); // app.UseSwaggerWithVersioning(); app.UseSwaggerUI(options => { var descriptions = app.DescribeApiVersions(); foreach (var description in descriptions) { var url = $"/swagger/{description.GroupName}/swagger.json"; var name = description.GroupName.ToUpperInvariant(); options.SwaggerEndpoint(url, name); } // options.RoutePrefix = ""; // swagger UI at the root index.html }); } app.UseSerilogRequestLogging(); app.UseHttpsRedirection(); app.UseMiddleware<AuthenticationMiddleware>(); app.UseMiddleware<AuthorizationMiddleware>(); app.UseMiddleware(typeof(ErrorHandlingMiddleware)); app.UseRouting(); app.UseCors("AllowMyOrigin"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.Run(); public partial class Program { }
import { createAsyncThunk, createEntityAdapter, createSlice, } from "@reduxjs/toolkit"; import { ModelVehicle, ModelVehicleParams, } from "../../app/models/ModelVehicle"; import { RootState } from "../../app/store/ConfigureStore"; import agent from "../../app/api/agent"; import { FieldValues } from "react-hook-form"; import { toast } from "react-toastify"; import { MetaData } from "../../app/models/Pagination"; interface ModelVehicleState { modelVehicle: ModelVehicle | null; modelVehicleLoaded: boolean; modelVehicleParams: ModelVehicleParams; metaData: MetaData | null; } const modelVehiclesAdapter = createEntityAdapter<ModelVehicle>(); function getAxiosParams(modelVehicleParams: ModelVehicleParams) { const params = new URLSearchParams(); params.append("pageNumber", modelVehicleParams.pageNumber.toString()); params.append("pageSize", modelVehicleParams.pageSize.toString()); return params; } export const getModelVehiclesAsync = createAsyncThunk< ModelVehicle[], void, { state: RootState } >("modelVehicle/getModelVehiclesAsync", async (_, ThunkAPI) => { const params = getAxiosParams( ThunkAPI.getState().modelVehicle.modelVehicleParams ); try { const response = await agent.ModelVehicle.list(params); ThunkAPI.dispatch(setMetaData(response.metaData)); return response.items; } catch (error: any) { return ThunkAPI.rejectWithValue({ error: error.data }); } }); export const addModelVehicleAsync = createAsyncThunk<ModelVehicle, FieldValues>( "modelVehicle/addModelVehicleAsync", async (data, ThunkAPI) => { try { const response = await agent.ModelVehicle.create(data); return response; } catch (error: any) { return ThunkAPI.rejectWithValue({ error: error.data }); } } ); export const updateModelVehicleAsync = createAsyncThunk< ModelVehicle, FieldValues >("modelVehicle/updateModelVehicleAsync", async (data, ThunkAPI) => { try { const response = await agent.ModelVehicle.update(data.id, data); return response; } catch (error: any) { return ThunkAPI.rejectWithValue({ error: error.data }); } }); export const deleteModelVehicleAsync = createAsyncThunk( "modelVehicle/deleteModelVehicleAsync", async (id: string) => { try { await agent.ModelVehicle.delete(id); toast.success("Delete modelVehicle successfully!"); return id; } catch (error: any) { toast.error(error.data.message); throw error; } } ); function initParams() { return { pageNumber: 1, pageSize: 5, }; } export const ModelVehicleSlice = createSlice({ name: "modelVehicle", initialState: modelVehiclesAdapter.getInitialState<ModelVehicleState>({ modelVehicle: null, modelVehicleLoaded: false, modelVehicleParams: initParams(), metaData: null, }), reducers: { setModelVehicleParams: (state, action) => { state.modelVehicleParams = { ...state.modelVehicleParams, ...action.payload, }; }, resetModelVehicleParams: (state) => { state.modelVehicleParams = initParams(); }, setMetaData: (state, action) => { state.metaData = action.payload; }, setPageNumber: (state, action) => { state.modelVehicleLoaded = false; state.modelVehicleParams = { ...state.modelVehicleParams, ...action.payload, }; }, }, extraReducers: (builder) => { builder .addCase(getModelVehiclesAsync.fulfilled, (state, action) => { modelVehiclesAdapter.setAll(state, action.payload); state.modelVehicleLoaded = false; }) .addCase(getModelVehiclesAsync.pending, (state, action) => { state.modelVehicleLoaded = true; }) .addCase(getModelVehiclesAsync.rejected, (state, action) => { console.log("Get ModelVehicle rejected: ", action); state.modelVehicleLoaded = false; }); builder.addCase(addModelVehicleAsync.fulfilled, (state, action) => { toast.success("Add ModelVehicle successfully!"); modelVehiclesAdapter.addOne(state, action.payload); }); builder.addCase(updateModelVehicleAsync.fulfilled, (state, action) => { toast.success("Update ModelVehicle successfully!"); modelVehiclesAdapter.upsertOne(state, action.payload); }); builder.addCase(deleteModelVehicleAsync.fulfilled, (state, action) => { modelVehiclesAdapter.removeOne(state, action.payload); }); }, }); export const modelVehicleSelectors = modelVehiclesAdapter.getSelectors( (state: RootState) => state.modelVehicle ); export const { setModelVehicleParams, resetModelVehicleParams, setMetaData, setPageNumber, } = ModelVehicleSlice.actions;
Contributors: Stephen@swantech.us Tags: nft, authentication, content protection, web3 login, dApp Requires at least: 5.0 Tested up to: 6.4.2 Stable tag: 1.0.4 PHP: 8.2 License: GPL-3.0 License URI: https://www.gnu.org/licenses/gpl-3.0.en.html Discord: https://discord.gg/gqwrFkwcGg <h1>Fungate</h1> <figure> <img src="https://github.com/stepwn/Fungate/assets/7231316/f0b456fa-226e-47fd-ba5c-3466f605fb30.png" alt="Token Gated Content"> <figcaption>Token Gated Content</figcaption> </figure> <hr> Fungate is a powerful and easy-to-use WordPress plugin that enables users to gate content based on NFT ownership. With Fungate, you can easily protect your content and offer exclusive access to users who own a specific NFT. Fungate uses PHP and JS to run standalone on your WordPress site's server. (That means its free to use!) <h2>Features</h2> Protect content with NFT ownership verification based on token, minter, or NFT ID Supports WalletConnect for secure authentication Easy installation and configuration Safety First! <h2>Installation</h2> ![image](https://github.com/stepwn/Fungate/assets/7231316/c0d0a594-b735-4ff5-9daa-30ec8bc6b799) <hr> To install Fungate, simply follow these steps: <ul> <li>Download <a href="https://github.com/stepwn/Fungate/blob/main/Fungate.zip">Fungate.zip</a> <br><b>*If you clone the repo, rename the inner folder to "Fungate.zip"</b> <li>Upload the plugin to your WordPress site <li>Activate the plugin in your WordPress dashboard <li>Configure the plugin settings according to your requirements </ul> <h2>Configuration</h2> After installing Fungate, you'll need to configure the plugin according to your requirements or options. To configure Fungate, follow these steps: <ol> <li>Export your Loopring API key -> https://github.com/stepwn/Fungate/assets/7231316/00dad3da-61f8-49de-bfed-2f10adbf918d <br> Look for "api key" in the exported account. <li>Add your API key to the "Fungate Settings" on the main sidebar of the WordPress admin dashboard <li>Obtain a ProjectId from https://cloud.walletconnect.com and save it in the Fungate settings page. If you need any help with configuration, don't hesitate to reach out for support. https://discord.gg/gqwrFkwcGg ## Usage ![Shortcode](https://user-images.githubusercontent.com/7231316/235256376-74517595-6721-4087-919b-c793e913d625.png) *eg Shortcode placement in the WordPress Page Editor* --- ![Fungate Post Type](https://github.com/stepwn/Fungate/assets/7231316/51c672c0-4d05-4fc8-8fd5-340ba22e71fd) *Fungate Post Type* Using Fungate is easy. Here are the basic steps to get started: <ol> <li>Create a new post or page in WordPress <li>Use the [fungate token="tokencollectioncontract" minter="minterethaddress" nft_id="individualNFTID"] shortcode to protect content based on NFT ownership <li>Customize the shortcode attributes to fit your requirements (token or minter or nft_id is required) <li>Put your token gated content on the page using the WordPress content editor <li>At the end of your gated content put the [/fungate] shortcode tag. <li>Save and publish! For more detailed instructions and examples, check out our documentation. <h2>Support</h2> If you encounter any issues with Fungate, please don't hesitate to reach out for support. You can find help in the following ways: Visit our discord https://discord.gg/gqwrFkwcGg We're here to help, so don't hesitate to reach out if you need assistance. <h2>Frequently asked questions</h2> Q: How does Fungate verify NFT ownership? A: Fungate uses the Loopring Rest API to authenticate users and verify NFT ownership once the browser or WalletConnect finishes Public Key Verification. Q: How Safe is this plugin? A: Fungate sets up a local proxy for Loopring API requests so your key is never exposed to the client. Additionally, users are only signing a verification request to prove they own the Eth address they submit, Fungate can not transfer tokens. Q: How can I give away NFTs? A: Loopring has a NFT red packet system. you can put the red packet behind a token gate (or not!) Q: I have no idea whats happening A: <a href="https://github.com/stepwn/Fungate/blob/main/user-onboarding-guide.md">User Onboarding Guide</a> <h2>Summary</h2> Fungate is the ultimate WordPress plugin for gating content based on NFT ownership. With its powerful features and easy-to-use interface, you can protect your content and offer exclusive access to your audience. Download Fungate today and start gating your content based on NFT ownership!
class MyCircularDeque: from collections import deque def __init__(self, k: int): self.deque = deque() self.k = k def insertFront(self, value: int) -> bool: if len(self.deque) < self.k: try: self.deque.appendleft(value) return True except Exception: return False else: return False def insertLast(self, value: int) -> bool: if len(self.deque) < self.k: try: self.deque.append(value) return True except Exception: return False else: return False def deleteFront(self) -> bool: try: self.deque.popleft() return True except Exception: return False def deleteLast(self) -> bool: try: self.deque.pop() return True except Exception: return False def getFront(self) -> int: try: return self.deque[0] except Exception: return -1 def getRear(self) -> int: try: return self.deque[-1] except Exception: return -1 def isEmpty(self) -> bool: return len(self.deque) == 0 def isFull(self) -> bool: return len(self.deque) == self.k # Your MyCircularDeque object will be instantiated and called as such: # obj = MyCircularDeque(k) # param_1 = obj.insertFront(value) # param_2 = obj.insertLast(value) # param_3 = obj.deleteFront() # param_4 = obj.deleteLast() # param_5 = obj.getFront() # param_6 = obj.getRear() # param_7 = obj.isEmpty() # param_8 = obj.isFull()
//! Implementation of compiling the compiler and standard library, in "check"-based modes. use crate::core::build_steps::compile::{ add_to_sysroot, run_cargo, rustc_cargo, rustc_cargo_env, std_cargo, }; use crate::core::build_steps::tool::{prepare_tool_cargo, SourceType}; use crate::core::builder::{ self, crate_description, Alias, Builder, Kind, RunConfig, ShouldRun, Step, }; use crate::core::config::TargetSelection; use crate::{Compiler, Mode, Subcommand}; use std::path::{Path, PathBuf}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Std { pub target: TargetSelection, /// Whether to build only a subset of crates. /// /// This shouldn't be used from other steps; see the comment on [`compile::Rustc`]. /// /// [`compile::Rustc`]: crate::core::build_steps::compile::Rustc crates: Vec<String>, } /// Returns args for the subcommand itself (not for cargo) fn args(builder: &Builder<'_>) -> Vec<String> { fn strings<'a>(arr: &'a [&str]) -> impl Iterator<Item = String> + 'a { arr.iter().copied().map(String::from) } if let Subcommand::Clippy { fix, allow_dirty, allow_staged, allow, deny, warn, forbid } = &builder.config.cmd { // disable the most spammy clippy lints let ignored_lints = [ "many_single_char_names", // there are a lot in stdarch "collapsible_if", "type_complexity", "missing_safety_doc", // almost 3K warnings "too_many_arguments", "needless_lifetimes", // people want to keep the lifetimes "wrong_self_convention", ]; let mut args = vec![]; if *fix { #[rustfmt::skip] args.extend(strings(&[ "--fix", "-Zunstable-options", // FIXME: currently, `--fix` gives an error while checking tests for libtest, // possibly because libtest is not yet built in the sysroot. // As a workaround, avoid checking tests and benches when passed --fix. "--lib", "--bins", "--examples", ])); if *allow_dirty { args.push("--allow-dirty".to_owned()); } if *allow_staged { args.push("--allow-staged".to_owned()); } } args.extend(strings(&["--"])); if deny.is_empty() && forbid.is_empty() { args.extend(strings(&["--cap-lints", "warn"])); } let all_args = std::env::args().collect::<Vec<_>>(); args.extend(get_clippy_rules_in_order(&all_args, allow, deny, warn, forbid)); args.extend(ignored_lints.iter().map(|lint| format!("-Aclippy::{}", lint))); args.extend(builder.config.free_args.clone()); args } else { builder.config.free_args.clone() } } /// We need to keep the order of the given clippy lint rules before passing them. /// Since clap doesn't offer any useful interface for this purpose out of the box, /// we have to handle it manually. pub(crate) fn get_clippy_rules_in_order( all_args: &[String], allow_rules: &[String], deny_rules: &[String], warn_rules: &[String], forbid_rules: &[String], ) -> Vec<String> { let mut result = vec![]; for (prefix, item) in [("-A", allow_rules), ("-D", deny_rules), ("-W", warn_rules), ("-F", forbid_rules)] { item.iter().for_each(|v| { let rule = format!("{prefix}{v}"); let position = all_args.iter().position(|t| t == &rule).unwrap(); result.push((position, rule)); }); } result.sort_by_key(|&(position, _)| position); result.into_iter().map(|v| v.1).collect() } fn cargo_subcommand(kind: Kind) -> &'static str { match kind { Kind::Check => "check", Kind::Clippy => "clippy", Kind::Fix => "fix", _ => unreachable!(), } } impl Std { pub fn new(target: TargetSelection) -> Self { Self { target, crates: vec![] } } } impl Step for Std { type Output = (); const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { run.crate_or_deps("sysroot").path("library") } fn make_run(run: RunConfig<'_>) { let crates = run.make_run_crates(Alias::Library); run.builder.ensure(Std { target: run.target, crates }); } fn run(self, builder: &Builder<'_>) { builder.update_submodule(&Path::new("library").join("stdarch")); let target = self.target; let compiler = builder.compiler(builder.top_stage, builder.config.build); let mut cargo = builder::Cargo::new( builder, compiler, Mode::Std, SourceType::InTree, target, cargo_subcommand(builder.kind), ); std_cargo(builder, target, compiler.stage, &mut cargo); if matches!(builder.config.cmd, Subcommand::Fix { .. }) { // By default, cargo tries to fix all targets. Tell it not to fix tests until we've added `test` to the sysroot. cargo.arg("--lib"); } for krate in &*self.crates { cargo.arg("-p").arg(krate); } let _guard = builder.msg_check( format_args!("library artifacts{}", crate_description(&self.crates)), target, ); run_cargo( builder, cargo, args(builder), &libstd_stamp(builder, compiler, target), vec![], true, false, ); // We skip populating the sysroot in non-zero stage because that'll lead // to rlib/rmeta conflicts if std gets built during this session. if compiler.stage == 0 { let libdir = builder.sysroot_libdir(compiler, target); let hostdir = builder.sysroot_libdir(compiler, compiler.host); add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target)); } drop(_guard); // don't run on std twice with x.py clippy // don't check test dependencies if we haven't built libtest if builder.kind == Kind::Clippy || !self.crates.iter().any(|krate| krate == "test") { return; } // Then run cargo again, once we've put the rmeta files for the library // crates into the sysroot. This is needed because e.g., core's tests // depend on `libtest` -- Cargo presumes it will exist, but it doesn't // since we initialize with an empty sysroot. // // Currently only the "libtest" tree of crates does this. let mut cargo = builder::Cargo::new( builder, compiler, Mode::Std, SourceType::InTree, target, cargo_subcommand(builder.kind), ); // If we're not in stage 0, tests and examples will fail to compile // from `core` definitions being loaded from two different `libcore` // .rmeta and .rlib files. if compiler.stage == 0 { cargo.arg("--all-targets"); } std_cargo(builder, target, compiler.stage, &mut cargo); // Explicitly pass -p for all dependencies krates -- this will force cargo // to also check the tests/benches/examples for these crates, rather // than just the leaf crate. for krate in &*self.crates { cargo.arg("-p").arg(krate); } let _guard = builder.msg_check("library test/bench/example targets", target); run_cargo( builder, cargo, args(builder), &libstd_test_stamp(builder, compiler, target), vec![], true, false, ); } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Rustc { pub target: TargetSelection, /// Whether to build only a subset of crates. /// /// This shouldn't be used from other steps; see the comment on [`compile::Rustc`]. /// /// [`compile::Rustc`]: crate::core::build_steps::compile::Rustc crates: Vec<String>, } impl Rustc { pub fn new(target: TargetSelection, builder: &Builder<'_>) -> Self { let crates = builder .in_tree_crates("rustc-main", Some(target)) .into_iter() .map(|krate| krate.name.to_string()) .collect(); Self { target, crates } } } impl Step for Rustc { type Output = (); const ONLY_HOSTS: bool = true; const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { run.crate_or_deps("rustc-main").path("compiler") } fn make_run(run: RunConfig<'_>) { let crates = run.make_run_crates(Alias::Compiler); run.builder.ensure(Rustc { target: run.target, crates }); } /// Builds the compiler. /// /// This will build the compiler for a particular stage of the build using /// the `compiler` targeting the `target` architecture. The artifacts /// created will also be linked into the sysroot directory. fn run(self, builder: &Builder<'_>) { let compiler = builder.compiler(builder.top_stage, builder.config.build); let target = self.target; if compiler.stage != 0 { // If we're not in stage 0, then we won't have a std from the beta // compiler around. That means we need to make sure there's one in // the sysroot for the compiler to find. Otherwise, we're going to // fail when building crates that need to generate code (e.g., build // scripts and their dependencies). builder.ensure(crate::core::build_steps::compile::Std::new(compiler, compiler.host)); builder.ensure(crate::core::build_steps::compile::Std::new(compiler, target)); } else { builder.ensure(Std::new(target)); } let mut cargo = builder::Cargo::new( builder, compiler, Mode::Rustc, SourceType::InTree, target, cargo_subcommand(builder.kind), ); rustc_cargo(builder, &mut cargo, target, compiler.stage); // For ./x.py clippy, don't run with --all-targets because // linting tests and benchmarks can produce very noisy results if builder.kind != Kind::Clippy { cargo.arg("--all-targets"); } // Explicitly pass -p for all compiler crates -- this will force cargo // to also check the tests/benches/examples for these crates, rather // than just the leaf crate. for krate in &*self.crates { cargo.arg("-p").arg(krate); } let _guard = builder.msg_check( format_args!("compiler artifacts{}", crate_description(&self.crates)), target, ); run_cargo( builder, cargo, args(builder), &librustc_stamp(builder, compiler, target), vec![], true, false, ); let libdir = builder.sysroot_libdir(compiler, target); let hostdir = builder.sysroot_libdir(compiler, compiler.host); add_to_sysroot(builder, &libdir, &hostdir, &librustc_stamp(builder, compiler, target)); } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct CodegenBackend { pub target: TargetSelection, pub backend: &'static str, } impl Step for CodegenBackend { type Output = (); const ONLY_HOSTS: bool = true; const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { run.paths(&["compiler/rustc_codegen_cranelift", "compiler/rustc_codegen_gcc"]) } fn make_run(run: RunConfig<'_>) { for &backend in &["cranelift", "gcc"] { run.builder.ensure(CodegenBackend { target: run.target, backend }); } } fn run(self, builder: &Builder<'_>) { // FIXME: remove once https://github.com/rust-lang/rust/issues/112393 is resolved if builder.build.config.vendor && self.backend == "gcc" { println!("Skipping checking of `rustc_codegen_gcc` with vendoring enabled."); return; } let compiler = builder.compiler(builder.top_stage, builder.config.build); let target = self.target; let backend = self.backend; builder.ensure(Rustc::new(target, builder)); let mut cargo = builder::Cargo::new( builder, compiler, Mode::Codegen, SourceType::InTree, target, cargo_subcommand(builder.kind), ); cargo .arg("--manifest-path") .arg(builder.src.join(format!("compiler/rustc_codegen_{backend}/Cargo.toml"))); rustc_cargo_env(builder, &mut cargo, target, compiler.stage); let _guard = builder.msg_check(backend, target); run_cargo( builder, cargo, args(builder), &codegen_backend_stamp(builder, compiler, target, backend), vec![], true, false, ); } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct RustAnalyzer { pub target: TargetSelection, } impl Step for RustAnalyzer { type Output = (); const ONLY_HOSTS: bool = true; const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let builder = run.builder; run.path("src/tools/rust-analyzer").default_condition( builder .config .tools .as_ref() .map_or(true, |tools| tools.iter().any(|tool| tool == "rust-analyzer")), ) } fn make_run(run: RunConfig<'_>) { run.builder.ensure(RustAnalyzer { target: run.target }); } fn run(self, builder: &Builder<'_>) { let compiler = builder.compiler(builder.top_stage, builder.config.build); let target = self.target; builder.ensure(Rustc::new(target, builder)); let mut cargo = prepare_tool_cargo( builder, compiler, Mode::ToolRustc, target, cargo_subcommand(builder.kind), "src/tools/rust-analyzer", SourceType::InTree, &["in-rust-tree".to_owned()], ); cargo.allow_features(crate::core::build_steps::tool::RustAnalyzer::ALLOW_FEATURES); // For ./x.py clippy, don't check those targets because // linting tests and benchmarks can produce very noisy results if builder.kind != Kind::Clippy { // can't use `--all-targets` because `--examples` doesn't work well cargo.arg("--bins"); cargo.arg("--tests"); cargo.arg("--benches"); } let _guard = builder.msg_check("rust-analyzer artifacts", target); run_cargo( builder, cargo, args(builder), &stamp(builder, compiler, target), vec![], true, false, ); /// Cargo's output path in a given stage, compiled by a particular /// compiler for the specified target. fn stamp(builder: &Builder<'_>, compiler: Compiler, target: TargetSelection) -> PathBuf { builder.cargo_out(compiler, Mode::ToolRustc, target).join(".rust-analyzer-check.stamp") } } } macro_rules! tool_check_step { ($name:ident, $path:literal, $($alias:literal, )* $source_type:path $(, $default:literal )?) => { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct $name { pub target: TargetSelection, } impl Step for $name { type Output = (); const ONLY_HOSTS: bool = true; // don't ever check out-of-tree tools by default, they'll fail when toolstate is broken const DEFAULT: bool = matches!($source_type, SourceType::InTree) $( && $default )?; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { run.paths(&[ $path, $($alias),* ]) } fn make_run(run: RunConfig<'_>) { run.builder.ensure($name { target: run.target }); } fn run(self, builder: &Builder<'_>) { let compiler = builder.compiler(builder.top_stage, builder.config.build); let target = self.target; builder.ensure(Rustc::new(target, builder)); let mut cargo = prepare_tool_cargo( builder, compiler, Mode::ToolRustc, target, cargo_subcommand(builder.kind), $path, $source_type, &[], ); // For ./x.py clippy, don't run with --all-targets because // linting tests and benchmarks can produce very noisy results if builder.kind != Kind::Clippy { cargo.arg("--all-targets"); } let _guard = builder.msg_check(&concat!(stringify!($name), " artifacts").to_lowercase(), target); run_cargo( builder, cargo, args(builder), &stamp(builder, compiler, target), vec![], true, false, ); /// Cargo's output path in a given stage, compiled by a particular /// compiler for the specified target. fn stamp( builder: &Builder<'_>, compiler: Compiler, target: TargetSelection, ) -> PathBuf { builder .cargo_out(compiler, Mode::ToolRustc, target) .join(format!(".{}-check.stamp", stringify!($name).to_lowercase())) } } } }; } tool_check_step!(Rustdoc, "src/tools/rustdoc", "src/librustdoc", SourceType::InTree); // Clippy, miri and Rustfmt are hybrids. They are external tools, but use a git subtree instead // of a submodule. Since the SourceType only drives the deny-warnings // behavior, treat it as in-tree so that any new warnings in clippy will be // rejected. tool_check_step!(Clippy, "src/tools/clippy", SourceType::InTree); tool_check_step!(Miri, "src/tools/miri", SourceType::InTree); tool_check_step!(CargoMiri, "src/tools/miri/cargo-miri", SourceType::InTree); tool_check_step!(Rls, "src/tools/rls", SourceType::InTree); tool_check_step!(Rustfmt, "src/tools/rustfmt", SourceType::InTree); tool_check_step!(MiroptTestTools, "src/tools/miropt-test-tools", SourceType::InTree); tool_check_step!(Bootstrap, "src/bootstrap", SourceType::InTree, false); /// Cargo's output path for the standard library in a given stage, compiled /// by a particular compiler for the specified target. fn libstd_stamp(builder: &Builder<'_>, compiler: Compiler, target: TargetSelection) -> PathBuf { builder.cargo_out(compiler, Mode::Std, target).join(".libstd-check.stamp") } /// Cargo's output path for the standard library in a given stage, compiled /// by a particular compiler for the specified target. fn libstd_test_stamp( builder: &Builder<'_>, compiler: Compiler, target: TargetSelection, ) -> PathBuf { builder.cargo_out(compiler, Mode::Std, target).join(".libstd-check-test.stamp") } /// Cargo's output path for librustc in a given stage, compiled by a particular /// compiler for the specified target. fn librustc_stamp(builder: &Builder<'_>, compiler: Compiler, target: TargetSelection) -> PathBuf { builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc-check.stamp") } /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular /// compiler for the specified target and backend. fn codegen_backend_stamp( builder: &Builder<'_>, compiler: Compiler, target: TargetSelection, backend: &str, ) -> PathBuf { builder .cargo_out(compiler, Mode::Codegen, target) .join(format!(".librustc_codegen_{backend}-check.stamp")) }
import React from "react"; import { NavLink } from "react-router-dom"; import { PRESS_RELEASES } from "../utils/releases"; interface IisReleasePageProp { width: string; alignItems?: string; justifyContent?: string; textAlign?: string; textSize: string; isReleasePage: boolean; } function News({ width, alignItems, justifyContent, textAlign, textSize, isReleasePage, }: IisReleasePageProp) { return ( <> {PRESS_RELEASES.map((release, idx) => { return ( <div key={idx} className={`${width} flex flex-col ${justifyContent} ${alignItems}`} > {isReleasePage && ( <div className="w-[250px] h-[150px]"> <img className="w-full h-full object-contain" src={require("../assets/releases/" + release.src + ".jpg")} alt={release.alt} /> </div> )} <h2 className={`${textAlign} ${textSize} font-semibold mt-2 mb-2 cursor-default underline underline-offset-4 hover:text-darkGreen`} > {release.title} </h2> <p className="text-darkGray text-xs"> <NavLink className="hover:font-semibold" to={release.url} target="_blank" rel="noopener noreferrer" > Read More </NavLink> </p> </div> ); })} </> ); } export default News;
import React, {useEffect, useState} from 'react'; import Recipe from './Recipe'; import './App.css'; import { async } from 'q'; const App = () => { const APP_ID = '797ce1b3'; const APP_KEY = 'bae97fb6d6745d4fd78182ee4f42906d'; const [recipes, setRecipes] = useState([]); const [search, setSearch] = useState(''); const [query, setQuery] = useState('chicken'); useEffect(() => { getRecipes(); }, [query] ); const getRecipes = async () => { const response = await fetch( `https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`); const data = await response.json(); setRecipes(data.hits); // recipes = data.hits console.log(data.hits); } const updateSearch = e => { setSearch(e.target.value); } const getSearch = e => { e.preventDefault(); // this prevents the page refresh setQuery(search); setSearch(''); // this clears the form after every search } return ( <div className="App"> <form onSubmit={getSearch} className="search-form"> <input className="search-bar" type="text" value={search} onChange={updateSearch}/> <button className="search-button" type="submit">Search</button> </form> <div className="recipes"> {recipes.map(recipe =>( <Recipe key={recipe.recipe.label} title={recipe.recipe.label} calories={recipe.recipe.calories} image={recipe.recipe.image} ingredients={recipe.recipe.ingredients} /> ))} </div> </div> ); } // https://www.edamam.com/ export default App;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/shop_style.css"> <link rel="stylesheet" href="assets/checkout_style.css"> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script> <script src="https://kit.fontawesome.com/919d4b6d44.js" crossorigin="anonymous"></script> </head> <body> <!-- Navbar Start --> <nav class="navbar navbar-expand-lg navbar-dark sticky-top"> <div class="container"> <!-- Brand --> <a href="index.html" class="navbar-brand d-flex justify-content-between align-items-center order-lg-0"> <img src="assets/images/logo.png" alt="" class="navbar-brand"> <h1 class="navbar-header">ICEBORN</h1> </a> <!-- Nav Icon Buttons --> <div class="order-lg-2"> <a href="checkout.html" class="checkout-link"> <button type="button" class="btn text-light position-relative"> <i class="fa-solid fa-cart-shopping nav-link"></i> <span class="position-absolute start-100 translate-middle badge bg-primary text-dark">3</span> </button> </a> <button type="button" class="search-button btn text-light position-relative"> <i class="fa-solid fa-heart nav-link"></i> <span class="position-absolute start-100 translate-middle badge bg-primary text-dark">2</span> </button class="btn text-light position-relative" > </div> <!-- Nav Menu / Toggle Menu --> <button class="navbar-toggler border-0" type="button" data-bs-toggle="collapse" data-bs-target="#nav-menu"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse order-lg-1" id="nav-menu"> <ul class="navbar-nav mx-auto text-center"> <li class="nav-item p-2"> <a href="index.html" class="nav-link">Overview</a> </li> <li class="nav-item p-2"> <a href="shop.html" class="nav-link">Shop</a> </li> <li class="nav-item p-2"> <a href="#about" class="nav-link">About Iceborn</a> </li> </ul> </div> </div> </nav> <!-- Navbar End --> <!-- Checkout Form Start --> <div class="checkout-container container"> <main> <div class="py-5 text-center"> <h2 class="checkout-header">Checkout Form</h2> <p class="lead">Please fill up the necessary details below in order to purchase with Iceborn</p> </div> <div class="row g-5"> <!-- Billing Summary Start --> <div class="col-md-5 col-lg-4 order-md-last"> <h4 class="d-flex justify-content-between align-items-center mb-3"> <span class="bil-sum-label text-primary">Your Cart</span> <span class="badge bg-primary rounded-pill">3</span> </h4> <ul class="list-group mb-3"> <li class="list-group-item d-flex justify-content-between lh-sm"> <div> <h6 class="my-0">Liss Bag</h6> <span class="text-muted small">Stocks Available</span> </div> <span class="text-muted">&dollar; 3.75</span> </li> <li class="list-group-item d-flex justify-content-between lh-sm"> <div> <h6 class="my-0">Iceborn T-Shirt</h6> <span class="text-muted small">Stocks Available</span> </div> <span class="text-muted">&dollar; 5.00</span> </li> <li class="list-group-item d-flex justify-content-between lh-sm"> <div> <h6 class="my-0">Liss Poster</h6> <span class="text-muted small">Stocks Available</span> </div> <span class="text-muted">&dollar; 10.00</span> </li> <li class="highlighted-item list-group-item d-flex justify-content-between bg-light"> <div class="text-success"> <h6 class="promo-header my-0">Promo Code</h6> <span class="promo-text small"> IBORNBENEFITS </span> </div> <span class="promo-text text-success">- &dollar; 3.75</span> </li> <li class="list-group-item d-flex justify-content-between"> <span>Total (USD)</span> <span class="fw-bold">&dollar; 15</span> </li> </ul> <form class="card p-2"> <div class="input-group"> <input type="text" class="form-control" placeholder="Promo Code"> <button type="submit" class="btn-redeem btn btn-primary">Redeem</button> </div> </form> </div> <!-- Billing Summary End --> <!-- Billing Form Start --> <div class="col-md-7 col-lg-8"> <h4 class="bill-form-label mb-3">Billing Address</h4> <form action="#" class="needs-validation"> <div class="row g-3"> <div class="col-sm-6"> <label for="firstName" class="form-label">First name</label> <input type="text" class="form-control" id="firstName" placeholder="Juan" required> <div class="invalid-feedback"> Valid first name is required. </div> </div> <div class="col-sm-6"> <label for="lastName" class="form-label">Last name</label> <input type="text" class="form-control" id="lastName" placeholder="Dela Cruz" required> <div class="invalid-feedback"> Valid last name is required. </div> </div> <div class="col-12"> <label for="address" class="form-label">Address</label> <input type="text" class="form-control" id="address" placeholder="House Number, Street, Barangay, City/Municipality & Province" required> <div class="invalid-feedback"> Please enter your shipping address. </div> </div> <div class="col-4"> <label for="cxRegion">Region: </label> <select name="cxRegion" id="cxRegion" class="form-select"> <option value="NCR" title="National Capital Region">NCR</option> <option value="CAR" title="Cordillera Administrative Region">CAR</option> <option value="BARMM" title="Bangsamoro Autonomous Region in Muslim Mindanao">BARMM</option> <option value="region1" title="Ilocos Region">Region I</option> <option value="region2" title="Cagayan Valley">Region II</option> <option value="region3" title="Central Luzon">Region III</option> <option value="region4A" title="CALABARZON">Region IV-A</option> <option value="region4B" title="MIMAROPA">Region IV-B</option> <option value="region5" title="Bicol Region">Region V</option> <option value="region6" title="Western Visayas">Region VI</option> <option value="region7" title="Central Visayas">Region VII</option> <option value="region8" title="Eastern Visayas">Region VIII</option> <option value="region9" title="Zamboanga Peninsula">Region IX</option> <option value="region10" title="Northern Mindanao">Region X</option> <option value="region11" title="Davao Region">Region XI</option> <option value="region12" title="SOCCSKSARGEN">Region XII</option> <option value="region13" title="Caraga">Region XIII</option> </select> </div> <div class="col-8"> <label for="cxNum">Contact Number: </label> <input type="tel" id="cxNum" name="cxNum" class="form-control" pattern="[0]{1}[9]{1}[0-9]{9}" placeholder="Please enter your 11-digit mobile no., ex.(09123456789)"required> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="save-info"> <label class="form-check-label" for="save-info">Save this information for next time</label> </div> <hr class="my-4"> <h4 class="payment-label mb-3">Payment</h4> <div class="my-3"> <div class="form-check"> <div class="payment-select"> <input type="radio" id="cOD" name="paymentMethod" value="coD" class="form-check-input" checked required> <label for="cOD">Cash on Delivery</label> </div> <div class="payment-select"> <input type="radio" id="masterCard" name="paymentMethod" value="masterCard" class="form-check-input" checked required> <label for="masterCard">Master Card</label> </div> <div class="payment-select"> <input type="radio" id="visa" name="paymentMethod" value="visa" class="form-check-input" checked required> <label for="visa">Visa</label> </div> <div class="payment-select"> <input type="radio" id="payPal" name="paymentMethod" value="payPal" class="form-check-input" checked required> <label for="americanEx">Paypal</label> </div> </div> </div> <hr class="my-4"> <button class="btn-checkout w-100 mb-4 btn btn-primary btn-lg" type="submit">Continue to checkout</button> </form> <!-- Billing Form End --> </div> </div> </main> </div> <!-- Checkout Form End --> <!-- Footer Start --> <footer class="footer p-4 pb-1 bg-dark text-white text-center position-relative" id="about"> <div class="container"> <div class="footer-content"> <h3 class="pb-2">Iceborn</h3> <p class="pb-1"> For gamers. By gamers.</p> <p> Contact us here:</p> <ul class="footer-social d-flex justify-content-center align-items-center"> <li><a href="#" class="text-light"><i class="fa fa-facebook"></i></a></li> <li><a href="#" class="text-light"><i class="fa fa-twitter"></i></a></li> <li><a href="#" class="text-light"><i class="fa fa-google-plus"></i></a></li> <li><a href="#" class="text-light"><i class="fa fa-youtube"></i></a></li> <li><a href="#" class="text-light"><i class="fa fa-linkedin-square"></i></a><li> </ul> </div> <p>Iceborn isn’t endorsed by Riot Games and doesn’t reflect the views or opinions of Riot Games or anyone officially involved in producing or managing League of Legends. League of Legends™ and Riot Games are trademarks or registered trademarks of Riot Games, Inc.</p> <div class="footer-copyright"> <p> Copyright &copy;2023 Iceborn. Designed By <span class="opacity-50 font-weight-bold">JDC</span></p> </div> </div> </footer> <!-- Footer End --> </body> </html>
--- title: "[백준] 🥈 1940 주몽" excerpt: "실력향상을 위한 백준 문제 및 풀이" categories: - BaekJoon tags: - ["1940", 주몽, Two Pointer, Java, Coding_Test, Coding, Test, baekJoon, 백준] toc: true toc_sticky: true date: 2023-02-02 last_modified_at: 2023-02-04 --- ## 📌 난이도 🥈 Silver 4 <br> ## 📌 문제 <https://www.acmicpc.net/problem/1940> <br> ![image](https://user-images.githubusercontent.com/37824506/216262254-fd1ac437-f29d-4e80-b6aa-062a872a4a90.png) <br> ## 📌 풀이 분명히 `Two Pointer`를 사용하여 푸는 문제이지만, 그렇게 안하고 **O(n x log(n))** 정도의 시간복잡도를 가진 `for`문을 통해 해결하였다. 간단하게 **0-n** 까지의 i값과 **i-n** 까지의 j값을 통한 이중 `for`문으로 해결하였다. 자바로 문제를 풀어서 생각보다 시간이 널널했던 것 같다. <br> ## 📌 Code ```java package TwoPointer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class N1940 { static int[] material; static int count; static int target; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); count = Integer.parseInt(br.readLine()); target = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); material = new int[count]; for (int i = 0; i < count; i++) { material[i] = Integer.parseInt(st.nextToken()); } MakeArmor(); } public static void MakeArmor() { int result = 0; for (int i = 0; i < count; i++) { for (int j = i + 1; j < count; j++) { if (material[i] + material[j] == target) { result += 1; break; } } } System.out.println(result); } } ``` package (이름); 를 때고, class 이름을 `Main`으로 변경하면 된다. {: .notice} <br> *** 개인 공부 기록용 블로그입니다. 틀리거나 오류가 있을 경우 제보해주시면 감사하겠습니다.😁
// // UIButtonContent.swift // Swiftent // // Created by Dmitry Fa[n]tastik on 18/07/2016. // Copyright © 2016 Fantastik Solution. All rights reserved. // import Foundation public struct UIButtonContent { let normal : UIButtonStateContent? let highlighted : UIButtonStateContent? let disabled : UIButtonStateContent? let selected : UIButtonStateContent? public init(normal: UIButtonStateContent?, highlighted: UIButtonStateContent?, disabled: UIButtonStateContent?, selected: UIButtonStateContent?) { self.normal = normal self.highlighted = highlighted self.disabled = disabled self.selected = selected } public init(normal: UIButtonStateContent?) { self.normal = normal self.highlighted = nil self.disabled = nil self.selected = nil } public init(normal: UIButtonStateContent?, selected: UIButtonStateContent?) { self.normal = normal self.selected = selected self.disabled = nil self.highlighted = nil } } public struct UIButtonStateContent { let text : Text let image : UIImage? let titleColor : UIColor? = nil let titleShadowColor : UIColor? = nil let backgroundImage : UIImage? = nil public init(text: Text, image: UIImage?) { self.text = text self.image = image } public init(text: Text) { self.text = text self.image = nil } public init(image: UIImage?) { self.text = Text.Raw(nil) self.image = image } public static let None = UIButtonStateContent(text: Text.Raw(nil), image: nil) }
{{noteTA |G1=IT }} {{copyedit|time=2010-08-21T08:41:04+00:00}} {{other uses}} {{Infobox OS | name = bada | logo = [[File:bada_logo_1.png|150px]] | screenshot = [[File:Bada.svg|150px]] | caption = | developer = [[三星電子|三星電子]] | family = [[POSIX|POSIX]] | working state = 停止(由[[Tizen|Tizen]]代替) | source model = | latest release version = 2.0.6 SDK | latest release date = {{Start date and age |2013|02|28}} | frequently updated = 無 | marketing target = [[智能手機|智能手機]] | language = [[多語言|多語言]] | programmed_in = [[C++|C++]]<ref>{{cite web |url=http://www.lextrait.com/Vincent/implementations.html |title=The Programming Languages Beacon |edition=10.0 |first=Vincent |last=Lextrait |date=January 2010 |accessdate=January 5, 2010 |archive-url=https://archive.is/20120530/http://www.lextrait.com/Vincent/implementations.html |archive-date=2012-05-30 |dead-url=yes }}</ref> | updatemodel = | package manager = [[Samsung_Kies|Samsung Kies]] | kernel type = [[專有軟件|專利]]或[[Linux_kernel|Linux kernel]] | ui = [[TouchWiz|TouchWiz]] | license = [[專有軟件|專利]] | website = {{URL |http://www.bada.com/}} }} {{Infobox Korean name |title = bada | hangul = 바다 | rr = bada | mr = Pada }} '''bada'''({{lang-ko|바다}})是韩国[[三星電子|三星電子]]自行開發的[[智能手机|智能手机]]平台,底層為[[Linux核心|Linux核心]]。支援丰富功能和用户体验的软件应用,于2009年11月10日发布。bada在[[韩語|韩語]]裏是“[[海洋|海洋]]”({{lang|ko|바다}})的意思。<ref name="Electronista">{{cite news |title=Samsung launches bada open mobile OS |newspaper=Electonista |date=9 November 2009 |url=http://www.electronista.com/articles/09/11/09/samsung.bada.to.rival.android.linux/ |access-date=2009-11-30 |archive-url=https://web.archive.org/web/20091202171153/http://www.electronista.com/articles/09/11/09/samsung.bada.to.rival.android.linux |archive-date=2009-12-02 |dead-url=yes }}</ref> bada的设计目标是开创人人能用的智能手机的时代(Smartphone for Everyone)。<ref name="Samsung">{{cite web |url=http://www.bada.com/whatisbada/ |title=存档副本 |accessdate=2011-07-21 |deadurl=yes |archiveurl=https://web.archive.org/web/20110707204625/http://www.bada.com/whatisbada/ |archivedate=2011-07-07 }}</ref>它的特点是配置灵活、用户交互性佳、面向服务優。非常重视SNS整合和基于位置服务应用。 2013年2月27日,三星电子宣布终止bada系统的开发。 == 历史 == 第一部基于bada的手机——[[Samsung_Wave_S8500|Samsung Wave S8500]]。于2010年2月在[[MWC|MWC大会]]上推出。1GHz CPU,有[[TouchWiz|TouchWiz 3.0]]界面,[[AMOLED|SUPER AMOLED]]屏幕和无缝一体外壳。能够支援社交网络、设备同步、内容管理等,且支援Java程式。<ref>{{cite web |url=http://www.bada.com/badadevices/ |title=存档副本 |accessdate=2010-02-16 |deadurl=yes |archiveurl=https://web.archive.org/web/20101201175752/http://www.bada.com/badadevices/ |archivedate=2010-12-01 }}</ref> 此外,三星也为bada开放应用软件商店,并为第三方开发人员提供支持,截至2011年5月,已经有超过5000款支持的软件。<ref>{{Cite web |url=http://www.totaltele.com/view.aspx?ID=453260 |title=存档副本 |accessdate=2010-03-01 |archive-date=2010-02-27 |archive-url=https://web.archive.org/web/20100227083715/http://www.totaltele.com/view.aspx?ID=453260 |dead-url=no }}</ref>。 2012年1月17日,三星宣布將bada整合至[[Tizen|Tizen]]。<ref>{{cite news|url=http://news.cnyes.com/Content/20120117/KFHZDGPY1FGXU.shtml?c=pic|title=三星加快擺脫Android 拉攏英特爾合作OS|publisher=[[鉅亨網|鉅亨網]]|date=2012-01-17|language=zh-tw|deadurl=yes|archiveurl=https://web.archive.org/web/20130309001704/http://news.cnyes.com/Content/20120117/KFHZDGPY1FGXU.shtml?c=pic|archivedate=2013-03-09|accessdate=2021-02-05}}</ref> 2013年2月27日,三星在[[MWC|MWC大会]]上表示為了把流動業務進一步向[[Tizen|Tizen]]整合發展,決定終止對bada系統的開發,意味著所有運行bada的設備(例如三星Wave系列手機)將會全面停產和淡出市場。<ref>{{cite news|url=http://news.xinhuanet.com/tech/2013-02/27/c_124393954.htm|title=三星放弃自主操作系统bada 改用Tizen系统|publisher=[[新华网|新华网]]|date=2013-02-27|language=zh-cn|accessdate=2013-05-10|archive-date=2013-03-04|archive-url=https://web.archive.org/web/20130304155407/http://news.xinhuanet.com/tech/2013-02/27/c_124393954.htm|dead-url=no}}</ref> == 系统架构 == bada系统由[[操作系统|操作系统]]内核层、设备层、服务层和框架层组成。支持设备应用、服务应用和Web与Flash应用。其中: * 操作系统内核层:根据设备配置不同,可以是[[Linux操作系统|Linux操作系统]]或者其他[[实时操作系统|实时操作系统]]。 * 设备层:在操作系统之上提供设备平台的核心功能,包括系统和不安全管理、图形和窗口系统、数据协议、电话和视频音频多媒体管理等。 * 服务层:由应用引擎和Web服务组件组成,它们与bada[[服务器|服务器]]互联,提供以服务为中心的功能。 * 框架层:由应用框架和底层提供的函数组成,不为第三方开发者提供[[C++|C++]]开放API。 按bada首席架构师、三星手机副总裁[[Justin_Hong|Justin Hong]]的说法,设备层来自三星十年前开始开发的自有平台,而服务层和框架层的开发始于四年前。 在工具方面,bada使用[[Eclipse|Eclipse]]和[[GNU|GNU]]工具链。 == 市場份額 == {| class="wikitable" |- ! 年度 !! 全球銷量(%) !! 售出(百萬) |- | Q2 2013 || 0.4 || 0.84 |- | Q1 || 0.7 || 1.37 |- | Q4 2012 || 1.3 || 2.7 |- | Q3 || 3 || 5.2 |- | Q2 || 2.7 || 4.2 |- | Q1 || 2.7 || 3.8 |- | Q4 2011 || 2.1 || 3.1 |- | Q3 || 2.2 || 2.5 |- | Q2 || 1.9 || 2.1 |- | Q1 || 1.9 || 1.9 |- | Q4 2010 || 2.0 || 2.0 |- | Q3 || 1.1 || 0.9 |- | Q2 || 0.9 || 0.6 |} == 参考链接 == * [http://www.bada.com bada官方网站]*{{Wayback|url=http://www.bada.com/ |date=20100223093317 }} * [http://www.badadev.com/ badaDev]{{Wayback|url=http://www.badadev.com/ |date=20100307210848 }} == 注釋 == {{reflist}} {{智能手機操作系統}} [[Category:嵌入式操作系统|Category:嵌入式操作系统]] [[Category:Linux發行版|Category:Linux發行版]] [[Category:智能手機|Category:智能手機]] [[Category:三星軟體|Category:三星軟體]]
# # Copyright (c) 2017 # # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER # OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # @author Oriode # @date 02/08/2017 (DMY) # @file U4CollisionsTools.py # @brief Blender Addon for easy creation of collisions boxes for any Unreal4 project. bl_info = { "name": "U4 Collisions Tools", "author": "Oriode", "version": (1, 2), "blender": (2, 78, 0), "location": "View3D > Tools > U4 Collisions Tools", "description": "Tools for easy U4 Collisions Box creation in Blender.", "warning": "", "wiki_url": "", "tracker_url": "", "category": "Mesh", } # Import Librairies import bpy import math from mathutils import Vector from bpy.props import FloatVectorProperty import time import fnmatch import re from enum import Enum import copy # @brief Main Class class U4CollisionsTools( ): m_isCollisionRegex = re.compile('U(BX|CX|CP|SP)_') class CollisionType( Enum ): BOX = 0 SPHERE = 1 CAPSULE = 2 CONVEX = 3 SIMPLECONVEX = 4 CollisionsPrefixList = ( 'UBX_', 'USP_', 'UCP_', 'UCX_', 'UCX_' ) @staticmethod def getU4Prefix( collisionType ): return U4CollisionsTools.CollisionsPrefixList[ int(collisionType.value) ] # @brief Deselect all @staticmethod def deselectAll(): bpy.ops.object.select_all( action = 'DESELECT' ) @staticmethod def selectObjList( objList ): U4CollisionsTools.deselectAll() for obj in objList: obj.select = True @staticmethod def getChildren( ob ): def isParent(ob, c): if c.parent is not None: if c.parent.name == ob.name: return True else: return False return [c for c in bpy.data.objects if isParent(ob, c)] @staticmethod def getCollisions( obList ): return [obj for obj in obList if U4CollisionsTools.isCollisionBox( obj ) ] @staticmethod def deleteObjList( obList ): U4CollisionsTools.deselectAll() for obj in obList: obj.select = True bpy.ops.object.delete() @staticmethod def isCollisionBox( obj ): return ( U4CollisionsTools.m_isCollisionRegex.match( obj.name ) != None ) def deleteCollisionsBox( self, obj ): objChildList = self.getChildren( obj ) objCollisionsList = self.getCollisions( objChildList ) self.deleteObjList( objCollisionsList ) @staticmethod def setActive( obj ): U4CollisionsTools.deselectAll() # Deselect everything obj.select = True # Set 'obj' selected bpy.context.scene.objects.active = obj # Set 'obj' as the active object @staticmethod def getActive(): return bpy.context.scene.objects.active # @brief Get the selected objects list # @return List of selected objects @staticmethod def getSelectedObj(): return bpy.context.selected_objects # @brief Add a modifier to a specific object # @param obj Object to add a modifier # @param modifierType Type of the modifier to add # @param modifierName Name of the modifier to add # @return modifier just added # @see https://docs.blender.org/api/blender_python_api_current/bpy.types.ObjectModifiers.html#bpy.types.ObjectModifiers @staticmethod def addModifier( obj, modifierType, modifierName ): return obj.modifiers.new( modifierName, modifierType) # @brief Retrieve the 3D cursor position # @return Vector of position of the 3D cursor # @see https://blender.stackexchange.com/questions/39291/get-current-scene-on-blender-2-74-using-python @staticmethod def get3DCursorPos(): currentScene = bpy.context.scene currentSpace = bpy.context.space_data return ( currentSpace if currentSpace and currentSpace.type == 'VIEW_3D' else currentScene ).cursor_location # @brief Set the 3D cursor position # @param pos Vector of position of the 3D cursor # @see https://blender.stackexchange.com/questions/39291/get-current-scene-on-blender-2-74-using-python @staticmethod def set3DCursorPos( pos ): currentScene = bpy.context.scene currentSpace = bpy.context.space_data ( currentSpace if currentSpace and currentSpace.type == 'VIEW_3D' else currentScene ).cursor_location = pos # @brief Apply a modifier to it's associated object # @param obj Object # @param mod Modifier to be aplied @staticmethod def applyModifier( obj, mod ): self.setActive( obj ) bpy.ops.object.modifier_apply( apply_as = 'DATA', modifier = mod.name ) @staticmethod def setVisibleLayer( num ): for i in range(20): if i == num: bpy.context.space_data.layers[i] = True else: bpy.context.space_data.layers[i] = False @staticmethod def setVisibleLayers( boolList ): bpy.context.space_data.layers = boolList @staticmethod def getVisibleLayers(): return bpy.context.space_data.layers @staticmethod def isInVisibleLayer( obj ): visibleLayers = U4CollisionsTools.getVisibleLayers() for i in range(20): if obj.layers[i] == True and visibleLayers[i] == True: return True return False @staticmethod def deleteDegenerate(): objList = [ obj for obj in bpy.data.objects if obj.type == 'MESH' and ( obj.data == None or len( obj.data.vertices ) == 0 ) ] U4CollisionsTools.selectObjList( objList ) bpy.ops.object.delete() # @brief Create collisions boxes using the U4 template from a specific object list # @param objList List of objects to create collisions boxes # @param collisionType type of the Collision primitive to create # @param multipleOnArray Create multiple Boxes for the Array modifier # @param multipleOnMirror Create multiple Boxes for the Mirror modifier # @param scaleMult multiplier of the scale of Collisions boxes # @param convexComplexity Complexity of resulting convex shape (only used if collisionType == CONVEX) # @return List of Collisions Boxes freshly created def createCollisionsBoxes( self, objList, collisionType, multipleOnArray = True, multipleOnMirror = True, scaleMult = 1.0, convexComplexity = 10.0 ): # Check if we have a type we can handle if collisionType != self.CollisionType.BOX and collisionType != self.CollisionType.SPHERE and collisionType != self.CollisionType.SIMPLECONVEX and collisionType != self.CollisionType.CONVEX: return [] # Ensure we can handle every objects selected objList = [ obj for obj in objList if self.isCollisionBox( obj ) == False and obj.hide_select == False and obj.hide == False and obj.type == 'MESH' and self.isInVisibleLayer( obj ) ] # If we have no object, work completed if len( objList ) == 0: return [] # if we have no active if self.getActive() == None: self.report({'ERROR'}, 'No Active object.') return [] obj = self.getActive() # Save the current 3D Cursor position init3DCursorPosition = Vector( self.get3DCursorPos() ) collisionsBoxesList = [] # Duplicate the object to work on a copy bpy.ops.object.duplicate( linked = False, mode = 'TRANSLATION' ) objListCopy = self.getSelectedObj() objCopy = self.getActive() # Remove constraints for objCopyTmp in objListCopy: for constraint in objCopyTmp.constraints: if constraint.type == 'COPY_TRANSFORMS' or constraint.type == 'COPY_LOCATION': objConstraint = objCopyTmp foundedFinalObject = False while foundedFinalObject == False: noConstraint = False for constraint2 in objConstraint.constraints: if constraint2.type == constraint.type: objConstraint = constraint2.target noConstraint = True break if noConstraint == False: foundedFinalObject = True objCopyTmp.location = objConstraint.location objCopyTmp.constraints.remove( constraint ) if len( objListCopy ) > 1: # Apply visible modifiers for objCopyTmp in objListCopy: for modifier in objCopyTmp.modifiers: if modifier.show_viewport: self.setActive( objCopyTmp ) bpy.ops.object.modifier_apply( apply_as = 'DATA', modifier = modifier.name ) # Join all the copies self.selectObjList( objListCopy ) bpy.context.scene.objects.active = objCopy # Set 'objCopy' as the active object bpy.ops.object.join() objCopy = self.getActive() # Save the reference of the freshly created copy. objCopy.name = 'U4CT.tmp' # Because we wants to work in World Space, clear parenting bpy.ops.object.parent_clear( type = 'CLEAR_KEEP_TRANSFORM' ) bpy.ops.object.duplicate( linked = False, mode = 'TRANSLATION' ) objCopy2 = self.getActive() # Save the reference of the freshly created copy. objCopy2.name = 'U4CT.tmp2' # Delete all the already existing Collisions Boxes for 'obj' self.deleteCollisionsBox( obj ) # Disable Mirror and Array for a correct Collision Box self.setActive( objCopy ) for modifier in objCopy.modifiers: if modifier.show_viewport == False: bpy.ops.object.modifier_remove( modifier = modifier.name ) if modifier.type == 'ARRAY': if multipleOnArray == True: modifier.show_viewport = False modifier.use_merge_vertices = False else: bpy.ops.object.modifier_apply( apply_as = 'DATA', modifier = modifier.name ) elif modifier.type == 'MIRROR': if multipleOnMirror == True: modifier.show_viewport = False modifier.use_mirror_merge = False else: bpy.ops.object.modifier_apply( apply_as = 'DATA', modifier = modifier.name ) else: bpy.ops.object.modifier_apply( apply_as = 'DATA', modifier = modifier.name ) objCopy.rotation_euler = ( 0.0, 0.0, 0.0 ) # Ensure everything is enabled objCopy.lock_location = ( False, False, False ) objCopy.lock_scale = ( False, False, False ) objCopy.lock_rotation = ( False, False, False ) # Set the 3D cursor to the origin of our object self.setActive( objCopy ) bpy.ops.view3d.snap_cursor_to_selected() initObjPositionWS = Vector( self.get3DCursorPos() ) # Set the origin at the center of mass (Because it's the easiest way to retrieve the center of mass of a mesh) bpy.ops.object.origin_set( type = 'ORIGIN_GEOMETRY', center = 'BOUNDS' ) bpy.context.scene.update() # Update the context to recompute the dimensions initObjScaleWS = Vector( objCopy.scale ) # We will use the 3D Cursor for placing the new box at the right position (Copying the position won't work in case of parenting) bpy.ops.view3d.snap_cursor_to_selected() relativePos = self.get3DCursorPos() - initObjPositionWS if collisionType == self.CollisionType.BOX: bpy.ops.mesh.primitive_cube_add() elif collisionType == self.CollisionType.SPHERE: # Apply scale transformation on objCopy because we will use the mesh to compute the bounding sphere bpy.ops.object.transform_apply( location = False, rotation = False, scale = True ) newRadius = 0.0 for vertex in objCopy.data.vertices: v = vertex.co #v[0] *= initObjScaleWS.x #v[1] *= initObjScaleWS.y #v[2] *= initObjScaleWS.z newRadius = max( ( newRadius, math.sqrt( ( v[0] * v[0] ) + ( v[1] * v[1] ) + ( v[2] * v[2] ) ) ) ) bpy.ops.mesh.primitive_uv_sphere_add( segments = 16, ring_count = 8, size = newRadius ) elif collisionType == self.CollisionType.SIMPLECONVEX: bpy.ops.mesh.primitive_cube_add() elif collisionType == self.CollisionType.CONVEX: # Here we gonna use the objCopy (He is already active) bpy.ops.object.mode_set( mode = 'EDIT' ) bpy.ops.mesh.select_all( action = 'SELECT' ) bpy.ops.mesh.convex_hull( delete_unused = True, use_existing_faces = True, make_holes = False, join_triangles = True, face_threshold = 3.14, shape_threshold = 3.14, uvs = False, vcols = False, seam = False, sharp = False, materials = False ) bpy.ops.mesh.select_all( action = 'SELECT' ) bpy.ops.mesh.quads_convert_to_tris() # Triangulate the shape for an exact number of triangles bpy.ops.object.mode_set( mode = 'OBJECT' ) # Now lets create an decimate modifier for having a specified number of triangle per volume area = objCopy.dimensions.x * objCopy.dimensions.y * objCopy.dimensions.z numTriangles = len( objCopy.data.polygons ) decimateModifier = self.addModifier( objCopy, 'DECIMATE', 'U4CT_Decimate' ) decimateModifier.ratio = max( ( convexComplexity / ( numTriangles / area ), 1.0 / ( numTriangles / 12 ) ) ) bpy.ops.object.modifier_apply( apply_as = 'DATA', modifier = decimateModifier.name ) newCollisionBox = self.getActive() # Save the reference of the freshly created box. # Set the visibility of the new collision box same as obj newCollisionBox.layers = obj.layers # Set our new mesh as active self.setActive( newCollisionBox ) if collisionType != self.CollisionType.SPHERE: objCopy.scale = ( 1.0, 1.0, 1.0 ) # Because of the Array/Mirror modifier, we will have to work with the same scale bpy.context.scene.update() # Update the context to recompute the dimensions newCollisionBox.dimensions = objCopy.dimensions # Set the scale of the Collision Box (will be applied) # Set the location at [0:0:0] because we will set it as a child of our object newCollisionBox.location = ( 0.0, 0.0, 0.0 ) newCollisionBox.name = self.getU4Prefix( collisionType ) + obj.name + '.000' # Set the name correctly using the Unreal Engine 4 documentation newCollisionBox.draw_type = 'WIRE' # Set the Draw Type to WIRE # Disable Visibility in Cycles newCollisionBox.cycles_visibility.camera = False newCollisionBox.cycles_visibility.transmission = False newCollisionBox.cycles_visibility.diffuse = False newCollisionBox.cycles_visibility.scatter = False newCollisionBox.cycles_visibility.glossy = False newCollisionBox.cycles_visibility.shadow = False # Apply the scale on the new bounding box (for the array modifier) bpy.ops.object.transform_apply( location = False, rotation = False, scale = True ) # Set the origin of the Collision Box same as 'obj' self.set3DCursorPos( Vector( ( -relativePos.x / initObjScaleWS.x, -relativePos.y / initObjScaleWS.y, -relativePos.z / initObjScaleWS.z ) ) ) bpy.ops.object.origin_set( type = 'ORIGIN_CURSOR' ) # Now put the collision box as a child of our object self.setActive( obj ) newCollisionBox.select = True bpy.ops.object.parent_no_inverse_set() # Parent it WITHOUT any 'parent inverse' matrix # Transfer the modifier from 'obj' to the new Collision Box self.setActive( obj ) newCollisionBox.select = True bpy.ops.object.make_links_data( type = 'MODIFIERS' ) # Apply the Array and Mirror modifier if nessessary self.setActive( newCollisionBox ) if multipleOnArray: for modifier in newCollisionBox.modifiers: if modifier.type == 'ARRAY' and modifier.show_viewport == True: bpy.ops.object.modifier_apply( apply_as = 'DATA', modifier = modifier.name ) if multipleOnMirror: for modifier in newCollisionBox.modifiers: if modifier.type == 'MIRROR' and modifier.show_viewport == True: modifier.use_mirror_merge = False bpy.ops.object.modifier_apply( apply_as = 'DATA', modifier = modifier.name ) for modifier in newCollisionBox.modifiers: bpy.ops.object.modifier_remove( modifier = modifier.name ) # Now split all the loose parts and rename them correctly bpy.ops.object.mode_set( mode = 'EDIT' ) bpy.ops.mesh.separate( type = 'LOOSE' ) bpy.ops.object.mode_set( mode = 'OBJECT' ) def replaceDot( matchobj ): return matchobj.group(0).replace('.', '_') # All the looses parts are selected, Now set the origin to the center of mass bpy.ops.object.origin_set( type = 'ORIGIN_GEOMETRY', center = 'BOUNDS' ) loosePartsObjects = bpy.context.selected_objects for looseObj in loosePartsObjects: looseObj.name = re.sub(r'\.[0-9]+$', replaceDot, looseObj.name) looseObj.data.name = looseObj.name collisionsBoxesList.append(looseObj) # Append the loose part to the Collisions Boxes list # If we are creating Simple Convex, apply a scrinkwarp if collisionType == self.CollisionType.SIMPLECONVEX: self.report({'INFO'}, 'TEST') self.setActive( looseObj ) # Add a SHRINKWRAP modifier to the collision box shrinkWarpModifier = self.addModifier( looseObj, 'SHRINKWRAP', 'U4CT_SHRINKWRAP' ) shrinkWarpModifier.target = objCopy2 shrinkWarpModifier.wrap_method = 'NEAREST_VERTEX' bpy.ops.object.modifier_apply( apply_as = 'DATA', modifier = shrinkWarpModifier.name ) self.selectObjList( collisionsBoxesList ) # Link the object data of all the looses parts if collisionType == self.CollisionType.SPHERE: bpy.context.scene.objects.active = newCollisionBox bpy.ops.object.make_links_data(type='OBDATA') # If we are using sphere, set the scaling equal on each axis if collisionType == self.CollisionType.SPHERE: scaleVector = Vector( ( 1.0 / initObjScaleWS.x, 1.0 / initObjScaleWS.y, 1.0 / initObjScaleWS.z ) ) * scaleMult for looseObj in loosePartsObjects: looseObj.scale = scaleVector else: newScale = Vector( ( scaleMult, scaleMult, scaleMult ) ) for looseObj in loosePartsObjects: looseObj.scale = newScale # Everything is finished for this object, we can delete the objCopy if collisionType != self.CollisionType.CONVEX: self.setActive( objCopy ) bpy.ops.object.delete( use_global = False ) self.setActive( objCopy2 ) bpy.ops.object.delete( use_global = False ) self.set3DCursorPos( init3DCursorPosition ) return collisionsBoxesList # @brief Class of the 'Select Collisions Datas' Button class U4CollisionsTools_SelectCollisionsBoxes(bpy.types.Operator, U4CollisionsTools): bl_label = 'Select Collisions Datas' # blender will use this as a tooltip for menu items and buttons. bl_idname = 'object.u4collisionstools_selectallcollisionsboxes' # unique identifier for buttons and menu items to reference. bl_context = '3dview' # display name in the interface. bl_options = {'REGISTER', 'UNDO'} # enable undo for the operator. p_extend = bpy.props.BoolProperty( name = 'Extend', description = 'Extend selection.', default = False ) def execute( self, context ): selectedObjList = self.getSelectedObj() # If we don't want to extend, deselect all if self.p_extend == False: self.deselectAll() for obj in selectedObjList: if self.isCollisionBox( obj ): obj.select = True continue objChildList = self.getChildren( obj ) objCollisionsList = self.getCollisions( objChildList ) for objCollisions in objCollisionsList: objCollisions.select = True return {'FINISHED'} # @brief Class of the 'Create Boxes' button class U4CollisionsTools_CreateCollisionBox(bpy.types.Operator, U4CollisionsTools): bl_label = 'Create Boxes' # blender will use this as a tooltip for menu items and buttons. bl_idname = 'object.u4collisionstools_createcollisionsboxes' # unique identifier for buttons and menu items to reference. bl_context = '3dview' # display name in the interface. bl_options = {'REGISTER', 'UNDO'} # enable undo for the operator. p_multipleOneMirror = bpy.props.BoolProperty( name = 'Multiple on Mirror', description = 'Multiple Boxes generated with Mirror Modifier.', default = True ) p_multipleOneArray = bpy.props.BoolProperty( name = 'Multiple on Array', description = 'Multiple Boxes generated with Array Modifier.', default = True ) p_scaleMult = bpy.props.FloatProperty( name = 'Scale Multiplier', description = 'Multiply the resulting scale to this factor', default = 1.0, min = 0.01, max = 2.00 ) # Main method of the class: def execute( self, context ): collisionsBoxesList = self.createCollisionsBoxes( self.getSelectedObj(), self.CollisionType.BOX, self.p_multipleOneArray, self.p_multipleOneMirror, self.p_scaleMult ) # Set back everything so nothing has changed self.deselectAll() for collisionsBox in collisionsBoxesList: collisionsBox.select = True return {'FINISHED'} # @brief Class of the 'Create Simple Convex' button class U4CollisionsTools_CreateCollisionSimpleConvex(bpy.types.Operator, U4CollisionsTools): bl_label = 'Create Simple Convex' # blender will use this as a tooltip for menu items and buttons. bl_idname = 'object.u4collisionstools_createcollisionssimpleconvex' # unique identifier for buttons and menu items to reference. bl_context = '3dview' # display name in the interface. bl_options = {'REGISTER', 'UNDO'} # enable undo for the operator. p_multipleOneMirror = bpy.props.BoolProperty( name = 'Multiple on Mirror', description = 'Multiple Boxes generated with Mirror Modifier.', default = True ) p_multipleOneArray = bpy.props.BoolProperty( name = 'Multiple on Array', description = 'Multiple Boxes generated with Array Modifier.', default = True ) p_scaleMult = bpy.props.FloatProperty( name = 'Scale Multiplier', description = 'Multiply the resulting scale to this factor', default = 1.0, min = 0.01, max = 2.00 ) # Main method of the class: def execute( self, context ): # First we are created boxes same as 'Create Boxes' collisionsBoxesList = self.createCollisionsBoxes( self.getSelectedObj(), self.CollisionType.SIMPLECONVEX, self.p_multipleOneArray, self.p_multipleOneMirror, self.p_scaleMult ) # Set back everything so nothing has changed self.deselectAll() for collisionsBox in collisionsBoxesList: collisionsBox.select = True return {'FINISHED'} # @brief Class of the 'Create Convex' button class U4CollisionsTools_CreateCollisionConvex(bpy.types.Operator, U4CollisionsTools): bl_label = 'Create Convex' # blender will use this as a tooltip for menu items and buttons. bl_idname = 'object.u4collisionstools_createcollisionsconvex' # unique identifier for buttons and menu items to reference. bl_context = '3dview' # display name in the interface. bl_options = {'REGISTER', 'UNDO'} # enable undo for the operator. p_multipleOneMirror = bpy.props.BoolProperty( name = 'Multiple on Mirror', description = 'Multiple Boxes generated with Mirror Modifier.', default = True ) p_multipleOneArray = bpy.props.BoolProperty( name = 'Multiple on Array', description = 'Multiple Boxes generated with Array Modifier.', default = True ) p_scaleMult = bpy.props.FloatProperty( name = 'Scale Multiplier', description = 'Multiply the resulting scale to this factor', default = 1.0, min = 0.01, max = 2.00 ) p_complexity = bpy.props.FloatProperty( name = 'Complexity', description = 'Complexity of the resulting convex shape', default = 10.0, min = 0.001, max = 1000, soft_min = 0.1, soft_max = 100.00 ) # Main method of the class: def execute( self, context ): # First we are created boxes same as 'Create Boxes' collisionsBoxesList = self.createCollisionsBoxes( self.getSelectedObj(), self.CollisionType.CONVEX, self.p_multipleOneArray, self.p_multipleOneMirror, self.p_scaleMult, self.p_complexity ) # Set back everything so nothing has changed self.deselectAll() for collisionsBox in collisionsBoxesList: collisionsBox.select = True return {'FINISHED'} # @brief Class of the 'Create Spheres' button class U4CollisionsTools_CreateCollisionSpheres(bpy.types.Operator, U4CollisionsTools): bl_label = 'Create Spheres' # blender will use this as a tooltip for menu items and buttons. bl_idname = 'object.u4collisionstools_createcollisionsspheres' # unique identifier for buttons and menu items to reference. bl_context = '3dview' # display name in the interface. bl_options = {'REGISTER', 'UNDO'} # enable undo for the operator. p_multipleOneMirror = bpy.props.BoolProperty( name = 'Multiple on Mirror', description = 'Multiple Boxes generated with Mirror Modifier.', default = True ) p_multipleOneArray = bpy.props.BoolProperty( name = 'Multiple on Array', description = 'Multiple Boxes generated with Array Modifier.', default = True ) p_scaleMult = bpy.props.FloatProperty( name = 'Scale Multiplier', description = 'Multiply the resulting scale to this factor', default = 1.0, min = 0.01, max = 2.00 ) # Main method of the class: def execute( self, context ): # First we are created boxes same as 'Create Boxes' collisionsBoxesList = self.createCollisionsBoxes( self.getSelectedObj(), self.CollisionType.SPHERE, self.p_multipleOneArray, self.p_multipleOneMirror, self.p_scaleMult ) # Set back everything so nothing has changed self.deselectAll() for collisionsBox in collisionsBoxesList: collisionsBox.select = True return {'FINISHED'} # @brief Panel class of the Addon Used to register the whole script. class U4CollisionsTools_Panel(bpy.types.Panel): bl_label = "U4 Collisions Tools" bl_idname = "U4CollisionsTools" bl_space_type = "VIEW_3D" bl_region_type = "TOOLS" bl_category = "Tools" first_draw = True def draw(self, context): layout = self.layout layout.operator(U4CollisionsTools_CreateCollisionBox.bl_idname, icon = 'VIEW3D' ) layout.operator(U4CollisionsTools_CreateCollisionSimpleConvex.bl_idname, icon = 'VIEW3D' ) layout.operator(U4CollisionsTools_CreateCollisionConvex.bl_idname, icon = 'VIEW3D' ) layout.operator(U4CollisionsTools_CreateCollisionSpheres.bl_idname, icon = 'MESH_UVSPHERE' ) layout.operator(U4CollisionsTools_SelectCollisionsBoxes.bl_idname, icon = 'HAND' ) def register(): bpy.utils.register_class(U4CollisionsTools_Panel) bpy.utils.register_class(U4CollisionsTools_CreateCollisionBox) bpy.utils.register_class(U4CollisionsTools_CreateCollisionSimpleConvex) bpy.utils.register_class(U4CollisionsTools_CreateCollisionConvex) bpy.utils.register_class(U4CollisionsTools_CreateCollisionSpheres) bpy.utils.register_class(U4CollisionsTools_SelectCollisionsBoxes) def unregister(): bpy.utils.unregister_class(U4CollisionsTools_SelectCollisionsBoxes) bpy.utils.unregister_class(U4CollisionsTools_CreateCollisionSpheres) bpy.utils.unregister_class(U4CollisionsTools_CreateCollisionConvex) bpy.utils.unregister_class(U4CollisionsTools_CreateCollisionSimpleConvex) bpy.utils.unregister_class(U4CollisionsTools_CreateCollisionBox) bpy.utils.unregister_class(U4CollisionsTools_Panel) if __name__ == "__main__": register()
package ca.ulaval.glo4003.small.repul.payment.infra; import static org.junit.jupiter.api.Assertions.*; import ca.ulaval.glo4003.repul.payment.domain.ClientRepository; import ca.ulaval.glo4003.repul.payment.domain.client.Client; import ca.ulaval.glo4003.repul.payment.domain.client.ClientId; import ca.ulaval.glo4003.repul.payment.domain.client.credit_card.CardExpirationDate; import ca.ulaval.glo4003.repul.payment.domain.client.credit_card.CardNumber; import ca.ulaval.glo4003.repul.payment.domain.client.credit_card.Ccv; import ca.ulaval.glo4003.repul.payment.domain.client.credit_card.CreditCard; import ca.ulaval.glo4003.repul.payment.infra.InMemoryClientRepository; import ca.ulaval.glo4003.repul.payment.infra.exception.ClientNotFoundException; import org.junit.jupiter.api.Test; class InMemoryClientRepositoryTest { private final ClientId CLIENT_ID = new ClientId("idul123"); private final CardNumber CARD_NUMBER = new CardNumber("1234567812345678"); private final CardExpirationDate CARD_EXPIRATION_DATE = new CardExpirationDate( "12-2099" ); private final Ccv CCV = new Ccv("123"); private final Client CLIENT = new Client( CLIENT_ID, new CreditCard(CARD_NUMBER, CARD_EXPIRATION_DATE, CCV) ); private final ClientRepository clientRepository = new InMemoryClientRepository(); @Test void saveClient_clientIsSaved() { clientRepository.save(CLIENT); Client clientFound = clientRepository.findById(CLIENT_ID); assertNotSame(CLIENT, clientFound); assertEquals(CLIENT, clientFound); } @Test void existingClient_findById_clientIsReturned() { clientRepository.save(CLIENT); Client clientFound = clientRepository.findById(CLIENT_ID); assertNotSame(CLIENT, clientFound); assertEquals(CLIENT, clientFound); } @Test void newClient_findById_clientNotFoundExceptionIsThrown() { assertThrows( ClientNotFoundException.class, () -> clientRepository.findById(CLIENT_ID) ); } }
import type { ActionFunctionArgs } from "@remix-run/node"; import { json } from "@remix-run/node"; import { verifyADR36Amino } from "@keplr-wallet/cosmos" import { Buffer } from "buffer"; import { chains } from "chain-registry" import { updateUserCosmosAddress } from "~/models/user.server"; import { requireUserId } from "~/session.server"; export const action = async ({ request }: ActionFunctionArgs) => { const userId = await requireUserId(request); const formData = await request.formData(); const chain = formData.get("chain"); const signer = formData.get("signer"); const data = formData.get("data"); const pubKey = formData.get("pubKey"); const signature = formData.get("signature"); const prefix = chains.find(c => c.chain_name === chain)?.bech32_prefix if (typeof chain !== "string" || typeof signer !== "string" || typeof signature !== "string" || typeof data !== "string" || typeof pubKey !== "string" || chain.length === 0 || signer.length === 0 || signature.length === 0 || data.length === 0 || pubKey.length === 0 || !prefix || prefix.length === 0) { return json( { errors: { message: "Validation Failed" } }, { status: 400 }, ); } // Convert public key from hex to Buffer const enPubkey = Buffer.from(pubKey, "hex"); // verify if signature is valid if (verifyADR36Amino(prefix, signer, data, enPubkey, Buffer.from(signature as string, "base64"))) { try { // Signature is valid update the user's cosmos address await updateUserCosmosAddress(userId, signer) return json( { success: true, message: "Address added successfully" }, { status: 200 }, ); } catch (error) { return json( { errors: { message: "Something went wrong" } }, { status: 400 }, ); } } else { return json( { errors: { message: "Validation Failed" } }, { status: 400 }, ); } }
import React from 'react'; import styled from 'styled-components'; import {Link} from 'react-router-dom'; import PropTypes from 'prop-types'; import {ProductConsumer} from './context.js'; const Product = (props) => { const {id,title,img,price,inCart} = props.product; return ( <ProductWrapper className='col-9 mx-auto col-md-6 col-lg-3 my-3'> <div className='card'> <ProductConsumer> {(data) => { const {handleDetails,addToCart,openModal} = data; return( <div className='img-container p-5' onClick={() => handleDetails(id)}> <Link to='/details'> <img src={img} alt={title} className='card-img-top'/> </Link> <button onClick={(event) => {addToCart(id); openModal(id); }} disabled={inCart} className='cart-button' > { inCart ? (<p className='text-capitalize' disabled>in cart</p>) : (<i className='fas fa-cart-plus'/>) } </button> </div> ); }} </ProductConsumer> {/* card footer */} <div className='card-footer d-flex justify-content-between'> <p className='align-self-center mb-0'> {title} </p> <h5 className='text-blue font-italic mb-0'> <span className='mr-1'>$</span> {price} </h5> </div> </div> </ProductWrapper> ); }; Product.propTypes = { product: PropTypes.shape({ id: PropTypes.number, img: PropTypes.string, title: PropTypes.string, price: PropTypes.number, inCart: PropTypes.bool }).isRequired }; const ProductWrapper = styled.div` .card{ border-color: transparent; transition: all 1s linear; } .card-footer{ background: transparent; border-top: transparent; transition: all 1s linear; } &:hover{ .card{ border:0.04rem solid rgba(0,0,0,0.2); box-shadow:2px 2px 2px 0px rgba(0,0,0,0.2); } .card-footer{ background: rgba(247,247,247) } } .img-container{ position: relative; overflow: hidden; } .card-img-top{ transition: all 1s linear; } .img-container:hover .card-img-top{ transform: scale(1.2) } .cart-button{ position: absolute; bottom: 0; right: 0; padding: 0.2rem 0.4rem; background: var(--lightBlue); border: none; color: var(--mainWhite); font-size: 1.2rem; border-radius: 0.5rem 0 0 0; transform: translate(100%, 100%); transition: all 1s linear; } .img-container:hover .cart-button{ transform: translate(0, 0); } .cart-button:hover{ color: var(--mainBlue); cursor: pointer; } `; export default Product;
import React, { useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useDispatch } from 'react-redux'; import axios from 'axios'; import { Modal } from 'bootstrap'; import ModalMsg from '../ModalMsg'; import { userActions } from '../../store/users/usersSlice'; import { homeId, loginId } from '../Header/MenuItems'; import { baseApi } from '../../tools/tools'; const string = require("string-sanitizer"); const LogIn = props => { const { setActiveMenuItem } = props; setActiveMenuItem(loginId); const dispatch = useDispatch() const navigate = useNavigate(); const [formData, setFormData] = useState({ email: '', password: '' }); const [formErrors, setFormErrors] = useState({ email: '', password: '' }); const [showPassword, setShowPassword] = useState(false); const [modalInfo, setModalInfo] = useState({ title: "title", message: "message" }) let sanitized = {} const validateForm = () => { let errors = {}; let isValid = true; sanitized = {}; // email if (!formData.email.trim()) { errors.email = 'Email is required'; isValid = false; } else if (!string.validate.isEmail(formData.email)) { errors.email = 'Email is not valid'; isValid = false; } else { errors.email = ''; sanitized.email = formData.email; } // password if (!formData.password.trim()) { errors.password = 'Password is required'; isValid = false; } else if (!string.validate.isPassword8to15(formData.password)) { errors.password = 'Password not in a valid format: at least 1 lower case, 1 UPPER case, 1 digit, 1 special character'; isValid = false; } else { errors.password = ''; } setFormErrors(errors); return isValid; } const handleInputChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); }; // { // "email": "mike@email.com", // "password": "7hxk@ZSOLdY%4AD" // } const handleSubmit = async (e) => { e.preventDefault(); if (validateForm()) { try { const response = await axios({ method: "post", data: { email: sanitized.email, password: formData.password }, withCredentials: true, url: `${baseApi}/auth/login`, }); if (response.status === 200) { // successfull login // set user in redux store dispatch(userActions.loggedIn(response.data.user)); navigate('/products'); setActiveMenuItem(homeId); } else { console.log('Login - Non error return, but not status 200'); showModal("Internal Error", "Something went wrong"); } } catch (err) { if (err.response && err.response.status && err.response.data && err.response.data.message) { if (err.response.status === 401) { showModal("Invalid Data", "Incorrect email or password") } else if (err.response.status === 500) { showModal("Internal Error", err.response.data.message) } else { console.log(err.response.data.message) showModal("Internal Error", "Something went wrong"); } } else { let errMsg = "Something went wrong" let errTitle = "Internal Error" if (err.message) { if (err.message === 'Network Error') { errTitle = 'Network Error'; errMsg = 'Could not connect to the server'; } console.log(err.message) } else if (err.response.data.message) { console.log(err.response.data.message) } else { console.log('Login - unknown error') } showModal(errTitle, errMsg); } } } else { showModal("Invalid Data", "Login data is invalid. Enter valid data to login."); } } const showModal = (title, message) => { setModalInfo({ title: title, message: message }) var myModal = new Modal(document.getElementById('modalPopup')) myModal.show(); } const togglePasswordVisibility = () => { setShowPassword(!showPassword); } return ( <div> <p className="h2 m-2">Log In</p> <p className='h6 m-2'>Log in to the web site</p> {/* modal popup message */} <ModalMsg modalId="modalPopup" title={modalInfo.title} message={modalInfo.message} /> {/* form */} <form onSubmit={handleSubmit}> <div class="row m-3"> <div class="col-md-4"> <label for="loginEmail" class="form-label"> Email </label> <input type="text" class={`form-control ${formErrors.email && "is-invalid"}`} id="loginEmail" name="email" onChange={handleInputChange} /> <div class="invalid-feedback">{formErrors.email}</div> </div> </div> <div class="row m-3"> <div class="col-md-4"> <label for="loginPassword" class="form-label"> Password </label> <div class="input-group"> <input type={showPassword ? "text" : "password"} class={`form-control ${formErrors.password && "is-invalid"}`} id="loginPassword" name="password" onChange={handleInputChange} /> <button class="btn btn-outline-secondary" type="button" onClick={togglePasswordVisibility} > {showPassword ? "Hide" : "Show"} </button> <div class="invalid-feedback">{formErrors.password}</div> </div> </div> </div> <div class="btn-toolbar mt-4 ms-4"> <button type="submit" id="btnSubmit" class="btn btn-primary me-3"> Log In </button> <a href={`${baseApi}/auth/google`}> <button type="button" id="btnGoogle" class="btn btn-secondary" > <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-google" viewBox="0 0 16 16" > <path d="M15.545 6.558a9.42 9.42 0 0 1 .139 1.626c0 2.434-.87 4.492-2.384 5.885h.002C11.978 15.292 10.158 16 8 16A8 8 0 1 1 8 0a7.689 7.689 0 0 1 5.352 2.082l-2.284 2.284A4.347 4.347 0 0 0 8 3.166c-2.087 0-3.86 1.408-4.492 3.304a4.792 4.792 0 0 0 0 3.063h.003c.635 1.893 2.405 3.301 4.492 3.301 1.078 0 2.004-.276 2.722-.764h-.003a3.702 3.702 0 0 0 1.599-2.431H8v-3.08h7.545z" /> </svg>{" "} Log in with Google </button> </a> </div> </form> </div> ); }; // html for svg google icon export default LogIn;
import { useState } from 'react'; import { useSelector } from 'react-redux'; import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js'; import { selectCartTotal } from '../../store/cart/cart.selector'; import { selectCurrentUser } from '../../store/user/user.selector'; import Button, { BUTTON_TYPE_CLASSES } from '../../components/button/button.component'; import PaymentForm from '../../components/payment-form/payment-form.component'; import { CheckoutWrapper, CheckoutContainer, CheckoutDetails, Total } from './checkout.styles'; const Checkout = () => { const stripe = useStripe(); const elements = useElements(); const amount = useSelector(selectCartTotal); const currentUser = useSelector(selectCurrentUser); const [ isProcessingPayment, setIsProcessingPayment ] = useState(false); const handlePayment = async event => { event.preventDefault(); if (!stripe || !elements) return; setIsProcessingPayment(true); const response = await fetch('/.netlify/functions/create-payment-intent', { method: 'post', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ amount: amount * 100 }) }).then(res => res.json()); const clientSecret = response.paymentIntent.client_secret; const paymentResult = await stripe.confirmCardPayment(clientSecret, { payment_method: { card: elements.getElement(CardElement), billing_details: { name: currentUser ? currentUser.displayName : 'Guest' } } }); setIsProcessingPayment(false); if (paymentResult.error) { alert('payment error!'); } else { if (paymentResult.paymentIntent.status === 'succeeded') { alert('payment successful'); } } }; return ( <CheckoutWrapper> <CheckoutContainer> <PaymentForm /> </CheckoutContainer> <CheckoutDetails> <Total>Total: ${amount}</Total> <Button onClick={handlePayment} buttonType={BUTTON_TYPE_CLASSES.inverted} isLoading={isProcessingPayment} > Pay Now </Button> </CheckoutDetails> </CheckoutWrapper> ); }; export default Checkout;
import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:khwahish_provider/Components/DialogueBox/imagePickerPopUp.dart'; import 'package:khwahish_provider/Components/buttons.dart'; import 'package:khwahish_provider/Components/textField.dart'; import 'package:khwahish_provider/Components/util.dart'; import 'package:khwahish_provider/Services/serviceManager.dart'; import 'package:khwahish_provider/Theme/colors.dart'; import 'package:khwahish_provider/Theme/style.dart'; import 'package:image_cropper/image_cropper.dart'; class VerifyAccount extends StatefulWidget { const VerifyAccount({super.key}); @override State<VerifyAccount> createState() => _VerifyAccountState(); } class _VerifyAccountState extends State<VerifyAccount> { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final TextEditingController panCard = TextEditingController(); final TextEditingController aadhaar = TextEditingController(); final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final ImagePicker _picker = ImagePicker(); File? _aadhaarFrontImage; File? _aadhaarBackImage; File? _panCardImage; void pickImageFromGallery(int num) async { var pickedImage = await _picker.pickImage(source: ImageSource.gallery); if (pickedImage != null) { final croppedFile = await ImageCropper().cropImage( sourcePath: pickedImage.path, aspectRatioPresets: [ CropAspectRatioPreset.square, CropAspectRatioPreset.ratio3x2, CropAspectRatioPreset.original, CropAspectRatioPreset.ratio4x3, CropAspectRatioPreset.ratio16x9 ], uiSettings: [ AndroidUiSettings( toolbarTitle: 'Crop Image', toolbarColor: kMainColor, toolbarWidgetColor: Colors.white, initAspectRatio: CropAspectRatioPreset.original, lockAspectRatio: false), IOSUiSettings( title: 'Cropper', ), ], ); if (croppedFile != null) { if(num == 1){ setState(() { _aadhaarFrontImage = File(croppedFile.path); }); } else if(num == 2) { setState(() { _aadhaarBackImage = File(croppedFile.path); }); } else { setState(() { _panCardImage = File(croppedFile.path); }); } } } } void pickImageFromCamera(int num) async { var pickedImage = await _picker.pickImage(source: ImageSource.camera); if (pickedImage != null) { final croppedFile = await ImageCropper().cropImage( sourcePath: pickedImage.path, aspectRatioPresets: [ CropAspectRatioPreset.square, CropAspectRatioPreset.ratio3x2, CropAspectRatioPreset.original, CropAspectRatioPreset.ratio4x3, CropAspectRatioPreset.ratio16x9 ], uiSettings: [ AndroidUiSettings( toolbarTitle: 'Crop Image', toolbarColor: kMainColor, toolbarWidgetColor: Colors.white, initAspectRatio: CropAspectRatioPreset.original, lockAspectRatio: false), IOSUiSettings( title: 'Cropper', ), ], ); if (croppedFile != null) { if(num == 1){ setState(() { _aadhaarFrontImage = File(croppedFile.path); }); } else if(num == 2) { setState(() { _aadhaarBackImage = File(croppedFile.path); }); } else { setState(() { _panCardImage = File(croppedFile.path); }); } } } } bool panCardVerified = false; bool documentUploaded = false; bool isLoading = false; @override void initState() { super.initState(); getUserData(); } void getUserData() async { var collection = _firestore.collection('provider'); var docs = await collection.doc(ServiceManager.userID).get(); if(docs.exists){ aadhaar.text = '${docs['aadhaar']}'; panCard.text = '${docs['panCard']}'; if(docs['aadhaar'] != '' && docs['panCard'] != ''){ documentUploaded = true; } setState(() {}); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Verify Account'), ), body: SingleChildScrollView( child: Form( key: _formKey, child: Column( children: [ if(documentUploaded != false) Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Container( width: MediaQuery.of(context).size.width, padding: EdgeInsets.symmetric(horizontal: 15, vertical: 25), decoration: BoxDecoration( color: kMainColor.withOpacity(0.4), borderRadius: BorderRadius.circular(10), ), child: Text('Your document is under process', style: kLargeStyle(), ), ), ), if(documentUploaded != true) Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Row( children: [ Text('To verify your account submit your document.', style: k10Text(), ), ], ), ), SizedBox(height: 5), KTextField( readOnly: documentUploaded != false ? true : false, title: 'Aadhaar Card Number', controller: aadhaar, textInputType: TextInputType.number, textLimit: 12, onChanged: (value){ _formKey.currentState!.validate(); }, validate: (value){ if(value!.isEmpty || value.length < 12){ return 'Please Enter Proper Aadhaar Card Number'; } return null; }, ), SizedBox(height: 10), _aadhaarFrontImage == null ? SizedBox.shrink() : Image.file(_aadhaarFrontImage!, height: 200.0), documentUploaded != true ? KButton( title: _aadhaarFrontImage == null ? 'Upload Aadhaar Front Image' : 'Change Aadhaar Front Image', onClick: (){ showModalBottomSheet( context: context, builder: (context){ return ImagePickerPopUp( onCameraClick: (){ Navigator.pop(context); pickImageFromCamera(1); }, onGalleryClick: (){ Navigator.pop(context); pickImageFromGallery(1); }, ); }, ); }, ) : disabledButton(title: 'Upload Aadhaar Front Image'), SizedBox(height: 10), _aadhaarBackImage == null ? SizedBox.shrink() : Image.file(_aadhaarBackImage!, height: 200.0), documentUploaded != true ? KButton( title: _aadhaarBackImage == null ? 'Upload Aadhaar Back Image' : 'Change Aadhaar Back Image', onClick: (){ showModalBottomSheet( context: context, builder: (context){ return ImagePickerPopUp( onCameraClick: (){ Navigator.pop(context); pickImageFromCamera(2); }, onGalleryClick: (){ Navigator.pop(context); pickImageFromGallery(2); }, ); }, ); }, ) : disabledButton(title: 'Upload Aadhaar Back Image'), kDivider(), Padding( padding: const EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0), child: TextFormField( readOnly: documentUploaded != false ? true : false, controller: panCard, textCapitalization: TextCapitalization.characters, style: TextStyle(fontWeight: FontWeight.w600), decoration: InputDecoration( border: outlineBorderStyle(), focusedBorder: focusBorderStyle(), enabledBorder: enableBorderStyle(), contentPadding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 10.0), fillColor: Theme.of(context).scaffoldBackgroundColor, hintText: 'Pan Card Number', hintStyle: hintTextStyle(context), labelText: 'Pan Card Number', // suffixIconColor: Colors.green, // suffixIcon: panCardVerified != false ? Icon(Icons.check) : null, ), onChanged: (value){ _formKey.currentState!.validate(); }, validator: (value) { String pattern = r'^[A-Z]{5}[0-9]{4}[A-Z]{1}$'; RegExp regExp = RegExp(pattern); if (value == null || value.isEmpty) { return 'Please Enter PanCard Number'; } else if (!regExp.hasMatch(value)) { setState(() { panCardVerified = false; }); return 'Please Enter Valid PanCard Number'; } return null; }, ), ), // Row( // children: [ // Padding( // padding: const EdgeInsets.only(left: 10, bottom: 10), // child: Text(validatePanCard(panCard.text), // style: k10Text(), // ), // ), // ], // ), SizedBox(height: 5), _panCardImage == null ? SizedBox.shrink() : Image.file(_panCardImage!, height: 200.0), documentUploaded != true ? KButton( title: _panCardImage == null ? 'Upload Pan Card Image' : 'Change Pan Card Image', onClick: (){ showModalBottomSheet( context: context, builder: (context){ return ImagePickerPopUp( onCameraClick: (){ Navigator.pop(context); pickImageFromCamera(3); }, onGalleryClick: (){ Navigator.pop(context); pickImageFromGallery(3); }, ); }, ); }, ) : disabledButton(title: 'Upload Pan Card Image'), kBottomSpace(), ], ), ), ), floatingActionButton: documentUploaded != true ? isLoading != true ? KButton( title: 'Submit', onClick: (){ if(_formKey.currentState!.validate()){ if(_aadhaarFrontImage != null && _aadhaarBackImage != null && _panCardImage != null){ setState(() { isLoading = true; }); uploadDocument(); } else { toastMessage(message: 'Upload document image', colors: kRedColor); } } else { toastMessage(message: 'Fill the required fields', colors: kRedColor); } }, ) : LoadingButton() : disabledButton(title: 'Submit'), ); } void uploadDocument() async { try { String aadhaarFrontImageURL = await ServiceManager().uploadImage(_aadhaarFrontImage!.path, 'document'); String aadhaarBackImageURL = await ServiceManager().uploadImage(_aadhaarBackImage!.path, 'document'); String panCardImagePath = await ServiceManager().uploadImage(_panCardImage!.path, 'document'); _firestore.collection('provider').doc(ServiceManager.userID).update({ 'aadhaar': aadhaar.text, 'aadhaarBackImage': aadhaarBackImageURL, 'aadhaarFrontImage': aadhaarFrontImageURL, 'panCard': panCard.text, 'panCardImage': panCardImagePath, }).then((value) => { Navigator.pop(context), toastMessage(message: 'Document Uploaded'), }); } catch (e) { setState(() { isLoading = false; }); toastMessage(message: 'Something went wrong', colors: kRedColor); } } } KButton disabledButton({required String title}) { return KButton( color: Colors.grey, title: title, onClick: (){}, ); }
const { DiscordStreamClient } = require('discord-stream-client'); module.exports = { name: 'livestream', description: 'Starts or stops a live stream in a voice channel with a provided video link.', async execute(message, args, deleteTimeout) { if (args[0] === 'stop') { if (message.client.voiceConnection) { message.client.voiceConnection.disconnect(); message.client.voiceConnection = null; if (message.client.currentPlayer) { message.client.currentPlayer.stop(); message.client.currentPlayer.removeAllListeners('end'); message.client.currentPlayer = null; } return message.channel.send('Livestream stopped.').then(msg => setTimeout(() => msg.delete().catch(console.error), deleteTimeout)); } else { return message.channel.send('No active livestream to stop.').then(msg => setTimeout(() => msg.delete().catch(console.error), deleteTimeout)); } } if (args.length < 2) { return message.channel.send('Usage: .livestream <channelId> <videoLink> | .livestream stop') .then(msg => setTimeout(() => msg.delete().catch(console.error), deleteTimeout)); } const channelId = args[0]; const videoLink = args[1]; const channel = message.client.channels.cache.get(channelId); if (!channel) { return message.channel.send('Channel not found.') .then(msg => setTimeout(() => msg.delete().catch(console.error), deleteTimeout)); } const voiceState = message.guild.members.me.voice; if (voiceState.channel) { console.log('Already in a voice channel, leaving...'); await voiceState.disconnect(); } try { if (message.client.currentPlayer) { message.client.currentPlayer.stop(); } const connection = await message.client.streamClient.joinVoiceChannel(channel, { selfDeaf: true, selfMute: true, selfVideo: false, }); const stream = await connection.createStream(); const player = message.client.streamClient.createPlayer(videoLink, stream.udp); message.client.currentPlayer = player; player.on('error', err => console.error(err)); const playStream = () => { player.play(videoLink, { kbpsVideo: 7000, fps: 60, hwaccel: true, kbpsAudio: 128, volume: 1, }); }; player.on('finish', () => { console.log('Media ended, replaying...'); playStream(); }); playStream(); message.channel.send('Livestream started with the provided video link.') .then(msg => setTimeout(() => msg.delete().catch(console.error), deleteTimeout)); } catch (error) { console.error(error); message.channel.send('Failed to start the livestream.') .then(msg => setTimeout(() => msg.delete().catch(console.error), deleteTimeout)); } }, };
@extends('admin.users.layout') @section('users.content') <div class="container"> <div class="card"> <div class="card-header d-flex flex-column flex-md-row align-items-md-center justify-content-between"> <div class="text-center my-2 m-2"> <a href="{{ route('users.create', []) }}" class="btn btn-primary"><i class="fa fa-plus"></i> @lang('Tambah Data')</a> </div> <ol class="breadcrumb m-0 p-0 flex-grow-1 mb-2 mb-md-0"> <li class="breadcrumb-item"><a href="{{ implode('/', ['','users']) }}"> Users</a></li> </ol> <form action="{{ route('users.index', []) }}" method="GET" class="m-0 p-0"> <div class="input-group"> <input type="text" class="form-control form-control-sm me-2" name="search" placeholder="Search Users..." value="{{ request()->search }}"> <span class="input-group-btn"> <button class="btn btn-info btn-sm" type="submit"><i class="fa fa-search"></i> @lang('Go!')</button> </span> </div> </form> </div> <div class="card-body"> <table class="table table-striped table-responsive table-hover"> <thead role="rowgroup"> <tr role="row"> <th role='columnheader'>No</th> <th role='columnheader'>Name</th> <th role='columnheader'>Email</th> <th role='columnheader'>Role</th> <th scope="col" data-label="Actions">Actions</th> </tr> </thead> <tbody> <?php $no = 0; ?> @foreach($users as $user) <?php $no++; ?> <tr> <td data-label="Name">{{ $no }}</td> <td data-label="Name">{{ $user->name ?: "(blank)" }}</td> <td data-label="Email">{{ $user->email ?: "(blank)" }}</td> <td data-label="Role">{{ $user->role }}</td> <td data-label="Actions:" class="text-nowrap"> <a href="{{route('users.show', compact('user'))}}" type="button" class="btn btn-primary btn-sm me-1">@lang('Show')</a> <div class="btn-group btn-group-sm"> <button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"><i class="fa fa-cog"></i></button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="{{route('users.edit', compact('user'))}}">@lang('Edit')</a></li> <li> <form action="{{route('users.destroy', compact('user'))}}" method="POST" style="display: inline;" class="m-0 p-0"> @csrf @method('DELETE') <button type="submit" class="dropdown-item">@lang('Delete')</button> </form> </li> </ul> </div> </td> </tr> @endforeach </tbody> </table> {{ $users->withQueryString()->links() }} </div> </div> </div> @endsection
package webhooksrv import ( "github.com/LeeZXin/zall/pkg/apisession" "github.com/LeeZXin/zall/pkg/webhook" "github.com/LeeZXin/zall/util" "net/url" "strings" ) type CreateWebhookReqDTO struct { RepoId int64 `json:"repoId"` HookUrl string `json:"hookUrl"` Secret string `json:"secret"` Events webhook.Events `json:"events"` Operator apisession.UserInfo `json:"operator"` } func (r *CreateWebhookReqDTO) IsValid() error { parsedUrl, err := url.Parse(r.HookUrl) if err != nil || !strings.HasPrefix(parsedUrl.Scheme, "http") { return util.InvalidArgsError() } if !r.Operator.IsValid() { return util.InvalidArgsError() } if len(r.Secret) == 0 || len(r.Secret) > 1024 { return util.InvalidArgsError() } if !r.Events.IsValid() { return util.InvalidArgsError() } return nil } type DeleteWebhookReqDTO struct { WebhookId int64 `json:"webhookId"` Operator apisession.UserInfo `json:"operator"` } func (r *DeleteWebhookReqDTO) IsValid() error { if r.WebhookId <= 0 { return util.InvalidArgsError() } if !r.Operator.IsValid() { return util.InvalidArgsError() } return nil } type PingWebhookReqDTO struct { WebhookId int64 `json:"webhookId"` Operator apisession.UserInfo `json:"operator"` } func (r *PingWebhookReqDTO) IsValid() error { if r.WebhookId <= 0 { return util.InvalidArgsError() } if !r.Operator.IsValid() { return util.InvalidArgsError() } return nil } type ListWebhookReqDTO struct { RepoId int64 `json:"repoId"` Operator apisession.UserInfo `json:"operator"` } func (r *ListWebhookReqDTO) IsValid() error { if r.RepoId <= 0 { return util.InvalidArgsError() } if !r.Operator.IsValid() { return util.InvalidArgsError() } return nil } type WebhookDTO struct { Id int64 RepoId int64 HookUrl string Secret string Events webhook.Events } type UpdateWebhookReqDTO struct { WebhookId int64 `json:"webhookId"` HookUrl string `json:"hookUrl"` Secret string `json:"secret"` Events webhook.Events `json:"events"` Operator apisession.UserInfo `json:"operator"` } func (r *UpdateWebhookReqDTO) IsValid() error { if r.WebhookId <= 0 { return util.InvalidArgsError() } parsedUrl, err := url.Parse(r.HookUrl) if err != nil || !strings.HasPrefix(parsedUrl.Scheme, "http") { return util.InvalidArgsError() } if !r.Operator.IsValid() { return util.InvalidArgsError() } if len(r.Secret) > 1024 { return util.InvalidArgsError() } if !r.Events.IsValid() { return util.InvalidArgsError() } return nil }
import { ReactClientFieldSetting, Avatar as SnAvatar } from '@sensenet/controls-react' import { ReferenceFieldSetting, User } from '@sensenet/default-content-types' import { useLogger, useRepository } from '@sensenet/hooks-react' import React from 'react' import { FileWithFullPath, useDialog } from '../../dialogs' import { DefaultAvatarTemplate } from './default-avatar-template' interface AddItemParams { setAvatar: React.Dispatch<any> } interface UploadAvatarParams extends AddItemParams { files: FileWithFullPath[] | undefined progressObservable: { current: any } } export const Avatar: React.FunctionComponent<ReactClientFieldSetting<ReferenceFieldSetting, User>> = (props) => { const repo = useRepository() const logger = useLogger('Avatar') const { openDialog } = useDialog() const add = ({ setAvatar }: AddItemParams) => { openDialog({ name: 'upload', props: { uploadPath: props.content?.Path || '', disableMultiUpload: true, customUploadFunction: (files: FileWithFullPath[] | undefined, progressObservable: any) => uploadAvatar({ files, progressObservable, setAvatar }), }, dialogProps: { open: true, fullScreen: false }, }) } const uploadAvatar = async ({ files, progressObservable, setAvatar }: UploadAvatarParams) => { if (!files || !props.content) { return } try { const previousAvatarPath = props.content.Avatar?.Url //Upload the actual avatar file under the User content const response = await repo.upload.file({ file: files[files.length - 1], parentPath: props.content.Path, fileName: files[files.length - 1].name, overwrite: true, binaryPropertyName: 'Binary', progressObservable: progressObservable.current, }) //Replace the ImageRef field of the user with the new avatar await repo.patch<User>({ idOrPath: props.content.Id, content: { ImageRef: response.Id, }, }) setAvatar(response.Url) //Remove the previous avatar image from the User if (previousAvatarPath && !previousAvatarPath.startsWith('/binaryhandler')) { await repo.delete({ idOrPath: previousAvatarPath, permanent: true, }) } } catch (error) { logger.error({ message: 'Something went wrong', data: { error } }) } } return <SnAvatar handleAdd={add} hideLabel avatarTemplateOverride={DefaultAvatarTemplate} {...props} /> }
import React from 'react'; import pizzas from '../data/pizzas.json'; import PizzaItem from './Pizza'; import AppCSS from './App.module.css'; import PizzaSVG from '../svg/pizza.svg'; import Cart from './Cart'; import { AppStateProvider } from './AppState'; import SpecialOffer from './SpecialOffer'; const App = () => { const specialOfferPizza = pizzas.find(pizza => pizza.specialOffer); return ( <AppStateProvider> <div className={AppCSS.container}> <div className={AppCSS.header}> <PizzaSVG width={120} height={120} /> <div className={AppCSS.siteTitle}>Delicious Pizza</div> <Cart /> </div> { specialOfferPizza ? <SpecialOffer pizza={specialOfferPizza} /> : null } <ul className={AppCSS.pizzaList}> {pizzas.map((item) => <PizzaItem key={item.id} pizza={item} />)} </ul> </div> </AppStateProvider> ); } export default App;
import React, { ChangeEvent, FC } from 'react'; import { Button, Typography } from '@material-ui/core'; import { User } from '../../core/users/users.types'; import './app.css'; const App: FC<Props> = ({ users, file, onFileChange, onFileUpload }) => { const uploadDisabled = !file; const onInputChange = (event: ChangeEvent<HTMLInputElement>) => { if (event.target.files && event.target.files.length) { onFileChange(event.target.files[0]); } }; const getUsersList = () => users.length ? ( <div className="users-data"> <Typography className="title">Users data:</Typography> <div> {users.map((user) => ( <div>{JSON.stringify(user)}</div> ))} </div> </div> ) : null; return ( <div className="app"> <Typography variant="h3" className="title"> Test task </Typography> <input type="file" onChange={onInputChange} /> <Button disabled={uploadDisabled} variant="contained" color="primary" onClick={onFileUpload}> Upload file </Button> {getUsersList()} </div> ); }; type Props = { onFileChange: (file: File) => void; onFileUpload: () => void; users: User[]; file: File | null; }; export default App;
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <style> .selected { background: #0f0; } li { cursor: pointer; } </style> <script src="https://cdn.polyfill.io/v1/polyfill.js?features=CustomEvent,Element.prototype.closest"></script> </head> <body> Use: <br> Ctrl(Cmd)+Click <br> Shift+Click <br> <ul id="cities"> <li>Lübeck</li> <li>Hamburg</li> <li>München</li> <li>Berlin</li> <li>Leipzig</li> </ul> <script> var listSelect = new ListSelect({ elem: document.querySelector('#cities') }); document.querySelector('#cities').addEventListener('select', function(event) { alert(event.detail); }); function ListSelect(options) { var elem = options.elem; var lastClickedLi = null; elem.onmousedown = function() { return false; }; elem.onclick = function(e) { var li = e.target.closest('li'); if (!li) return; if (e.metaKey || e.ctrlKey) { toggleSelect(li); } else if (e.shiftKey) { selectFromLast(li); } else { selectSingle(li); } dispatchEvent(); lastClickedLi = li; }; function deselectAll() { [].forEach.call(elem.children, function(child) { child.classList.remove('selected') }); } function toggleSelect(li) { li.classList.toggle('selected'); } function selectSingle(li) { deselectAll(); li.classList.add('selected'); } function selectFromLast(target) { var startElem = lastClickedLi || elem.children[0]; target.classList.add('selected'); if (startElem == target) { return; } var isLastClickedBefore = startElem.compareDocumentPosition(target) & 4; if (isLastClickedBefore) { for (var elem = startElem; elem != target; elem = elem.nextElementSibling) { elem.classList.add('selected'); } } else { for (var elem = startElem; elem != target; elem = elem.previousElementSibling) { elem.classList.add('selected'); } } } function dispatchEvent() { var widgetEvent = new CustomEvent("select", { bubbles: true, detail: getSelected() }); elem.dispatchEvent(widgetEvent); } function getSelected() { return [].map.call(elem.querySelectorAll('.selected'), function(li) { return li.innerHTML; }); }; this.getSelected = getSelected; } </script> </body> </html>
import { createContext, useEffect, useReducer } from "react"; import toast from "react-hot-toast"; export const MyContext = createContext(); const Reducer = (state, action) => { switch (action.type) { case "LOGIN": return { ...state, user: action.payload } case "LOGOUT": return { ...state, user: null } default: return state } } const initialState = { user: null } const AuthContext = ({ children }) => { const [state, dispatch] = useReducer(Reducer, initialState); const Login = (data) => { dispatch({ type: "LOGIN", payload: data }) } const Logout = () => { localStorage.removeItem("Logged_In_User") dispatch({ type: "LOGOUT" }) toast.success("Logout Successful !!!") } useEffect(()=>{ // alert("User refreshed the page") const isUserLoggedIn=JSON.parse(localStorage.getItem("Logged_In_User")) if(isUserLoggedIn){ const users=JSON.parse(localStorage.getItem("USER_DB")); for(var i=0;i<users.length;i++){ if(isUserLoggedIn.email===users[i].email){ Login({name:users[i].name,email:users[i].email}) } } } },[]) return ( <MyContext.Provider value={{ state, Login, Logout }}> {children} </MyContext.Provider> ) } export default AuthContext;
import styles from './Mail.module.css'; import {useState, useEffect, useRef} from 'react' import { callGetMailAPI, callDELETEMailAPI, callPutMailAPI, callSeleteDELETEMailAPI, callPutReadMailAPI, } from '../../apis/MailAPICalls'; import { useDispatch, useSelector } from 'react-redux'; import MailDetails from "../../pages/Mail/MailDetails" import {useInView} from "react-intersection-observer"; import SockJS from 'sockjs-client'; import Stomp from 'stompjs'; import {decodeJwt} from "../../util/tokenUtils"; // import * as StompJs from "@stomp/stompjs"; function MailContent(){ const [search, setSearch] = useState(''); const [result, setResult] = useState('절대로아무도검색하지않을만한값입니다.'); const dispatch = useDispatch(); const mailData = useSelector(state => state.mailReducer); const [currentPage, setCurrentPage] = useState(1); const pageNumber = []; const pageInfo = mailData.pageInfo; if(pageInfo){ for(let i = 1; i <= pageInfo.pageEnd ; i++){ pageNumber.push(i); } } const onClickMailDelete = async () => { dispatch( callDELETEMailAPI() ); window.location.reload(); alert('성공적으로 삭제가 되었습니다!') } const onClickSearch = async () =>{ console.log(result) dispatch( callGetMailAPI(currentPage, result) ) } // // 무한 스크롤 페이지네이션 const [ref, inView] = useInView(); console.log(mailData.data) useEffect( () => { if(inView){ setCurrentPage((prev) => prev + 1) } } ,[inView] ); useEffect(() => { dispatch(callGetMailAPI(currentPage,result)) } , [currentPage, dispatch, result] ) const onClickTest = function() { console.log(mailData.data); } return( <div className={styles.content}> <div className={styles.mainHeader}> <div onClick={onClickTest} className={styles.contentHeader}> 받은 쪽지 </div> <div onClick={onClickMailDelete} className={styles.allDelete}> 전체 삭제 </div> <div style={{display: "flex", justifyContent:"flex-start"}}> <div className={styles.type}> 제목</div> <input value={search} onChange={ (e) => { console.log(search); setResult(e.target.value); return setSearch(e.target.value)} } type="text" className={styles.inputText}/> <input onClick={ () => onClickSearch() } type="button" value="검색" className={styles.inputButton}/> </div> </div> <div> { mailData.data && mailData.data.map((mail) => ( <> <MailItem key={mail.mailNo} mail={mail} /> </> )) } </div> {/* 새로운 값을 가져오는 영역 */} <div ref={ref} style={mailData.data !== null && mailData.data.length ? { width:'auto', height:'100px'} : {display:'none'}} > </div> {/* 페이지 버튼 */} {/*<div style={{ listStyleType: "none", display: "flex", justifyContent: "center" }}>*/} {/* { Array.isArray(mailData.data) &&*/} {/* <button style={ mailData.data.length > 1 ? {border:"none", color:"black", fontWeight:"500", backgroundColor:"white", fontSize:"20px"} : {display:"none"}}*/} {/* onClick={() => setCurrentPage(currentPage - 1)}*/} {/* disabled={currentPage === 1}*/} {/* >*/} {/* &lt;*/} {/* </button>*/} {/* }*/} {/* {pageNumber.map((num) => (*/} {/* <li key={num} onClick={() => setCurrentPage(num)}>*/} {/* <button*/} {/* style={ currentPage === num ? {backgroundColor : 'white', border:"none", fontSize:"20px", color:"", cursor:"pointer"} : {backgroundColor : 'white', border:"none", color:"", cursor:"pointer"} }*/} {/* >*/} {/* {num}*/} {/* </button>*/} {/* </li>*/} {/* ))}*/} {/* { Array.isArray(mailData.data) &&*/} {/* <button style={ mailData.data.length > 1 ? {border:"none", color:"black", fontWeight:"500", backgroundColor:"white", fontSize:"20px"} : {display:"none"}}*/} {/* onClick={() => {return setCurrentPage(currentPage + 1)}}*/} {/* disabled={currentPage === pageInfo.pageEnd || pageInfo.total == 0}*/} {/* >*/} {/* &gt;*/} {/* </button>*/} {/* }*/} {/*</div>*/} </div> ) } function MailItem({ mail }) { const [modal, setModal] = useState(false); const inputDate = mail.goDate; const date = new Date(inputDate); const outputDate = date.toISOString().substr(0, 19); const updatedDate = outputDate.replace("T", " "); const dispatch = useDispatch(); const onClickModal = () => { setModal(!modal); } // 북마크 const onClickbookmark = () => { dispatch( callPutMailAPI(mail) ); window.location.reload(); }; // 읽음 처리 const onClickReadMail = () =>{ dispatch(callPutReadMailAPI(mail)); } // 쪽지 삭제 const onClickSelectDelete = (mail) =>{ dispatch( callSeleteDELETEMailAPI(mail) ) window.location.reload(); } return ( <> <div className={styles.receivedNote}> <div style={(mail.status == 'Y') ? {color : "gold"} : {}} className={styles.bookmark} onClick={onClickbookmark}> {( mail.status == 'Y') ? '★' : '☆'} </div> <div onClick={ () => onClickModal() } className={styles.noteHeader}> <div onClick={() => onClickReadMail()} style={mail.read === 'Y' ? { color:"gray", marginBottom: "5px", cursor:"pointer"} : { marginBottom: "5px", cursor:"pointer"}}> {mail.title} </div> <div style={{ display: "flex" }}> <div style={{ color: "gray" }}> {updatedDate} </div> <div style={{ marginLeft: "15px", color: "gray" }}> {mail.receiver} </div> </div> </div> <div onClick={ () => onClickSelectDelete(mail)} className={styles.deleteButton}> x </div> </div> <div style={ modal ? {display:"inline"} : {display: "none"} }> <MailDetails setModal = { setModal } mail={ mail } /> </div> </> ); } export default MailContent;
'use client'; import React, {type ForwardedRef, forwardRef, type ReactNode} from 'react'; import {type AriaButtonOptions, useButton} from 'react-aria'; import {useObjectRef} from '@react-aria/utils'; import {type VariantProps} from '@/lib/cva.ts'; import buttonVariant from '@/components/button/button-variants.tsx'; export type ButtonProps = { readonly children?: ReactNode; readonly className?: string; } & AriaButtonOptions<'button'> & VariantProps<typeof buttonVariant>; export default forwardRef((props: ButtonProps, ref: ForwardedRef<HTMLButtonElement>) => { const {children} = props; const buttonRef = useObjectRef(ref); const {buttonProps} = useButton({ ...props, // Workaround for react/react-aria #1513 onPress(event) { if (event.pointerType === 'mouse' || event.pointerType === 'keyboard') { props.onPress?.(event); return; } setTimeout(() => { props.onPress?.(event); }, 1); }, }, buttonRef); return ( <button {...buttonProps} ref={buttonRef} className={buttonVariant(props)} > {children} </button> ); });
// // ContentView.swift // LoginPage // // Created by Sena Kurtak on 12.06.2022. // import SwiftUI struct ContentView: View { var body: some View { Home() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct Home : View { var body : some View{ VStack{ Login() } } } struct Login : View { @State var color = Color.black.opacity(0.7) @State var email = "" @State var pass = "" @State var visible = false @State var checkedSubscribe = false @State var checkedTerms = false var body : some View{ VStack{ Image("logo") Text("Log into your account") .font(.title) .fontWeight(.bold) .foregroundColor(self.color) .padding(.top, 35) TextField("Email", text: self.$email) .padding() .padding(.top,25) HStack (spacing: 15){ VStack{ if self.visible{ TextField("Password", text: self.$pass) } else { SecureField("Password", text: self.$pass) } } Button(action: { self.visible.toggle() }){ Image(systemName: self.visible ? "eye.slash.fill" : "eye.fill").foregroundColor(self.color) } } .padding() } VStack{ HStack{ Image(systemName: checkedSubscribe ? "checkmark.square.fill" : "square") .foregroundColor(checkedSubscribe ? Color(red: (104/250), green: 141/250, blue: 102/250) : Color.secondary) .onTapGesture { self.checkedSubscribe.toggle() } .padding() Text("Unsubscribe from the mailing list") Spacer() .background(.white) } HStack{ Image(systemName: checkedTerms ? "checkmark.square.fill" : "square") .foregroundColor(checkedTerms ? Color(red: (104/250), green: 141/250, blue: 102/250) : Color.secondary) .onTapGesture { self.checkedTerms.toggle() } .padding() Text("I accept the Terms of use") Spacer() .background(.white) } .background(.white) } } }
// // PlacesSearchListView.swift // TodoMap // // Created by Suguru on 8/21/23. // import SwiftUI struct PlaceSearchListView: View { @EnvironmentObject private var vm: PlaceSearchViewModel var predictions: [Prediction] var nearbySearchResults: [NearbySearchResult] var onPredictionSelected: ((_ prediction: Prediction) -> ())? var onNearBySearhcResultSelected: ((_ result: NearbySearchResult) -> ())? var body: some View { ScrollView { LazyVStack(spacing: 0) { if !predictions.isEmpty { HStack { Text(String.constants.autocomplete) .font(.callout) .fontWeight(.bold) .foregroundColor(Color.theme.text) Spacer() } .padding(.horizontal, 5) ForEach(predictions, id: \.self.id) { prediction in Button { onPredictionSelected?(prediction) UIApplication.shared.endEditing() } label: { AutoCompleteListRowView(prediction: prediction) } } } if !nearbySearchResults.isEmpty { HStack { Text(String.constants.nearbySearch) .font(.callout) .fontWeight(.bold) .foregroundColor(Color.theme.text) Spacer() } .padding(.horizontal, 5) ForEach(nearbySearchResults, id: \.self.id) { result in Button { onNearBySearhcResultSelected?(result) UIApplication.shared.endEditing() } label: { NearBySearchListRowView(result: result, region: vm.region) } } } } } .scrollDismissesKeyboard(.interactively) } } struct PlacesSearchListView_Previews: PreviewProvider { static var previews: some View { PlaceSearchListView(predictions: dev.placePredictions, nearbySearchResults: dev.nearbySearchResults) .environmentObject(PlaceSearchViewModel()) .preferredColorScheme(.dark) PlaceSearchListView(predictions: dev.placePredictions, nearbySearchResults: dev.nearbySearchResults) .environmentObject(PlaceSearchViewModel()) } }
import http.client import json import os from database.auth_db import get_auth_token from database.token_db import get_token , get_br_symbol, get_symbol, get_oa_symbol from broker.fivepaisa.mapping.transform_data import transform_data , map_product_type, reverse_map_product_type, transform_modify_order_data from broker.fivepaisa.mapping.transform_data import map_exchange, map_exchange_type, reverse_map_exchange # Retrieve the BROKER_API_KEY and BROKER_API_SECRET environment variables broker_api_key = os.getenv('BROKER_API_KEY') api_secret = os.getenv('BROKER_API_SECRET') api_key, user_id, client_id = broker_api_key.split(':::') json_data = { "head": { "key": api_key }, "body": { "ClientCode": client_id } } def get_api_response(endpoint, auth, method="GET", payload=''): AUTH_TOKEN = auth conn = http.client.HTTPSConnection("Openapi.5paisa.com") headers = { 'Authorization': f'bearer {AUTH_TOKEN}', 'Content-Type': 'application/json', } conn.request(method, endpoint, payload, headers) res = conn.getresponse() data = res.read() return json.loads(data.decode("utf-8")) def get_order_book(auth): payload = json.dumps(json_data) return get_api_response("/VendorsAPI/Service1.svc/V3/OrderBook",auth,method="POST",payload=payload) def get_trade_book(auth): payload = json.dumps(json_data) return get_api_response("/VendorsAPI/Service1.svc/V1/TradeBook",auth,method="POST",payload=payload) def get_positions(auth): payload = json.dumps(json_data) return get_api_response("/VendorsAPI/Service1.svc/V2/NetPositionNetWise",auth,method="POST",payload=payload) def get_holdings(auth): payload = json.dumps(json_data) return get_api_response("/VendorsAPI/Service1.svc/V3/Holding",auth,method="POST",payload=payload) def get_open_position(tradingsymbol, exchange, Exch,ExchType , producttype,auth): #Convert Trading Symbol from OpenAlgo Format to Broker Format Before Search in OpenPosition tradingsymbol = get_br_symbol(tradingsymbol,exchange) positions_data = get_positions(auth) net_qty = '0' if positions_data and positions_data.get('body'): for position in positions_data['body']['NetPositionDetail']: if position.get('ScripName').upper() == tradingsymbol and position.get('Exch') == Exch and position.get('ExchType') == ExchType and position.get('OrderFor') == producttype: net_qty = position.get('NetQty', '0') break # Assuming you need the first match return net_qty def place_order_api(data,auth): AUTH_TOKEN = auth token = get_token(data['symbol'], data['exchange']) newdata = transform_data(data, token) headers = { 'Content-Type': 'application/json', 'Authorization': f'bearer {AUTH_TOKEN}' } json_data = { "head": { "key": api_key }, "body": newdata } payload = json.dumps(json_data) print(payload) conn = http.client.HTTPSConnection("Openapi.5paisa.com") conn.request("POST", "/VendorsAPI/Service1.svc/V1/PlaceOrderRequest", payload, headers) res = conn.getresponse() response_data = json.loads(res.read().decode("utf-8")) print(response_data) if response_data['head']['statusDescription'] == "Success": orderid = response_data['body']['ExchOrderID'] else: orderid = None return res, response_data, orderid def place_smartorder_api(data,auth): AUTH_TOKEN = auth #If no API call is made in this function then res will return None res = None # Extract necessary info from data symbol = data.get("symbol") exchange = data.get("exchange") product = data.get("product") position_size = int(data.get("position_size", "0")) exch = map_exchange(exchange) exchtype = map_exchange_type(exchange) # Get current open position for the symbol current_position = int(get_open_position(symbol, exchange, exch, exchtype, map_product_type(product),AUTH_TOKEN)) print(f"position_size : {position_size}") print(f"Open Position : {current_position}") # Determine action based on position_size and current_position action = None quantity = 0 # If both position_size and current_position are 0, do nothing if position_size == 0 and current_position == 0: action = data['action'] quantity = data['quantity'] #print(f"action : {action}") #print(f"Quantity : {quantity}") res, response, orderid = place_order_api(data,auth) # print(res) # print(response) # print(orderid) return res , response, orderid elif position_size == current_position: response = {"status": "success", "message": "No action needed. Position size matches current position."} orderid = None return res, response, orderid # res remains None as no API call was mad if position_size == 0 and current_position>0 : action = "SELL" quantity = abs(current_position) elif position_size == 0 and current_position<0 : action = "BUY" quantity = abs(current_position) elif current_position == 0: action = "BUY" if position_size > 0 else "SELL" quantity = abs(position_size) else: if position_size > current_position: action = "BUY" quantity = position_size - current_position #print(f"smart buy quantity : {quantity}") elif position_size < current_position: action = "SELL" quantity = current_position - position_size #print(f"smart sell quantity : {quantity}") if action: # Prepare data for placing the order order_data = data.copy() order_data["action"] = action order_data["quantity"] = str(quantity) #print(order_data) # Place the order res, response, orderid = place_order_api(order_data,auth) #print(res) print(response) print(orderid) return res , response, orderid def close_all_positions(current_api_key,auth): # Fetch the current open positions AUTH_TOKEN = auth positions_response = get_positions(AUTH_TOKEN) # Check if the positions data is null or empty if positions_response['body']['NetPositionDetail'] is None or not positions_response['body']['NetPositionDetail']: return {"message": "No Open Positions Found"}, 200 if positions_response['body']['NetPositionDetail']: # Loop through each position to close for position in positions_response['body']['NetPositionDetail']: # Skip if net quantity is zero if int(position['NetQty']) == 0: continue # Determine action based on net quantity action = 'SELL' if int(position['NetQty']) > 0 else 'BUY' quantity = abs(int(position['NetQty'])) exchange = reverse_map_exchange(position['Exch'],position['ExchType']) #get openalgo symbol to send to placeorder function symbol = get_oa_symbol(position['ScripName'].upper(),exchange) # Prepare the order payload place_order_payload = { "apikey": current_api_key, "strategy": "Squareoff", "symbol": symbol, "action": action, "exchange": exchange, "pricetype": "MARKET", "product": reverse_map_product_type(position['OrderFor'],exchange), "quantity": str(quantity) } print(place_order_payload) # Place the order to close the position res, response, orderid = place_order_api(place_order_payload,auth) # print(res) # print(response) # print(orderid) # Note: Ensure place_order_api handles any errors and logs accordingly return {'status': 'success', "message": "All Open Positions SquaredOff"}, 200 def cancel_order(orderid,auth): # Assuming you have a function to get the authentication token AUTH_TOKEN = auth # Set up the request headers headers = { 'Authorization': f'bearer {AUTH_TOKEN}', 'Content-Type': 'application/json', } # Prepare the payload json_data = { "head": { "key": api_key }, "body": { "ExchOrderID": orderid, } } payload = json.dumps(json_data) print(payload) # Establish the connection and send the request conn = http.client.HTTPSConnection("Openapi.5paisa.com") # Adjust the URL as necessary conn.request("POST", "/VendorsAPI/Service1.svc/V1/CancelOrderRequest", payload, headers) res = conn.getresponse() data = json.loads(res.read().decode("utf-8")) print(data) # Check if the request was successful if data["head"]["status"]=='0' and data["body"]["Status"]==0 : # Return a success response return {"status": "success", "orderid": orderid}, 200 else: # Return an error response return {"status": "error", "message": data.get('body', {}).get('Message', 'Failed to cancel order')}, res.status def modify_order(data,auth): # Assuming you have a function to get the authentication token AUTH_TOKEN = auth transformed_data = transform_modify_order_data(data) # You need to implement this function # Set up the request headers headers = { 'Authorization': f'bearer {AUTH_TOKEN}', 'Content-Type': 'application/json', } # Prepare the payload json_data = { "head": { "key": api_key }, "body": transformed_data } payload = json.dumps(json_data) print(payload) conn = http.client.HTTPSConnection("Openapi.5paisa.com") conn.request("POST", "/VendorsAPI/Service1.svc/V1/ModifyOrderRequest", payload, headers) res = conn.getresponse() data = json.loads(res.read().decode("utf-8")) response = print(f'The response is {data}') if data['body']['Message'] == "Success" or data['body']['Message'] == "SUCCESS": return {"status": "success", "orderid": data["body"]["ExchOrderID"]}, 200 else: return {"status": "error", "message": data.get('body', {}).get('Message', 'Failed to Modify order')}, res.status def cancel_all_orders_api(data,auth): # Get the order book AUTH_TOKEN = auth order_book_response = get_order_book(AUTH_TOKEN) #print(order_book_response) if order_book_response['body']['OrderBookDetail'] is None: return [], [] # Return empty lists indicating failure to retrieve the order book # Filter orders that are in 'open' or 'trigger_pending' state orders_to_cancel = [order for order in order_book_response['body']['OrderBookDetail'] if order['OrderStatus'] in ['Pending','Modified']] #print(orders_to_cancel) canceled_orders = [] failed_cancellations = [] # Cancel the filtered orders for order in orders_to_cancel: orderid = order['ExchOrderID'] cancel_response, status_code = cancel_order(orderid,auth) if status_code == 200: canceled_orders.append(orderid) else: failed_cancellations.append(orderid) return canceled_orders, failed_cancellations
import "./App.css"; import Header from "./components/Header"; import Create from "./components/Create"; import Read from "./components/Read"; import { BlogDetail } from "./components/BlogDetail"; import Update from "./components/Update"; import Home from "./components/Home"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import "bootstrap/dist/css/bootstrap.min.css"; function App() { return ( <div className="App"> <BrowserRouter> <Header /> <Routes> <Route path="/" element={<Home />}></Route> <Route path="/createblog" element={<Create />}></Route> <Route path="/allblogs" element={<Read />}></Route> <Route path="/allblogs/:id" element={<BlogDetail />}></Route> <Route path="/updateblog/:id" element={<Update />}></Route> </Routes> </BrowserRouter> </div> ); } export default App;
import { useCallback, useEffect, useState } from "react"; interface ISize { clientWidth: number; clientHeight: number; } const useResize = (contentId: string = "resizable-content") => { const [size, setSize] = useState<ISize>({ clientWidth: 0, clientHeight: 0, }); const handleChangeResize = useCallback(() => { try { const content = document.getElementById(contentId); if (content) { setSize({ clientWidth: content?.clientWidth || 0, clientHeight: content?.clientHeight || 0, }); } } catch (error) { console.error("useResize - handleChangeResize function error: ", error); } }, [contentId]); useEffect(() => { handleChangeResize(); window.addEventListener("resize", handleChangeResize); return () => { window.removeEventListener("resize", handleChangeResize); }; }, [handleChangeResize]); return size; }; export default useResize;
import React, {useContext} from 'react'; import {observer} from "mobx-react-lite"; import {Context} from "../index"; import {ListGroup, ListGroupItem} from "react-bootstrap"; const TypeBar = observer(() => { const {device} = useContext(Context) return ( <ListGroup> <ListGroupItem disabled={true} className="fw-light">Тип:</ListGroupItem> {device.types.map(type => <ListGroup.Item action variant="light" style={{cursor: "pointer"}} active={type.id === device.selectedType.id} onClick={() => device.setSelectedType(type)} key={type.id} > {type.name} </ListGroup.Item> )} </ListGroup> ); }); export default TypeBar;
import { EntityRepository, Repository } from "typeorm"; import { Subscribe } from "../entity/Subscribe"; @EntityRepository(Subscribe) export class SubscribeRepository extends Repository<Subscribe> { // 구독 생성 async createSubscribe(subscribeModel: Subscribe): Promise<void> { await this.save(subscribeModel); } async updateSubscribe(subscribeId: string, date: Date): Promise<void> { await this.update(subscribeId, { expiredDate: date }); } // 해당 구독의 만료일자 업데이트 async updateExpiredDate(subscribeId: string, date: Date): Promise<void> { await this.update(subscribeId, { expiredDate: date }); } // 해당 유저의 모든 구독 반환 async querySubscribes(userId: string, options?: { subscribeId?: string payment?: { startDate: Date; endDate: Date; }, service?: boolean; }) { let query = this.createQueryBuilder("subscribe") .select([ "subscribe", "subscribe.user", "subscribeItems.amount", "subscribeItems.reserved", "product"]) .where(`subscribe.user = "${userId}"`) .innerJoin("subscribe.user", "user") .innerJoin("subscribe.subscribeItems", "subscribeItems") .innerJoin("subscribeItems.product", "product") if (options) { if (options.payment) { query = query.addSelect([ "payment.id", "payment.amount", "payment.paymentDate", "payment.paymentComplete", "payment.paymentFailure", "payment.failureReason", "payment.paidCardVendor", "payment.paidCardNumber", "payment.createdAt", "payment.updatedAt" ]) if (options.payment.endDate && options.payment.startDate) { query = query.innerJoin('subscribe.payments', "payment", `payment.paymentDate <= "${options.payment.endDate.toISOString()}" AND payment.paymentDate >= "${options.payment.startDate.toISOString()}"`); } else { query = query.innerJoin('subscribe.payments', "payment"); } query = query.leftJoinAndSelect('payment.reward', 'reward'); query = query.orderBy('payment.paymentDate', 'DESC') } if (options.service) { query = query.innerJoinAndSelect("product.service", "service"); } if (options.subscribeId) { query = query.andWhere(`subscribe.id = "${options.subscribeId}"`) } } return await query.getMany() } // 해당 서비스에 대한 구독만 반환 async querySubscribesByServiceId(userId: string, serviceId: string) { return await this.createQueryBuilder("subscribe") .select([ "subscribe", "subscribe.user", "subscribeItems.amount", "subscribeItems.reserved", "product", "payment.id", "payment.amount", "payment.paymentDate", "payment.paymentComplete", "payment.paymentFailure", "payment.failureReason", "payment.paidCardVendor", "payment.paidCardNumber", "payment.createdAt", "payment.updatedAt"]) .where(`subscribe.user = "${userId}"`) .innerJoin("subscribe.user", "user") .innerJoin("subscribe.subscribeItems", "subscribeItems") .innerJoin("subscribeItems.product", "product", `product.serviceId = "${serviceId}"`) .innerJoin('subscribe.payments', "payment") .getOne(); } }
package dev.turtywurty.gamedashboard.view.add_game; import dev.turtywurty.gamedashboard.data.GameService; import dev.turtywurty.gamedashboard.util.ImageCache; import dev.turtywurty.gamedashboard.data.APIConnector; import dev.turtywurty.gamedashboard.data.Database; import dev.turtywurty.gamedashboard.util.Utils; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.TextAlignment; import javafx.stage.FileChooser; import javafx.util.Duration; import javafx.util.StringConverter; import org.jetbrains.annotations.Nullable; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; public class AddGamePane extends BorderPane { private final ComboBox<String> serviceComboBox = new ComboBox<>(); private final Label serviceErrorLabel = new Label(); private final ComboBox<String> gameTitleComboBox = new ComboBox<>(); private final Label gameTitleErrorLabel = new Label(); private final TextField gameExecutableTextField = new TextField(); private final Button browseButton = new Button("Browse"); private final Label gameExecutableErrorLabel = new Label(); private final Button cancelButton = new Button("Cancel"); private final Button nextButton = new Button("Next"); private final AtomicBoolean closedFromNext = new AtomicBoolean(false); public AddGamePane() { Label title = new Label("Add Game"); title.setTextFill(Color.web("#eee")); title.setAlignment(Pos.CENTER); title.setTextAlignment(TextAlignment.CENTER); title.setPrefHeight(50); title.setPrefWidth(400); title.setStyle("-fx-font-size: 20px; -fx-font-weight: bold;"); setTop(title); setCenter(createForm()); setBottom(createButtons()); setPadding(Utils.createInsets(10)); setBackground(Utils.createBackground("#3f3f4a")); } private HBox createButtons() { var buttons = new HBox(this.cancelButton, this.nextButton); buttons.setSpacing(10); buttons.setAlignment(Pos.CENTER); buttons.setBackground(Utils.createBackground("#3f3f4a")); this.cancelButton.setOnAction(event -> { getScene().getWindow().hide(); this.closedFromNext.set(false); }); this.nextButton.setOnAction(event -> { // Validate boolean valid = true; if (this.serviceComboBox.getValue() == null || this.serviceComboBox.getValue().isBlank()) { this.serviceErrorLabel.setText("Please select a service"); this.serviceErrorLabel.setVisible(true); valid = false; } else { try { GameService.valueOf(this.serviceComboBox.getValue().toUpperCase(Locale.ROOT)); this.serviceErrorLabel.setVisible(false); } catch (IllegalArgumentException ignored) { this.serviceErrorLabel.setText("Invalid service"); this.serviceErrorLabel.setVisible(true); valid = false; } } if (this.gameTitleComboBox.getValue() == null || this.gameTitleComboBox.getValue().isBlank()) { this.gameTitleErrorLabel.setText("Please select a game title"); this.gameTitleErrorLabel.setVisible(true); valid = false; } else if (hasGame(this.gameTitleComboBox.getValue())) { this.gameTitleErrorLabel.setText("Game already exists in database"); this.gameTitleErrorLabel.setVisible(true); valid = false; } else { this.gameTitleErrorLabel.setVisible(false); } if (this.gameExecutableTextField.getText() == null || this.gameExecutableTextField.getText().isBlank()) { this.gameExecutableErrorLabel.setText("Please select the game's executable"); this.gameExecutableErrorLabel.setVisible(true); valid = false; } else { String dir = this.gameExecutableTextField.getText(); Path path = Path.of(dir); if (Files.notExists(path)) { this.gameExecutableErrorLabel.setText("Invalid game executable"); this.gameExecutableErrorLabel.setVisible(true); valid = false; } else { if (Files.isDirectory(path)) { this.gameExecutableErrorLabel.setText("Game executable cannot be a directory"); this.gameExecutableErrorLabel.setVisible(true); valid = false; } else if (!Files.isExecutable(path)) { this.gameExecutableErrorLabel.setText("Game executable must be executable"); this.gameExecutableErrorLabel.setVisible(true); valid = false; } else { this.gameExecutableErrorLabel.setVisible(false); } } } if (!valid) return; GameService service = GameService.valueOf(this.serviceComboBox.getValue().toUpperCase(Locale.ROOT)); String gameTitle = this.gameTitleComboBox.getValue(); Path gameExecutable = Path.of(this.gameExecutableTextField.getText()); Scene scene = getScene(); switch (service) { case STEAM -> scene.setRoot(new AddSteamGamePane(gameTitle, gameExecutable)); case ORIGIN -> scene.setRoot(new AddOriginGamePane(gameTitle, gameExecutable)); case EPIC_GAMES -> scene.setRoot(new AddEpicGamesGamePane(gameTitle, gameExecutable)); case UPLAY -> scene.setRoot(new AddUplayGamePane(gameTitle, gameExecutable)); case BATTLE_NET -> scene.setRoot(new AddBattleNetGamePane(gameTitle, gameExecutable)); case OTHER -> { APIConnector.GameResult gameResult = construct(); if (gameResult == null) { scene.setRoot(new AddOtherGamePane(gameTitle, gameExecutable)); scene.getWindow().setWidth(720); scene.getWindow().setHeight(600); } else { scene.getWindow().hide(); this.closedFromNext.set(true); } } default -> { this.serviceErrorLabel.setText("Invalid service, please choose from (" + Arrays.stream(GameService.values()) .map(GameService::getName) .reduce((a, b) -> a + ", " + b) .orElse("") + ")"); this.serviceErrorLabel.setVisible(true); System.err.println("Invalid service was provided: " + service); } } }); return buttons; } private static boolean hasGame(String gameTitle) { if (gameTitle == null || gameTitle.isBlank()) return false; return Database.getInstance().getGames().stream() .anyMatch(game -> game.getTitle().trim().equalsIgnoreCase(gameTitle.trim())); } private VBox createForm() { var form = new VBox(); var serviceLabel = new Label("Service"); serviceLabel.setPrefWidth(100); serviceLabel.setAlignment(Pos.CENTER_LEFT); serviceLabel.setTextFill(Color.web("#eee")); var gameTitleLabel = new Label("Game Title"); gameTitleLabel.setPrefWidth(100); gameTitleLabel.setAlignment(Pos.CENTER_LEFT); gameTitleLabel.setTextFill(Color.web("#eee")); var gameExecutableLabel = new Label("Game Executable"); gameExecutableLabel.setPrefWidth(100); gameExecutableLabel.setAlignment(Pos.CENTER_LEFT); gameExecutableLabel.setTextFill(Color.web("#eee")); var serviceHContainer = new HBox(serviceLabel, this.serviceComboBox); serviceHContainer.setSpacing(10); serviceHContainer.setAlignment(Pos.CENTER_LEFT); serviceHContainer.setFillHeight(false); var serviceContainer = new VBox(serviceHContainer, this.serviceErrorLabel); for (GameService service : GameService.values()) { if (service == GameService.OTHER) { this.serviceComboBox.getItems().add(service.getName()); continue; } if (service != GameService.STEAM) { this.serviceComboBox.getItems().add(service.getName() + " (Coming Soon)"); } } this.serviceComboBox.setCellFactory(param -> new ListCell<>() { @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { setText(item); setDisable(!GameService.OTHER.getName().equals(item)); } } }); this.serviceComboBox.setValue(GameService.OTHER.getName()); this.serviceErrorLabel.setVisible(false); this.serviceErrorLabel.setTextFill(Color.web("#ff0000")); var gameTitleHContainer = new HBox(gameTitleLabel, this.gameTitleComboBox); gameTitleHContainer.setSpacing(10); gameTitleHContainer.setAlignment(Pos.CENTER_LEFT); gameTitleHContainer.setFillHeight(false); var gameTitleContainer = new VBox(gameTitleHContainer, this.gameTitleErrorLabel); this.gameTitleErrorLabel.setVisible(false); this.gameTitleErrorLabel.setTextFill(Color.web("#ff0000")); this.gameTitleComboBox.setEditable(true); this.gameTitleComboBox.setCellFactory(param -> new ListCell<>() { @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setText(null); setGraphic(null); return; } String[] split = item.split("\\|\\|"); setText(split[0]); if (split.length > 1) { ImageView imageView = new ImageView(ImageCache.getImage(split[1])); imageView.setFitWidth(35); imageView.setFitHeight(35); setGraphic(imageView); } } }); this.gameTitleComboBox.editorProperty().get().textProperty().addListener(new ChangeListener<>() { private final Timeline timeline = new Timeline(new KeyFrame( Duration.millis(500), event -> { String newValue = gameTitleComboBox.editorProperty().get().getText(); if (newValue == null || newValue.isBlank()) return; CompletableFuture<List<APIConnector.GameResult>> gameResultsFuture = APIConnector.search(newValue); gameResultsFuture.thenAccept(gameResults -> { String[] items = gameResults.stream() .map(result -> result.getName() + "||" + result.getThumbCoverURL()) .toArray(String[]::new); Platform.runLater(() -> { if (items.length != 0) { gameTitleComboBox.getItems().setAll(items); gameTitleComboBox.show(); } }); }); } )); @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { gameTitleComboBox.hide(); gameTitleComboBox.getItems().clear(); this.timeline.stop(); this.timeline.play(); } }); this.gameTitleComboBox.setConverter(new StringConverter<>() { @Override public String toString(String object) { if (object == null || object.isBlank()) return ""; String[] split = object.split("\\|\\|"); return split[0]; } @Override public String fromString(String string) { if (string == null || string.isBlank()) return ""; String[] split = string.split("\\|\\|"); return split[0]; } }); this.gameTitleComboBox.setVisibleRowCount(5); this.gameTitleComboBox.setPrefWidth(300); var gameExecutableHContainer = new HBox(gameExecutableLabel, this.gameExecutableTextField, this.browseButton); gameExecutableHContainer.setSpacing(10); gameExecutableHContainer.setAlignment(Pos.CENTER_LEFT); gameExecutableHContainer.setFillHeight(false); var gameExecutableContainer = new VBox(gameExecutableHContainer, this.gameExecutableErrorLabel); this.browseButton.setOnAction(event -> { FileChooser chooser = new FileChooser(); chooser.setTitle("Select Game Executable"); chooser.setInitialDirectory(Path.of(System.getProperty("user.home")).toFile()); chooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("Executable Files", "*.exe"), new FileChooser.ExtensionFilter("All Files", "*.*") ); chooser.setSelectedExtensionFilter(chooser.getExtensionFilters().get(0)); File result = chooser.showOpenDialog(getScene().getWindow()); if (result == null) return; Path path = Path.of(result.getAbsolutePath()); this.gameExecutableTextField.setText(path.toAbsolutePath().toString()); }); this.gameExecutableErrorLabel.setVisible(false); this.gameExecutableErrorLabel.setTextFill(Color.web("#ff0000")); form.getChildren().addAll(serviceContainer, gameTitleContainer, gameExecutableContainer); form.setSpacing(10); form.setAlignment(Pos.CENTER); form.setBackground(Utils.createBackground("#3f3f4a")); return form; } public @Nullable APIConnector.GameResult construct() { if (!this.closedFromNext.get()) return null; if (this.gameTitleComboBox.getValue() == null || this.gameTitleComboBox.getValue().isBlank()) return null; if (this.gameExecutableTextField.getText() == null || this.gameExecutableTextField.getText().isBlank()) return null; if (this.serviceComboBox.getValue() == null || this.serviceComboBox.getValue().isBlank()) return null; // validate executable Path executable = Path.of(this.gameExecutableTextField.getText()); if (Files.notExists(executable) || Files.isDirectory(executable) || !Files.isExecutable(executable)) return null; // validate service try { GameService.valueOf(this.serviceComboBox.getValue().toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException ignored) { return null; } // validate game title CompletableFuture<List<APIConnector.GameResult>> gameResultsFuture = APIConnector.search(this.gameTitleComboBox.getValue().split("\\|\\|")[0], true); List<APIConnector.GameResult> gameResults = gameResultsFuture.join(); if (gameResults.isEmpty()) return null; // find closest match String gameTitle = this.gameTitleComboBox.getValue(); AtomicReference<APIConnector.GameResult> gameResult = new AtomicReference<>(); for (APIConnector.GameResult result : gameResults) { if (result.getName().equalsIgnoreCase(gameTitle)) { gameResult.set(result); break; } } if (gameResult.get() == null) { // sort by levenshtein distance gameResults.stream().min((a, b) -> { int aDist = Utils.levenshteinDistance(a.getName(), gameTitle); int bDist = Utils.levenshteinDistance(b.getName(), gameTitle); return Integer.compare(aDist, bDist); }) .ifPresent(gameResult::set); } return gameResult.get(); } public String getExecutablePath() { return this.gameExecutableTextField.getText(); } public GameService getService() { return GameService.valueOf(this.serviceComboBox.getValue().toUpperCase(Locale.ROOT)); } }
import React, { useState } from 'react' import { Grid } from '@mui/material'; import Chat from './Chat'; import Drawer from './Drawer'; import Conversations from './Conversations'; import Error from './Error'; type DataDiverProps = { drawerOpen: boolean } function DataDiver({drawerOpen} : Readonly<DataDiverProps>) { const [dbURL, setDbURL] = useState('datadiverserver.database.windows.net') const [dbName, setDbName] = useState('DemoDB') const [dbUsername, setDbUsername] = useState('datadiveradmin') const [dbPassword, setDbPassword] = useState('ouda2023!') const [errorMesssage, setErrorMessage] = useState<null | string>(null); return ( <> <Grid item xs={2}> <Conversations setErrorMessage={setErrorMessage}/> </Grid> <Grid item xs={drawerOpen ? 7 : 10}> <Error errorMessage={errorMesssage} setErrorMessage={setErrorMessage}/> <Chat dbURL={dbURL} dbName={dbName} dbUsername={dbUsername} dbPassword={dbPassword} /> </Grid> <Grid item xs={3} hidden={!drawerOpen}> <Drawer dbURL={dbURL} dbName={dbName} dbUsername={dbUsername} dbPassword={dbPassword} setDbURL={setDbURL} setDbName={setDbName} setDbUsername={setDbUsername} setDbPassword={setDbPassword}/> </Grid> </> ); } export default DataDiver;
using System; using UnityEngine; namespace Bingyan { /// <summary> /// 用于将一个暴露给Unity字符串变成自定义ID选择器的Attribute /// </summary> [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public class StrIDAttribute : PropertyAttribute { private string idGroupKey; private bool allowNew; private string prefix; public string IdGroup => idGroupKey; public bool AllowNew => allowNew; public string Prefix => prefix; /// <summary> /// 用于将一个暴露给Unity字符串变成自定义ID选择器的Attribute /// </summary> /// <param name="idGroup">这个id的组别。不同组别的id允许出现相同的项,且不会冲突</param> /// <param name="allowNew">是否出现【创建新的id】选项</param> /// <param name="prefix">ID的前缀。【不要】在其中混入英文冒号':'</param> public StrIDAttribute(string idGroup, bool allowNew = true, string prefix = "") { this.idGroupKey = idGroup; this.allowNew = allowNew; this.prefix = prefix.Trim(' ', ':'); } } }
import { createSlice } from '@reduxjs/toolkit'; import { AuthState } from '../types'; const initialState: AuthState = { isLogin: false, user: null, }; const authSlice = createSlice({ name: 'auth', initialState, reducers: { login(state, { payload }) { if (payload.user) { state.user = payload.user; state.isLogin = true; } }, logOut(state) { state.user = null; state.isLogin = false; }, }, }); export const authAction = authSlice.actions; export default authSlice.reducer;
import os from natsort import natsorted, ns from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QLabel, QFileDialog from PyQt5.QtGui import QPixmap from PyQt5.QtCore import Qt import sys class ImageViewer(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('One Dark Image Viewer') self.setGeometry(100, 100, 800, 600) self.currentImagePath = None self.currentImageIndex = 0 self.imageFiles = [] self.initUI() def initUI(self): self.statusBar = self.statusBar() openAction = QAction('&Open Image', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Open image') openAction.triggered.connect(self.openImage) menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(openAction) self.imageLabel = QLabel(self) self.imageLabel.setAlignment(Qt.AlignCenter) self.setCentralWidget(self.imageLabel) self.applyOneDarkTheme() def openImage(self, filePath=None): if not filePath: filePath, _ = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.jpeg *.bmp *.gif)") if not filePath: # User cancelled the selection return # Exit the method if no file was selected filePath = os.path.abspath(filePath) # Convert to absolute path for consistency self.currentImagePath = filePath directory = os.path.dirname(filePath) # Construct absolute paths for comparison self.imageFiles = natsorted([os.path.abspath(os.path.join(directory, f)) for f in os.listdir(directory) if f.endswith(('png', 'jpg', 'jpeg', 'bmp', 'gif'))], alg=ns.IGNORECASE) if filePath in self.imageFiles: self.currentImageIndex = self.imageFiles.index(filePath) pixmap = QPixmap(filePath) self.imageLabel.setPixmap(pixmap.scaled(self.imageLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) self.updateStatusBar() else: print(f"Debug: filePath not in imageFiles. FilePath: {filePath}") # Debugging output for f in self.imageFiles: # Debugging output print(f"Available: {f}") # Debugging output self.statusBar.showMessage("Selected file is not in the current directory's list.") def wheelEvent(self, event): delta = event.angleDelta().y() if delta > 0 and self.imageFiles: # Scroll up self.loadPreviousImage() def loadPreviousImage(self): if self.currentImageIndex > 0: self.currentImageIndex -= 1 else: self.currentImageIndex = len(self.imageFiles) - 1 nextImagePath = self.imageFiles[self.currentImageIndex] self.openImage(nextImagePath) def updateStatusBar(self): if self.currentImagePath: fileIndex = self.imageFiles.index(self.currentImagePath) + 1 self.statusBar.showMessage(f"Image {fileIndex} of {len(self.imageFiles)} in directory (Sorted naturally)") def applyOneDarkTheme(self): self.setStyleSheet(""" QMainWindow { background-color: #282c34; } QLabel { color: #abb2bf; } QMenuBar { background-color: #282c34; color: #abb2bf; } QMenuBar::item:selected { background-color: #3e4451; } QMenu { background-color: #282c34; color: #abb2bf; } QMenu::item:selected { background-color: #3e4451; } """) def main(): app = QApplication(sys.argv) viewer = ImageViewer() viewer.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
[index](index.html) :: [data](category_data.html) --- # data.mlist ###### multidimensional list container *доступно с версии:* 0.6 --- ## информация Syntax: values are separated by spaces: (1 2 3) - list of 1, 2 and 3 Nested lists: (1 2 3 (nested list values)) Symbols with spaces: (&#34;single item list&#34;) [![example](../examples/img/data.mlist.jpg)](../examples/pd/data.mlist.pd) ## аргументы: * **VALUE** initial list values in (). For example: (1 2 3 (1 2) 4)<br> _тип:_ atom<br> ## методы: * **(....)** sets new list without output<br> * **append** adds values to the end of the list<br> __параметры:__ - **VAL** appended value<br> тип: atom <br> обязательно: True <br> * **at** outputs atom at the specified position<br> __параметры:__ - **IDX** position (negative indexes are supported: -1 means last element)<br> тип: int <br> обязательно: True <br> * **back** output last list element<br> * **choose** choose random element in list and output it<br> * **clear** removes all list elements<br> * **dump** dump object info to Pd window<br> * **fill** fills with specified value<br> __параметры:__ - **VAL** fill value<br> тип: atom <br> обязательно: True <br> * **front** output first list element<br> * **insert** inserts values to the specified position<br> __параметры:__ - **IDX** insert position<br> тип: int <br> обязательно: True <br> - **VAL** value<br> тип: atom <br> обязательно: True <br> * **pop** removes last list element<br> * **prepend** inserts values to the list beginning<br> __параметры:__ - **VAL** prepended value<br> тип: atom <br> обязательно: True <br> * **remove** removes specified element<br> __параметры:__ - **IDX** element index<br> тип: int <br> обязательно: True <br> * **reverse** reverses list<br> * **set** sets new list without output<br> __параметры:__ - **LIST** new list content<br> тип: list <br> обязательно: True <br> * **shuffle** put elements in random order<br> * **sort** sorts list<br> ## свойства: * **@empty** (readonly) Запросить 1 if list is empty, otherwise 0<br> _тип:_ bool<br> _по умолчанию:_ 1<br> * **@size** (readonly) Запросить number of elements in list<br> _тип:_ int<br> _минимальное значение:_ 0<br> _по умолчанию:_ 0<br> * **@value** Запросить/установить mlist value<br> _тип:_ atom<br> _по умолчанию:_ []<br> ## входы: * output current list value<br> _тип:_ control ## выходы: * output list or list elements<br> _тип:_ control ## ключевые слова: [data](keywords/data.html) [multilist](keywords/multilist.html) **Смотрите также:** [\[data.list\]](data.list.html) **Авторы:** Serge Poltavsky **Лицензия:** GPL3 or later
//头文件 #include<stdio.h> #include<assert.h> #include<stdlib.h> #pragma once typedef int SQDataType; typedef struct SeqList { SQDataType* a; int size;//有效数据的个数 int capacity;//顺序表的容量 }SL; //顺序表的初始化 打印 销毁 void SeqListInit(SL* ps); void SeqListPrint(SL* ps); void DistroySeqList(SL* ps); //顺序表的增删改查等功能 //尾插 头插 尾删 头删 随机插入 随即删除 查找 删除 void SeqListPushBack(SL* ps,SQDataType x); void SeqListPushFront(SL* ps, SQDataType x); void SeqListPopBack(SL* ps); void SeqListPopFront(SL* ps); void SeqListInsert(SL* ps,int pos, SQDataType x); void SeqListErase(SL* ps,int pos); int SeqListSearch(SL* ps, SQDataType x); void SeqListModify(SL* ps, int pos, SQDataType x); //源文件 #include"SeqList.h" //初始化顺序表 void SeqListInit(SL* ps) { ps->a = NULL; ps->size = 0; ps->capacity = 0; } //打印顺序表 void SeqListPrint(SL* ps) { int i = 0; for (i = 0; i < ps->size; i++) { printf("%d ", ps->a[i]); } printf("\n"); } //销毁顺序表 void DistroySeqList(SL* ps) { free(ps->a); ps->a = NULL; } void Check_Capacity(SL* ps) { if (ps->size == ps->capacity) { int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2; SQDataType* pf = (SQDataType*)realloc(ps->a,sizeof(SQDataType) * newcapacity); if (pf == NULL) { perror(""); return; } else { ps->a = pf; } ps->capacity = newcapacity; } } //尾插法 void SeqListPushBack(SL* ps, SQDataType x) { Check_Capacity(ps); ps->a[ps->size] = x; ps->size++; } //头插法 void SeqListPushFront(SL* ps, SQDataType x) { Check_Capacity(ps); int end = ps->size - 1; while (end>=0) { ps->a[end + 1] = ps->a[end]; end--; } ps->a[0] = x; ps->size++; } //尾删 void SeqListPopBack(SL* ps) { assert(ps->size > 0); ps->size--; } //头删 void SeqListPopFront(SL* ps) { assert(ps->size > 0); int start = 0; while (start <ps->size) { ps->a[start] = ps->a[start + 1]; start++; } ps->size--; } //随机插入 void SeqListInsert(SL* ps, int pos, SQDataType x) { Check_Capacity(ps); assert(pos < ps->size); int end = ps->size - 1; while (end >= pos) { ps->a[end + 1] = ps->a[end]; end--; } ps->a[pos] = x; ps->size++; } //随机删除 void SeqListErase(SL* ps, int pos) { assert(pos < ps->size); while (pos<ps->size) { ps->a[pos] = ps->a[pos + 1]; pos++; } ps->size--; } //查找 int SeqListSearch(SL* ps, SQDataType x) { int i = 0; for (i = 0; i<ps->size; i++) { if (ps->a[i] == x) { return i; } } return -1; } //删除 void SeqListModify(SL* ps,int pos, SQDataType x) { assert(pos<ps->size); ps->a[pos] = x; } //源文件 #include"SeqList.h" void menu() { printf("*************************************\n"); printf("**1.尾插数据 2.头插数据 \n"); printf("**3.删除尾数据 4.删除首数据\n"); printf("**5.随机插入数据 6.随机删除数据\n"); printf("**7.查找数据 8.修改数据**\n"); printf("**9.打印数据 0.退出程序\n"); printf("*************************************\n"); printf("请输入你的选择:>\n"); } int main() { SL s; int x = 0; int input = 0; int pos = 0; SeqListInit(&s); do { menu(); scanf("%d", &input); switch (input) { case 1: printf("请输入你要插入的数据,以-1结束\n"); do { scanf("%d", &x); if (x != -1) { SeqListPushBack(&s, x); } } while (x != -1); break; case 2: printf("请输入你要插入的数据,以-1结束\n"); do { scanf("%d", &x); if (x != -1) { SeqListPushFront(&s, x); } } while (x != -1); break; case 3: SeqListPopBack(&s); break; case 4: SeqListPopFront(&s); break; case 5: printf("请输入你要插入的数据\n"); do { scanf("%d", &x); if (x != -1) { printf("请输入你要插入的下标,以-1结束:\n"); scanf("%d", &pos); SeqListInsert(&s,pos,x); } }while (x != -1); break; case 6: printf("请输入你要删除的下标,以-1结束:\n"); do { scanf("%d", &x); if (x != -1) { SeqListErase(&s, x); } } while (x != -1); break; case 7: printf("请输入你要查找的数据,以-1结束:\n"); do { scanf("%d", &x); if (x != -1) { int ret=SeqListSearch(&s, x); if (ret == -1) { printf("该数字不存在\n"); } else { printf("该数字存在,且下标为:%d", ret); } } } while (x != -1); break; case 8: printf("请输入你要修改的数据\n"); do { scanf("%d", &x); if (x != -1) { printf("请输入你要修改的下标,以-1结束:\n"); scanf("%d", &pos); SeqListModify(&s, pos, x); } } while (x != -1); break; case 9: SeqListPrint(&s); break; case 0: printf("退出程序!\n"); break; default: printf("输入错误,请重新输入!\n"); break; } } while (input); DistroySeqList(&s); return 0; }
import { Alert, StyleSheet, Text, TextInput, TouchableOpacity, View, } from 'react-native'; import React, {useState} from 'react'; import CustomCheckbox from '../../components/CustomCheckbox'; import auth from '@react-native-firebase/auth'; const LoginScreen = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [passwordError, setPasswordError] = useState(''); const [isChecked, setIsChecked] = useState(false); const passwordRegex = /^(?=.*[A-Z]).{8,}$/; const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; const LoginFun = () => { if (!email) { alert('Please enter your email.'); } else if (!emailRegex.test(email)) { alert('Invalid email.'); } else if (!password) { alert('Please enter your password.'); } else if (!passwordRegex.test(password)) { alert('Password should be minimum 8 characters and 1 uppercase.'); } else { auth() .signInWithEmailAndPassword(email, password) .then(res => { console.log(JSON.stringify(res)); Alert.alert('User Logged In'); }) .catch(error => { console.log(error); }); } }; return ( <View style={styles.container}> <TextInput style={styles.input} placeholder="Email" onChangeText={text => setEmail(text)} value={email} keyboardType="email-address" /> <TextInput style={styles.input} placeholder="Password" onChangeText={text => setPassword(text)} value={password} secureTextEntry /> <CustomCheckbox label="I accept the terms & conditions" value={isChecked} onValueChange={setIsChecked} /> <Text>Checkbox is {isChecked ? 'checked' : 'unchecked'}</Text> {passwordError ? ( <Text style={styles.errorText}>{passwordError}</Text> ) : null} <TouchableOpacity style={styles.loginButton} disabled={!isChecked} onPress={LoginFun}> <Text style={styles.loginButtonText}>Login</Text> </TouchableOpacity> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20, }, input: { width: '100%', height: 40, borderWidth: 1, borderColor: 'gray', marginBottom: 10, paddingHorizontal: 10, }, errorText: { color: 'red', marginBottom: 10, }, loginButton: { backgroundColor: 'blue', padding: 10, borderRadius: 5, }, loginButtonText: { color: 'white', textAlign: 'center', }, }); export default LoginScreen;
package ks.sequoia.aware.impl; import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; import ks.sequoia.aware.CacheServiceAware; import ks.sequoia.bobj.DomainBObj; import ks.sequoia.eobj.DomainEObj; import ks.sequoia.eobj.LRU; import ks.sequoia.utils.IdFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.DigestUtils; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.sql.Timestamp; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Service public abstract class AbstractCacheServiceImpl implements CacheServiceAware { /** * 计算因子,011111b,计算去除digits的数组下标 */ private static final int DEFAULT_FACTOR = (1 << 6) - 1; /** * 长域名大于8时,最大的迭代次数 */ private static final int TOTAL = 1 << 3; /** * 每次迭代的跨度 */ private static final int SPAN = 1 << 2; /** * 前7段和最后一段的计算因子 */ private static final int LAST_CAL_FACTOR = (TOTAL - 1) * SPAN; /** * int类型的最大bit */ private static final int MAX_BIT = 1 << 5; /** * 初始化缓存容量 */ protected static final int INITIAL_CAPACITY = 102400; //2^6 final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-', '_'}; @Resource private DomainBObj domainBObj; /** * 长域名的内存存储对象,初始化容量是10240W,避免内存移除,保存热点数据 */ protected Map<String, DomainEObj> longMappingMap = new ConcurrentHashMap<>(INITIAL_CAPACITY); /** * 短域名的内存存储对象,初始化容量是1W,避免内存移除,保存热点数据 */ protected Map<String, DomainEObj> shortMappingMap = new ConcurrentHashMap<>(INITIAL_CAPACITY); /** * LRU队列 ,当内存不足以写入新数据时候,移除最近少使用的key */ protected LRU<Long, DomainEObj> lruList = new LRU<>(INITIAL_CAPACITY); @PostConstruct private void init() { List<DomainEObj> domainEObjList = domainBObj.queryLatest10000Times(); if (domainEObjList == null || domainEObjList.size() == 0) { return; } for (DomainEObj domainEObj : domainEObjList) { lruList.put(domainEObj.getDomainId(), domainEObj); addCache(domainEObj.getLongDomain(), domainEObj, longMappingMap); addCache(domainEObj.getShortDomain(), domainEObj, shortMappingMap); } } //短域名长度最大为 8 个字符 protected DomainEObj transformShortDomain(String longDomain) { DomainEObj domainEObj = longMappingMap.get(longDomain); //使用HashCode方法和equals生成短域名 if (domainEObj == null) { //得到longDomain的Hash值,^和>>>减少Hash碰撞 StringBuffer sb = new StringBuffer(); int pos = hash(longDomain) & DEFAULT_FACTOR;//元素的第一个位置 sb.append(digits[pos]); if (longDomain.length() < 8) { char[] chars = longDomain.toCharArray(); for (char c : chars) { int p = hash(c) & DEFAULT_FACTOR; sb.append(digits[p]); } } else { int hashCode = longDomain.hashCode(); //将hashCode一分为8,最后一位参与^运算,减少hash碰撞 for (int ind = 1; ind < TOTAL; ind++) { int cal = hashCode >> ((MAX_BIT - ind * SPAN)) ^ (hashCode >>> LAST_CAL_FACTOR); int p = cal & DEFAULT_FACTOR; sb.append(digits[p]); } } DomainEObj domain = this.getDomainBObj().queryEObjByShortDomain(sb.toString()); if (domain != null) { DomainEObj one = new DomainEObj(); domainEObj.setLongDomain(longDomain); domainEObj.setShortDomain(sb.toString()); domainEObj.setCreateTime(new Timestamp(System.currentTimeMillis())); domainEObj.setUpdateTime(new Timestamp(System.currentTimeMillis())); return one; } return addDomainEObj(longDomain, sb.toString()); } return domainEObj; } private DomainEObj addDomainEObj(String longDomain, String shortDomain) { DomainEObj domainEObj = new DomainEObj(); domainEObj.setLongDomain(longDomain); domainEObj.setShortDomain(shortDomain); domainEObj.setCreateTime(new Timestamp(System.currentTimeMillis())); domainEObj.setUpdateTime(new Timestamp(System.currentTimeMillis())); this.getDomainBObj().addEObj(domainEObj); return domainEObj; } static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } private void addCache(String flag, DomainEObj domainEObj, Map<String, DomainEObj> cacheMap) { if (cacheMap.get(flag) == null) { cacheMap.put(flag, domainEObj); } else { throw new RuntimeException("repeat domain name[" + flag + "]"); } } public DomainBObj getDomainBObj() { return domainBObj; } }
import React, { useState } from "react"; import "./Product.css"; import { Link } from "react-router-dom"; import { FaHeart, FaRegHeart } from "react-icons/fa"; import { IoEyeSharp } from "react-icons/io5"; const Product = (props) => { const products = props.products; const [hoverStates, setHoverStates] = useState( products ? new Array(products.length).fill(false) : [] ); const handleMouseHover = (index) => { const newHoverStates = [...hoverStates]; newHoverStates[index] = true; setHoverStates(newHoverStates); }; const handleMouseLeave = (index) => { const newHoverStates = [...hoverStates]; newHoverStates[index] = false; setHoverStates(newHoverStates); }; // console.log(hoverStates); let { id, title, thumbnail, category, price, discountPercentage, rating } = props.product; let MRP = price / (1 - discountPercentage / 100); let MRPInt = Math.round(MRP); return ( <div className="product-container"> <Link to={`/products/${id}`} className="product-img"> <img className="image" src={thumbnail} alt={`${category}-img`} /> </Link> <div className="product-body"> <div className="product-stock"> <small>{category}</small> <i onMouseOver={() => handleMouseHover(props.index)} onMouseLeave={() => handleMouseLeave(props.index)} > {hoverStates[props.index] ? ( <FaHeart className="heart" /> ) : ( <FaRegHeart /> )} </i> </div> <Link to={`/products/${id}`} className="product-name"> <p>{title.length > 25 ? title.substring(0, 25) + "..." : title}</p> </Link> <div className="product-buy"> <p>₹ {price}</p> <small> <span>₹ {MRPInt}</span> {discountPercentage}% off{" "} </small> <small className="rating">{rating} ★</small> </div> <div className="product-btn"> <Link to={"/cart"} className="btn"> Add To Cart </Link> <Link to={`/products/${id}`} className="btn view-btn"> <i> <IoEyeSharp /> </i> </Link> </div> </div> </div> ); } export default Product;
import { ethers, deployments, getNamedAccounts } from 'hardhat'; import { Contract } from 'ethers'; import * as Type from '@typechained'; import { evm, wallet } from '@utils'; import { toUnit } from '@utils/bn'; import { getContractFromFixture } from '@utils/contracts'; import { calculateSalt } from '@utils/misc'; import { TEST_FEE } from 'utils/constants'; import { getNodeUrl } from 'utils/env'; import forkBlockNumber from './fork-block-numbers'; import { expect } from 'chai'; describe('@skip-on-coverage Fixture', () => { let deployer: string; let dataFeed: Type.DataFeed; let dataFeedStrategy: Type.DataFeedStrategy; let strategyJob: Type.StrategyJob; let dataReceiver: Type.DataReceiver; let oracleFactory: Type.OracleFactory; let oracleSidechain: Type.OracleSidechain; let uniswapV3Factory: Type.IUniswapV3Factory; let uniswapV3Pool: Type.IUniswapV3Pool; let tokenA: Type.IERC20; let tokenB: Type.IERC20; let senderAdapter: Contract; let receiverAdapter: Contract; let poolSalt: string; const NONE_TRIGGER = 0; const TIME_TRIGGER = 1; const TWAP_TRIGGER = 2; const OLD_TRIGGER = 3; beforeEach(async () => { ({ deployer } = await getNamedAccounts()); await evm.reset({ jsonRpcUrl: getNodeUrl('goerli'), blockNumber: forkBlockNumber.goerli, }); }); describe('deployments', () => { it('should deploy base contracts', async () => { await deployments.fixture(['oracle-factory']); }); }); describe('cascade test setup', () => { beforeEach(async () => { await deployments.fixture(['dummy-test-setup']); oracleFactory = (await getContractFromFixture('OracleFactory')) as Type.OracleFactory; dataFeed = (await getContractFromFixture('DataFeed')) as Type.DataFeed; dataReceiver = (await getContractFromFixture('DataReceiver')) as Type.DataReceiver; senderAdapter = await getContractFromFixture('DummyAdapterForTest'); receiverAdapter = await getContractFromFixture('DummyAdapterForTest'); }); it('should set correct test settings', async () => { expect(await oracleFactory.dataReceiver()).to.eq(dataReceiver.address); expect(await dataReceiver.oracleFactory()).to.eq(oracleFactory.address); expect(await dataFeed.strategy()).to.eq(deployer); expect(await dataFeed.whitelistedAdapters(senderAdapter.address)).to.be.true; expect(await dataReceiver.whitelistedAdapters(receiverAdapter.address)).to.be.true; }); describe('when pool is deployed', () => { beforeEach(async () => { await deployments.fixture(['save-tokens', 'pool-whitelisting'], { keepExistingDeployments: true }); tokenA = (await getContractFromFixture('TokenA', 'IERC20')) as Type.IERC20; tokenB = (await getContractFromFixture('TokenB', 'IERC20')) as Type.IERC20; uniswapV3Pool = (await getContractFromFixture('UniswapV3Pool', 'IUniswapV3Pool')) as Type.IUniswapV3Pool; poolSalt = calculateSalt(tokenA.address, tokenB.address, TEST_FEE); await evm.advanceTimeAndBlock(86400 * 5); // avoids !OLD error }); it('should work with manual-fetch-observation fixture', async () => { await deployments.fixture(['manual-fetch-observation'], { keepExistingDeployments: true }); }); it('should work with manual-send-test-observation fixture', async () => { await deployments.fixture(['manual-send-test-observation'], { keepExistingDeployments: true }); }); describe('when the strategy is setup', () => { beforeEach(async () => { await deployments.fixture(['setup-strategy'], { keepExistingDeployments: true }); }); it('should work with fetch-observation', async () => { await deployments.fixture(['fetch-observation'], { keepExistingDeployments: true }); }); describe('when an observation was fetched', () => { beforeEach(async () => { await deployments.fixture(['fetch-observation'], { keepExistingDeployments: true }); }); it('should work with dummy-bridge-observation', async () => { await deployments.fixture(['dummy-bridge-observation'], { keepExistingDeployments: true }); }); }); describe('when the job is setup', () => { beforeEach(async () => { await deployments.fixture(['setup-keeper'], { keepExistingDeployments: true }); dataFeedStrategy = (await getContractFromFixture('DataFeedStrategy')) as Type.DataFeedStrategy; strategyJob = (await getContractFromFixture('StrategyJob')) as Type.StrategyJob; await addCreditsToJob(strategyJob.address); }); it('should set correct test settings', async () => { expect(await dataFeed.strategy()).to.eq(dataFeedStrategy.address); expect(await dataFeedStrategy.dataFeed()).to.eq(dataFeed.address); }); it('should be able to work-fetch observations', async () => { await expect(strategyJob['work(bytes32,uint8)'](poolSalt, TIME_TRIGGER)).not.to.be.reverted; }); describe('when dummy adapter is default', () => { beforeEach(async () => { await deployments.fixture(['setup-dummy-default'], { keepExistingDeployments: true }); }); it('should be able to fetch and send observations', async () => { await strategyJob['work(bytes32,uint8)'](poolSalt, TIME_TRIGGER); const lastPoolNonce = (await dataFeed.lastPoolStateObserved(poolSalt)).poolNonce; const evtFilter = dataFeed.filters.PoolObserved(poolSalt, lastPoolNonce); const queryResults = await dataFeed.queryFilter(evtFilter); const fetchData = dataFeed.interface.decodeEventLog('PoolObserved', queryResults[0].data); const RANDOM_CHAIN_ID = 5; await expect( strategyJob['work(uint32,bytes32,uint24,(uint32,int24)[])']( RANDOM_CHAIN_ID, poolSalt, lastPoolNonce, fetchData._observationsData ) ).not.to.be.reverted; const oracleAddress = await oracleFactory['getPool(address,address,uint24)'](tokenA.address, tokenB.address, TEST_FEE); oracleSidechain = (await ethers.getContractAt('OracleSidechain', oracleAddress)) as Type.OracleSidechain; expect((await oracleSidechain.slot0()).observationCardinality).to.eq(144); }); it('should work with send-test-observation fixture', async () => { await deployments.fixture(['send-test-observation'], { keepExistingDeployments: true }); }); }); describe('when connext adapter is default', () => { beforeEach(async () => { await deployments.fixture(['setup-connext-default'], { keepExistingDeployments: true }); }); it('should be able to fetch and send observations', async () => { await strategyJob['work(bytes32,uint8)'](poolSalt, TIME_TRIGGER); const lastPoolNonce = (await dataFeed.lastPoolStateObserved(poolSalt)).poolNonce; const evtFilter = dataFeed.filters.PoolObserved(poolSalt, lastPoolNonce); const queryResults = await dataFeed.queryFilter(evtFilter); const fetchData = dataFeed.interface.decodeEventLog('PoolObserved', queryResults[0].data); const REAL_CHAIN_ID = 420; await expect( strategyJob['work(uint32,bytes32,uint24,(uint32,int24)[])'](REAL_CHAIN_ID, poolSalt, lastPoolNonce, fetchData._observationsData) ).not.to.be.reverted; }); it('should work with send-observation fixture', async () => { await deployments.fixture(['send-observation'], { keepExistingDeployments: true }); }); }); describe('when adapters redeploy', () => { beforeEach(async () => { await deployments.fixture(['setup-connext-default'], { keepExistingDeployments: true }); }); it('should not redeploy the job', async () => { expect(strategyJob.address).to.eq((await getContractFromFixture('StrategyJob')).address); }); }); }); }); }); }); describe('production setup', () => { beforeEach(async () => { await deployments.fixture(['base-contracts']); await deployments.fixture(['connext-setup', 'pool-whitelisting'], { keepExistingDeployments: true }); }); it('should work with manual-send-test-observation', async () => { await deployments.fixture(['manual-send-test-observation'], { keepExistingDeployments: true }); }); describe('strategy job setup', () => { beforeEach(async () => { await deployments.fixture(['setup-keeper'], { keepExistingDeployments: true }); strategyJob = (await getContractFromFixture('StrategyJob')) as Type.StrategyJob; await evm.advanceTimeAndBlock(86400 * 5); // avoids !OLD error await addCreditsToJob(strategyJob.address); }); it('should work with work-job', async () => { await deployments.fixture(['work-job'], { keepExistingDeployments: true }); }); it('should work with dummy-work-job', async () => { await deployments.fixture(['dummy-work-job'], { keepExistingDeployments: true }); }); }); describe('after observation was fetched', () => { beforeEach(async () => { await deployments.fixture(['fetch-observation'], { keepExistingDeployments: true }); }); it('should work with bridge-observation', async () => { await deployments.fixture(['bridge-observation'], { keepExistingDeployments: true }); }); }); }); }); /* HELPER FUNCTIONS */ const addCreditsToJob = async (jobAddress: string) => { const keep3rContract = await getContractFromFixture('Keep3r', 'IKeep3r'); const governor = await wallet.impersonate(await keep3rContract.governance()); await wallet.setBalance(governor._address, toUnit(10)); await keep3rContract.connect(governor).forceLiquidityCreditsToJob(jobAddress, toUnit(100)); };
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Landing extends Model { public $guarded = ["id","created_at","updated_at"]; protected $table="table_home"; public $timestamps=true; protected $primaryKey = "id"; public $incrementing = true; public static function findRequested() { $query = Landing::query(); // search results based on user input \Request::input('id') and $query->where('id',\Request::input('id')); \Request::input('nama_mempelai') and $query->where('nama_mempelai','like','%'.\Request::input('nama_mempelai').'%'); \Request::input('keterangan') and $query->where('keterangan','like','%'.\Request::input('keterangan').'%'); \Request::input('url_foto') and $query->where('url_foto','like','%'.\Request::input('url_foto').'%'); \Request::input('created_at') and $query->where('created_at',\Request::input('created_at')); \Request::input('updated_at') and $query->where('updated_at',\Request::input('updated_at')); // sort results \Request::input("sort") and $query->orderBy(\Request::input("sort"),\Request::input("sortType","asc")); // paginate results return $query->paginate(15); } public static function validationRules( $attributes = null ) { $rules = [ 'nama_mempelai' => 'string|max:191', 'keterangan' => 'string|max:500', 'url_foto' => 'string|max:500', ]; // no list is provided if(!$attributes) return $rules; // a single attribute is provided if(!is_array($attributes)) return [ $attributes => $rules[$attributes] ]; // a list of attributes is provided $newRules = []; foreach ( $attributes as $attr ) $newRules[$attr] = $rules[$attr]; return $newRules; } public function roleUser(){ return $this->hasOne('App\Models\RoleUser','user_id'); } public function pk(){ return $this->{$this->primaryKey}; } }
# -*- coding: utf-8 -*- """ Created on Thu Mar 10 15:00:34 2022 @author: laaltenburg Algoritmes to detect the flame front of confinded and unconfined flames from raw PIV images """ #%% IMPORT PACKAGES import os import sys # Add the 'main' folder to sys.path parent_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # flame_front_detection_directory = os.path.abspath(os.path.join(parent_folder, 'flame_front_detection')) # flame_simulations_directory = os.path.abspath(os.path.join(parent_folder, 'flame_simulations')) plot_parameters_directory = os.path.abspath(os.path.join(parent_folder, 'plot_parameters')) # Add the flame_object_directory to sys.path sys.path.append(parent_folder) # sys.path.append(flame_front_detection_directory) # sys.path.append(flame_simulations_directory) sys.path.append(plot_parameters_directory) import cv2 import numpy as np from matplotlib import pyplot as plt from scipy.signal import find_peaks, peak_prominences from scipy import stats import imutils import pickle figures_folder = 'figures' if not os.path.exists(figures_folder): os.makedirs(figures_folder) #%% GET CONTOUR DATA def get_contour_data(procedure_nr, window_size, pre_data_path, post_data_path, image_nr, extension, toggle_plot, save_image): google_red = '#db3236' google_green = '#3cba54' google_blue = '#4885ed' google_yellow = '#f4c20d' bright_green = '#66ff00' if procedure_nr == 1: color = bright_green #google_red shape, contour, contour_length_pixels = get_contour_procedure_pixel_density_method(window_size, pre_data_path, post_data_path, image_nr, extension, color, toggle_plot, save_image) elif procedure_nr == 2: color = google_red #google_green shape, contour, contour_length_pixels = get_contour_procedure_bilateral_filter_method(window_size, pre_data_path, post_data_path, image_nr, extension, color, toggle_plot, save_image) elif procedure_nr == 3: color = google_red #google_green shape, contour, contour_length_pixels = get_contour_procedure_bilateral_filter_method2(window_size, pre_data_path, post_data_path, image_nr, extension, color, toggle_plot, save_image) return shape, contour, contour_length_pixels #%% METHOD A: PIXEL DENSITY METHOD def get_contour_procedure_pixel_density_method(window_size, pre_data_path, post_data_path, image_nr, extension, color, toggle_plot, save_image): #%% Step 1: read raw image image_file = f'B{image_nr:04d}{extension}' image_path = os.path.join(pre_data_path, image_file) img_raw = cv2.imread(image_path, cv2.IMREAD_ANYDEPTH) shape = img_raw.shape #%% Step 2: normalize the signal intensity of raw image to unity based on global raw image maxima and minima img_normalized = cv2.normalize(img_raw, dst=None, alpha=0, beta=1.0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) #%% Step 3: apply averaging filter on normalized image w_size = int(window_size) kernel = np.ones((w_size, w_size), np.float32)/(w_size**2) img_pixel_density = cv2.filter2D(img_normalized, -1, kernel) #%% Step 4: obtain threshold value corresponding to a minimum probability threshold_value = get_thresholding_value(img_pixel_density, toggle_plot) #%% Step 5: binarize the bilateral filtered image threshold_type, maxVal = cv2.THRESH_BINARY, 1 ret, img_binary = cv2.threshold(img_pixel_density, threshold_value, maxVal, threshold_type) #%% Step 6: extract largest contour == flame front contour, contour_length_pixels = find_and_draw_flame_contours(img_binary) #%% Turn plots on or off brighten_factor = 8 if toggle_plot: toggle_contour = False title = 'raw image (\#' + str(image_nr) + ')' # title = '' plot_image(title, img_raw, brighten_factor, contour, toggle_contour, color) title = 'Average filtered image (\#' + str(image_nr) + ')' # title = '' plot_image(title, img_pixel_density, brighten_factor, contour, toggle_contour, color) toggle_contour = True title = 'raw image (\#' + str(image_nr) + ')' + ' with contour' # title = '' plot_image(title , img_raw, brighten_factor, contour, toggle_contour, color) #%% Final step: save images with contour drawn into the raw image if save_image: sep = os.path.sep path = os.path.join(post_data_path, 'pdm', f'w_size_{w_size}') save_contour_images(path, image_nr, img_raw, brighten_factor, contour, color) return shape, contour, contour_length_pixels #%% METHOD B: BILATERAL FILTER METHOD def get_contour_procedure_bilateral_filter_method(window_size, pre_data_path, post_data_path, image_nr, extension, color, toggle_plot, save_image): # image_file = f'B{image_nr:04d}{extension}' # image_path = os.path.join(pre_data_path, image_file) # img_raw_real = cv2.imread(image_path, cv2.IMREAD_ANYDEPTH) #%% [1] Read raw image image_file = f'B{image_nr:04d}{extension}' image_path = os.path.join(pre_data_path, image_file) img_raw = cv2.imread(image_path, cv2.IMREAD_ANYDEPTH) shape = img_raw.shape #%% [2] Normalize the signal intensity of raw image to unity based on global raw image maxima and minima img_normalized = cv2.normalize(img_raw, dst=None, alpha=0, beta=1.0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) #%% [3] Apply bilateral filter on normalized image w_size = int(window_size) filter_diameter = w_size sigma_color = 0.1 sigma_space = filter_diameter/2.0 img_bilateral = cv2.bilateralFilter(img_normalized, filter_diameter, sigma_color, sigma_space) #%% [4] Obtain threshold value corresponding to a minimum probability threshold_value = get_thresholding_value(img_bilateral, toggle_plot) #%% [5] Binarize the bilateral filtered image threshold_type, maxVal = cv2.THRESH_BINARY, 1 ret, img_binary = cv2.threshold(img_bilateral, threshold_value, maxVal, threshold_type) #%% [6] Extract largest contour == flame front contour, contour_length_pixels = find_and_draw_flame_contours(img_binary) #%% [7]Turn plots on or off brighten_factor = 8 toggle_plot = True if toggle_plot: fig, axs = plt.subplots(1, 3,) # figsize=(10, 6)) plt.subplots_adjust(wspace=-.3) plot_images(axs, img_raw, img_bilateral, brighten_factor, contour, color) fig.tight_layout() filename = f'H{flame.H2_percentage}_Re{flame.Re_D}_detection_B{image_nr}' eps_path = os.path.join('figures', f"{filename}.eps") fig.savefig(eps_path, format='eps', dpi=300, bbox_inches='tight') toggle_contour = False # title = 'raw image (\#' + str(image_nr) + ')' title = '' plot_image(title, img_raw, brighten_factor, contour, toggle_contour, color) # title = 'Bilateral filtered image (\#' + str(image_nr) + ')' toggle_contour = False title = '' plot_image(title, img_bilateral, brighten_factor, contour, toggle_contour, color) toggle_contour = True # title = 'raw image (\#' + str(image_nr) + ')' + ' with contour' title = '' plot_image(title , img_raw, brighten_factor, contour, toggle_contour, color) #%% [8] Save images with contour drawn into the raw image if save_image: path = os.path.join(post_data_path, 'bfm', f'w_size_{w_size}') save_contour_images(path, image_nr, img_raw, brighten_factor, contour, color) return shape, contour, contour_length_pixels #%% METHOD C: BILATERAL FILTER METHOD + INTENSITY CORRECTION def get_contour_procedure_bilateral_filter_method2(window_size, pre_data_path, post_data_path, image_nr, extension, color, toggle_plot, save_image): #%% [1] Read raw image image_file = f'B{image_nr:04d}{extension}' image_path = os.path.join(pre_data_path, image_file) img_raw = cv2.imread(image_path, cv2.IMREAD_ANYDEPTH) shape = img_raw.shape w_size = int(window_size) #%% [2] Normalize the signal intensity of raw image to unity based on global raw image maxima and minima img_normalized = cv2.normalize(img_raw, dst=None, alpha=0, beta=1.0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) img_raw_boxfilter = cv2.boxFilter(img_normalized, -1, (w_size, w_size)) img_divide = np.divide(img_normalized, img_raw_boxfilter) img_normalized = cv2.normalize(img_divide, dst=None, alpha=0, beta=1.0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) #%% [3] Apply bilateral filter on normalized image filter_diameter = w_size sigma_color = 0.1 sigma_space = filter_diameter/2.0 img_bilateral = cv2.bilateralFilter(img_normalized, filter_diameter, sigma_color, sigma_space) #%% [4] Obtain threshold value corresponding to a minimum probability threshold_value = get_thresholding_value(img_bilateral, toggle_plot) #%% [5] Binarize the bilateral filtered image threshold_type, maxVal = cv2.THRESH_BINARY, 1 ret, img_binary = cv2.threshold(img_bilateral, threshold_value, maxVal, threshold_type) #%% [6] Extract largest contour == flame front contour, contour_length_pixels = find_and_draw_flame_contours(img_binary) #%% [7]Turn plots on or off brighten_factor = 4 toggle_plot = True if toggle_plot: fig, axs = plt.subplots(1, 3, figsize=(10, 6)) plot_images(axs, img_raw, img_bilateral, brighten_factor, contour, color) fig.tight_layout() filename = f'H{flame.H2_percentage}_Re{flame.Re_D}_detection_B{image_nr}' eps_path = os.path.join('figures', f"{filename}.eps") # fig.savefig(eps_path, format='eps', dpi=300, bbox_inches='tight') toggle_contour = False # title = 'raw image (\#' + str(image_nr) + ')' title = '' plot_image(title, img_raw, brighten_factor, contour, toggle_contour, color) # title = 'Bilateral filtered image (\#' + str(image_nr) + ')' toggle_contour = False title = '' plot_image(title, img_divide, brighten_factor, contour, toggle_contour, color) toggle_contour = True # title = 'raw image (\#' + str(image_nr) + ')' + ' with contour' title = '' plot_image(title , img_raw, brighten_factor, contour, toggle_contour, color) #%% [8] Save images with contour drawn into the raw image if save_image: path = os.path.join(post_data_path, 'bfm', f'w_size_{w_size}') save_contour_images(path, image_nr, img_raw, brighten_factor, contour, color) return shape, contour, contour_length_pixels #%% MAIN FUNCTIONS def get_thresholding_value(image, toggle_plot): quantity = image.flatten() # Compute the 99th percentile percentile_99 = np.percentile(quantity, 99) percentile_99_double = 1*percentile_99 # Filter the data using the double the value of the 99th percentile quantity = quantity[quantity <= percentile_99_double] # Create a Gaussian Kernel Density Estimation (KDE) object using quantity gkde_obj = stats.gaussian_kde(quantity) x_pts = np.linspace(0, np.max(quantity), 1000) estimated_pdf = gkde_obj.evaluate(x_pts) # Extract fitted distribution dist_data_x = x_pts dist_data_y = estimated_pdf # Find the peaks in the distribution peaks, _ = find_peaks(dist_data_y) # Obtain the prominences of the peaks prominences = peak_prominences(dist_data_y, peaks)[0] # Create a list of tuples containing peak information: (peak index, prominence, x coordinate, y coordinate) peak_coords = list(zip(peaks, prominences, dist_data_x[peaks], dist_data_y[peaks])) # Sort the peak coordinates in descending order based on prominence peak_coords_prominence_descending = sorted(peak_coords, key = lambda x:x[1], reverse=True) # Sort the top 2 peak coordinates in ascending order based on probability peak_coords_sorted_probability = sorted(peak_coords_prominence_descending[0:2], key = lambda x:x[3]) # Sort the peak coordinates based on the index accepted_peak_coords = sorted(peak_coords_sorted_probability, key = lambda x:x[0]) # print(accepted_peak_coords) accepted_peaks = [accepted_peak_coord[0] for accepted_peak_coord in accepted_peak_coords] quantity_range = dist_data_x[accepted_peaks[0]:accepted_peaks[-1]] probability_range = dist_data_y[accepted_peaks[0]:accepted_peaks[-1]] min_probability_index = np.argmin(probability_range) toggle_plot = True if toggle_plot: quantity_coord = quantity_range[min_probability_index] probability_coord = probability_range[min_probability_index] fig, ax = plot_pixel_density_histogram(image, percentile_99_double) ax.plot(dist_data_x, dist_data_y, color='#000080', ls='-', label='kernel density estimation') ax.plot(quantity_coord, probability_coord, color='#db3236', marker='x', ms=10, mew=2, ls='None', label='minimum probability') # Plot the vertical line on the axis ax.axvline(x=quantity_coord, ymin=0, ymax=0.6, color='#db3236', ls='--') # ax.axvline(x=0.5*(quantity_range[0] + quantity_range[-1]), ymin=0, ymax=0.6, color='k', ls='--') # This is in data coordinates point = (quantity_coord, probability_coord) trans = ax.transData.transform(point) trans = ax.transAxes.inverted().transform(trans) # Add text to the left of the line text_left = 'P' ax.text(trans[0] - 0.05, 0.5, text_left, ha='right', va='center', transform=ax.transAxes, fontsize=20, fontweight='bold') # Add text to the right of the line text_right = 'R' ax.text(trans[0] + 0.05, 0.5, text_right, ha='left', va='center', transform=ax.transAxes, fontsize=20, fontweight='bold') ax.legend(loc='best', prop={'size': 16}) fig.tight_layout() filename = f'H{flame.H2_percentage}_Re{flame.Re_D}_histogram_B{image_nr}' eps_path = os.path.join('figures', f"{filename}.eps") fig.savefig(eps_path, format='eps', dpi=300, bbox_inches='tight') # Determine threshold pixel density (separating unburnt and burnt side) [value corresponding to minimum probability] threshold = quantity_range[min_probability_index] return threshold def find_and_draw_flame_contours(img_binary): img_binary_8bit = (img_binary * (2 ** 8 - 1)).astype(np.uint8) # Find the contours src = img_binary_8bit # Input image array contour_retrieval = cv2.RETR_TREE # Contour retrieval mode contours_approx = cv2.CHAIN_APPROX_NONE contours_found = cv2.findContours(src, contour_retrieval, contours_approx) contours = imutils.grab_contours(contours_found) # Find the largest contour largest_contour = max(contours, key=cv2.contourArea) # print(largest_contour[:]) # Compute point where flame anchors at burner rim on right and left hand side # image axis start in top left corner and are positive in right and downward direction contour_all_y_values = np.hstack(largest_contour[:,:,1]) y_max = np.where(contour_all_y_values == max(contour_all_y_values))[0] contour_x_values_at_y_max = np.hstack(largest_contour[y_max,:,0]) x_right = np.where(contour_x_values_at_y_max == max(contour_x_values_at_y_max))[0] x_left = np.where(contour_x_values_at_y_max == min(contour_x_values_at_y_max))[0] right_point_index = y_max[x_right[0]] left_point_index = y_max[x_left[0]] diff = len(largest_contour) - right_point_index right_indices = np.linspace(right_point_index, (len(largest_contour) - 1), diff) left_indices = np.linspace(0, left_point_index, left_point_index + 1) total_indices = np.concatenate((right_indices, left_indices)).astype('int64') contour = largest_contour[total_indices] closed_contour = False contour_length_pixels = cv2.arcLength(contour, closed_contour) return contour, contour_length_pixels def bilateral_filter(image, diameter, sigma_color, sigma_space): # create a zero-filled output image filtered_image = np.zeros_like(image) # compute half of the diameter for convenience radius = diameter // 2 # create a Gaussian kernel for spatial smoothing x, y = np.meshgrid(np.arange(-radius, radius+1), np.arange(-radius, radius+1)) spatial_kernel = np.exp(-(x ** 2 + y ** 2) / (2 * sigma_space ** 2)) # compute the weights for the color distances color_weights = np.exp(-np.arange(2**0) ** 2 / (2 * sigma_color ** 2)) # loop over all pixels in the input image for i in range(radius, image.shape[0] - radius): for j in range(radius, image.shape[1] - radius): # extract the current pixel pixel = image[i, j] # compute the squared color distances for all neighboring pixels color_dists = (pixel - image[i - radius:i + radius + 1, j - radius:j + radius + 1]) ** 2 # compute the weights for the color distances color_weights_ = color_weights[np.sqrt(color_dists).astype(np.int32)] # compute the combined weights for all pixels combined_weights = color_weights_ * spatial_kernel # normalize the weights weights_sum = np.sum(combined_weights) normalized_weights = combined_weights / weights_sum if weights_sum > 0 else combined_weights # compute the weighted sum of neighboring pixels filtered_pixel = np.sum(normalized_weights * image[i - radius:i + radius + 1, j - radius:j + radius + 1]) # assign the filtered pixel to the output image filtered_image[i, j] = filtered_pixel return filtered_image #%% AUXILIARY PLOT FUNCTIONS def plot_images(axs, image1, image2, brighten_factor, contour, color): ax1 = axs[0] ax2 = axs[1] ax3 = axs[2] ax1.imshow(image1, cmap="gray", vmin=np.min(image1.flatten())/brighten_factor, vmax=np.max(image1.flatten())/brighten_factor) ax1.set_ylabel('pixels', fontsize=24) ax1.yaxis.set_label_coords(-.1, .8) # Adjust the position as needed toggle_contour = False if toggle_contour: contour_x = contour[:,:,0] contour_y = contour[:,:,1] ax1.plot(contour_x, contour_y, color) custom_y_ticks = [0, 400, 800] ax1.set_yticks(custom_y_ticks) ax2.imshow(image2, cmap="gray", vmin=np.min(image2.flatten())/brighten_factor, vmax=np.max(image2.flatten())/brighten_factor) ax2.set_xlabel('pixels', fontsize=24) toggle_contour = False if toggle_contour: contour_x = contour[:,:,0] contour_y = contour[:,:,1] ax1.plot(contour_x, contour_y, color) ax2.tick_params(axis='y', labelleft=False) ax3.imshow(image1, cmap="gray", vmin=np.min(image1.flatten())/brighten_factor, vmax=np.max(image1.flatten())/brighten_factor) toggle_contour = True if toggle_contour: contour_x = contour[:,:,0] contour_y = contour[:,:,1] ax3.plot(contour_x, contour_y, color) ax3.set_ylabel('') ax3.tick_params(axis='y', labelleft=False) labels = ['a', 'b', 'c'] for i, ax in enumerate(axs): ax.tick_params(axis='both', labelsize=20) # Add textbox with timestamp left, width = .2, .7 bottom, height = .25, .7 right = left + width top = bottom + height ax.text(right, top, labels[i], horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=24, bbox=dict(facecolor="w", edgecolor='k', boxstyle='round') ) def plot_image(title, image, brighten_factor, contour, toggle_contour, color): fig, ax = plt.subplots() ax.set_title(title) ax.imshow(image, cmap="gray", vmin=np.min(image.flatten())/brighten_factor, vmax=np.max(image.flatten())/brighten_factor) ax.set_xlabel('pixels', fontsize=20) ax.set_ylabel('pixels', fontsize=20) if toggle_contour: contour_x = contour[:,:,0] contour_y = contour[:,:,1] ax.plot(contour_x, contour_y, color) custom_y_ticks = [0, 800] ax.set_yticks(custom_y_ticks) # plt.title(title) # plt.imshow(image, cmap="gray", vmin=np.min(image.flatten())/brighten_factor, vmax=np.max(image.flatten())/brighten_factor) # plt.xlabel('pixels') # plt.ylabel('pixels') # if toggle_contour: # contour_x = contour[:,:,0] # contour_y = contour[:,:,1] # plt.plot(contour_x, contour_y, color) # return fig def plot_pixel_density_histogram(image, x_lim_right): fig, ax = plt.subplots(figsize=(6, 6)) # fig, ax = plt.subplots() ax.grid() quantity = image.flatten() y, x, _ = ax.hist(quantity, bins='auto', density=True, color='lightblue', edgecolor='k') ax.set_xlim(0, .1) ax.set_ylim(0, 100) custom_x_ticks = [.0, .02, .04, .06, .08, .1] custom_x_tick_labels = [f'{tick:.2f}' for tick in custom_x_ticks] # Replace with your desired tick labels ax.set_xticks(custom_x_ticks) ax.set_xticklabels(custom_x_tick_labels) # Use this line to set custom tick labels custom_y_ticks = [0, 25, 50, 75, 100] ax.set_yticks(custom_y_ticks) ax.tick_params(axis='both', labelsize=16) ax.set_xlabel('$I_{f}$', fontsize=20) ax.set_ylabel('pdf', fontsize=20) return fig, ax def save_contour_images(path,image_nr, img_raw, brighten_factor, contour, color): # create a new directory because it does not exist if not os.path.exists(path): os.makedirs(path) filename = os.path.join(path, f"B{image_nr:04d}") dpi = 1200 toggle_contour = False plot_image('', img_raw, brighten_factor, contour, toggle_contour, color) # plt.savefig(filename + '_raw.png', dpi=dpi) # plt.clf() toggle_contour = True plot_image('', img_raw, brighten_factor, contour, toggle_contour, color) # plt.savefig(filename + '.png', dpi=dpi) # plt.clf() # Using cv2.imwrite() method # Saving the image # cv2.imwrite(file_name + '_raw.png', img) # cv2.imwrite(file_name + '.png', img) # fig1.savefig(file_name + '_raw.png', dpi=dpi) # fig2.savefig(file_name + '.png', dpi=dpi) #%% MAIN if __name__ == "__main__": google_red = '#db3236' google_green = '#3cba54' google_blue = '#4885ed' google_yellow = '#f4c20d' cv2.destroyAllWindows() plt.close("all") # data_dir = "Y:/tube/" data_dir = 'U:\\staff-umbrella\\High hydrogen\\laaltenburg\\data\\tube_burner_campaign2\\selected_runs\\' cwd = os.getcwd() #%%% Define cases react_names_ls = [ # ('react_h0_c3000_ls_record1', 57), # ('react_h0_s4000_ls_record1', 58), # ('react_h100_c12000_ls_record1', 61), # ('react_h100_c12500_ls_record1', 61), # ('react_h100_s16000_ls_record1', 62) ] react_names_hs = [ # ('react_h0_f2700_hs_record1', 57), ('react_h0_c3000_hs_record1', 57), # ('react_h0_s4000_hs_record1', 58), # ('react_h100_c12500_hs_record1', 61), # ('react_h100_s16000_hs_record1', 62) ] if react_names_ls: spydata_dir = os.path.join(parent_folder, 'spydata\\udf') elif react_names_hs: spydata_dir = os.path.join(parent_folder, 'spydata') pre_data_folder = "pre_data" post_data_folder = "post_data" # flame_nr = 1 # flame_name = 'flame_' + str(flame_nr) # record_name = "Cam_Date=190923_Time=164708" # frame_nr = 0 # extension = ".tif" # flame_nr = 2 # flame_name = 'flame_' + str(flame_nr) # record_name = "Cam_Date=190920_Time=173417" # frame_nr = 0 # extension = ".tif" # flame_nr = 3 # flame_name = 'flame_' + str(flame_nr) # record_name = "Cam_Date=210708_Time=150209_ExtractVolume" # frame_nr = 0 # extension = ".tif" # flame_nr = 4 # flame_name = 'flame_' + str(flame_nr) # record_name = 'Cam_Date=210917_Time=134643_ExtractVolume' # frame_nr = 0 # extension = '.tif' # scale = 12.7493 # units: pixels.mm^{-1} # flame_nr = 5 # flame_name = 'flame_' + str(flame_nr) # record_name = "Cam_Date=211021_Time=162640_ExtractVolume" # frame_nr = 0 # extension = ".tif" # scale = 13.8182 # units: pixels.mm^{-1} # flame_nr = 6 # flame_name = 'flame_' + str(flame_nr) # record_name = 'Cam_Date=210910_Time=153000_phi=1' # frame_nr = 0 # extension = '.tif' # scale = 13.6028 # units: pixels.mm^{-1} frame_nr = 0 segment_length_mm = 1 # units: mm window_size = 31 # units: pixels react_names_ls = [ # ('react_h0_c3000_ls_record1', 57), # ('react_h0_s4000_ls_record1', 58), # ('react_h100_c12000_ls_record1', 61), # ('react_h100_c12500_ls_record1', 61), # ('react_h100_s16000_ls_record1', 62) ] react_names_hs = [ # ('react_h0_f2700_hs_record1', 57), # ('react_h0_c3000_hs_record1', 57), ('react_h0_s4000_hs_record1', 58), # ('react_h100_c12500_hs_record1', 61), # ('react_h100_s16000_hs_record1', 62) ] react_names = react_names_ls + react_names_hs for name, nonreact_run_nr in react_names: fname = f'{name}_segment_length_{segment_length_mm}mm_wsize_{window_size}pixels' with open(os.path.join(spydata_dir, fname + '.pkl'), 'rb') as f: flame = pickle.load(f) # %%% 0: Load flame data # segment_length_mm = 1 #0.125 # units: mm # window_size = 27 # units: pixels # spydata_dir = "spydata/" # file_pickle = spydata_dir + "flame_" + str(flame_nr) + '_' + 'unfiltered' + '_' +'segment_length_' + str(segment_length_mm) + 'mm_' + 'wsize_' + str(window_size) + 'pixels.pkl' # with open(file_pickle, 'rb') as f: # flame = pickle.load(f) # pre_data_path = data_dir + sep + pre_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nr) + sep # post_data_path = data_dir + sep + post_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nr) + sep # image_nr = 1 # img_raw = cv2.imread(pre_data_path + 'B%.4d' % image_nr + extension, cv2.IMREAD_ANYDEPTH) # toggle_plot = True # toggle_contour = False # save_image = False # brighten_factor = 8 # color = 'r' # # plot_image('raw image ' + str(image_nr), img_raw, brighten_factor, [], toggle_contour, color) # procedure_nr = flame.get_contour_procedure_nr # shape, contour, contour_length_pixels = get_contour_data(procedure_nr, window_size, pre_data_path, post_data_path, image_nr, extension, toggle_plot, save_image) # contour_nr = image_nr - 1 # segmented_contour = flame.frames[frame_nr].contour_data.segmented_contours[contour_nr] # segmented_contour_x = segmented_contour[:,0,0] # segmented_contour_y = segmented_contour[:,0,1] # plt.plot(segmented_contour_x, segmented_contour_y, color) # 0: Load flame data # %%% A: Single procedure, single image, single frame # pre_data_path = os.path.join(cwd, flame.pre_data_folder, flame.name, f'session_{flame.session_nr:03}' , flame.record_name, 'Correction', 'Resize', f'Frame{frame_nr}', 'Export_01') pre_data_path = os.path.join(data_dir, f'session_{flame.session_nr:03}' , flame.record_name, 'Correction', 'Resize', f'Frame{frame_nr}', 'Export_01') post_data_path = os.path.join(cwd, flame.post_data_folder, flame.name, f'session_{flame.session_nr:03}', f'{flame.record_name}_Frame{frame_nr}') # pre_data_path = os.path.join(data_dir, pre_data_folder, flame_name, f"{record_name}_Frame{frame_nr}") # post_data_path = os.path.join(data_dir, post_data_folder, flame_name, f"{record_name}_Frame{frame_nr}") image_nr = 1699 toggle_plot = True save_image = False procedure_nr = 2 extension = flame.extension shape, contour, contour_length_pixels = get_contour_data(procedure_nr, window_size, pre_data_path, post_data_path, image_nr, extension, toggle_plot, save_image) # A: Single procedure, single image, single frame #%%% B: Multiple procedures, single image, single frame # window_size = np.ceil(2*scale) // 2 * 2 + 1 # Get closest odd number # pre_data_path = data_dir + sep + pre_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nr) + sep # post_data_path = data_dir + sep + post_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nr) + sep # image_nr = 197 # img_raw = cv2.imread(pre_data_path + 'B%.4d' % image_nr + extension, cv2.IMREAD_ANYDEPTH) # toggle_plot = False # save_image = False # fig, ax = plot_image('raw image ' + str(image_nr), img_raw, brighten_factor=8) # procedure_nrs = [1, 2] # colors = ['r', 'g'] # for i, procedure_nr in enumerate(procedure_nrs): # shape, contour, contour_length_pixels = get_contour_data(procedure_nr, window_size, pre_data_path, post_data_path, image_nr, extension, toggle_plot, save_image) # contour_x = contour[:,:,0] # contour_y = contour[:,:,1] # ax.plot(contour_x, contour_y, colors[i]) # B: Multiple procedures, single image, single frame #%%% C: Single procedure, single image, double frame # procedure_nr = 2 # frame_nrs = [0, 1] # colors = ['r', 'g'] # image_nr = 197 # pre_data_path = data_dir + sep + pre_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nrs[0]) + sep # img_raw = cv2.imread(pre_data_path + 'B%.4d' % image_nr + extension, cv2.IMREAD_ANYDEPTH) # toggle_plot = False # save_image = False # fig, ax = plot_image('raw image ' + str(image_nr), img_raw, brighten_factor=8) # window_size = np.ceil(2*scale) // 2 * 2 + 1 # Get closest odd number # for i, frame_nr in enumerate(frame_nrs): # pre_data_path = data_dir + sep + pre_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nr) + sep # post_data_path = data_dir + sep + post_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nr) + sep # shape, contour, contour_length_pixels = get_contour_data(procedure_nr, window_size, pre_data_path, post_data_path, image_nr, extension, toggle_plot, save_image) # contour_x = contour[:,:,0] # contour_y = contour[:,:,1] # ax.plot(contour_x, contour_y, colors[i]) # C: Single procedure, single image, double frame #%%% D: Single procedure, double image, single frame # procedure_nr = 2 # image_nrs = [197, 198] # colors = ['r', 'g'] # frame_nr = 0 # image_nr = image_nrs[0] # pre_data_path = data_dir + sep + pre_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nr) + sep # img_raw = cv2.imread(pre_data_path + 'B%.4d' % image_nr + extension, cv2.IMREAD_ANYDEPTH) # toggle_plot = False # save_image = False # fig, ax = plot_image('raw image ' + str(image_nr), img_raw, brighten_factor=8) # window_size = np.ceil(2*scale) // 2 * 2 + 1 # Get closest odd number # for i, image_nr in enumerate(image_nrs): # pre_data_path = data_dir + sep + pre_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nr) + sep # post_data_path = data_dir + sep + post_data_folder + sep + flame_name + sep + record_name + "_Frame" + str(frame_nr) + sep # shape, contour, contour_length_pixels = get_contour_data(procedure_nr, window_size, pre_data_path, post_data_path, image_nr, extension, toggle_plot, save_image) # contour_x = contour[:,:,0] # contour_y = contour[:,:,1] # ax.plot(contour_x, contour_y, colors[i]) # D: Single procedure, double image, single frame # os.chdir(pre_data_path) # for filename in os.listdir(pre_data_path): # print(filename) # os.rename(filename, filename.replace('B', 'B0')) # # x and y coordinates of the discretized (segmented) flame front # contour_nr = image_nr - 1 # contour_x = flame.tortuosity_data.x_list[contour_nr] # contour_y = flame.tortuosity_data.y_list[contour_nr] # ax.plot(contour_x, contour_y, color='y') # shape = (5, 5) # dtype = np.uint16 # data type # img_empty = 3000*np.ones(shape, dtype) # Destination image # factor = 2**0 # img_empty_8bit = (img_empty/factor).astype(np.uint8) # code snippets # print(pixel_density_threshold) # #%% Step 3-2: # pixel_density_gradient = np.gradient(img_pixel_density) # pixel_density_gradient_x = np.abs(pixel_density_gradient[0]) # pixel_density_gradient_y = np.abs(pixel_density_gradient[1]) # pixel_density_gradient_combined = np.abs(pixel_density_gradient_x + pixel_density_gradient_y) # plot_number_density(pixel_density_gradient_combined[::-1]) # w_size = int(window_size/2) # kernel = np.ones((w_size, w_size),np.float32)/(w_size**2) # img_pixel_density_gradient_combined = cv2.filter2D(pixel_density_gradient_combined, -1, kernel) # plot_number_density(img_pixel_density_gradient_combined[::-1]) # figx, axx = plt.subplots() # axx.grid() # distplot2 = sns.histplot(img_pixel_density_gradient_combined.flatten(), kde=True, stat='density', ax=axx) # # Extract fitted distribution # dist_data = distplot2.get_lines()[0].get_data() # dist_data_x = dist_data[0] # dist_data_y = dist_data[1] # peaks, _ = find_peaks(dist_data_y) # prominences = peak_prominences(dist_data_y, peaks)[0] # peak_coords = list(zip(peaks, prominences, dist_data_x[peaks], dist_data_y[peaks])) # peak_coords_prominence_descending = sorted(peak_coords, key = lambda x:x[1], reverse=True) # peak_coords_sorted_probability = sorted(peak_coords_prominence_descending[0:2], key = lambda x:x[3]) # accepted_peak_coords = sorted(peak_coords_sorted_probability, key = lambda x:x[0]) # accepted_peaks = [accepted_peak_coord[0] for accepted_peak_coord in accepted_peak_coords] # axx.plot(dist_data_x[accepted_peaks], dist_data_y[accepted_peaks], color='b', marker='x', ms=8, mew=2, ls='None') # print(np.max(dist_data_x[accepted_peaks])) # #%% Determine threshold pixel density (separating unburnt and burnt side) [value corresponding to minimum probability] # threshold2 = np.max(dist_data_x[accepted_peaks]) # #%% Step 4: Binarize image # src = img_pixel_density_gradient_combined # Input image array (must be in Grayscale) # thresholdValue = threshold2 #140 # flame 1 and 2 (.tif) require a different threshold value compared to flame 3 (.bmp) # maxVal = 2**8 - 1 # Maximum value that can be assigned to a pixel. # threshold_type = cv2.THRESH_BINARY # The type of thresholding to be applied. # ret2, img_binary2 = cv2.threshold(src, thresholdValue, maxVal, threshold_type) # code snippets
/*************** type.h file for LEVEL-1 ****************/ #ifndef TYPE #define TYPE #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <ext2fs/ext2_fs.h> #include <string.h> #include <libgen.h> #include <sys/stat.h> #include <time.h> typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; // struct ext2_super_block { // u32 s_inodes_count; /* Inodes count */ // u32 s_blocks_count; /* Blocks count */ // u32 s_r_blocks_count; /* Reserved blocks count */ // u32 s_free_blocks_count; /* Free blocks count */ // u32 s_free_inodes_count; /* Free inodes count */ // u32 s_first_data_block; /* First Data Block */ // u32 s_log_block_size; /* Block size */ // u32 s_log_cluster_size; /* Allocation cluster size */ // u32 s_blocks_per_group; /* # Blocks per group */ // u32 s_clusters_per_group; /* # Fragments per group */ // u32 s_inodes_per_group; /* # Inodes per group */ // u32 s_mtime; /* Mount time */ // u32 s_wtime; /* Write time */ // u16 s_mnt_count; /* Mount count */ // s16 s_max_mnt_count; /* Maximal mount count */ // u16 s_magic; /* Magic signature */ // // more non-essential fields // u16 s_inode_size; /* size of inode structure */ // } typedef struct ext2_super_block SUPER; // struct ext2_group_desc { // u32 bg_block_bitmap; // Bmap block number // u32 bg_inode_bitmap; // Imap block number // u32 bg_inode_table; // Inodes begin block number // u16 bg_free_blocks_count; // THESE are OBVIOUS // u16 bg_free_inodes_count; // u16 bg_used_dirs_count; // u16 bg_pad; // ignore these // u32 bg_reserved[3]; // }; typedef struct ext2_group_desc GD; // struct ext2_inode { // u16 i_mode; // 16 bits = |tttt|ugs|rwx|rwx|rwx| // u16 i_uid; // owner uid // u32 i_size; // file size in bytes // u32 i_atime; // time fields in seconds // u32 i_ctime; // since 00:00:00,1-1-1970 // u32 i_mtime; // u32 i_dtime; // u16 i_gid; // group ID // u16 i_links_count; // hard-link count // u32 i_blocks; // number of 512-byte sectors // u32 i_flags; // IGNORE // u32 i_reserved1; // IGNORE // u32 i_block[15]; // See details below // u32 i_pad[7]; // for inode size = 128 bytes // }; typedef struct ext2_inode INODE; // struct ext2_dir_entry_2{ // u32 inode; // inode number; count from 1, NOT 0 // u16 rec_len; // this entry’s length in bytes // u8 name_len; // name length in bytes // u8 file_type; // not used // char name[EXT2_NAME_LEN]; // name: 1-255 chars, no ending NULL // }; typedef struct ext2_dir_entry_2 DIR; SUPER *sp; GD *gp; INODE *ip; DIR *dp; #define FREE 0 #define READY 1 #define BLKSIZE 1024 #define NMINODE 128 #define NPROC 4 #define NOFT 64 #define NFD 10 #define NMTABLE 8 typedef struct minode{ INODE INODE; // INODE structure on disk int dev, ino; // (dev, ino) of INODE int refCount; // in use count int dirty; // 0 for clean, 1 for modified int mounted; // for level-3 struct Mount *mptr; // for level-3 }MINODE; typedef struct oft { // OpenFileTable int mode; // 0 R | 1 W | 2 RW | 3 APP int refCount; MINODE *minodePtr; int offset; } OFT; typedef struct Mount { int dev; // dev (opened vdisk fd number) 0 means FREE int ninodes; // from superblock int nblocks; int bmap; // from GD block int imap; int iblk; MINODE *mounted_inode; char name[64]; // device name e.g. mydisk char mount_name[64]; // mounted DIR pathname } MOUNT; typedef struct proc{ struct proc *next; int pid; // process ID int uid; // user ID int gid; int ppid; // parent process ID int status; // 0 = free, 1 = alive, 2 = dead MINODE *cwd; // CWD directory pointer OFT *fd[NFD]; }PROC; MINODE minode[NMINODE]; OFT oft[NOFT]; MINODE *root; PROC proc[NPROC], *running; MOUNT mountTable[NMTABLE]; // set all dev = 0 in init() char gpath[128]; // global for tokenized components char *name[64]; // assume at most 64 components in pathname int n; // number of component strings int fd, dev; int nblocks, ninodes, bmap, imap, iblk; char line[128], cmd[32], pathname[128]; char *disk = "disk2copy"; // change this to YOUR virtual #endif
import React, { useState } from 'react'; import styles from "../styles/gptSearchBar.module.css" import lang from '../utils/languageConstants'; import { useSelector, useDispatch } from 'react-redux'; import openai from '../utils/openAI'; import { useRef } from 'react'; import { options } from '../utils/constants'; import { addGPTMovies, setGptShimmer } from '../redux/gptSlice'; function GPTSearchBar() { const dispatch = useDispatch(); const searchText = useRef(null); const code = useSelector((state)=>state.config.lang); const handleSubmit = async (event)=>{ console.log("handle submit is called ") event.preventDefault(); // Api call to open AI const gptQuery = "Act as a movie recommendation system and suggest some movies for the query " + searchText.current.value + "give only 5 movies names in comma separted format, remember comma format is compulsory like Example1, Example2, Example3, Example4, Example5 " const gptResult = await openai.chat.completions.create({ messages: [{ role: 'user', content: gptQuery }], model: 'gpt-3.5-turbo', }); if(!gptResult.choices){ return; } const gptSearchResults = gptResult.choices?.[0].message?.content.split(","); const lowercaseSearchResults = gptSearchResults.map((movie) => movie.toLowerCase().trim()); console.log(lowercaseSearchResults); const promiseArray = gptSearchResults.map((movie)=> fetchMovieTMDB(movie)); const finalRes = await Promise.all(promiseArray); const result = finalRes.flat(1); const filteredMovies = lowercaseSearchResults.map((movie)=>{ return result.filter((m)=>m.title.toLowerCase()==movie); }); const finalMovies = filteredMovies.flat(1); console.log(finalMovies); dispatch(addGPTMovies({ gptMovies: finalMovies, gptSearchResults: gptSearchResults })) } const fetchMovieTMDB= async (movie)=>{ const url =`https://api.themoviedb.org/3/search/movie?query= ${movie} &include_adult=false&language=en-US&page=1` const res = await fetch(url, options); const data = await res.json(); return data.results; } return ( <div className={styles.container}> <form onSubmit={handleSubmit} className={styles.form}> <input ref={searchText} type='text' className={styles.input} placeholder={lang[code].gptSearch} /> <button type='submit' className={styles.btn}> {lang[code].search}</button> </form> </div> ) } export default GPTSearchBar
const router = require("express").Router(); const { User, validate } = require("../models/user"); const bcrypt = require("bcrypt"); const crypto = require("crypto"); const Token = require("../models/token"); const sendEmail = require("../utils/sendEmail"); const connection = require("../db"); const multer = require("multer"); const { CloudinaryStorage } = require("multer-storage-cloudinary"); const cloudinary = require("cloudinary").v2; const Joi = require('joi'); // Configure Cloudinary cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET }); // Set up Multer storage with Cloudinary const storage = new CloudinaryStorage({ cloudinary: cloudinary, params: { folder: "profile_images", allowed_formats: ["jpg", "jpeg", "png"] } }); const upload = multer({ storage: storage }) // POST /api/users - Create a new user with profile image upload router.post("/", upload.single("profileImage"), async (req, res) => { try { const { error } = validate(req.body); if (error) return res.status(400).send({ message: error.details[0].message }); const { firstName, lastName, email, password } = req.body; const existingUser = await getUserByEmail(email); if (existingUser) return res.status(409).send({ message: "User with given email already exists!" }); const salt = await bcrypt.genSalt(Number(process.env.SALT)); const hashPassword = await bcrypt.hash(password, salt); const newUser = { firstName, lastName, email, password: hashPassword, profileImage: req.file.path }; await createUser(newUser); // Create verification token and send email const tokenValue = crypto.randomBytes(32).toString("hex"); await createVerificationToken(newUser.email, tokenValue); const url = `${process.env.BASE_URL}users/${newUser.id}/verify/${tokenValue}`; await sendEmail(newUser.email, "Verify Email", url); res.status(201).send({ message: "An Email has been sent to your account, please verify" }); } catch (error) { console.log(error); res.status(500).send({ message: "Internal Server Error" }); } }); // Route for verifying email router.get("/:id/verify/:token/", async (req, res) => { try { const user = await getUserById(req.params.id); if (!user) return res.status(400).send({ message: "Invalid link" }); const token = await getTokenByUserId(user.id); if (!token || token.token !== req.params.token) return res.status(400).send({ message: "Invalid link" }); await updateUserVerification(user.id); await deleteToken(token.id); res.status(200).send({ message: "Email verified successfully" }); } catch (error) { res.status(500).send({ message: "Internal Server Error" }); } }); // GET /api/users - Get all users router.get("/", async (req, res) => { try { const users = await getAllUsers(); res.status(200).json(users); } catch (error) { console.error(error); res.status(500).send({ message: "Internal Server Error" }); } }); // DELETE /api/users/:id - Delete a user router.delete("/:id", async (req, res) => { try { const user = await deleteUserById(req.params.id); if (!user) { return res.status(404).send({ message: "User not found" }); } res.status(200).send({ message: "User deleted successfully" }); } catch (error) { console.error(error); res.status(500).send({ message: "Internal Server Error" }); } }); router.put("/:id", async (req, res) => { try { const { error } = validateUpdate(req.body); if (error) { return res.status(400).send({ message: error.details[0].message }); } const updatedUser = await updateUserById(req.params.id, req.body); if (!updatedUser) { return res.status(404).send({ message: "User not found" }); } res.status(200).json(updatedUser); } catch (error) { console.error(error); res.status(500).send({ message: "Internal Server Error" }); } }); // Helper functions const createUser = async (user) => { return new Promise((resolve, reject) => { connection.query('INSERT INTO users SET ?', user, (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }; const getUserByEmail = async (email) => { return new Promise((resolve, reject) => { connection.query('SELECT * FROM users WHERE email = ?', [email], (err, results) => { if (err) { reject(err); } else { resolve(results[0]); } }); }); }; const getAllUsers = async () => { return new Promise((resolve, reject) => { connection.query('SELECT * FROM users', (err, results) => { if (err) { reject(err); } else { resolve(results); } }); }); }; const deleteUserById = async (userId) => { return new Promise((resolve, reject) => { connection.query('DELETE FROM users WHERE id = ?', [userId], (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }; const updateUserById = async (userId, userData) => { return new Promise((resolve, reject) => { connection.query('UPDATE users SET ? WHERE id = ?', [userData, userId], (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }; const createVerificationToken = async (userId, tokenValue) => { return new Promise((resolve, reject) => { connection.query('INSERT INTO tokens (userId, token) VALUES (?, ?)', [userId, tokenValue], (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }; const getTokenByUserId = async (userId) => { return new Promise((resolve, reject) => { connection.query('SELECT * FROM tokens WHERE userId = ?', [userId], (err, results) => { if (err) { reject(err); } else { resolve(results[0]); } }); }); }; const deleteToken = async (tokenId) => { return new Promise((resolve, reject) => { connection.query('DELETE FROM tokens WHERE id = ?', [tokenId], (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }; const updateUserVerification = async (userId) => { return new Promise((resolve, reject) => { connection.query('UPDATE users SET verified = true WHERE id = ?', [userId], (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }; const validateUpdate = (data) => { const schema = Joi.object({ firstName: Joi.string().required().label("First Name"), lastName: Joi.string().required().label("Last Name"), email: Joi.string().email().required().label("Email"), }); return schema.validate(data); }; module.exports = router;
import 'package:flutter/material.dart'; class AddVehiculeDialog extends StatefulWidget { final Function(String, String, String) onAddVehicule; const AddVehiculeDialog({ required this.onAddVehicule, Key? key, }) : super(key: key); @override _AddVehiculeDialogState createState() => _AddVehiculeDialogState(); } class _AddVehiculeDialogState extends State<AddVehiculeDialog> { final TextEditingController _modelController = TextEditingController(); final TextEditingController _registrationNumberController = TextEditingController(); final TextEditingController _typeController = TextEditingController(); final _formKey = GlobalKey<FormState>(); @override void dispose() { _modelController.dispose(); _registrationNumberController.dispose(); _typeController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), elevation: 0, backgroundColor: Colors.transparent, child: SingleChildScrollView( child: Container( padding: EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(12), ), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( 'Add Vehicle', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), SizedBox(height: 20), Form( key: _formKey, child: Column( children: [ TextFormField( decoration: InputDecoration( labelText: 'Model', border: OutlineInputBorder(), ), controller: _modelController, validator: (value) { if (value!.isEmpty) { return 'Model is required'; } return null; }, ), SizedBox(height: 12), TextFormField( decoration: InputDecoration( labelText: 'Registration Number', border: OutlineInputBorder(), ), controller: _registrationNumberController, validator: (value) { if (value!.isEmpty) { return 'Registration number is required'; } else if (!RegExp(r'^[1-9]\d{0,2} \d{1,4}$') .hasMatch(value)) { return 'Invalid registration number format'; } return null; }, ), SizedBox(height: 12), TextFormField( decoration: InputDecoration( labelText: 'Type', border: OutlineInputBorder(), ), controller: _typeController, validator: (value) { if (value!.isEmpty) { return 'Type is required'; } return null; }, ), ], ), ), SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( onPressed: () => Navigator.pop(context), child: Text( 'Cancel', style: TextStyle( fontSize: 16, color: Colors.grey, ), ), ), TextButton( onPressed: () { if (_formKey.currentState!.validate()) { final String model = _modelController.text; final String registrationNumber = _registrationNumberController.text; final String type = _typeController.text; widget.onAddVehicule(model, registrationNumber, type); Navigator.pop(context); } }, child: Text( 'Add', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.blue, ), ), ), ], ), ], ), ), ), ); } }
package study.querydsl.repository; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.jpa.impl.JPAQueryFactory; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; import study.querydsl.dto.MemberSearchCondition; import study.querydsl.dto.MemberTeamDto; import study.querydsl.dto.QMemberTeamDto; import study.querydsl.entity.Member; import javax.persistence.EntityManager; import java.util.List; import java.util.Optional; import static org.springframework.util.StringUtils.hasText; import static study.querydsl.entity.QMember.member; import static study.querydsl.entity.QTeam.team; @Repository @RequiredArgsConstructor public class MemberJpaRepository { private final EntityManager em; private final JPAQueryFactory queryFactory; public void save(Member member){ em.persist(member); } public Optional<Member> findById(Long id){ Member findMember = em.find(Member.class, id); return Optional.ofNullable(findMember); } public List<Member> findAll(){ return em.createQuery("select m from Member m", Member.class) .getResultList(); } public List<Member> findAll_Querydsl(){ return queryFactory .selectFrom(member) .fetch(); } public List<Member> findByUsername(String username){ return em.createQuery("select m from Member m where m.username = :username", Member.class) .setParameter("username", username) .getResultList(); } public List<Member> findByUsername_Querydsl(String username){ return queryFactory .selectFrom(member) .where(member.username.eq(username)) .fetch(); } //검색 빌더 이용 public List<MemberTeamDto> searchByBulider(MemberSearchCondition condition){ BooleanBuilder bulider = new BooleanBuilder(); if(hasText(condition.getUsername())){ bulider.and(member.username.eq(condition.getUsername())); } if(hasText(condition.getTeamName())) { bulider.and(team.name.eq(condition.getTeamName())); } if(condition.getAgeGoe() != null){ bulider.and(member.age.goe(condition.getAgeGoe())); } if(condition.getAgeLoe() != null){ bulider.and(member.age.loe(condition.getAgeLoe())); } return queryFactory .select(new QMemberTeamDto( member.id.as("memberId"), member.username, member.age, team.id.as("teamId"), team.name.as("teamName"))) .from(member) .leftJoin(member.team, team) .where(bulider) .fetch(); } //검색 where 파라미터로 public List<MemberTeamDto> search(MemberSearchCondition condition){ return queryFactory .select(new QMemberTeamDto( member.id.as("memberId"), member.username, member.age, team.id.as("teamId"), team.name.as("teamName"))) .from(member) .leftJoin(member.team, team) .where( usernameEq(condition.getUsername()), teamNameEq(condition.getTeamName()), ageGoe(condition.getAgeGoe()), ageLoe(condition.getAgeLoe()) ) .fetch(); } private BooleanExpression usernameEq(String username) { return hasText(username) ? member.username.eq(username) : null; } private BooleanExpression teamNameEq(String teamName) { return hasText(teamName) ? team.name.eq(teamName) : null; } private BooleanExpression ageGoe(Integer ageGoe) { return ageGoe != null ? member.age.goe(ageGoe) : null; } private Predicate ageLoe(Integer ageLoe) { return ageLoe != null ? member.age.loe(ageLoe) : null; } }
import { Body, ClassSerializerInterceptor, Controller, Delete, Get, Logger, Post, Req, UseGuards, UseInterceptors, } from '@nestjs/common'; import { ApiBody, ApiConflictResponse, ApiCreatedResponse, ApiOkResponse, ApiOperation, ApiTags, ApiUnauthorizedResponse, } from '@nestjs/swagger'; import { Request } from 'express'; import { GoogleSignInDto } from 'src/user/dto/sign-in-with-google.dto'; import { User } from 'src/user/entities/user.entity'; import { UserService } from 'src/user/user.service'; import { RegisterWithPasswordDto } from '../user/dto/register-with-password.dto'; import { AuthService } from './auth.service'; import { LoginDto } from './dto/login.dto'; import { CookieAuthGuard } from './guards/cookie-auth.guard'; import { LogInWithCredentialsGuard } from './guards/login-with-credentials.guard'; import { SignInWithGoogleGuard } from './guards/sign-in-with-google.guard'; @ApiTags('authentication') @Controller('auth') @UseInterceptors(ClassSerializerInterceptor) export class AuthController { constructor( private readonly authService: AuthService, private userService: UserService, ) {} @ApiOperation({ summary: 'Email and password registration' }) @ApiCreatedResponse({ type: User, description: 'Registration was successful, returning the created new user', }) @ApiConflictResponse({ description: 'Email is already registered.', }) @Post('register') async register(@Body() registrationData: RegisterWithPasswordDto) { return this.authService.register(registrationData); } @ApiOperation({ description: 'Logs in and returns the authentication cookie', }) @ApiBody({ type: LoginDto }) @ApiCreatedResponse({ description: 'Login was successful', headers: { 'SET-COOKIE': { schema: { type: 'string', example: 'connect.sid=keyboard cat; Path=/; Expires=Future date; SameSite=Strict', }, description: 'Authentication cookie', }, }, }) @ApiUnauthorizedResponse({ description: 'email is not registered or password is invalid', }) @UseGuards(LogInWithCredentialsGuard) @Post('login') async logIn(@Req() request: Request) { return this.userService.getLoginData(request.user!); } @ApiOperation({ summary: 'Google OIDC', description: 'Logs in user if google account email is in the database, creates new account if not.', }) @ApiBody({ type: GoogleSignInDto, required: true }) @ApiCreatedResponse({ type: User, description: 'Registration was successful, returning the created new user', }) @UseGuards(SignInWithGoogleGuard) @Post('google-sign-in') async signInWithGoogle(@Req() req: Request) { const result = await this.userService.getLoginData(req.user!); return result; } @ApiOperation({ summary: 'Destroys user sessions', description: 'Must call for Google OIDC and simple email/password login', }) @ApiOkResponse({ description: 'User logged out, session was succesfully destroyed', }) @UseGuards(CookieAuthGuard) @Delete('logout') async logOut(@Req() request: Request) { this.authService.logout(request); } @ApiOperation({ description: 'Returns user if theres a valid session', }) @ApiOkResponse() @UseGuards(CookieAuthGuard) @Get() async authenticate(@Req() request: Request) { return this.userService.getLoginData(request.user!); } @ApiOperation({ summary: 'DEVELOPMENT', description: 'Destroy session, but do not clear users cookie', }) @ApiOkResponse() @UseGuards(CookieAuthGuard) @Delete('destroy-session') async destroySession(@Req() request: Request) { request.session.destroy((err: any) => { if (err !== null) { Logger.error(`Error while destroying session:\n${err}`, 'Session'); } }); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html> <script> /*Object Destructuring: JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays. */ //Normal way to extract from an object property: const obj = { _name: "Priyanka", city: "Pune", mobileNo: 7383441173, education: "Bachelors", graduationCity: "Amravati", } // console.log(_name); const _name1 = obj._name; const city1 = obj.city; const mobileNo1 = obj.mobileNo; const education1 = obj.education; const graduationCity1 = obj.graduationCity; console.log(_name1); const obj2 = { _name2: _name1, city2: city1, mobileNo2: mobileNo1, education2: education1, graduationCity2: graduationCity1, } //Using destructuring: const obj0 = { _name: "Priyanka", city: "Pune", mobileNo: 7383441173, education: "Bachelors", graduationCity: "Amravati", } const { _name, city, mobileNo, education, graduationCity} = obj0; const obj3 = { _name3: _name, city3: city, mobileNo3: mobileNo, education3: education, graduationCity3: graduationCity, } console.log(obj3); // Array destructuring let arr1 = ["John", "Smith"]; let [FN, LN, age=15] = arr1; console.log(age) </script>
import { Controller, Get, Param, Req, Post, Body, Delete, Put, Inject, UseGuards, Res, } from '@nestjs/common'; import { BooksService } from './books.service'; import { Request } from 'express'; import { BookDto } from './book.dto'; import { ApiOperation, ApiResponse, ApiTags, ApiBearerAuth, } from '@nestjs/swagger'; import { Book } from './book.entity'; import { AuthGuard } from '@nestjs/passport'; import { WINSTON_MODULE_PROVIDER } from 'nest-winston'; import { Logger } from 'winston'; import { HttpStatus } from '@nestjs/common'; @ApiTags('book') @Controller('books') @UseGuards(AuthGuard('jwt')) @ApiBearerAuth('access-token') export class BooksController { /** * * @param {BooksService} booksService Servicio de libros */ constructor( private booksService: BooksService, @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger, ) {} /** * * @returns {Book[]} Devuelve una lista de libros * @param {Request} request Lista de parámetros para filtrar */ @Get() @ApiOperation({ summary: 'Obtener lista de libros' }) @ApiResponse({ status: HttpStatus.OK, description: 'Lista de libros', type: [Book], }) async findAll(@Req() request: Request, @Res() res): Promise<Book[]> { let startTime = Date.now(); let data = await this.booksService.findAll(request.query); this.writeLog(startTime, request, HttpStatus.OK); return res.status(HttpStatus.OK).json({ statusCode: HttpStatus.OK, message: 'OK', data: data, }); } /** * * @returns {Book} Devuelve un libro específico * @param {string} bookId Identificador del libro a buscar */ @Get(':bookId') @ApiOperation({ summary: 'Devuelve información sobre un libro específico' }) @ApiResponse({ status: HttpStatus.OK, description: 'Datos del libro', type: Book, }) async findBook( @Req() request: Request, @Param('bookId') bookId: string, @Res() res, ): Promise<Book> { let message = 'OK'; let startTime = Date.now(); let data = await this.booksService.findBook(bookId); if (!data) { message = 'A book with the specified id was not found'; } this.writeLog(startTime, request, HttpStatus.OK); return res.status(HttpStatus.OK).json({ statusCode: HttpStatus.OK, message: message, data: data, }); } /** * * @returns {Book} Devuelve el libro creado * @param {JSON} newBook Libro a crear */ @Post() @ApiOperation({ summary: 'Crear un libro' }) @ApiResponse({ status: HttpStatus.CREATED, description: 'Datos del libro creado', type: Book, }) @ApiResponse({ status: 403, description: 'Forbidden.' }) async createBook( @Req() request: Request, @Body() newBook: BookDto, @Res() res, ): Promise<Book> { let startTime = Date.now(); let data = await this.booksService.createBook(newBook); this.writeLog(startTime, request, HttpStatus.CREATED); return res.status(HttpStatus.CREATED).json({ statusCode: HttpStatus.CREATED, message: 'OK', data: data, }); } /** * * @returns {Book} Eliminar un libro específico * @param {string} bookId Identificador del libro a eliminar */ @Delete(':bookId') @ApiOperation({ summary: 'Eliminar un libro específico' }) @ApiResponse({ status: 200, description: 'Datos del libro eliminado', }) async deleteBook( @Req() request: Request, @Param('bookId') bookId: string, @Res() res, ): Promise<Book> { let message = 'OK'; let startTime = Date.now(); let data = await this.booksService.deleteBook(bookId); if (data['affected'] == 0) { message = 'A book with the specified id was not found'; data = {}; } this.writeLog(startTime, request, HttpStatus.OK); return res.status(HttpStatus.OK).json({ statusCode: HttpStatus.OK, message: message, data: data, }); } /** * * @returns {Book} Modificar un libro específico * @param {string} bookId Identificador del libro a modificar * @param {JSON} newBook Libro actualizado */ @Put(':bookId') @ApiOperation({ summary: 'Actualizar un libro específico' }) @ApiResponse({ status: 200, description: 'Datos del libro actualizado', type: Book, }) async updateBook( @Req() request: Request, @Param('bookId') bookId: string, @Body() newBook: BookDto, @Res() res, ): Promise<Book> { let message = 'OK'; let startTime = Date.now(); let data = await this.booksService.updateBook(bookId, newBook); if (!data) { message = 'A book with the specified id was not found'; } this.writeLog(startTime, request, HttpStatus.OK); return res.status(HttpStatus.OK).json({ statusCode: HttpStatus.OK, message: message, data: data, }); } writeLog(startTime: any, request: any, statusCode: number) { let finishTime = Date.now(); let elapsedTime = finishTime - startTime; this.logger.log({ level: 'info', message: '', statusCode: statusCode, method: request['method'], url: request['url'], user: request['user'].username, duration: elapsedTime, }); } }
import styles from "./InsertRow.module.css"; import { useRef, useContext } from "react"; import { dataContext } from "./App"; import { Modal } from "./Modal"; import { AgeInput } from "./AgeInput"; import { SubscribeInput } from "./SubscribeInput"; import { CheckBox } from "./CheckBox"; export function FormInput() { const { data, setData, state, dispatch } = useContext(dataContext); const nameInputRef = useRef<HTMLInputElement>(null); const submitHandler = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (state.name === "") { nameInputRef.current!.style.backgroundColor = "rgba(255, 20, 20, 0.5)"; return; } if (state.age === "") { dispatch({ type: "set_red_age" }); return; } if (state.subscribe === "") { dispatch({ type: "set_red_subscribe" }); return; } data.push({ name: state.name, age: state.age, subscription: state.subscribe, employment: state.isEmployed, id: Date.now().toString().slice(-6), }); setData([...data]); localStorage.setItem("data", JSON.stringify(data)); dispatch({ type: "set_initialState" }); }; const inputNameHandler = (e: React.ChangeEvent<HTMLInputElement>) => { dispatch({ type: "set_name", name: e.target.value }); nameInputRef.current!.style.backgroundColor = "transparent"; }; return ( <form onSubmit={submitHandler} className={styles["insert-form"]} action="" > <input ref={nameInputRef} onChange={inputNameHandler} className={styles["form-input"]} type="text" placeholder="Name" value={state.name} /> <AgeInput /> <SubscribeInput /> {state.isVisibleModal && <Modal />} <CheckBox /> <input className={styles["form-input-submit"]} type="submit" value="Insert" /> </form> ); }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('products', function (Blueprint $table) { $table->id(); $table->Text('product_name')->nullable(); $table->integer('min_purchase_qty')->nullable(); $table->integer('max_purchase_qty')->nullable(); $table->json('product_images')->nullable(); $table->Text('regular_price')->nullable(); $table->Text('sku')->nullable(); $table->Text('stock_status')->nullable()->comment("0 = out of stock, 1 = in stock"); $table->date('discount_start_date')->nullable(); $table->date('discount_end_date')->nullable(); $table->integer('discount')->nullable(); $table->Text('discount_type')->nullable()->comment('1 = flate, 2 = percent'); $table->Text('product_description')->nullable(); $table->Text('meta_title')->nullable(); $table->Text('meta_description')->nullable(); $table->Text('slug')->nullable(); $table->Integer('product_status')->comment('0 = draft, 1 = publish'); $table->unsignedBigInteger('brand')->nullable(); $table->unsignedBigInteger('main_category')->nullable(); $table->unsignedBigInteger('sub_category')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('products'); } };
package Enum; enum Status { Running, Stopped, Pending, Complete; } enum Laptop { Apple(1000), Dell(800), HP, Lenovo(600), Acer(500); private int price; Laptop() { price = 0; // For HP } Laptop(int p) { price = p; } int getPrice() { return price; } } class Main { public static void main(String[] args) { Status s = Status.Running; System.out.println(s); System.out.println("Index of " + s + ": " + s.ordinal()); Status[] arr = Status.values(); for(Status ss: arr) { System.out.println(ss + ": " + ss.ordinal()); } if(s == Status.Running) { System.out.println("Running"); } switch (s) { case Running: System.out.println("Running"); break; case Stopped: System.out.println("Stopped"); break; case Pending: System.out.println("Pending"); break; case Complete: System.out.println("Complete"); break; default: break; } for(Laptop l: Laptop.values()) { System.out.println(l + ": " + l.getPrice()); } } }
/********************************************* * Imports *********************************************/ const login = require('@test_data/environment.json')[0]; const {homePage} = require('../../shared_page_objects/home'); const {loginPage} = require('../../shared_page_objects/login'); const {demographicsPage} = require('../../shared_page_objects/demographics_page'); const {plansPage} = require('../../shared_page_objects/plans_page'); const testData = require('@test_data/quote_edit.json'); const using = require('custom_jasmine_data_provider'); const {isDisplayed} = require('actions'); const {reviewPlanPage} = require('../page_objects/review_plan_page'); const {planDetailsPage} = require('../../shared_page_objects/plan_details_page'); let planName, primaryPlanBenefits, monthlyPremium, deductible, outOfPocketMax, dentalPlanName, dentalBenefits, dentalMonthlyPremium, dentalDeductible, dentalPlanMaximum; using(testData, data => { describe('Suite: Aspirus MA SP - Plan details edit from review quote page validation', () => { it('Login to the application', async () => { // Open the app await loginPage.openHomePage(login.url); await loginPage.login(login.username, login.password); expect(await isDisplayed(homePage.$button('Log Out'))).toBe(true, 'Expect the user to get logged in to application successfully'); }); it('Select Home menu', async () => { await homePage.clickMenuTab('Home'); expect(await isDisplayed(homePage.$button('Actions'))).toBe(true, 'Expect home page is opening'); }); it('Click on shop for plans menu', async () => { await homePage.clickButton('Actions'); await homePage.clickSubMenuTab('Shop for Plans'); expect(await isDisplayed(demographicsPage.$zipCode)).toBe(true, 'Expect user navigate to application creation section'); }); it('Enter demographics details & navigate to plans page', async () => { await demographicsPage.setZipCode(data.zipCode); expect(await demographicsPage.getSelectedCounty(data.county)).toContain(data.county, `Expect county for '${data.zipCode}' to be '${data.county}'`); await demographicsPage.selectCoverageDate(data.planYear); expect(await demographicsPage.returnSelectedCoverageDate()).toContain(data.planYear, `Expect ${data.planYear} year coverage effective date to be selected`); await demographicsPage.clickButton('View Plans'); expect(await isDisplayed(plansPage.$pageHeader('View and Compare Health Plans'))).toBe(true, 'Expect user navigate to plans page'); }); it(`Selecting ${data.planTabLabel} plan`, async () => { await plansPage.selectPlanTab(data.planTabLabel); await plansPage.selectPlan(data.planName); //Fetching the selected plan details planName = await plansPage.getSelectedPlanName(); primaryPlanBenefits = await plansPage.getPrimaryPlanBenefitValues(planName); monthlyPremium = primaryPlanBenefits[0]; deductible = primaryPlanBenefits[1]; outOfPocketMax = primaryPlanBenefits[2]; expect(await isDisplayed(plansPage.$selectedPlanIndicator)).toBe(true, 'Expect plan selection done successfully'); expect(await isDisplayed(plansPage.$planFooter(data.planTabLabel))).toBe(true, `Expect ${data.planTabLabel} to be shown in the footer`); await plansPage.clickButton('Continue'); //No dental plan is selected so continue here await plansPage.clickButton('Continue'); expect(await isDisplayed(reviewPlanPage.$pageHeader('Review Plan'))).toBe(true, 'Expect user navigate to Review Plan page'); }); it('Reviewing plan details in review plan page', async () => { let primaryBenefits = await reviewPlanPage.getPrimaryPlanBenefitValues(planName); let monthlyPremiumValue = primaryBenefits[0]; let deductibleValue = primaryBenefits[1]; let outOfPocketValue = primaryBenefits[2]; //Validating the primary plan benefits expect(await isDisplayed(reviewPlanPage.$planName(planName))).toBe(true, `Expect ${planName} selected in plans page to be displayed in review plans page`); expect(monthlyPremiumValue).toBe(monthlyPremium, `Expect ${monthlyPremium} should match ${monthlyPremiumValue} present in quotes page`); expect(deductibleValue).toBe(deductible, `Expect ${deductible} should match ${deductibleValue} present in quotes page`); expect(outOfPocketValue).toBe(outOfPocketMax, `Expect ${outOfPocketMax} should match ${outOfPocketValue} present in quotes page`); }); it('Reviewing zip code & county details', async () => { expect(await reviewPlanPage.getPlanDetails('ZIP Code')).toBe(data.zipCode, 'Expect zip code should be same as entered in demographics page'); expect(await reviewPlanPage.getPlanDetails('County')).toContain(data.county, 'Expect county should be same as entered in demographics page'); }); it('Click edit button on the plans section', async () => { await reviewPlanPage.clickEditButton('Plan Selected'); expect(await isDisplayed(plansPage.$pageHeader('View and Compare Health Plans'))).toBe(true, 'Expect user navigate to plans page'); }); it(`Selecting new ${data.planTabLabel} plan`, async () => { //unselecting selected plan await plansPage.clickButton('Selected'); await plansPage.selectPlanTab(data.newPlanTabLabel); await plansPage.selectPlan(data.newPlanName); //Fetching the selected plan details planName = await plansPage.getSelectedPlanName(); primaryPlanBenefits = await plansPage.getPrimaryPlanBenefitValues(planName); monthlyPremium = primaryPlanBenefits[0]; deductible = primaryPlanBenefits[1]; outOfPocketMax = primaryPlanBenefits[2]; await plansPage.clickButton('Continue'); //No dental plan is selected so continue here await plansPage.clickButton('Continue'); expect(await isDisplayed(reviewPlanPage.$pageHeader('Review Plan'))).toBe(true, 'Expect user navigate to Review Plan page'); }); it('Reviewing new plan details in review plan page', async () => { let newPrimaryBenefits = await reviewPlanPage.getPrimaryPlanBenefitValues(planName); let newMonthlyPremiumValue = newPrimaryBenefits[0]; let newDeductibleValue = newPrimaryBenefits[1]; let newOutOfPocketValue = newPrimaryBenefits[2]; //Validating the primary plan benefits expect(await isDisplayed(reviewPlanPage.$planName(planName))).toBe(true, `Expect new ${planName} selected in plans page to be displayed in review plans page`); expect(newMonthlyPremiumValue).toBe(monthlyPremium, `Expect ${monthlyPremium} should match ${newMonthlyPremiumValue} present in quotes page`); expect(newDeductibleValue).toBe(deductible, `Expect ${deductible} should match ${newDeductibleValue} present in quotes page`); expect(newOutOfPocketValue).toBe(outOfPocketMax, `Expect ${outOfPocketMax} should match ${newOutOfPocketValue} present in quotes page`); }); it('Saving edited quote details', async () => { await reviewPlanPage.clickButton('Save Plan'); expect(await isDisplayed(planDetailsPage.$pageHeader('Your Plan Has Been Saved'))).toBe(true, 'Expect user navigate to Review Plan page'); }); it('Log out from the application', async () => { await reviewPlanPage.clickLogoutButton(); expect(await isDisplayed(loginPage.$passwordLabel)).toBe(true, 'Expect the login page is displayed'); }); }); });
/* Piecewise linear advection scheme */ /* Written by Mladen Ivkovic, JAN 2020 * mladen.ivkovic@hotmail.com */ /* -------------------------------------*/ #include <math.h> #include <stdio.h> #include "cell.h" #include "defines.h" #include "io.h" #include "limiter.h" #include "params.h" #include "solver.h" #include "utils.h" #if NDIM == 1 extern cell *grid; #elif NDIM == 2 extern cell **grid; #endif extern params pars; void solver_step(float *t, float *dt, int step, int *write_output) { /* ------------------------------------------------------- * Main routine for the actual hydro step * ------------------------------------------------------- */ solver_init_step(); solver_get_advection_dt(dt); /* check this here in case you need to limit time step for output */ *write_output = io_is_output_step(*t, dt, step); #if NDIM == 1 solver_compute_fluxes(dt, /*dimension =*/0); solver_advance_step_advection(dt); #elif NDIM == 2 int dimension = step % 2; /* gives 0 or 1, switching each step */ solver_compute_fluxes(dt, dimension); solver_advance_step_advection(dt); dimension = (dimension + 1) % 2; /* 1 -> 0 or 0 -> 1 */ solver_init_step(); solver_compute_fluxes(dt, dimension); solver_advance_step_advection(dt); #endif } void solver_init_step() { /* --------------------------------------------- * Do everything that needs to be done before * we can compute the fluxes, the timestep, and * finally advance the simulation * --------------------------------------------- */ debugmessage("Called solver_init_step"); cell_reset_fluxes(); cell_set_boundary(); } void solver_compute_fluxes(float *dt, int dimension) { /* ------------------------------------------------------ * Computes the actual *net* fluxes between cells * Here we compute F^{n+1/2}_{i-1/2} - F^{n+1/2}_{i+1/2} * and store it in cell.pflux * dimension: 0 for x, 1 for y. Only used with Strang * splitting. * ------------------------------------------------------ */ debugmessage("Called solver_compute_fluxes; dimension = %d", dimension); cell *c; /* this cell */ cell *uw; /* the cell upwind of the flux at the interface of *c */ cell *dw; /* the cell downwind of the flux at the interface of *c */ #if NDIM == 1 for (int i = BC; i < pars.nx + BC; i++) { c = &grid[i]; if (c->prim.u[0] > 0) { /* we do upwind differencing */ dw = c; uw = &(grid[i - 1]); } else { dw = &(grid[i + 1]); uw = c; } solver_compute_cell_pair_flux(c, uw, dw, dt, /*dimension=*/0); } #elif NDIM == 2 if (dimension == 0) { for (int i = BC; i < pars.nx + BC; i++) { for (int j = BC; j < pars.nx + BC; j++) { c = &(grid[i][j]); if (c->prim.u[0] > 0) { dw = c; uw = &(grid[i - 1][j]); } else { dw = &(grid[i + 1][j]); uw = c; } solver_compute_cell_pair_flux(c, uw, dw, dt, dimension); } } } else if (dimension == 1) { for (int i = BC; i < pars.nx + BC; i++) { for (int j = BC; j < pars.nx + BC; j++) { c = &(grid[i][j]); if (c->prim.u[1] > 0) { dw = c; uw = &(grid[i][j - 1]); } else { dw = &(grid[i][j + 1]); uw = c; } solver_compute_cell_pair_flux(c, uw, dw, dt, dimension); } } } #endif /* ndim */ } void solver_compute_cell_pair_flux(cell *c, cell *uw, cell *dw, float *dt, int dim) { /* -------------------------------------------------------------------- * Compute the net flux for a given cell w.r.t. a specific cell pair * c: pointer to cell to work with * uw: the cell of the pair which is upwind * dw: the cell of the cell pair which is downwind * * dim: integer along which dimension to advect. 0: x. 1: y. * -------------------------------------------------------------------- */ pstate sl, sr; /* slopes left and right of the cell */ gas_init_pstate(&sl); gas_init_pstate(&sr); limiter_get_advection_slope_left(c, &sl, dim); limiter_get_advection_slope_right(c, &sr, dim); /* assign the slopes to the upwind/downwind cells */ pstate su; /* slope of upwind cell */ pstate sd; /* slope of downwind cell */ if (uw->id < dw->id) { su = sl; sd = sr; } else { su = sr; sd = sl; } /* Now compute the net fluxes */ float dsu, dsd; /* dx - |v|*dt for upwind and downwind flux */ if (uw->prim.u[dim] >= 0) { dsu = pars.dx - uw->prim.u[dim] * (*dt); } else { dsu = -pars.dx - uw->prim.u[dim] * (*dt); } if (dw->prim.u[dim] >= 0) { dsd = pars.dx - dw->prim.u[dim] * (*dt); } else { dsd = -pars.dx - dw->prim.u[dim] * (*dt); } c->pflux.rho = uw->prim.u[dim] * (uw->prim.rho + 0.5 * su.rho * dsu) - dw->prim.u[dim] * (dw->prim.rho + 0.5 * sd.rho * dsd); #ifndef ADVECTION_KEEP_VELOCITY_CONSTANT c->pflux.u[0] = uw->prim.u[dim] * (uw->prim.u[0] + 0.5 * su.u[0] * dsu) - dw->prim.u[dim] * (dw->prim.u[0] + 0.5 * sd.u[0] * dsd); c->pflux.u[1] = uw->prim.u[dim] * (uw->prim.u[1] + 0.5 * su.u[1] * dsu) - dw->prim.u[dim] * (dw->prim.u[1] + 0.5 * sd.u[1] * dsd); #endif c->pflux.p = uw->prim.u[dim] * (uw->prim.p + 0.5 * su.p * dsu) - dw->prim.u[dim] * (dw->prim.p + 0.5 * sd.p * dsd); }
<script setup lang="ts"> import { computed, watch, watchEffect } from 'vue'; import { useAuthStore, useCompletionStore } from '@/stores/counter'; import { useQuery, useMutation, useQueryClient } from '@tanstack/vue-query'; import Task from './Task.vue'; import TaskCreator from './Tasks/TaskCreator.vue'; import { getTasks } from '@/utils/getters'; const authStore = useAuthStore(); const queryClient = useQueryClient(); const completionState = useCompletionStore() const goalId = authStore.goalId; const { data, error, isLoading, isError } = useQuery({ queryKey: ['tasks'], queryFn: () => getTasks(goalId), enabled: !!goalId, // Only run if the ID exists }); const allTasksCompleted = computed(() => data?.value?.every(task => task.completed) ?? false); watch( () => data, (newTasks) => { if (newTasks) { completionState.setGoalCompletion(allTasksCompleted.value); } }, { immediate: true, deep: true } ); </script> <template> <div> <div class="mb-6"> <TaskCreator /> </div> <ul class="flex flex-col gap-3"> <Task v-for="(task, index) in data" :key="task._id" :task="task" /> </ul> </div> </template> <style scoped></style>
const { DataTypes, Model } = require('sequelize'); const bcrypt = require('bcrypt'); class User extends Model { } User.init({ id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true, }, username: { type: DataTypes.STRING, allowNull: false, unique: true }, password: { type: DataTypes.STRING, allowNull: false, validate: { len: { args: 6, msg: 'Your password must be at least 6 characters in length.' } } } }, { sequelize: require('../config/db_connection'), modelName: 'user', freezeTableName: true, underscored: true, hooks: { beforeCreate: async (user) => { user.password = await bycrypt.hash(user.password, 10); return user; }, beforeUpdate: async (updatedUser) => { updatedUser.password = await bycrypt.hash(updatedUser.password, 10); return updatedUser; } } }); module.exports = User;
#include "stdio.h" #include "string.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_wifi_types.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_netif.h" #include "esp_log.h" #include "esp_http_server.h" #include "nvs_flash.h" #include "esp_err.h" #include "cJSON.h" #include "driver/gpio.h" #include "stdint.h" #define MIN(x, y) ((x) < (y) ? (x) : (y)) #define WIFI_SSID "SCS-WLAN-MA" #define WIFI_PASS "1Zurx7O0MU0F" #define PORT 80 static const char *TAG = "ESP32_SERVER"; static bool is_event_loop_created = false; void init_gpio(gpio_num_t freePin, gpio_num_t stoppedPin, gpio_num_t underRepairPin) { gpio_config_t io_conf; io_conf.intr_type = GPIO_INTR_DISABLE; io_conf.mode = GPIO_MODE_OUTPUT; io_conf.pin_bit_mask = (1ULL << freePin); io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE; io_conf.pull_up_en = GPIO_PULLUP_DISABLE; gpio_config(&io_conf); io_conf.pin_bit_mask = (1ULL << stoppedPin); gpio_config(&io_conf); io_conf.pin_bit_mask = (1ULL << underRepairPin); gpio_config(&io_conf); } void handle_json_data(const char *json_data, const char *part_no, gpio_num_t freePin, gpio_num_t stoppedPin, gpio_num_t UnderRepair) { // Parse JSON data cJSON *root = cJSON_Parse(json_data); if (root == NULL) { ESP_LOGE(TAG, "Failed to parse JSON data"); return; } cJSON *injection_plastique = cJSON_GetObjectItem(root, "Injection plastique "); if (injection_plastique == NULL) { ESP_LOGE(TAG, "Failed to find 'Injection plastique' in JSON data"); cJSON_Delete(root); return; } cJSON *part = cJSON_GetObjectItem(injection_plastique, part_no); if (part == NULL) { ESP_LOGE(TAG, "Failed to find part number '%s' in JSON data", part_no); cJSON_Delete(root); return; } cJSON *status = cJSON_GetObjectItem(part, "Status"); if (status == NULL || !cJSON_IsString(status)) { ESP_LOGE(TAG, "Failed to find 'Status' for part number '%s' in JSON data", part_no); cJSON_Delete(root); return; } init_gpio(freePin, stoppedPin, UnderRepair); if (strcmp(status->valuestring, "Free") == 0) { gpio_set_level(freePin, 1); gpio_set_level(stoppedPin, 0); gpio_set_level(UnderRepair, 0); ESP_LOGI(TAG, "Status is Free: GPIO %d set high", freePin); } else if (strcmp(status->valuestring, "Stopped") == 0) { gpio_set_level(freePin, 0); gpio_set_level(stoppedPin, 1); gpio_set_level(UnderRepair, 0); ESP_LOGI(TAG, "Status is Blocked: GPIO %d set high", stoppedPin); } else if (strcmp(status->valuestring, "Under repair") == 0) { gpio_set_level(freePin, 0); gpio_set_level(stoppedPin, 0); gpio_set_level(UnderRepair, 1); ESP_LOGI(TAG, "Status is UnderRepair : GPIO %d set high", UnderRepair); } else { gpio_set_level(freePin, 0); gpio_set_level(stoppedPin, 0); gpio_set_level(UnderRepair, 0); ESP_LOGI(TAG, "Status is neither Free nor Blocked: both GPIOs set low"); } cJSON_Delete(root); } esp_err_t post_handler(httpd_req_t *req) { char buf[100]; int ret, remaining = req->content_len; // Allocate memory for body buffer char* body = (char*)malloc(remaining + 1); if (!body) { httpd_resp_send_500(req); return ESP_FAIL; } char* body_ptr = body; while (remaining > 0) { ret = httpd_req_recv(req, buf, MIN(remaining, sizeof(buf))); if (ret <= 0) { if (ret == HTTPD_SOCK_ERR_TIMEOUT) { continue; } free(body); httpd_resp_send_500(req); return ESP_FAIL; } memcpy(body_ptr, buf, ret); body_ptr += ret; remaining -= ret; } *body_ptr = '\0'; ESP_LOGI(TAG, "Received JSON data: %s", body); handle_json_data(body,"01 041 335 20", 12, 14, 16); handle_json_data(body,"123 501 00 00", 18, 20, 22); httpd_resp_send(req, "Data received successfully", HTTPD_RESP_USE_STRLEN); free(body); return ESP_OK; } httpd_handle_t start_webserver(void) { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); httpd_handle_t server = NULL; if (httpd_start(&server, &config) == ESP_OK) { // Set URI handler for POST requests httpd_uri_t post_uri = { .uri = "/receive_data", .method = HTTP_POST, .handler = post_handler, .user_ctx = NULL }; httpd_register_uri_handler(server, &post_uri); ESP_LOGI(TAG, "HTTP server started on port: %d", config.server_port); return server; } ESP_LOGI(TAG, "Failed to start HTTP server"); return NULL; } static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { esp_wifi_connect(); } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { esp_wifi_connect(); ESP_LOGI(TAG, "retry to connect to the AP"); } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data; char ip_str[IP4ADDR_STRLEN_MAX]; // Buffer to hold the IP address string esp_ip4addr_ntoa(&event->ip_info.ip, ip_str, IP4ADDR_STRLEN_MAX); ESP_LOGI(TAG, "Got IP: %s", ip_str); start_webserver(); } } void wifi_init(void) { ESP_LOGI(TAG, "Starting..."); if (!is_event_loop_created) { ESP_ERROR_CHECK(esp_event_loop_create_default()); is_event_loop_created = true; } ESP_ERROR_CHECK(esp_netif_init()); esp_netif_create_default_wifi_sta(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); esp_event_handler_instance_t instance_any_id; esp_event_handler_instance_t instance_got_ip; ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, &instance_any_id)); ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, &instance_got_ip)); wifi_config_t wifi_config = {}; strcpy((char*)wifi_config.sta.ssid, WIFI_SSID); strcpy((char*)wifi_config.sta.password, WIFI_PASS); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config)); ESP_ERROR_CHECK(esp_wifi_start()); } void app_main(void) { ESP_LOGI(TAG, "Starting..."); esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { // NVS partition was truncated and needs to be erased ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } ESP_ERROR_CHECK(ret); esp_netif_init(); // Initialize network interface wifi_init(); }
import React, {Component} from 'react'; import {AttributesFilterProps} from '../../../types'; import s from './Select.module.css'; interface SelectProps extends AttributesFilterProps { onSaveTag: (index: string, tag:string) => void, } export class Select extends Component<SelectProps> { onHandleClick = (e: React.ChangeEvent<HTMLSelectElement>) => { this.props.onSaveTag(this.props.nameSelector, e.target.value); }; render() { const {nameSelector, optionSelector} = this.props; return ( <div className="NameAndOptionsFilterItem" > <div className="NameFilter" > {nameSelector} </div> { (!!optionSelector.length) && <div> <select multiple={true} onChange={this.onHandleClick} className={s.SelectStyle} > { optionSelector.map((option) => <option key={option} > {option} </option>) } </select> </div> } </div> ); } }
#include "lists.h" /** * list_len - returns the number of elements in a linked list_t list * * @h: pointer to the header of the list * * Return: the number of elements in a linked list_t list */ size_t list_len(const list_t *h) { int l = 0; while (h != NULL) { h = h->next; l++; } return (l); }
package dev.mateux.application import dev.mateux.adapters.UserEntity import dev.mateux.application.util.JwtUtil import dev.mateux.ports.BCryptUtil import dev.mateux.ports.UserRepository import jakarta.enterprise.context.ApplicationScoped import jakarta.inject.Inject import jakarta.transaction.Transactional import jakarta.ws.rs.WebApplicationException import org.eclipse.microprofile.config.inject.ConfigProperty @ApplicationScoped class AuthService( @Inject private var userRepository: UserRepository, @Inject private var jwtUtil: JwtUtil, @ConfigProperty(name = "bcrypt.iteration-count", defaultValue = "14") private var iterationCount: String, @Inject private var bcryptUtilImpl: BCryptUtil, ) { private val strongPasswordRegex: Regex = Regex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\da-zA-Z]).{8,}\$") fun authenticate(username: String, password: String): String { val user = userRepository.findByUsername(username) ?: throw WebApplicationException("User not found", 404) val passwordHash = user.password ?: throw WebApplicationException("User has no password", 500) val salt = user.salt ?: throw WebApplicationException("User has no salt", 500) val publicId = user.publicId ?: throw WebApplicationException("User has no publicId", 500) if (bcryptUtilImpl.validatePassword(password, username, salt, passwordHash)) { return jwtUtil.generateToken(username, publicId) } else { throw WebApplicationException("Invalid password", 401) } } @Transactional(rollbackOn = [Exception::class], value = Transactional.TxType.REQUIRED) fun register(username: String, email: String, password: String): String { if (!isPasswordStrong(password)) throw WebApplicationException("Password must be at least 8 characters long and include a mix of uppercase, lowercase, digit, and special character.", 400) val salt = bcryptUtilImpl.generateSalt(username) val passwordHash = bcryptUtilImpl.generatePasswordHash(password, username, salt, iterationCount.toInt()) ?: throw WebApplicationException("Failed to hash password", 500) val user = UserEntity.withoutId(username, email, passwordHash, salt) try { userRepository.save(user) } catch (e: Exception) { if (e.message?.contains("unique constraint") == true) { throw WebApplicationException("Username or email already exists", 400) } else { throw e } } val publicId = user.publicId ?: throw WebApplicationException("User has no publicId", 500) return jwtUtil.generateToken(username, publicId) } private fun isPasswordStrong(password: String): Boolean { return strongPasswordRegex.matches(password) } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="assets/css/style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/remixicon/3.4.0/remixicon.css" crossorigin=""> <title>my portfolio</title> </head> <body> <header class="header" id="header"> <nav class="nav container"> <a href="#" class="nav__logo"> <span class="nav__logo-circle">A</span> <span class="nav__logo-name">Abas Muzi</span> </a> <div class="nav__menu" id="nav-menu"> <span class="nav__title">Menu</span> <h3 class="nav__name">Muzi</h3> <ul class="nav__list"> <li class="nav__item"><a href="#home" class="nav__link">Home</a></li> <li class="nav__item"><a href="#about" class="nav__link">About Me</a></li> <li class="nav__item"><a href="#projects" class="nav__link">Projects</a></li> <li class="nav__item"><a href="#contact" class="nav__link nav__link-button">Contact Me</a></li> </ul> <!--- == CLOSE BUTTON === --> <div class="nav__close" id="nav-close"> <i class="ri-close-line"></i> </div> </div> <div class="nav__buttons"> <!--- THEME BUTTONS --> <i class="ri-moon-line change-theme" id="theme-button"></i> <!--- TOGGLE SWITCH --> <div class="nav__toggle" id="nav-toggle"> <i class="ri-menu-4-line"></i> </div> </div> </nav> </header> <main class="main"> <section class="home section" id="home"> <div class="home__container container grid"> <h1 class="home__name">Abas Muzi</h1> <div class="home__perfil"> <div class="home__image"> <img src="assets/img/perfilEdit.png" alt="image" class="home__img"> <div class="home__shadow"></div> <img src="assets/img/curved-arrow.svg" alt="" class="home__arrow"> <img src="assets/img/random-lines.svg" alt="" class="home__line"> <div class="geometric-box"></div> </div> <div class="home__social"> <a href="#" target="_blank" class="home__social-link"> <i class="ri-instagram-line"></i> </a> <a href="https://linkedin.com/in/abas-mngomezulu-303bb2270" target="_blank" class="home__social-link"> <i class="ri-linkedin-box-line"></i> </a> <a href="https://github.com/AbasPortfolio" target="_blank" class="home__social-link"> <i class="ri-github-line"></i> </a> </div> </div> <div class="home__info"> <p class="home__description"> <b>Web Developer</b>, I primarly design and program websites, considering the efficiency of the user interface. </p> <a href="#about" class="home__scroll"> <div class="home__scroll-box"> <i class="ri-arrow-down-s-line"></i> </div> <span class="home__scroll-text">Scroll Down</span> </a> </div> </div> </section> <section class="about section" id="about"> <div class="about__container container grid"> <h2 class="section__title-1"> <span>About Me</span> </h2> <div class="about__perfil"> <div class="about__image"> <img src="assets/img/profile_pic.png" alt="about image" class="about__img"> <div class="about__shadow"></div> <div class="geometric-box"></div> <img src="assets/img/random-lines.svg" alt="" class="about__line"> <div class="about__box"></div> </div> </div> <div class="about__info"> <p class="about__description"> Passionate about creating <b>Web Pages</b> with <b>UI/UX User Interface</b> I have years of experience and I strive to deliver the best work for my clients. </p> <ul class="about__list"> <li class="about__item"> <b>My Skills Are</b> HTML, CSS, Javascript, React, Git & Github, Bootstrap, Flutter & Figma. </li> </ul> <div class="about__buttons"> <a href="#contact" class="button"> <i class="ri-send-plane-line"></i> Contact Me </a> <a href="https://www.linkedin.com" class="button__ghost" target="_blank"> <i class="ri-linkedin-box-line"></i> </a> </div> </div> </div> </section> <section class="services section"> <h2 class="section__title-2"> <span>Services</span> </h2> <div class="services__container container grid"> <article class="services__card"> <div class="services__border"></div> <div class="services__content"> <div class="services__icon"> <div class="services__box"> </div> <i class="ri-layout-4-line"></i> </div> <h2 class="services__title">Web Design</h2> <p class="services__description">Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasent to use for the user. </p> </div> </article> <article class="services__card"> <div class="services__border"></div> <div class="services__content"> <div class="services__icon"> <div class="services__box"></div> <i class="ri-code-box-line"></i> </div> <h2 class="services__title">Development</h2> <p class="services__description">Custom web development tailored to your specificatons, designed to provide flawless user experience. </p> </div> </article> <article class="services__card"> <div class="services__border"></div> <div class="services__content"> <div class="services__icon"> <div class="services__box"></div> <i class="ri-smartphone-line"></i> </div> <h2 class="services__title">Mobile App</h2> <p class="services__description">Design and transform website projects into mobile apps to provide a seamless user experience. </p> </div> </article> </div> </section> <section class="projects section" id="projects"> <h2 class="section__title-1"> <span>Projects</span> </h2> <div class="projects__container container grid"> <article class="projects__card"> <div class="projects__image"> <img src="assets/img/tod-640.png" alt="image" class="projects__img"> <a href="https://abasportfolio.github.io/Todo-list/" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">App</h3> <h2 class="projects__title">A To-Do App</h2> <p class="projects__description"> Never lose track of your tasks to do for the day. You can carry them with you and access them from anywhere, with your phone or tablet. </p> </div> <div class="projects__buttons"> <a href="https://github.com//AbasPortfolio/Todo-list" target="_blank" class="projects__link"> <i class="ri-github-line"></i> View </a> <a href="https://abasportfolio.github.io/Todo-list/" target="_blank" class="projects__link"> <i class="ri-dribbble-line"></i> View </a> </div> </article> <article class="projects__card"> <div class="projects__image"> <img src="assets/img/project-640.png" alt="image" class="projects__img"> <a href="https://abasportfolio.github.io/company-website/" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">Website</h3> <h2 class="projects__title">Company Website</h2> <p class="projects__description"> A company website that showcases the company's goals and values. Detailing exactly what the mission and objective is for their clients and employees. </p> </div> <div class="projects__buttons"> <a href="https://github.com/AbasPortfolio/company-website" target="_blank" class="projects__link"> <i class="ri-github-line"></i> View </a> <a href="https://abasportfolio.github.io/company-website/" target="_blank" class="projects__link"> <i class="ri-dribbble-line"></i> View </a> </div> </article> <article class="projects__card"> <div class="projects__image"> <img src="assets/img/pendent-640.png" alt="image" class="projects__img"> <a href="https://abasportfolio.github.io/company-website/" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">Landing Page</h3> <h2 class="projects__title">Pandent Landing Page</h2> <p class="projects__description"> Landing page that highlights a product for your clients. This lets your clients become aware of your latest sales and offers to your business. </p> </div> <div class="projects__buttons"> <a href="https://github.com/AbasPortfolio/company-website" target="_blank" class="projects__link"> <i class="ri-github-line"></i> View </a> <a href="https://abasportfolio.github.io/company-website/" target="_blank" class="projects__link"> <i class="ri-dribbble-line"></i> View </a> </div> </article> <article class="projects__card"> <div class="projects__image"> <img src="assets/img/rastuarant.png" alt="image" class="projects__img"> <a href="https://abasportfolio.github.io/mzansifood/" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">Website</h3> <h2 class="projects__title">Food and Restuarant Website</h2> <p class="projects__description"> Having a website for your restuarant is a great way to keep your regular customers updated with your menu, specials and/or events. </p> </div> <div class="projects__buttons"> <a href="https://github.com/AbasPortfolio/mzansifood" target="_blank" class="projects__link"> <i class="ri-github-line"></i> View </a> <a href="https://abasportfolio.github.io/mzansifood/" target="_blank" class="projects__link"> <i class="ri-dribbble-line"></i> View </a> </div> </article> <article class="projects__card"> <div class="projects__image"> <img src="assets/img/search-640.png" alt="image" class="projects__img"> <a href="https://abasportfolio.github.io/searchapp/" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">App</h3> <h2 class="projects__title">Search App</h2> <p class="projects__description"> A search app to keep yourself informed with all the latest news all over the world. Research your favourite topics, using this application powered by the wikipedia api. </p> </div> <div class="projects__buttons"> <a href="https://github.com/AbasPortfolio/searchapp" target="_blank" class="projects__link"> <i class="ri-github-line"></i> View </a> <a href="https://abasportfolio.github.io/searchapp/" target="_blank" class="projects__link"> <i class="ri-dribbble-line"></i> View </a> </div> </article> </div> </section> <section class="contact section" id="contact"> <div class="contact__container grid"> <div class="contact__data"> <h2 class="section__title-2"> <span>Contact Me.</span> </h2> <p class="contact__description-1"> I will read all emails. Send me any message you want and i'll get back to you. </p> <p class="contact__description-2"> I need your <b>Name</b> and <b>Email Address</b>, but you wont receive anything other your reply. </p> <div class="geometric-box"></div> </div> <div class="contact__mail"> <h2 class="contact__title"> Send Me A Message </h2> <form action="" class="contact__form" id="contact-form"> <div class="contact__group"> <div class="contact__box"> <input type="text" class="contact__input" id="name" name="user_name" required placeholder="First Name"> <label for="name" class="contact__label">First Name</label> </div> <div class="contact__box"> <input type="email" class="contact__input" id="name" name="user_email" required placeholder="Email Address"> <label for="email" class="contact__label">Email Address</label> </div> <div class="contact__box"> <input type="text" class="contact__input" id="name" name="user_subject" required placeholder="User Subject"> <label for="subject" class="contact__label">Subject</label> </div> <div class="contact__box contact__area"> <textarea name="user_message" id="message" class="contact__input" required placeholder="Message"></textarea> <label for="message" class="contact__label">Message</label> </div> <p class="contact__message" id="contact-message"></p> </div> <button type="submit" class="contact__button button"> <i class="ri-send-plane-line"></i> Send Message </button> </form> </div> <div class="contact__social"> <img src="assets/img/curved-arrow.svg" alt="" class="contact__social-arrow"> <div class="contact__social-data"> <div> <p class="contact__social-description-1"> Does not send emails </p> <p class="contact__social-description-2"> Write me on my social networks </p> </div> <div class="contact__social-links"> <a href="https://facebook.com" target="_blank" class="contact__social-link"> <i class="ri-facebook-circle-line"></i> </a> <a href="https://instagram/" target="_blank" class="contact__social-link"> <i class="ri-instagram-line"></i> </a> <a href="https://www.linkedin.com/in/abas-mngomezulu-303bb2270" target="_blank" class="contact__social-link"> <i class="ri-linkedin-box-line"></i> </a> </div> </div> </div> </div> </section> </main> <footer class="footer"> <div class="footer__container container grid"> <ul class="footer__links"> <li> <a href="#about" class="footer__link">About</a> </li> <li> <a href="#services" class="footer__link">Services</a> </li> <li> <a href="#projects" class="footer__link">Projects</a> </li> </ul> <span class="footer__copy">&#169; All right Reserved By <a href="#">Abas Muzi</a></span> </div> </footer> <a href="#" class="scrollup" id="scroll-up"> <i class="ri-arrow-up-s-line"></i> </a> <script src="assets/js/scrollreveal.min.js"></script> <!----- EMAIL JS --> <script src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js"></script> <script src="assets/js/main.js"></script> </body> </html>
// Write a menu driven program to implement circular queue operations such as Enqueue, Dequeue, Peek, Display of elements, IsEmpty, IsFull using static array. #include <stdio.h> #include <stdlib.h> int queue[100], size, front = -1, rear = -1; void IsEmpty() { if (front == -1 && rear == -1) printf("Queue is empty \n"); else printf("Queue is not empty \n"); } void IsFull() { if (rear == size - 1) printf("Queue is full \n"); else printf("Queue is not full \n"); } void Enqueue(int val) { if ((rear+1)%size == front) printf("Queue is full \n"); else { rear=(rear+1)%size; queue[rear] = val; } } int Dequeue() { int x; if (front == rear) { printf("Queue Underflow \n"); } else { front=(front+1)%size; x=queue[front]; } return x; } void Peek() { if (front == rear+1) { printf("Queue Underflow \n"); return; } else { printf("The peeked element is %d \n", queue[front]); } } void Display() { int i=front+1; do { printf("%d", queue[i]); i=(i+1)%size; } while (i!=(rear+1)%size); printf(" \n"); } int main() { printf("Enter the capacity"); scanf("%d", &size); int ch, val; printf("0) Check if queue is empty \n"); printf("1) Check if queue is full \n"); printf("2) Enqueue \n"); printf("3) Dequeue \n"); printf("4) Peek \n"); printf("5) Display \n"); printf("6) Exit \n"); do { printf("Enter choice : "); scanf("%d", &ch); switch (ch) { case 0: { IsEmpty(); break; } case 1: { IsFull(); break; } case 2: { printf("Enter the value to be enqueued : "); scanf("%d", &val); Enqueue(val); break; } case 3: { printf("%d ",Dequeue()); break; } case 4: { Peek(); break; } case 5: { Display(); break; } case 6: { printf("Exit \n"); break; } default: { printf("Invalid choice \n"); } } } while (ch != 6); return 0; }
import Head from "next/head"; import { Table, Button, Modal, ConfigProvider } from "antd"; import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import store from "store"; export default function DashBoard() { const router = useRouter(); useEffect(() => { const initialData = store.get("dashboardDb") ?? []; if (store.get("searchScan")) { initialData.push(store.get("searchScan")); setActiveDetails(store.get("searchScan")); store.set("searchScan", undefined); } setDataSource(initialData) if ((Object.keys(activeDetails).length === 0)) { setActiveDetails(initialData[0]) } store.set("dashboardDb", initialData) setFirstRender(false); }, []) // console.log(store.get("searchScan")) // const [activeDetails, setActiveDetails] = useState({ // url: "https://www.virustotal.com", // ip: "192.168.1.1", // hostingProvider: "Google LLC", // originalDeposition: "Phishing", // detectionDate: "2022-04-23", // modalPredection: 40, // probability: 80, // communityScore: 22, // }); const [activeDetails, setActiveDetails] = useState({}); const [showModal, setShowModal] = useState(false) const [firstRender, setFirstRender] = useState(true); // store.set("dashboardDb",[ // { // url: "https://www.a.com", // ip: "192.168.1.1", // hostingProvider: "Google LLC", // originalDeposition: "Phishing", // detectionDate: "2022-04-23", // modalPredection: 10, // probability: 20, // communityScore: 56 // }, // { // url: "https://www.b.com", // ip: "192.168.1.1", // hostingProvider: "Google LLC", // originalDeposition: "Legitimate", // detectionDate: "2022-04-23", // modalPredection: 30, // probability: 40, // communityScore: 69 // }, // { // url: "https://www.c.com", // ip: "192.168.1.1", // hostingProvider: "Google LLC", // originalDeposition: "Phishing", // detectionDate: "2022-04-23", // modalPredection: 50, // probability: 60, // communityScore: 29, // }, // { // url: "https://www.d.com", // ip: "192.168.1.1", // hostingProvider: "Google LLC", // originalDeposition: "Legitimate", // detectionDate: "2022-04-23", // modalPredection: 70, // probability: 80, // communityScore: 7 // }, // { // url: "https://www.e.com", // ip: "192.168.1.1", // hostingProvider: "Google LLC", // originalDeposition: "Phishing", // detectionDate: "2022-04-23", // modalPredection: 90, // probability: 100, // communityScore: 100 // }, // ]) const [dataSource, setDataSource] = useState([]) return <> <Head> <title>DashBoard | Sarthak Rana</title> </Head> {!firstRender && <main className="bg-slate-100 min-h-screen pt-12 px-24"> <Modal open={showModal} footer={null} width="750" centered onCancel={() => { setShowModal(false) }}> <main className="m-6 grid grid-cols-2 gap-4"> <div className="w-96 border flex flex-col gap-6 p-4"> <div className=""> <div className="text-black/60 font-bold">Source URL:</div> <a href={activeDetails.source_url} className="">{activeDetails.source_url}</a> </div> <div className="grid grid-cols-2"> <div className=""> <div className="text-black/60 font-bold">IP Address:</div> <a href={activeDetails["ip-address"]} className="">{activeDetails["ip-address"]}</a> </div> <div className=""> <div className="text-black/60 font-bold">Status:</div> <div className="text-black/60 font-medium">{activeDetails.predication}</div> </div> </div> <div className="grid grid-cols-2"> <div className=""> <div className="text-black/60 font-bold">Location:</div> <div className="text-black/60 font-medium">{activeDetails["location_details"].capital}</div> </div> <div className=""> <div className="text-black/60 font-bold">Domain:</div> <div className="text-black/60 font-medium">{activeDetails.domain}</div> </div> </div> <div className="grid grid-cols-2"> {/* <div className=""> <div className="text-black/60 font-bold">Title:</div> <div className="text-black/60 font-medium">{activeDetails.detectionDate}</div> </div> */} <div className=""> <div className="text-black/60 font-bold">First Submission:</div> <div className="text-black/60 font-medium">{new Date(activeDetails["virus-total-data"].firstSubmission * 1000).toDateString()}</div> </div> </div> <div className="grid grid-cols-2"> <div className=""> <div className="text-black/60 font-bold">Last Submission:</div> <div className="text-black/60 font-medium">{new Date(activeDetails["virus-total-data"].lastSubmission * 1000).toDateString()}</div> </div> {/* <div className=""> <div className="text-black/60 font-bold">Scan Date:</div> <div className="text-black/60 font-medium">{activeDetails.detectionDate}</div> </div> */} </div> </div> <div className="w-96 h-96 border p-4 overflow-hidden"> <h3 className="text-black/60 font-bold">Vendors:</h3> <div className=" overflow-scroll h-full w-full divide-y divide-solid divide-black/10"> {Object.entries(activeDetails["virus-total-data"]["last_analysis_results"]).map((data, index) => { return <div key={index} className="grid grid-cols-2 py-2"> <div className="">{data[0]}</div> <div className="">{data[1].result}</div> </div> })} </div> </div> <div className="w-96 h-96 border"> <img className="h-full w-full object-fit" src={activeDetails["location_details"]["screenshot_url"]} alt="" /> </div> <div className="w-96 h-96 border"> <iframe className="w-full h-full" frameborder="0" marginheight="0" marginwidth="0" src={`https://www.google.com/maps/embed/v1/search?key=AIzaSyCcvA7rnY_w30l6wnb0Ng7T4o-jJMlbKJ0&q=${activeDetails["location_details"]["latitude"]},${activeDetails["location_details"]["longitude"]}`} > </iframe> </div> </main> </Modal> <h1 className="text-7xl text-black/70 font-bold">Dashboard</h1> <div className="flex flex-row-reverse w-full mb-4"> <ConfigProvider theme={{ token: { colorPrimary: "#0369a1" } }}> <Button className="" type="primary" onClick={() => { router.push("/") }}><span className='px-8 font-bold'>Scan New URL</span></Button> </ConfigProvider> </div> <div className="p-8 bg-gradient-to-t from-sky-500 to-sky-700 my-6 rounded-lg flex text-white relative items-center divide-x-2 divide-slate-300/60"> <div className="top-2 mr-8 left-4 bg-white p-4 text-black/60 text-2xl shadow-slate-500/50 font-bold rounded-xl shadow-md"> {activeDetails["virus-total-data"]['last_analysis_stats'].malicious} </div> <div className="flex gap-2 items-start flex-col w-full px-12"> <div className="text-2xl font-semibold text-white/90">URL:</div> <a href={activeDetails.source_url} className="text-lg text-gray-100">{activeDetails.source_url}</a> </div> <div className="flex gap-2 items-start flex-col w-full px-12"> <div className="text-xl font-medium text-white/90">Model Predication:</div> <div className="font-medium text-lg text-white/90">{activeDetails.predication}</div> </div> {/* <div className="flex gap-2 items-start flex-col w-full px-12"> <div className="text-xl font-medium text-white/90">Probability of the website being {activeDetails.originalDeposition}:</div> <div className={`font-medium text-lg ${activeDetails.originalDeposition === "Legitimate" ? "text-green-500" : "text-red-400"}`}>{activeDetails.probability}</div> </div> */} </div> <div className="w-full"> <Table columns={[{ dataIndex: "source_url" , title: "Source Url", render: (data: string) => { return <a href={data} className="text-blue-400">{data}</a> } }, { dataIndex: "ip-address", title: "IP Address" } , { dataIndex: "domain", title: "Domain" }, { dataIndex: "predication", title: "Original Deposition", render: (data: string) => { return <article className={`${data === "Legitimate" ? "text-green-500" : "text-red-400"}`}>{data}</article> } }, { dataIndex: "virus-total-data", title: "Detection Date", render: (data: any) => { return <article>{new Date(data["detectionDate"]).toDateString()}</article> } }, { dataIndex: "action", title: "Action", render: function (_, data) { // console.log(data); return <div className="flex gap-4"> <Button onClick={() => { setActiveDetails(data) }}>Info</Button> <Button onClick={() => { setActiveDetails(data);setShowModal(true) }}>Details</Button> </div> } } ]} dataSource={dataSource} tableLayout="fixed" ></Table> </div> </main> } </> }
/** * SPDX-FileCopyrightText: (c) 2023 Liferay, Inc. https://liferay.com * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06 */ package com.liferay.customer.object.model; import com.liferay.petra.string.StringBundler; import org.json.JSONObject; /** * @author Amos Fong */ public class TicketAttachment { public static final int STATUS_APPROVED = 0; public static final int STATUS_DRAFT = 2; public static final String STORAGE_PROVIDER_GCS = "gcs"; public TicketAttachment(JSONObject jsonObject) { _accountKey = jsonObject.getString("accountKey"); _fileName = jsonObject.getString("fileName"); _fileSize = jsonObject.getString("fileSize"); _gcsBucketName = jsonObject.getString("gcsBucketName"); _md5Checksum = jsonObject.getString("md5Checksum"); JSONObject statusJSONObject = jsonObject.getJSONObject("status"); _status = statusJSONObject.getInt("code"); _storageProvider = jsonObject.getString("storageProvider"); _ticketAttachmentId = jsonObject.getLong("id"); _type = jsonObject.optString("type"); _zendeskTicketId = jsonObject.getLong("zendeskTicketId"); } public String getAccountKey() { return _accountKey; } public String getFileName() { return _fileName; } public String getFileSize() { return _fileSize; } public String getGCSBucketName() { return _gcsBucketName; } public String getGCSObjectName() { StringBundler sb = new StringBundler(6); sb.append("tickets/"); sb.append(_zendeskTicketId); sb.append("/"); sb.append(_ticketAttachmentId); sb.append("/"); sb.append(_fileName); return sb.toString(); } public String getMD5Checksum() { return _md5Checksum; } public int getStatus() { return _status; } public String getStorageProvider() { return _storageProvider; } public long getTicketAttachmentId() { return _ticketAttachmentId; } public String getType() { return _type; } public long getZendeskTicketId() { return _zendeskTicketId; } public boolean isApproved() { if (_status == STATUS_APPROVED) { return true; } return false; } private final String _accountKey; private final String _fileName; private final String _fileSize; private final String _gcsBucketName; private final String _md5Checksum; private final int _status; private final String _storageProvider; private final long _ticketAttachmentId; private final String _type; private final long _zendeskTicketId; }
<div *ngIf="loading"> <app-loading-screen></app-loading-screen> </div> <section class="login"> <div class="container"> <div class="row"> <!----> <div class="col-md-7 col-sm-6"> <div class="loginDesc"> <div class="loginDescInner"> <label>Welcome to</label> <h1>BEC <span>Engineering</span></h1> <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur.</p> </div> </div> </div> <div class="col-md-5 col-sm-6"> <div class="loginForm"> <div class="loginFormInner"> <div class="loginLogo"><img src="assets/images/logo.png" alt="image" title="Logo" /></div> <h2>Login</h2> <div [ngClass]="messageObject.class" *ngIf="messageObject"> {{messageObject.message}} </div> <form [formGroup]="LoginForm"> <div class="row"> <div class="col-sm-12"> <div class="logForm" [ngClass]="{ 'has-error': formErrors.Email }"> <div class="form-group" > <label for="Email" class="control-label"><h3><i class="fa fa-user" aria-hidden="true"></i>Email</h3></label> <input type="text" class="form-control" placeholder="Email" formControlName="Email" (blur)="LogValidationError()"/> <span class="help-block" *ngIf="formErrors.Email"> {{ formErrors.Email }} </span> </div> </div> </div> <div class="col-sm-12"> <div class="logForm" [ngClass]="{ 'has-error': formErrors.Password }"> <h3><i class="fa fa-lock" aria-hidden="true"></i>Password</h3> <input type="password" class="form-control" placeholder="Password" formControlName="Password" (blur)="LogValidationError()"/> <span class="help-block" *ngIf="formErrors.Password"> {{ formErrors.Password }} </span> </div> </div> <div class="col-sm-6 full" > <div class="remember text-left"> <input type="checkbox" [(ngModel)]="rememberMe" [ngModelOptions]="{standalone: true}" />Remember Me </div> </div> <div class="col-sm-6 full"> <div class="forgotpassword text-right"> <a [routerLink]="['/forgotPassword']">Forgot Password</a> </div> </div> <div class="col-sm-12"> <div class="loginBtn text-left full-width"><button type="submit" (click)="onSubmit()" class="btn btn-blue logBtn">Login</button></div> </div> </div> </form> </div> </div> </div> <!----> </div> </div> </section>
namespace Exercises.Arrays; internal class Array2D { // You could check the full problem at www.hackerrank.com/challenges/2d-array/problem private static void PrintInput(List<List<int>> list) { foreach (var array in list) { foreach (var item in array) Console.Write($"{item} "); Console.Write("\n"); } } private static int HourglassSum(List<List<int>> list2D) { int? greatestSum = null; for (int i = 0; i <= 3; i++) // coluna { for (int j = 0; j <= 3; j++) // linha { int currentSum = 0; int sumFirstLine = list2D[i][j] + list2D[i][j + 1] + list2D[i][j + 2]; int sumSecondLine = list2D[i + 1][j + 1]; int sumThirdLine = list2D[i + 2][j] + list2D[i + 2][j + 1] + list2D[i + 2][j + 2]; currentSum += sumFirstLine + sumSecondLine + sumThirdLine; if (greatestSum is null) greatestSum = currentSum; if (currentSum > greatestSum) greatestSum = currentSum; } } return (int)greatestSum; } public static void Execute() { Console.WriteLine("\n\n-> Array 2D Exercise"); List<List<int>> list2D = [ [1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 2, 4, 4, 0], [0, 0, 0, 2, 0, 0], [0, 0, 1, 2, 4, 0], ]; /* negative 2D list to for tests: List<List<int>> negativeList2D = new() { [ -1, -1, 0, -9, -2, -2 ], [ -2, -1, -6, -8, -2, -5 ], [ -1, -1, -1, -2, -3, -4 ], [ -1, -9, -2, -4, -4, -5 ], [ -7, -3, -3, -2, -9, -9 ], [ -1, -3, -1, -2, -4, -5 ], }; */ PrintInput(list2D); var greatestHourglassSum = HourglassSum(list2D); Console.WriteLine($"Greatest hourglass sum: {greatestHourglassSum}"); } }
<template> <div :class="['scroller', `scroller-${name}`]"> <div :class="['swiper', `swiper-${name}`]"> <div :class="['swiper-wrapper', {'swiper-wrapper_not-init': !swiper}]"> <slot /> </div> <div class="swiper-pagination" /> </div> <div class="swiper__button swiper__button_prev"> <IconArrow class="swiper__icon-arrow" left :white="arrowColorWhite" /> </div> <div class="swiper__button swiper__button_next"> <IconArrow class="swiper__icon-arrow" right :white="arrowColorWhite" /> </div> </div> </template> <script setup> import { Lazy, Navigation, Pagination, Swiper } from 'swiper' import 'swiper/scss' const props = defineProps({ name: { type: String, required: true, default: '', }, options: { type: Object, default: () => {}, }, arrowColorWhite: { type: Boolean, default: false, }, }) const swiper = ref(null) const swiperOptions = { slidesPerView: 1, spaceBetween: 0, watchOverflow: true, pagination: { el: '.swiper-pagination', clickable: true, renderBullet (_index, className) { return '<span class="' + className + '"></span>' }, }, navigation: { nextEl: `.scroller-${props.name} .swiper__button_next`, prevEl: `.scroller-${props.name} .swiper__button_prev`, }, preloadImages: false, lazy: { checkInView: true, enabled: true, loadOnTransitionStart: true, }, watchSlidesProgress: true, } const options = { ...swiperOptions, ...props.options } Swiper.use([Navigation, Pagination, Lazy]) onMounted(() => { swiper.value = new Swiper(`.swiper-${props.name}`, options) }) </script> <style scoped lang="scss"> .scroller { position: relative; &:hover { .swiper { &__button { &.swiper-button-disabled { display: none; } &:not(.swiper-button-disabled) { @include mq($bp-medium) { opacity: 1; } } } } } } .swiper { width: 100%; &-wrapper { display: flex; &_not-init { @include mq($bp-small-medium) { display: grid; grid-template-rows: 1fr; grid-template-columns: repeat(2, 1fr); grid-auto-rows: 0; } @include mq($bp-small) { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); column-gap: 28px; } @include mq($bp-medium) { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); column-gap: 40px; } @include mq($bp-big) { grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); } } } &-slide { width: fit-content; @include mq($bp-medium) { height: initial; &:not(.swiper-slide-active) .swiper__card::after { position: absolute; top: 0; left: 0; width: 100%; height: 100%; content: ''; background: rgb(255 255 255 / 50%); } } } &-pagination { position: relative; bottom: 0 !important; display: flex; flex-direction: row; grid-gap: 8px; width: 200px !important; height: 5px; margin: 20px auto 0; @include mq($bp-medium) { display: none; } & :deep(.swiper-pagination-bullet) { display: flex; flex-direction: row; width: 100%; height: 100%; margin: 0 !important; background: var(--grayMediumLight); border-radius: 1.7px; opacity: 1; } & :deep(.swiper-pagination-bullet-active) { background: var(--blackLight); } } &__button { display: none; opacity: 0; @include mq($bp-medium) { position: absolute; top: calc(50% - 20px); z-index: 1; display: grid; place-items: center; width: 40px; height: 40px; cursor: pointer; background: white; border: 2px solid var(--grayLight); border-radius: 100px; box-shadow: 0 20px 24px rgb(153 155 168 / 15%); transition: opacity 0.2s ease-out; &_prev { left: -20px; } &_next { right: -20px; } @media (hover: hover) and (pointer: fine) { &:not(.swiper-button-disabled) { &:hover { background: var(--grayLight); } } } } &.swiper-button-lock { display: none; } } &__icon-arrow { width: 24px; height: 24px; } & :deep(.swiper-pagination-lock > .swiper-pagination-bullet-active) { opacity: 0 !important; } } </style>
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #pragma once // MOOSE #include "ResidualObject.h" #include "GeometricSearchInterface.h" #include "BlockRestrictable.h" #include "BoundaryRestrictable.h" #include "CoupleableMooseVariableDependencyIntermediateInterface.h" #include "MooseVariableInterface.h" // Forward declerations class NodalKernel; template <> InputParameters validParams<NodalKernel>(); /** * Base class for creating new types of boundary conditions * */ class NodalKernel : public ResidualObject, public BlockRestrictable, public BoundaryRestrictable, public GeometricSearchInterface, public CoupleableMooseVariableDependencyIntermediateInterface, public MooseVariableInterface<Real> { public: /** * Class constructor. * @param parameters The InputParameters for the object */ static InputParameters validParams(); NodalKernel(const InputParameters & parameters); /** * Gets the variable this is active on * @return the variable */ const MooseVariable & variable() const override { return _var; } /** * Compute the residual at the current node. * * Note: This is NOT what a user would normally want to override. * Usually a user would override computeQpResidual() */ virtual void computeResidual() override; /** * Compute the Jacobian at one node. * * Note: This is NOT what a user would normally want to override. * Usually a user would override computeQpJacobian() */ virtual void computeJacobian() override; /** * Compute the off-diagonal Jacobian at one node. * * Note: This is NOT what a user would normally want to override. * Usually a user would override computeQpOffDiagJacobian() */ virtual void computeOffDiagJacobian(unsigned int jvar) override; protected: /** * The user can override this function to compute the residual at a node. */ virtual Real computeQpResidual() = 0; /** * The user can override this function to compute the "on-diagonal" * Jacobian contribution. If not overriden, * returns 1. */ virtual Real computeQpJacobian(); /** * This is the virtual that derived classes should override for * computing an off-diagonal jacobian component. */ virtual Real computeQpOffDiagJacobian(unsigned int jvar); /// Reference to FEProblemBase FEProblemBase & _fe_problem; /// variable this works on MooseVariable & _var; /// current node being processed const Node * const & _current_node; /// Quadrature point index unsigned int _qp; /// Value of the unknown variable this is acting on const VariableValue & _u; /// The aux variables to save the residual contributions to bool _has_save_in; std::vector<MooseVariableFEBase *> _save_in; std::vector<AuxVariableName> _save_in_strings; /// The aux variables to save the diagonal Jacobian contributions to bool _has_diag_save_in; std::vector<MooseVariableFEBase *> _diag_save_in; std::vector<AuxVariableName> _diag_save_in_strings; };
class Book attr_accessor :title, :author attr_reader :rentals def initialize(title, author) @title = title @author = author @rentals = [] end def add_rental(person, date) Rental.new(date, self, person) end def to_hash(*) { title: @title, author: @author, rentals: @rentals.map { |rental| rental.to_hash(exclude_book: true) } } end end
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fyp_flutter/models/user.dart'; import 'package:fyp_flutter/providers/auth_provider.dart'; import 'package:fyp_flutter/views/layouts/authenticated_user_layout.dart'; import 'package:provider/provider.dart'; import 'package:readmore/readmore.dart'; import '../../../common/color_extension.dart'; class ExercisesStepDetails extends StatefulWidget { final Map eObj; const ExercisesStepDetails({super.key, required this.eObj}); @override State<ExercisesStepDetails> createState() => _ExercisesStepDetailsState(); } class _ExercisesStepDetailsState extends State<ExercisesStepDetails> { double burned = 0.0; late AuthProvider authProvider; @override void initState() { super.initState(); authProvider = Provider.of<AuthProvider>(context, listen: false); User user = authProvider.getAuthenticatedUser(); burned = (widget.eObj['metabolic_equivalent'] * user.profile.weight) / 60.0; } @override Widget build(BuildContext context) { var media = MediaQuery.of(context).size; return AuthenticatedLayout( child: Scaffold( appBar: AppBar( backgroundColor: TColor.white, centerTitle: true, elevation: 0, leading: InkWell( onTap: () { Navigator.pop(context); }, child: Container( margin: const EdgeInsets.all(8), height: 40, width: 40, alignment: Alignment.center, decoration: BoxDecoration( color: TColor.lightGray, borderRadius: BorderRadius.circular(10)), child: Image.asset( "assets/img/closed_btn.png", width: 15, height: 15, fit: BoxFit.contain, ), ), ), actions: [ InkWell( onTap: () {}, child: Container( margin: const EdgeInsets.all(8), height: 40, width: 40, alignment: Alignment.center, decoration: BoxDecoration( color: TColor.lightGray, borderRadius: BorderRadius.circular(10)), child: Image.asset( "assets/img/more_btn.png", width: 15, height: 15, fit: BoxFit.contain, ), ), ) ], ), backgroundColor: TColor.white, body: SingleChildScrollView( child: Container( padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 25), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Stack( alignment: Alignment.center, children: [ Container( width: media.width, height: media.width * 0.43, decoration: BoxDecoration( gradient: LinearGradient(colors: TColor.primaryG), borderRadius: BorderRadius.circular(20)), child: Image.network( 'http://10.0.2.2:8000/uploads/exercise/${widget.eObj['image']}', width: media.width, height: media.width * 0.43, fit: BoxFit.contain, errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) { // This function is called when the image fails to load // You can return a fallback image here return Image.asset( 'assets/img/non.png', // Path to your placeholder image asset width: 40, height: 40, fit: BoxFit.cover, ); }, ), ), Container( width: media.width, height: media.width * 0.43, decoration: BoxDecoration( color: TColor.black.withOpacity(0.2), borderRadius: BorderRadius.circular(20)), ), ], ), const SizedBox( height: 15, ), Text( widget.eObj["name"].toString(), style: TextStyle( color: TColor.black, fontSize: 16, fontWeight: FontWeight.w700), ), const SizedBox( height: 4, ), Text( "Easy |${burned.toStringAsFixed(2)} per minute", style: TextStyle( color: TColor.gray, fontSize: 12, ), ), const SizedBox( height: 15, ), Text( "Descriptions", style: TextStyle( color: TColor.black, fontSize: 16, fontWeight: FontWeight.w700), ), const SizedBox( height: 4, ), ReadMoreText( widget.eObj['description'].toString(), trimLines: 4, colorClickableText: TColor.black, trimMode: TrimMode.Line, trimCollapsedText: ' Read More ...', trimExpandedText: ' Read Less', style: TextStyle( color: TColor.gray, fontSize: 12, ), moreStyle: const TextStyle( fontSize: 12, fontWeight: FontWeight.w700), ), const SizedBox( height: 15, ), Text( "Custom Repetitions", style: TextStyle( color: TColor.black, fontSize: 16, fontWeight: FontWeight.w700), ), SizedBox( height: 200, child: CupertinoPicker.builder( itemExtent: 40, selectionOverlay: Container( width: double.maxFinite, height: 40, decoration: BoxDecoration( border: Border( top: BorderSide( color: TColor.gray.withOpacity(0.2), width: 1), bottom: BorderSide( color: TColor.gray.withOpacity(0.2), width: 1), ), ), ), onSelectedItemChanged: (index) {}, childCount: 60, itemBuilder: (context, index) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( "assets/img/burn.png", width: 15, height: 15, fit: BoxFit.contain, ), Text( "${((index + 1) * burned).toStringAsFixed(2)} Calories Burn", style: TextStyle(color: TColor.gray, fontSize: 10), ), Text( " ${index + 1} ", style: TextStyle( color: TColor.gray, fontSize: 24, fontWeight: FontWeight.w500), ), Text( " minutes", style: TextStyle(color: TColor.gray, fontSize: 16), ) ], ); }, ), ), ], ), ), ), ), ); } }
# Week 8 - Summary [TOC] ## Divide and conquer * Break up a problem into disjoint subproblems * Combine these subproblem solutions efficiently * **Examples** * **Merge sort** * Split into left and right half and sort each half separately * Merge the sorted halves * **Quicksort** * Rearrange into lower and upper partitions, sort each partition separately * Place pivot between sorted lower and upper partitions ## Divide and conquer example ### Counting inversions * Compare your profile with other customers * Identify people who share your likes and dislikes * No inversions – rankings identical * Every pair inverted – maximally dissimilar * Number of inversions ranges from 0 to n(n – 1) / 2 <img src="../assets/w8i1.png" width=50% /> * An inversion is a pair (i, j), i < j, where j appears before i * Recurrence: $T(n) = 2T(n / 2) + n = 𝑂(n log 𝑛)$ **Implementation** ```python def mergeAndCount(A,B): (m,n) = (len(A),len(B)) (C,i,j,k,count) = ([],0,0,0,0) while k < m+n: if i == m: C.append(B[j]) j += 1 k += 1 elif j == n: C.append(A[i]) i += 1 k += 1 elif A[i] < B[j]: C.append(A[i]) i += 1 k += 1 else: C.append(B[j]) j += 1 k += 1 count += m-i return(C,count) def inversionCount(A): n = len(A) if n <= 1: return(A,0) (L,countL) = inversionCount(A[:n//2]) (R,countR) = inversionCount(A[n//2:]) (B,countB) = mergeAndCount(L,R) return(B,countL + countR + countB) L = [2,4,3,1,5] print(inversionCount(L)[1]) ``` **Output** ```python 4 # 4 is the number of inversions ``` ### Closest pair of points * Several objects on screen * Basic step: find closest pair of objects * $n$ objects — naive algorithm is $n^2$ * For each pair of objects, compute their distance * Report minimum distance across all pairs * There is a clever algorithm that takes time $O(n log n)$ using divide and conquer * Given n points $p1, p2, . . . , pn$ find the closest pair * Assume no two points have same $x$ or $y$ coordinate * Split the points into two halves by vertical line * Recursively compute closest pair in each half * Compare shortest distance in each half to shortest distance across the dividing line * Recurrence: $𝑇 𝑛 = 2𝑇 𝑛 / 2 + 𝑂(𝑛)$ * Overall: $𝑂(𝑛 log 𝑛)$ **Pseudocode** ```python def ClosestPair(Px,Py): if len(Px) <= 3: compute pairwise distances return closest pair and distance Construct (Qx,Qy), (Rx,Ry) (q1,q2,dQ) = ClosestPair(Qx,Qy) (r1,r2,dR) = ClosestPair(Rx,Ry) Construct Sy from Qy,Ry Scan Sy, find (s1,s2,dS) return (q1,q2,dQ), (r1,r2,QR), (s1,s2,dS) #depending on which of dQ, dR, dS is minimum ``` **Implementation** ```python import math # Returns eucledian disatnce between points p and q def distance(p, q): return math.sqrt(math.pow(p[0] - q[0],2) + math.pow(p[1] - q[1],2)) def minDistanceRec(Px, Py): s = len(Px) # Given number of points cannot be less than 2. # If only 2 or 3 points are left return the minimum distance accordingly. if (s == 2): return distance(Px[0],Px[1]) elif (s == 3): return min(distance(Px[0],Px[1]), distance(Px[1],Px[2]), distance(Px[2],Px[0])) # For more than 3 points divide the poitns by point around median of x coordinates m = s//2 Qx = Px[:m] Rx = Px[m:] xR = Rx[0][0] # minimum x value in Rx # Construct Qy and Ry in O(n) rather from Py Qy=[] Ry=[] for p in Py: if(p[0] < xR): Qy.append(p) else: Ry.append(p) # Extract Sy using delta delta = min(minDistanceRec(Qx, Qy), minDistanceRec(Rx, Ry)) Sy = [] for p in Py: if abs(p[0]-xR) <= delta: Sy.append(p) #print(xR,delta,Sy) sizeS = len(Sy) if sizeS > 1: minS = distance(Sy[0], Sy[1]) for i in range(1, sizeS-1): for j in range(i, min(i+15, sizeS)-1): minS = min(minS, distance(Sy[i], Sy[j+1])) return min(delta, minS) else: return delta def minDistance(Points): Px = sorted(Points) Py = Points Py.sort(key=lambda x: x[-1]) #print(Px,Py) return round(minDistanceRec(Px, Py), 2) pts = [(2, 15), (40, 5), (20, 1), (21, 14), (1,4), (3, 11)] mul = 0 if (len(pts) > 100): mul = 0 result = minDistance(pts) for i in range(mul): minDistance(pts) print(result) ``` **Output** ```python 4.12 ``` ### Integer multiplication * Traditional method: $𝑂(𝑛 ^2 ) $ * Naïve divide and conquer strategy: $𝑇(𝑛) = 4𝑇(𝑛 / 2) + 𝑛 = 𝑂(𝑛^2 ) $ * Karatsuba’s algorithm: $𝑇(𝑛) = 3𝑇 𝑛 / 2 + 𝑛 ≈ 𝑂 𝑛 ~log~3)$ **Implementation** ```python # here 10 represent base of input numbers x and y def Fast_Multiply(x,y,n): if n == 1: return x * y else: m = n/2 xh = x//10**m xl = x % (10**m) yh = y//10**m yl = y % (10**m) a = xh + xl b = yh + yl p = Fast_Multiply(xh, yh, m) q = Fast_Multiply(xl, yl, m) r = Fast_Multiply(a, b, m) return p*(10**n) + (r - q - p) * (10**(n/2)) + q print(Fast_Multiply(3456,8902,4)) ``` **Output** ``` 30765312.0 ``` ### Quick select and Fast select * Find the $𝑘_{𝑡ℎ}$ smallest value in a sequence of length $𝑘$ * Sort in descending order and look at position $𝑘~ –~ 𝑂 (𝑛 log 𝑛) $ * For any fixed $𝑘$, find maximum for $𝑘$ times – $𝑂(𝑘𝑛) $ * $𝑘 = n / 2$ (median) – $𝑂 (𝑛^2) $ * Median of medians –$ 𝑂(𝑛) $ * Selection becomes $𝑂(𝑛)$ in Fast select algorithm * Quicksort becomes $𝑂 (𝑛 log n)$ using MoM **Implementation** ```python def quickselect(L,l,r,k): # k-th smallest in L[l:r] if (k < 1) or (k > r-l): return(None) (pivot,lower,upper) = (L[l],l+1,l+1) for i in range(l+1,r): if L[i] > pivot: # Extend upper segment upper = upper + 1 else: # Exchange L[i] with start of upper segment (L[i], L[lower]) = (L[lower], L[i]) (lower,upper) = (lower+1,upper+1) (L[l],L[lower-1]) = (L[lower-1],L[l]) # Move pivot lower = lower - 1 # Recursive calls lowerlen = lower - l if k <= lowerlen: return(quickselect(L,l,lower,k)) elif k == (lowerlen + 1): return(L[lower]) else: return(quickselect(L,lower+1,r,k-(lowerlen+1))) print(quickselect([5,3,7,2,1],0,5,2)) ``` **Output** ``` 2 ``` ### Median of Medians(MoM) * Divide L into blocks of 5 * Find the median of each block (brute force) * Let M be the list of block medians * Recursively apply the process to M * We can visualize the blocks as follows <img src="../assets/w8i2.png" width=100% /> * Each block of 5 is arranged in ascending order, top to bottom * Block medians are the middle row * The median of block medians lies between 3len(L)/10 and 7len(L)/10 <img src="../assets/w8i3.png" width=100% /> **Implementation** ```python def MoM(L): # Median of medians if len(L) <= 5: L.sort() return(L[len(L)//2]) # Construct list of block medians M = [] for i in range(0,len(L),5): X = L[i:i+5] X.sort() M.append(X[len(X)//2]) return(MoM(M)) print(MoM([4,3,5,6,2,1,8,9,7,10,13,15,18,17,11])) ``` **Output** ``` 8 ``` ### Fast select using MOM **Implementation** ```python def MoM(L): # Median of medians if len(L) <= 5: L.sort() return(L[len(L)//2]) # Construct list of block medians M = [] for i in range(0,len(L),5): X = L[i:i+5] X.sort() M.append(X[len(X)//2]) return(MoM(M)) def fastselect(L,l,r,k): # k-th smallest in L[l:r] if (k < 1) or (k > r-l): return(None) # Find MoM pivot and move to L[l] pivot = MoM(L[l:r]) pivotpos = min([i for i in range(l,r) if L[i] == pivot]) (L[l],L[pivotpos]) = (L[pivotpos],L[l]) (pivot,lower,upper) = (L[l],l+1,l+1) for i in range(l+1,r): if L[i] > pivot: # Extend upper segment upper = upper + 1 else: # Exchange L[i] with start of upper segment (L[i], L[lower]) = (L[lower], L[i]) (lower,upper) = (lower+1,upper+1) (L[l],L[lower-1]) = (L[lower-1],L[l]) # Move pivot lower = lower - 1 # Recursive calls lowerlen = lower - l if k <= lowerlen: return(fastselect(L,l,lower,k)) elif k == (lowerlen + 1): return(L[lower]) else: return(fastselect(L,lower+1,r,k-(lowerlen+1))) print(fastselect([4,3,5,6,2,1,8,9,7,10,13,15,18,17,11],0,15,4)) ``` **Output** ``` 4 ``` ## Recursion trees * **Recursion tree**-Rooted tree with one node for each recursive subproblem * **Value** of each node is time spent on that subproblem excluding recursive calls * Concretely, on an input of size $n$ * $f (n)$ is the time spent on non-recursive work * $r$ is the number of recursive calls * Each recursive call works on a subproblem of size $n/c $ * Resulting recurrence: $T(n) = rT(n/c) + f (n) $ * Root of recursion tree for $T(n)$ has value $f (n) $ * Root has $r$ children, each (recursively) the root of a tree for $T(n/c) $ * Each node at level $d$ has value $f (n/c^d ) $ * Assume, for simplicity, that $n$ was a power of $c$ <img src="../assets/w8i4.png" width=100% /> <img src="../assets/w8i5.png" width=100% /> <img src="../assets/w8i6.png" width=100% />