text
stringlengths
184
4.48M
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { ConfigService } from '@nestjs/config'; import * as sha256 from 'crypto-js/sha256'; import { FindOneOptions, FindOptionsRelations, FindOptionsSelect, Repository, } from 'typeorm'; import { pick } from 'lodash'; import { v4 as uuid } from 'uuid'; import { LocalOAuthProvidersEnum, OAuthProviders } from '@app/shared'; import { IAuthConfig } from '@app/configuration'; import { User } from '../entities'; import { UserAlreadyExistException, UserDeletedException, UserForbiddenException, UserNotDeletedException, UserNotFoundException, } from '../exceptions'; import { BaseEntitiesService } from './core'; @Injectable() export class UsersService extends BaseEntitiesService<User> { private authConfig = this.configService.getOrThrow<IAuthConfig>('auth'); constructor( private configService: ConfigService, @InjectRepository(User) repository: Repository<User>, ) { super(UsersService.name, repository); } async existByEmail( email: string, withDeleted = false, oAuthProvider: OAuthProviders = LocalOAuthProvidersEnum.LOCAL, ): Promise<boolean> { this.logger.verbose('existByEmail()'); // Fix: where options does not support generic entity type const opt: FindOneOptions<User> = { where: { email, oAuthProvider } } as any; if (withDeleted) { opt.withDeleted = withDeleted; } return !!(await this.repository.count(opt)); } async verifyPassword(email: string, password: string): Promise<string> { this.logger.verbose('verifyPassword()'); // Fix: where options does not support generic entity type const opt: FindOneOptions<User> = { where: { email, oAuthProvider: LocalOAuthProvidersEnum.LOCAL }, select: ['id', 'email', 'password'], } as any; const entity = await this.repository.findOne(opt); if (!entity) { return this.throwNotFoundException(); } const hashedPassword = await this.hashPassword(password, email); if (entity.password !== hashedPassword) { return this.throwNotFoundException(); } return entity.id; } async findOneByEmail( email: string, withDeleted = false, relations?: FindOptionsRelations<User>, select?: FindOptionsSelect<User>, ): Promise<User> { this.logger.verbose('findOneByEmail()'); const opt: FindOneOptions<User> = { where: { email } } as any; if (withDeleted) { opt.withDeleted = withDeleted; } if (relations) { opt.relations = relations; } if (select) { opt.select = select; } const entity = await this.repository.findOne(opt); if (!entity) { this.throwNotFoundException(); } return entity; } async findOneOrCreateForOAuthProvider( oAuthProvider: OAuthProviders, oAuthId: string, userData: Partial<User>, ): Promise<User> { this.logger.verbose('findOneOrCreateForOAuthProvider()'); const user = await this.repository.findOne({ where: { oAuthProvider, oAuthId } }); if (user) { return this.update(user, userData); } return this.create({ ...userData, oAuthProvider, oAuthId, }); } async create(userData: Partial<User>): Promise<User> { this.logger.verbose('create()'); const allowedProperties = [ 'oAuthProvider', 'oAuthId', 'password', 'firstName', 'lastName', 'preferredUsername', 'email', 'phoneNumber', ]; const allowedData = pick(userData, allowedProperties); if (!allowedData.oAuthProvider) { allowedData.oAuthProvider = LocalOAuthProvidersEnum.LOCAL; } if (allowedData.oAuthProvider === LocalOAuthProvidersEnum.LOCAL) { // Property oauthId can't be null and must be unique allowedData.oAuthId = uuid(); if (!allowedData.password) { throw new Error('Local user creation require a password'); } if (!allowedData.email) { throw new Error('Local user creation require an email'); } allowedData.password = await this.hashPassword(allowedData.password, allowedData.email); } if (allowedData.oAuthProvider !== LocalOAuthProvidersEnum.LOCAL) { if (allowedData.password) { throw new Error('Provided user creation can\'t have a password'); } } const user = this.repository.create(allowedData); await this.repository.save(user); return user; } private async update(user: User, updateData: Partial<User>): Promise<User> { this.logger.verbose('update()'); const allowedProperties = [ 'firstName', 'lastName', 'phoneNumber', ]; if (user.oAuthProvider !== 'local') { allowedProperties.push( 'preferredUsername', 'email', ); } const allowedData = pick(updateData, allowedProperties); return this._update(user.id, allowedData); } private async hashPassword(password: string, email: string): Promise<string> { this.logger.verbose('hashPassword()'); return sha256(`${password}-${email}-${this.authConfig.passwordSalt}`).toString(); } private throwAlreadyExistException(): never { this.logger.verbose('throwAlreadyExistException()'); throw new UserAlreadyExistException(); } protected override throwDeletedException(): never { this.logger.verbose('throwDeletedException()'); throw new UserDeletedException(); } protected override throwNotDeletedException(): never { this.logger.verbose('throwNotDeletedException()'); throw new UserNotDeletedException(); } protected override throwNotFoundException(): never { this.logger.verbose('throwNotFoundException()'); throw new UserNotFoundException(); } protected override throwForbiddenException(message?: string): never { this.logger.verbose('throwForbiddenException()'); throw new UserForbiddenException(message); } }
import * as firebase from 'firebase' export default { state: { loadedMeetups: [] }, mutations: { setLoadedMeetups (state, payload) { state.loadedMeetups = payload }, createMeetup (state, payload) { state.loadedMeetups.push(payload) }, updateMeetup (state, payload) { const meetup = state.loadedMeetups.find(meetup => { return meetup.id === payload.id }) if (payload.title) { meetup.title = payload.title } if (payload.description) { meetup.description = payload.description } if (payload.location) { meetup.location = payload.location } if (payload.date) { meetup.date = payload.date } } }, actions: { loadMeetups ({commit}) { commit('setLoading', true) firebase.database().ref('meetups').once('value') .then((data) => { const meetups = [] const obj = data.val() for (let key in obj) { meetups.push({ id: key, title: obj[key].title, description: obj[key].description, imageUrl: obj[key].imageUrl, date: obj[key].date, location: obj[key].location, creatorId: obj[key].creatorId }) } console.log(meetups) commit('setLoading', false) commit('setLoadedMeetups', meetups) }) .catch((error) => { commit('setLoading', false) console.log(error) }) }, createMeetup ({commit, getters}, payload) { commit('setLoading', true) const meetup = { title: payload.title, location: payload.location, description: payload.description, date: payload.date.toISOString(), creatorId: getters.user.uid } // variable for image Url and key let imageUrl let key // Reach to firebase and store it firebase.database().ref('meetups').push(meetup) .then((data) => { // get firebase record key/id key = data.key return key }) .then(key => { const filename = payload.image.name const ext = filename.slice(filename.lastIndexOf('.')) // Store Image on firebase storage return firebase.storage().ref('meetups/' + key + '.' + ext).put(payload.image) }) .then(fileData => { // get Image Url from firebase storage and referenced on Meetup // in firebase database imageUrl = fileData.metadata.downloadURLs[0] return firebase.database().ref('meetups').child(key).update({imageUrl: imageUrl}) }) .then(() => { commit('createMeetup', { ...meetup, id: key, imageUrl: imageUrl }) commit('setLoading', false) }) .catch((error) => { commit('setLoading', false) console.log(error) }) }, updateMeetup ({commit}, payload) { commit('setLoading', true) const updatedObj = { id: payload.id } if (payload.title) { updatedObj.title = payload.title } if (payload.description) { updatedObj.description = payload.description } if (payload.location) { updatedObj.location = payload.location } if (payload.date) { updatedObj.date = payload.date } firebase.database().ref('meetups').child(payload.id).update(updatedObj) .then((data) => { commit('setLoading', false) commit('updateMeetup', updatedObj) }) .catch((error) => { console.log(error) commit('setLoading', false) }) } }, getters: { loadedMeetups (state) { return state.loadedMeetups.sort((meetupA, meetupB) => { // Load meetups sorted by date return meetupA.date > meetupB.date }) }, loadedMeetup (state) { // Find specific meetup return (meetupId) => { return state.loadedMeetups.find((meetup) => { return meetup.id === meetupId }) } }, featuredMeetups (state, getters) { return getters.loadedMeetups.slice(0, 5) } } }
<?php // Start session to check user authentication session_start(); // Include the admin header include_once '../components/admin/admin_header.php'; // Check if user is logged in and is an admin if (!isset($_SESSION['login_id']) || $_SESSION['login_user_role'] !== 'admin') { // Redirect to login page if not logged in or not an admin header("Location: login.php"); exit(); } // Include the database connection file require_once '../includes/conn.php'; // Initialize variables to store form data and error messages $module_name = $module_description = ''; $module_nameErr = $module_descriptionErr = ''; // Check if module ID is provided in the URL if (isset($_GET['module_id']) && !empty($_GET['module_id'])) { $module_id = $_GET['module_id']; // Retrieve module data from the database $sql = "SELECT * FROM module WHERE module_id = '$module_id'"; $result = $conn->query($sql); if ($result->num_rows == 1) { $row = $result->fetch_assoc(); $module_name = $row['module_name']; $module_description = $row['module_description']; } else { // Module not found echo "Module not found."; exit(); } } else { // Module ID not provided echo "Module ID not provided."; exit(); } // Check if the form is submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { // Validate form data if (empty($_POST["module_name"])) { $module_nameErr = "Module Name is required"; } else { $module_name = $_POST["module_name"]; } if (empty($_POST["module_description"])) { $module_descriptionErr = "Module Description is required"; } else { $module_description = $_POST["module_description"]; } // If there are no input errors, proceed with updating module if (empty($module_nameErr) && empty($module_descriptionErr)) { // Prepare and execute SQL statement to update module data in the database $sql = "UPDATE module SET module_name='$module_name', module_description='$module_description' WHERE module_id='$module_id'"; if ($conn->query($sql) === TRUE) { // Module updated successfully, redirect to admin module page header("Location: admin_modules.php"); exit(); } else { echo "Error updating modules: " . $conn->error; } } } // Close database connection $conn->close(); ?> <div class="container"> <h2>Update Module</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> <div class="form-group"> <label for="module_name">Module Name:</label> <input type="text" id="module_name" name="module_name" value="<?php echo $module_name; ?>"> <span class="error"><?php echo $module_nameErr; ?></span> </div> <div class="form-group"> <label for="module_description">Module Description:</label> <textarea id="module_description" name="module_description"><?php echo $module_description; ?></textarea> <span class="error"><?php echo $module_descriptionErr; ?></span> </div> <button type="submit">Update Module</button> </form> </div> </body> </html>
from tkinter import Tk, Button, Label, filedialog, Frame from PIL import Image, ImageTk from ttkthemes import ThemedStyle # Global variables for storing images input_image = None encrypted_image = None decrypted_image = None # Function to encrypt image using XOR operation with a key def encrypt_image(image_path, key): global encrypted_image # Open the image try: img = Image.open(image_path) except Exception as e: print("Error opening image:", e) return None width, height = img.size # Convert image to RGB mode img = img.convert("RGB") # Resize image to reduce processing time try: img.thumbnail((width // 10, height // 10)) # Reduce image dimensions for faster processing except Exception as e: print("Error resizing image:", e) return None resized_width, resized_height = img.size # Encrypt each pixel for y in range(resized_height): for x in range(resized_width): # Get pixel value try: pixel = img.getpixel((x, y)) except Exception as e: print("Error getting pixel at (", x, ",", y, "):", e) continue # Encrypt pixel using XOR operation with key encrypted_pixel = tuple([(p ^ k) % 256 for p, k in zip(pixel, key)]) # Update pixel value img.putpixel((x, y), encrypted_pixel) # Save encrypted image encrypted_image = img print("Image encrypted successfully!") return img # Function to decrypt image using XOR operation with a key def decrypt_image(encrypted_img, key): global decrypted_image if encrypted_img: decrypted_img = encrypted_img.copy() width, height = decrypted_img.size # Decrypt each pixel for y in range(height): for x in range(width): # Get pixel value pixel = decrypted_img.getpixel((x, y)) # Decrypt pixel using XOR operation with key decrypted_pixel = tuple([(p ^ k) % 256 for p, k in zip(pixel, key)]) # Update pixel value decrypted_img.putpixel((x, y), decrypted_pixel) decrypted_image = decrypted_img print("Image decrypted successfully!") return decrypted_img else: print("No encrypted image to decrypt!") return None # Function to save images def save_images(): global encrypted_image global decrypted_image if encrypted_image: save_path = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG files", "*.png"), ("All files", "*.*")]) if save_path: try: encrypted_image.save(save_path) print("Encrypted image saved successfully!") except Exception as e: print("Error saving encrypted image:", e) else: print("No encrypted image to save!") if decrypted_image: save_path = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG files", "*.png"), ("All files", "*.*")]) if save_path: try: decrypted_image.save(save_path) print("Decrypted image saved successfully!") except Exception as e: print("Error saving decrypted image:", e) else: print("No decrypted image to save!") # Callback function for "Decrypt" button def decrypt_button_clicked(): key = (10, 20, 30) # Example key global encrypted_image global decrypted_image global output_label if encrypted_image: print("Decrypting image...") decrypted_image = decrypt_image(encrypted_image, key) if decrypted_image: print("Image decrypted.") decrypted_image.thumbnail((200, 200)) decrypted_photo = ImageTk.PhotoImage(decrypted_image) output_label.config(image=decrypted_photo) output_label.image = decrypted_photo else: print("Error decrypting image.") else: print("No encrypted image available!") # Callback function for "Encrypt" button def encrypt_button_clicked(): key = (10, 20, 30) # Example key global input_image global encrypted_image global output_label if input_image: print("Encrypting image...") encrypted_image = encrypt_image(input_image, key) if encrypted_image: print("Image encrypted.") encrypted_image.thumbnail((200, 200)) encrypted_photo = ImageTk.PhotoImage(encrypted_image) output_label.config(image=encrypted_photo) output_label.image = encrypted_photo else: print("Error encrypting image.") else: print("No input image selected!") # Callback function for selecting input image file def select_input_file(): global input_image file_path = filedialog.askopenfilename() if file_path: input_image = file_path input_image_display = Image.open(file_path) input_image_display.thumbnail((200, 200)) input_photo = ImageTk.PhotoImage(input_image_display) input_label.config(image=input_photo) input_label.image = input_photo from tkinter import Tk, Button, Label, filedialog, Frame from PIL import Image, ImageTk from ttkthemes import ThemedStyle # Create UI root = Tk() root.title("Image Encryption/Decryption") root.configure(bg="#f0f0f0") # Set background color # Load the icon file using PIL icon_image = Image.open("/Prodigy CY Task 2/app_icon.ico") # Convert the PIL image to a Tkinter-compatible format icon = ImageTk.PhotoImage(icon_image) # Set the window icon root.iconphoto(True, icon) style = ThemedStyle(root) style.set_theme("arc") # Choose the theme - you can try different themes # Create frames frame_input = Frame(root, bg="#f0f0f0") # Set background color for frames frame_input.pack(pady=10) frame_output = Frame(root, bg="#f0f0f0") frame_output.pack(pady=10) frame_buttons = Frame(root, bg="#f0f0f0") frame_buttons.pack(pady=10) input_label = Label(frame_input, text="Input Image:", bg="#f0f0f0", fg="#333333", font=("Arial", 12, "bold")) # Set label colors and font input_label.pack(side="left", padx=10) output_label = Label(frame_output, text="Output Image:", bg="#f0f0f0", fg="#333333", font=("Arial", 12, "bold")) output_label.pack(side="left", padx=10) select_input_button = Button(frame_buttons, text="Select Input Image", command=select_input_file, bg="#4CAF50", fg="white", font=("Arial", 10, "bold")) # Set button colors and font select_input_button.pack(side="left", padx=10) encrypt_button = Button(frame_buttons, text="Encrypt Image", command=encrypt_button_clicked, bg="#008CBA", fg="white", font=("Arial", 10, "bold")) encrypt_button.pack(side="left", padx=10) decrypt_button = Button(frame_buttons, text="Decrypt Image", command=decrypt_button_clicked, bg="#f44336", fg="white", font=("Arial", 10, "bold")) decrypt_button.pack(side="left", padx=10) save_button = Button(frame_buttons, text="Save Images", command=save_images, bg="#555555", fg="white", font=("Arial", 10, "bold")) save_button.pack(side="left", padx=10) root.mainloop()
import React from "react"; import "./App.css"; import SearchBar from "../SearchBar/SearchBar"; import SearchResult from "../SearchResults/SearchResults"; import Playlist from "../Playlist/Playlist"; import Spotify from "../../util/Spotify"; class App extends React.Component { constructor(props) { super(props); this.state = { searchResults: [ ], playlistName: "My Playlist", playlistTracks: [] , }; this.addTrack = this.addTrack.bind(this); this.removeTrack = this.removeTrack.bind(this); this.updatePlaylistName =this.updatePlaylistName.bind(this); this.savePlayList = this.savePlayList.bind(this); this.search = this.search.bind(this); } //add track from search results to playlist based on user input addTrack(track){ let tracks = this.state.playlistTracks; if(tracks.find( prevTrack => prevTrack.id === track.id)){ return; } tracks.push(track); this.setState({playlistTracks: tracks}); }; // remove the track from playlist based on user input removeTrack(track){ let currentPlaylistTracks =this.state.playlistTracks; let newPlaylistTracks = currentPlaylistTracks.filter( (prevTrack) => prevTrack.id !== track.id) this.setState({playlistTracks : newPlaylistTracks}); }; //updates playlist name based on user input updatePlaylistName(name){ this.setState( {playlistName: name}); } //Generates an array of Uri values and pushes them to an array savePlayList(){ let trackUris = []; this.state.playlistTracks.forEach( track => {trackUris.push(track.uri)}) Spotify.savePlaylist(this.state.playlistName, trackUris); } //sets the search term search(term){ let searchTerm = term; Spotify.search(searchTerm).then(searchResults => { this.setState({searchResults: searchResults})}); console.log(this.state.searchResults); } //gets access token right away componentDidMount(){ Spotify.getAccessToken(); } render() { return ( <div> <h1> Ja<span className="highlight">mmm</span>ing </h1> <div className="App"> <SearchBar onSearch={this.search}/> <div className="App-playlist"> <SearchResult searchResults={this.state.searchResults} onRemove={this.removeTrack} onAdd={this.addTrack} /> <Playlist onSave={this.savePlayList} onNameChange={this.updatePlaylistName} onRemove={this.removeTrack} onAdd={this.addTrack} playlistName={this.state.playlistName} playlistTracks={this.state.playlistTracks}/> </div> </div> </div> ); } } export default App;
import 'dart:convert'; import 'dart:io'; import 'package:Deal_Connect/api/auth.dart'; import 'package:Deal_Connect/components/alert/show_complete_dialog.dart'; import 'package:Deal_Connect/components/const/setting_colors.dart'; import 'package:Deal_Connect/components/const/setting_style.dart'; import 'package:Deal_Connect/components/custom/join_text_form_field.dart'; import 'package:Deal_Connect/components/layout/default_logo_layout.dart'; import 'package:Deal_Connect/components/layout/default_next_layout.dart'; import 'package:Deal_Connect/model/user.dart'; import 'package:Deal_Connect/utils/custom_dialog.dart'; import 'package:Deal_Connect/utils/shared_pref_utils.dart'; import 'package:Deal_Connect/components/const/setting_colors.dart'; import 'package:Deal_Connect/utils/utils.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:hexcolor/hexcolor.dart'; import 'package:image_picker/image_picker.dart'; class ProfileEditIndex extends StatefulWidget { const ProfileEditIndex({ Key? key, }) : super(key: key); @override State<ProfileEditIndex> createState() => _ProfileEditIndexState(); } class _ProfileEditIndexState extends State<ProfileEditIndex> { User? myPageData; File? _pickedImage; String name = ''; String phone = ''; String email = ''; List<String> keywords = []; final TextEditingController _keywordTextController = TextEditingController(); final TextEditingController _nameTextController = TextEditingController(); final TextEditingController _phoneTextController = TextEditingController(); final TextEditingController _emailTextController = TextEditingController(); bool isProcessable = false; @override void initState() { super.initState(); _initUserMyData(); } void _initUserMyData() { getMyUser().then((response) { if (response.status == 'success') { User user = User.fromJSON(response.data); setState(() { myPageData = user; _nameTextController.text = myPageData!.name; _phoneTextController.text = myPageData!.phone!; _emailTextController.text = myPageData!.email!; keywords = keywords = myPageData!.has_keywords! .map((userKeyword) => userKeyword.keyword) .toList(); }); } }); } void _addKeyword() { final text = _keywordTextController.text; if (text.isNotEmpty && keywords.length < 10) { setState(() { keywords.add(text); _keywordTextController.clear(); }); } } void _removeKeyword(String keyword) { setState(() { keywords.remove(keyword); }); } @override Widget build(BuildContext context) { ImageProvider? backgroundImage; if (myPageData != null && myPageData!.profile != null && myPageData!.profile!.has_profile_image != null) { backgroundImage = CachedNetworkImageProvider( Utils.getImageFilePath( myPageData!.profile!.has_profile_image!), ); } else { backgroundImage = AssetImage('assets/images/no-image.png'); } final bottomTextStyle = TextStyle( color: Color(0xFF232323), fontSize: 14.0, //fontWeight: FontWeight.w600 ); return DefaultNextLayout( titleName: '프로필 수정', nextTitle: '저장하기', prevTitle: '취소', isCancel: false, isProcessable: true, bottomBar: true, prevOnPressed: () {}, nextOnPressed: () { _submit(); }, child: GestureDetector( onTap: () { FocusScope.of(context).requestFocus(FocusNode()); }, child: SingleChildScrollView( child: Column( children: [ GestureDetector( onTap: () { buildShowModalBottomSheet(context, bottomTextStyle); }, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: 150, height: 150.0, decoration: BoxDecoration( color: Color(0xFFF5F5F5), borderRadius: BorderRadius.all( Radius.circular(75.0), ), ), child: Stack( fit: StackFit.expand, // Stack 내의 children을 컨테이너 크기에 맞춥니다. clipBehavior: Clip.none, // 자식이 Stack 범위 밖으로 나가도록 허용 children: [ ClipRRect( borderRadius: BorderRadius.all(Radius.circular(75.0)), child: _pickedImage == null ? Image( image: backgroundImage, fit: BoxFit .cover, // 이미지가 컨테이너를 꽉 채우도록 조정 ) : Image.file( _pickedImage!, fit: BoxFit.cover, ), ), Positioned( right: 0, bottom: 0, child: IconButton( icon: Icon( Icons.settings, color: Colors.grey, size: 40, ), onPressed: () { buildShowModalBottomSheet( context, bottomTextStyle); }, ), ), ], ), ), ], ), ], ), ), SizedBox( height: 20, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.symmetric(vertical: 10.0), child: Text( '이름', style: SettingStyle.NORMAL_TEXT_STYLE, ), ), TextFormField( controller: _nameTextController, decoration: SettingStyle.INPUT_STYLE ), ], ), SizedBox( height: 10.0, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.symmetric(vertical: 10.0), child: Text( '전화번호', style: SettingStyle.NORMAL_TEXT_STYLE, ), ), TextFormField( controller: _phoneTextController, decoration: SettingStyle.INPUT_STYLE ), ], ), SizedBox( height: 10.0, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.symmetric(vertical: 10.0), child: Text( '이메일', style: SettingStyle.NORMAL_TEXT_STYLE, ), ), TextFormField( controller: _emailTextController, decoration: SettingStyle.INPUT_STYLE ), ], ), SizedBox( height: 10.0, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 10.0), child: Text( '검색 키워드', style: SettingStyle.NORMAL_TEXT_STYLE, ), ), TextField( controller: _keywordTextController, decoration: SettingStyle.INPUT_STYLE.copyWith( labelText: '키워드 추가', suffixIcon: IconButton( icon: Icon(Icons.add), onPressed: _addKeyword, ) ), onSubmitted: (value) => _addKeyword(), ), SizedBox(height: 10), Wrap( spacing: 8.0, // 각 Chip의 간격 children: keywords .map((keyword) => Chip( label: Text(keyword), onDeleted: () => _removeKeyword(keyword), )) .toList(), ), ], ), ], ), ), ), ); } Future<dynamic> buildShowModalBottomSheet( BuildContext context, TextStyle bottomTextStyle) { return showModalBottomSheet( backgroundColor: Colors.white, showDragHandle: true, context: context, builder: (context) { return SafeArea( child: Padding( padding: const EdgeInsets.only(bottom: 20.0), child: Container( width: double.infinity, child: Column( mainAxisSize: MainAxisSize.min, children: [ GestureDetector( child: Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Text( '카메라로 촬영', style: bottomTextStyle, ), ), onTap: () { ImagePicker() .pickImage(source: ImageSource.camera) .then((xfile) { if (xfile != null) { setState(() { _pickedImage = File(xfile.path); isProcessable = true; }); } Navigator.maybePop(context); }); }, ), Divider( height: 1.0, color: Color(0xFFdddddd), ), GestureDetector( child: Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Text( '앨범에서 가져오기', style: bottomTextStyle, ), ), onTap: () { ImagePicker() .pickImage(source: ImageSource.gallery) .then((xfile) { if (xfile != null) { setState(() { _pickedImage = File(xfile.path); isProcessable = true; }); } Navigator.maybePop(context); }); }, ), ], ), ), ), ); }); } _submit() async { CustomDialog.showProgressDialog(context); updateProfile({ 'name': _nameTextController.text, 'phone': _phoneTextController.text, 'email': _emailTextController.text, 'keywords': jsonEncode(keywords), }, _pickedImage).then((response) async { CustomDialog.dismissProgressDialog(); if (response.status == 'success') { User user = User.fromJSON(response.data); SharedPrefUtils.setUser(user).then((value) { print(value); _showCompleteDialog(context); }); } else { CustomDialog.showServerValidatorErrorMsg(response); } }); } void _showCompleteDialog(BuildContext context) { showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) { return ShowCompleteDialog( messageTitle: '프로필 수정 완료', messageText: '프로필 수정이 완료 되었습니다.', buttonText: '확인', onConfirmed: () { Navigator.of(context).popUntil((route) => route.isFirst); }, ); }, ); } @override void dispose() { super.dispose(); } }
package ru.kata.spring.boot_security.demo.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import ru.kata.spring.boot_security.demo.models.User; import ru.kata.spring.boot_security.demo.services.AdminService; import ru.kata.spring.boot_security.demo.services.UserDataValidationService; import ru.kata.spring.boot_security.demo.util.DataValidator; import javax.validation.Valid; import java.security.Principal; import java.util.List; @Controller @RequestMapping("/admin") public class AdminController { private final AdminService adminService; private final DataValidator dataValidator; private final UserDataValidationService userDataValidationService; @Autowired public AdminController(AdminService adminService, DataValidator dataValidator, UserDataValidationService userDataValidationService) { this.adminService = adminService; this.dataValidator = dataValidator; this.userDataValidationService = userDataValidationService; } @GetMapping() public String showAllUsers(Model model, Principal principal) { User user = adminService.findUserByName(principal.getName()); model.addAttribute("currentUser", user); List<User> listOfUsers = adminService.getAllUsers(); model.addAttribute("listOfUsers", listOfUsers); model.addAttribute("user", new User()); model.addAttribute("allErrors", dataValidator.getAllErrorsAsString()); return "admin/users"; } @GetMapping("/new") public String showNewUserForm(Model model) { model.addAttribute("user", new User()); return "/admin/new"; } @PostMapping("") public String createUser(@ModelAttribute @Valid User user, @RequestParam(value = "roles", required = false) List<String> roles, RedirectAttributes redirectAttributes) { String allErrors = userDataValidationService.validateUserData(user, roles); if (!allErrors.isEmpty()) { redirectAttributes.addFlashAttribute("errorValidation", allErrors); return "redirect:/admin"; } adminService.create(user, roles); return "redirect:/admin"; } @PostMapping("/user/edit") public String update(@ModelAttribute("person") @Valid User user, @RequestParam(value = "role", required = false) @Valid List<String> role, RedirectAttributes redirectAttributes) { String allErrors = userDataValidationService.validateUserData(user, role); if (!allErrors.isEmpty()) { redirectAttributes.addFlashAttribute("errorValidation", allErrors); return "redirect:/admin"; } adminService.updateUser(user, role); return "redirect:/admin"; } @PostMapping("/user/delete") public String delete(@RequestParam Long id) { adminService.removeUser(id); return "redirect:/admin"; } }
<template> <div class="two"> <h3>路由传参</h3> <button class="btn btn-success" @click="getData">获取动态路径参数</button> <button class="btn btn-success" @click="getData2">获取查询字符串参数</button> <p>显示动态路径参数 id:{{$route.params.id}}</p> <p>显示查询字符串参数 code:{{$route.query.code}}</p> </div> </template> <script> export default { props: ['id'], // 当路由 设置props为true时,那么可以通过属性或取该参数, 参数只能是动态路径的形式 created(){ console.log(this.id || "") // 通过属性的方式获取路由参数 id }, methods:{ getData(){ console.log(this.$route.params) }, getData2(){ console.log(this.$route.query); } }, watch:{ // 监听路由参数变化 '$route'(to, from){ console.log(to, from) } }, /* 路由守卫 当书写了路由守卫时路由监听不生效 */ beforeRouteUpdate(to, from, next){ console.log('路由守卫'); }, beforeRouteLeave(to, from, next){ // 导航离开该组件的对应路由时调用 console.log("beforeRouteLeave"); next(); } } </script> <style scoped lang="stylus"> .two h3,p text-align: center </style>
import React from "react"; import styled from "styled-components"; import COLORS from "../../constants/color"; const Wrapper = styled.div``; const Label = styled.div` font-size: 1.3rem; color: ${COLORS.GREY[500]}; padding-bottom: 1rem; padding-left: 0.2rem; `; const InputWrapper = styled.input<{ size: number }>` ${({ size }) => ` width: ${size}rem; `} padding: 1.5rem 1.2rem; height: 2.5rem; border-radius: 0.625rem; border: 0.1rem solid ${COLORS.GREY[300]}; color: ${COLORS.GREY[500]}; font-size: 1.5rem; &::placeholder { color: ${COLORS.GREY[300]}; font-weight: 400; } &:focus { border-color: ${COLORS.BLUE}; outline: none; /* 커서가 focus 되었을 때의 기본 아웃라인 스타일 제거 */ // box-shadow: 0 0 0 2px ${COLORS.BLUE_HOVER}; /* focus 시에 박스 쉐도우 추가 */ } `; const Message = styled.p` font-size: 1.1rem; padding-top: 1rem; color: ${COLORS.BLACK}; `; type InputProps = { /** input 안의 초깃값 */ value: string | number; /** 변화가 일어났을떄 호출되는 함수 */ onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void; /** input type : ex> text,password,checkbox etc. */ type?: string; /** 자리표시자 */ placeholder?: string | number | null; /** label 숨길지 여부 */ labelHidden?: boolean; /** label 내용 */ label?: string; /** input 너비 */ size?: number; /** 필수로 채워야하는 필드 */ required?: boolean; /** 읽기 전용 */ readOnly?: boolean; /** input의 입력 조건 */ message?: string; className?: string; }; export default function Input({ value, onChange, type, placeholder = "", labelHidden = false, label, size = 35, required = false, className, readOnly = false, message = "", }: InputProps) { return ( <Wrapper className={className}> {label && !labelHidden && <Label>{label}</Label>} <InputWrapper value={value} onChange={onChange} type={type} placeholder={placeholder?.toString()} size={size} required={required} readOnly={readOnly} /> {message.length > 0 && <Message> {message}</Message>} </Wrapper> ); }
export {} // Implicit Data Types console.log("Implicit Data Types"); console.log("String"); let name:string="Nirmal Shah" console.log(name); console.log(""); console.log("Number"); let age:number=21 console.log(age); console.log(""); console.log("Boolean"); let isPlaced:boolean=true console.log(isPlaced); console.log(""); console.log("Undefined"); let x:undefined=undefined console.log(x); console.log(""); console.log("null"); let y:null =null console.log(y); console.log(""); // Explicit Data Types console.log("Explicit Data Types"); console.log("Array"); let names:string[] = ["Nirmal Shah", "Sibten Shekh"] console.log(names); console.log(""); console.log("Tuple"); let myTuple:[string, number, boolean]=["Nirmal", 51, false] console.log(myTuple); console.log(""); console.log("Object"); let detail:{name:string, age:number}={ name:"Nirmal", age:21 } console.log(detail); console.log(""); console.log("Interface"); interface Animal { sound: string, maxAge: number } const Lion: Animal = { sound: "Roars", maxAge: 10 }; const Dog: Animal = { sound: "Barks", maxAge: 12 }; console.log(Lion); console.log(Dog); console.log(""); console.log("Function"); function sayHello(name:string):string{ return "Hello, "+name+"!"; } console.log(sayHello("Nirmal"));
import {useMutation, useQueryClient} from "@tanstack/react-query"; import {createOrEditCabin} from "../../services/apiCabins.js"; import toast from "react-hot-toast"; export function useCreateCabin() { const queryClient = useQueryClient(); const {isLoading: isCreating, mutate: createCabin} = useMutation({ mutationFn: createOrEditCabin, // <==> (newCabin) => createCabin(newCabin) onSuccess: async () => { toast.success("New cabin successfully created"); await queryClient.invalidateQueries({ queryKey: ['cabins'] }); }, onError: error => toast.error(error.message) }); return {isCreating, createCabin}; }
import { Controller, Get, Post, Body, Patch, Param, Delete, } from '@nestjs/common'; import { TicketreturnsService } from './ticketreturns.service'; import { CreateTicketreturnDto } from './dto/create-ticketreturn.dto'; import { UpdateTicketreturnDto } from './dto/update-ticketreturn.dto'; @Controller('ticketreturns') export class TicketreturnsController { constructor(private readonly ticketreturnsService: TicketreturnsService) {} @Post() create(@Body() createTicketreturnDto: CreateTicketreturnDto) { return this.ticketreturnsService.create(createTicketreturnDto); } @Get() findAll() { return this.ticketreturnsService.findAll(); } @Get(':id') findOne(@Param('id') id: string) { return this.ticketreturnsService.findOne(+id); } @Patch(':id') update( @Param('id') id: string, @Body() updateTicketreturnDto: UpdateTicketreturnDto, ) { return this.ticketreturnsService.update(+id, updateTicketreturnDto); } @Delete(':id') remove(@Param('id') id: string) { return this.ticketreturnsService.remove(+id); } }
// // LegacyGetFollowedStreamsRequest.swift // TwitchKit // // Created by Tyler Prevost on 12/8/20. // /// Gets a list of online streams a user is following, based on a specified OAuth token. public struct LegacyGetFollowedStreamsRequest: APIRequest { public typealias AppToken = IncompatibleAccessToken public struct ResponseBody: Decodable { /// The returned list of streams the current user is following. public let streams: [LegacyStream] } /// The type of live stream to return. public enum StreamType: String { case live case playlist case all } public enum QueryParamKey: String { case streamType = "stream_type" case limit case offset } public let apiVersion: APIVersion = .kraken public let path = "/streams/followed" public let queryParams: [(key: QueryParamKey, value: String?)] /// Creates a new Get Followed Streams legacy request. /// /// - Parameters: /// - streamType: Constrains the type of streams returned. Playlists are offline streams of VODs /// (Video on Demand) that appear live. Default: live. /// - limit: Maximum number of objects to return. Default: 25. Maximum: 100. /// - offset: Object offset for pagination of results. Default: 0. Capped at 900. public init(streamType: StreamType? = nil, limit: Int? = nil, offset: Int? = nil) { queryParams = [ (.streamType, streamType?.rawValue), (.limit, limit?.description), (.offset, offset?.description) ] } }
# Meus Projetos de Programação Bem-vindo ao repositório dos meus projetos de programação do dia a dia! Este repositório contém diversos projetos que desenvolvi utilizando as bibliotecas `pygame` e `p5`. Cada projeto está organizado em pastas separadas, facilitando a navegação e a compreensão do código. ## Índice - [Visão Geral](#visão-geral) - [Projetos](#projetos) - [Como Executar](#como-executar) - [Pré-requisitos](#pré-requisitos) - [Instalação](#instalação) ## Visão Geral Este repositório é uma coleção dos meus projetos pessoais de programação. O objetivo é compartilhar meu progresso, aprendizado e fornecer exemplos de como utilizar as bibliotecas `pygame` e `p5` para criar aplicações interativas e jogos. Essas são algumas das pessoas que me inspiraram a criar esses projetos: <p align="center"> <a href="https://www.youtube.com/c/TheCodingTrain"> <img src="https://yt3.googleusercontent.com/99wepc_FTSN0n_GbR-FlFANyxed7TsbE8WxKIDWftdxssZlYo1-gW1CRD7cPgOzThMM8m4W8=s176-c-k-c0x00ffffff-no-rj" alt="The Coding Train" width="150" height="150" > </a> <a href="https://www.youtube.com/c/ClearCode"> <img src="https://yt3.googleusercontent.com/Wj9_npdrzYf5kxqLqfSLukT8iED0lR5r-lQ7giM3vXahULQYdm7cUtHstltUDLadmf9EyEANMA=s176-c-k-c0x00ffffff-no-rj" alt="Clear Code" width="150" height="150" > </a> <a href="https://www.youtube.com/@cartersemrad"> <img src="https://yt3.googleusercontent.com/2CqYziwk0tDVqQzg1pCU8g4qDnDXKjzlaDCMvkump6Q7rkU-xnSnHCKy9TsHedkFbIVB28Q2=s176-c-k-c0x00ffffff-no-rj" alt="Carter Semrad" width="150" height="150" > </a> <a href="https://www.youtube.com/c/SebastianLague"> <img src="https://yt3.googleusercontent.com/ytc/AIdro_khWt3vK98dhFYSgpIZZBli0zwd-dztKDv9r7rtOEtAVO8=s176-c-k-c0x00ffffff-no-rj" alt="Sebastian Lague" width="150" height="150" > </a> </p> <p align="center"> <a href="https://www.youtube.com/@TheCodingTrain">The Coding Train</a> &nbsp;|&nbsp; <a href="https://www.youtube.com/@ClearCode">Clear Code</a> &nbsp;|&nbsp; <a href="https://www.youtube.com/@cartersemrad">Carter Semrad</a> &nbsp;|&nbsp; <a href="https://www.youtube.com/@SebastianLague">Sebastian Lague</a> </p> ## Projetos ### 1. Projetos com Pygame <img src="assets/dotsGIF.gif" alt="Projeto com Pygame" width="200"> ### 2. Projetos com P5 <img src="assets/frac_img.png" alt="Projeto com P5" width="200"> ## Como Executar Para executar qualquer um dos projetos, siga os passos abaixo: 1. Clone este repositório: ```bash https://github.com/gabriellsar/coding-challenges.git ``` 2. Navegue até a pasta do projeto desejado: ```bash cd nome-do-projeto ``` 3. Crie e ative um ambiente virtual (venv): ```bash python -m venv venv ``` - No Windows: ```bash venv\Scripts\activate ``` - No macOS/Linux: ```bash source venv/bin/activate ``` 4. Execute o projeto: ```bash python main.py ``` ## Pré-requisitos Certifique-se de ter os seguintes pré-requisitos instalados: - Python 3.10.11 ou maior - Pip (gerenciador de pacotes do Python) ## Instalação Instale as dependências necessárias para cada projeto. As bibliotecas principais utilizadas são `pygame-ce` e `p5`. Você pode instalá-las usando os comandos abaixo: ### Pygame ```bash pip install pygame-ce ``` ### p5 ```bash pip install p5 ```
library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std_unsigned.all; -- This module performs the Continued Fraction calculations. Once initialized -- with the integer N, it will repeatedly output values X and Y, such that -- 1) X^2 = Y mod N. -- 2) |Y|<2*sqrt(N). -- In other words, the number of bits in Y is approximately half that of X and N. -- The value of Y is represented as a sign bit in W and an absolute value in P. -- Specifically, this module calculates a recurrence relation with the -- following initialiazation: -- p_0 = 1 -- r_0 = 0 -- x_0 = 1 -- p_1 = N - M*M -- s_1 = 2*M -- w_1 = -1 -- x_1 = M, -- and then for each n>=2: -- 1) a_n = s_n/p_n -- 2) r_n = s_n-a_n*p_n -- 3) s_(n+1) = 2*M - r\_n -- 4) p_(n+1) = a_n (r_n - r_(n-1)) + p_(n-1) -- 5) w_(n+1) = - w_n -- 6) x_(n+1) = a_n x_n + x_(n-1) mod N -- Steps 1 and 2 in the recurrence are performed simultaneously using the divmod module. -- Steps 4 and 6 are performed simultaneously using the add_mult and amm modules. entity cf is generic ( G_DATA_SIZE : integer ); port ( clk_i : in std_logic; rst_i : in std_logic; s_start_i : in std_logic; s_val_i : in std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); -- N m_ready_i : in std_logic; m_valid_o : out std_logic; m_res_x_o : out std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); -- X m_res_p_o : out std_logic_vector(G_DATA_SIZE - 1 downto 0); -- |Y| m_res_w_o : out std_logic -- sign(Y) ); end entity cf; architecture synthesis of cf is constant C_ZERO : std_logic_vector(G_DATA_SIZE - 1 downto 0) := (others => '0'); constant C_ONE : std_logic_vector(G_DATA_SIZE - 1 downto 0) := to_stdlogicvector(1, G_DATA_SIZE); -- State variables type state_type is (IDLE_ST, SQRT_ST, CALC_AR_ST, CALC_XP_ST); signal state : state_type; signal val_n : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal val_2root : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal p_prev : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal r_prev : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal x_prev : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal p_cur : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal s_cur : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal w_cur : std_logic; signal x_cur : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal a_cur : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal r_cur : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal p_new : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal s_new : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal w_new : std_logic; signal x_new : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); -- Signals connected to SQRT module signal sqrt_s_ready : std_logic; signal sqrt_s_valid : std_logic; signal sqrt_s_data : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal sqrt_m_ready : std_logic; signal sqrt_m_valid : std_logic; signal sqrt_m_res : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal sqrt_m_diff : std_logic_vector(G_DATA_SIZE downto 0); -- Signals connected to DIVMOD module signal divmod_s_ready : std_logic; signal divmod_s_valid : std_logic; signal divmod_s_val_n : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal divmod_s_val_d : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal divmod_m_ready : std_logic; signal divmod_m_valid : std_logic; signal divmod_m_res_q : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal divmod_m_res_r : std_logic_vector(G_DATA_SIZE - 1 downto 0); -- Signals connected to AMM module signal amm_s_ready : std_logic; signal amm_s_valid : std_logic; signal amm_s_val_a : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal amm_s_val_x : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal amm_s_val_b : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal amm_s_val_n : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal amm_m_ready : std_logic; signal amm_m_valid : std_logic; signal amm_m_res : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); -- Signals connected to ADD-MULT module signal add_mult_s_ready : std_logic; signal add_mult_s_valid : std_logic; signal add_mult_s_val_a : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal add_mult_s_val_x : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal add_mult_s_val_b : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal add_mult_m_ready : std_logic; signal add_mult_m_valid : std_logic; signal add_mult_m_res : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); -- Output signals signal res_x : std_logic_vector(2 * G_DATA_SIZE - 1 downto 0); signal res_p : std_logic_vector(G_DATA_SIZE - 1 downto 0); signal res_w : std_logic; begin fsm_proc : process (clk_i) begin if rising_edge(clk_i) then if m_ready_i = '1' then m_valid_o <= '0'; end if; -- Set default values res_x <= C_ZERO & C_ZERO; res_p <= C_ZERO; res_w <= '0'; sqrt_s_valid <= '0'; divmod_s_valid <= '0'; amm_s_valid <= '0'; add_mult_s_valid <= '0'; case state is when IDLE_ST => null; when SQRT_ST => -- Wait until data is ready if sqrt_s_valid = '0' and sqrt_m_valid = '1' then assert (divmod_s_ready = '1' and amm_s_ready = '1' and add_mult_s_ready = '1') or rst_i = '1'; -- Store input values val_2root <= sqrt_m_res(G_DATA_SIZE - 2 downto 0) & '0'; -- Let: p_0 = 1, r_0 = 0, x_0 = 1. p_prev <= C_ONE; r_prev <= C_ZERO; x_prev <= C_ZERO & C_ONE; -- Let: p_1 = N - M*M, s_1 = 2*M, w_1 = -1, x_1 = M. p_cur <= sqrt_m_diff(G_DATA_SIZE - 1 downto 0); s_cur <= sqrt_m_res(G_DATA_SIZE - 2 downto 0) & '0'; w_cur <= '1'; x_cur <= C_ZERO & sqrt_m_res; -- Store output values m_valid_o <= '1'; -- Start calculating a_n and p_n. divmod_s_valid <= '1'; state <= CALC_AR_ST; end if; when CALC_AR_ST => if divmod_s_valid = '0' and divmod_m_valid = '1' then -- Store new values of a_n and r_n a_cur <= divmod_m_res_q; r_cur <= divmod_m_res_r; -- Start calculating x_(n+1) and p_(n+1). amm_s_valid <= '1'; add_mult_s_valid <= '1'; state <= CALC_XP_ST; end if; when CALC_XP_ST => if amm_s_valid = '0' and amm_m_valid = '1' and add_mult_s_valid = '0' and add_mult_m_valid = '1' and (m_ready_i = '1' or m_valid_o = '0') then -- Update recursion s_cur <= s_new; p_cur <= p_new; w_cur <= w_new; x_cur <= x_new; p_prev <= p_cur; r_prev <= r_cur; x_prev <= x_cur; -- Store output values m_valid_o <= '1'; -- Start calculating a_n and p_n. divmod_s_valid <= '1'; state <= CALC_AR_ST; end if; end case; -- A start command should be processed from any state if s_start_i = '1' then m_valid_o <= '0'; val_n <= s_val_i; sqrt_s_valid <= '1'; state <= SQRT_ST; if s_val_i = 0 then sqrt_s_valid <= '0'; state <= IDLE_ST; end if; end if; if rst_i = '1' then m_valid_o <= '0'; sqrt_s_valid <= '0'; state <= SQRT_ST; end if; end if; end process fsm_proc; -- Calculate M=floor(sqrt(N)). sqrt_s_data <= val_n; -- Calculate a_n = s_n/p_n and r_n = s_n-a_n*p_n. divmod_s_val_n <= s_cur; divmod_s_val_d <= p_cur; -- Calculate x_(n+1) = (a_n * x_n + x_(n-1)) mod N. amm_s_val_a <= C_ZERO & a_cur; amm_s_val_x <= x_cur; amm_s_val_b <= x_prev; amm_s_val_n <= val_n; x_new <= amm_m_res; -- Calculate p_(n+1) = p_(n-1) + a_n*[r_n - r_(n-1)]. add_mult_s_val_a <= a_cur; add_mult_s_val_x <= r_cur - r_prev; add_mult_s_val_b <= C_ZERO & p_prev; p_new <= add_mult_m_res(G_DATA_SIZE - 1 downto 0); -- Calculate s_(n+1) = 2*M - r_n. s_new <= val_2root - r_cur; -- Calculate w_(n+1) = - w_n. w_new <= not w_cur; -------------------- -- Instantiate SQRT -------------------- sqrt_m_ready <= m_ready_i or not m_valid_o; sqrt_inst : entity work.sqrt generic map ( G_DATA_SIZE => G_DATA_SIZE ) port map ( clk_i => clk_i, rst_i => rst_i, s_ready_o => sqrt_s_ready, s_valid_i => sqrt_s_valid, s_data_i => sqrt_s_data, m_ready_i => sqrt_m_ready, m_valid_o => sqrt_m_valid, m_res_o => sqrt_m_res, m_diff_o => sqrt_m_diff ); -- sqrt_inst ---------------------- -- Instantiate DIVMOD ---------------------- divmod_m_ready <= m_ready_i or not m_valid_o; divmod_inst : entity work.divmod generic map ( G_DATA_SIZE => G_DATA_SIZE ) port map ( clk_i => clk_i, rst_i => rst_i, s_ready_o => divmod_s_ready, s_valid_i => divmod_s_valid, s_val_n_i => divmod_s_val_n, s_val_d_i => divmod_s_val_d, m_ready_i => divmod_m_ready, m_valid_o => divmod_m_valid, m_res_q_o => divmod_m_res_q, m_res_r_o => divmod_m_res_r ); -- divmod_inst ---------------------- -- Instantiate AMM ---------------------- amm_m_ready <= m_ready_i or not m_valid_o; amm_inst : entity work.amm generic map ( G_DATA_SIZE => G_DATA_SIZE ) port map ( clk_i => clk_i, rst_i => rst_i, s_ready_o => amm_s_ready, s_valid_i => amm_s_valid, s_val_a_i => amm_s_val_a, s_val_x_i => amm_s_val_x, s_val_b_i => amm_s_val_b, s_val_n_i => amm_s_val_n, m_ready_i => amm_m_ready, m_valid_o => amm_m_valid, m_res_o => amm_m_res ); -- amm_inst ------------------------ -- Instantiate ADD_MULT ------------------------ add_mult_m_ready <= m_ready_i or not m_valid_o; add_mult_inst : entity work.add_mult generic map ( G_DATA_SIZE => G_DATA_SIZE ) port map ( clk_i => clk_i, rst_i => rst_i, s_ready_o => add_mult_s_ready, s_valid_i => add_mult_s_valid, s_val_a_i => add_mult_s_val_a, s_val_x_i => add_mult_s_val_x, s_val_b_i => add_mult_s_val_b, m_ready_i => add_mult_m_ready, m_valid_o => add_mult_m_valid, m_res_o => add_mult_m_res ); -- add_mult_inst -------------------------- -- Connect output signals -------------------------- m_res_x_o <= x_cur; m_res_p_o <= p_cur; m_res_w_o <= w_cur; end architecture synthesis;
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { MonPremierComponent } from './mon-premier/mon-premier.component'; import { AppareilComponent } from './appareil/appareil.component'; import {FormsModule} from "@angular/forms"; import {AppareilService} from "./services/appareil.service"; import { AuthComponent } from './auth/auth.component'; import { AppareilViewComponent } from './appareil-view/appareil-view.component'; import {RouterModule, Routes} from "@angular/router"; const appRoutes: Routes = [ {path: 'appareils', component: AppareilViewComponent}, {path: 'auth', component: AuthComponent}, {path: '', component:AppareilViewComponent} ] @NgModule({ declarations: [ AppComponent, MonPremierComponent, AppareilComponent, AuthComponent, AppareilViewComponent, ], imports: [ BrowserModule, AppRoutingModule, FormsModule, RouterModule.forRoot(appRoutes) ], providers: [ AppareilService ], bootstrap: [AppComponent] }) export class AppModule { }
<!DOCTYPE html> <html lang="pt-br"> <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>Links</title> <style> body { font-family: Arial, Helvetica, sans-serif; } a { font-family: 'Times New Roman', Times, serif; color: blueviolet; text-decoration: none; font-weight: bold; font-size: 1.2em; } a:hover { background-color: rgb(255, 255, 131); padding: 3px; } a:active { color: black; background-color: rgba(0, 0, 0, 0); } a:visited { color: ; } a::after { content: ' [link]'; color: lightgray; font-size: 0.8em; font-weight: normal; } a::before { content: '✶ '; } .especial { background-color: aqua; padding: 3px; } .especial::after { content: none; } .especial:hover { background-color: black; } </style> </head> <body> <h1>Personalizando Links</h1> <p>Usando Pseudo-Classes e Pseudo-Elementos para estilizar links</p> <ul> <p><li><a href="https://erikasarti.com/html/dingbats-simbolos-desenhos/" target="_blank" rel="external">Ir para Símbolos</a></li></p> <p><li><a href="https://erikasarti.com/html/dingbats-simbolos-desenhos/" target="_blank" rel="external" class="especial">Ir para Círculo de Cores</a></li></p> <p><li><a href="https://erikasarti.com/html/dingbats-simbolos-desenhos/" target="_blank" rel="external">Ir para Emojis</a></li></p> </ul> </body> </html>
<template> <div class="w-full p-10px"> <TableMaster :columns="columns" :fetch-api="fetchUserData" ref="tableRef"> <template #controls="{ record }"> <a-space warp> <a-button type="dashed" size="small" @click="onOpenDrawer(record)"> 编辑 </a-button> <a-popconfirm title="请确认是否执行删除?" @confirm="onRemove(record)"> <a-button type="dashed" size="small" danger>删除</a-button> </a-popconfirm> </a-space> </template> <!-- <template #table-above> <a-button type="primary" @click="onOpenDrawer()"> 新增 </a-button> </template> --> </TableMaster> <a-drawer v-model:open="visible" title="编辑用户" width="60%" :footer-style="{ textAlign: 'right' }" > <FormMaster ref="formRef" :items="formItems" :form-props="formProps" v-model:model="formModel" @update:model="onUpdateModel" > <!-- <template #description="data"> 默认</template> <template #description-label="data"> label </template> --> </FormMaster> <template #footer> <a-space warp> <a-button @click="visible = false">取消</a-button> <a-button type="primary" @click="onSubmit">提交</a-button> </a-space> </template> </a-drawer> </div> </template> <script setup lang="ts"> import TableMaster from '@/components/table-master/index.vue'; import { tableColumns } from './columns'; import { formItems } from './formItems'; import { ref, UnwrapRef } from 'vue'; import { fetchUserData, UserData, deleteUserById, saveUser } from '@/api/user.api'; import FormMaster from '@/components/form-master/index.vue'; import { reactive } from 'vue'; import { FormProps, message, Modal } from 'ant-design-vue'; const columns = ref(tableColumns); const visible = ref(false); type UnPromisify<T> = T extends Promise<infer U> ? U : T; type UnPromisifyData<Api extends (...args: any) => Promise<any>> = UnPromisify<ReturnType<Api>>; type UnData = UnPromisifyData<typeof fetchUserData>['list'] extends (infer U)[] ? U : never; const formModel: UnwrapRef<Partial<UnData>> = reactive({}); const formProps: FormProps = { labelCol: { span: 5 }, wrapperCol: { span: 13 }, model: formModel, rules: { name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }], }, }; const tableRef = ref<GenericComponentExports<typeof TableMaster>>(); const initModel = formItems.reduce( (acc, cur) => { acc[cur.name] = cur.defaultValue ?? null; return acc; }, { id: null } as Record<string, any> ); function onOpenDrawer(record?: UserData) { if (!record?.id) { Object.assign(formModel, initModel); } visible.value = true; Object.assign(formModel, record); } function onUpdateModel(val: UnwrapRef<Partial<UnData>>) { // Object.assign(formModel, val); } function onRemove(record: UserData) { deleteUserById(record).then(() => { tableRef.value?.getData(); message.success('删除成功'); }); } const formRef = ref<GenericComponentExports<typeof FormMaster>>(); function onSubmit() { formRef.value?.submit().then((params: UserData) => { Modal.confirm({ title: '确认提交', content: '请确认是否执行提交?', centered: true, onOk() { saveUser({ ...params, id: formModel.id!, }).then(() => { tableRef.value?.getData(); message.success('提交成功'); visible.value = false; }); }, }); }); } </script> <style scoped></style> ./src/form-master/index.vue ./src/table-master/index.vue
# Detecting-COVID-19-from-Chest-CT-Scans As the Coronavirus Disease 2019 (COVID-19) pandemic continues to challenge many countries around the world, testing to detect COVID-19 and isolating individuals who test positive remains a crucial strategy for preventing community spread of the disease. In this context, automatic and accurate detection of COVID-19 using medical imaging modalities, such as Computed Tomography (CT), can be beneficial as a diagnostic tool. In this exercise, our goal is to develop Convolutional Neural Networks to automatically detect the subtle signs of COVID-19 infection in patients' lungs from CT images. Our dataset contains 1010 CT scans from individuals with COVID-19 and 1010 CT scans from patients with other pulmonary diseases (non-COVID-19). These data have been collected from real patients in hospitals from Sao Paulo, Brazil. Our training and validation sets include 1600 and 420 CT images, respectively (half COVID-19, half non-COVID-19). Given the small size of the original dataset, I did not set aside any images for the test set. We will use the validation accuracy to evaluate our models. This is OK since we are not going to use the validation performance as a feedback signal to fine tune the hyperparameters of our models. Your task is to classify the images correctly by building multiple CNNs and comparing their performance. Here are what a few of the CT images look like: ![ct-covid](https://www.dropbox.com/s/r9lld9dj7875rsw/ct-covid.jpg?dl=1) ## Note on training time I recommend you train your CNNs on GPU for faster training. To do so, from the Runtime tab above, go to Change runtime type and select GPU as Hardware accelerator. Training time of each model may take up to an hour on GPU (longer on CPU), so please be patient. ## Load the data First, add the `covid19_ct` folder from [here](https://drive.google.com/drive/folders/11-2z9P45FtJJPm9LbipVMAnNZ36kMQUH) to your Google Drive. For example, you can drag and drop the `covid19_ct` folder into your "My Drive"; this will add a shortcut to the original folder in your "My Drive". By doing so, you can run your code directly on the data that are stored on my Google Drive account without the need to download the images and upload them to your Drive. Mount your Google Drive and load the data. Be sure to change the directory path provided below to your own data path.
from django.db import models from ckeditor_uploader.fields import RichTextUploadingField # RichTextField yerine kullanacağız from django.utils.text import slugify class BlogPost(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True, blank=True) content = RichTextUploadingField() # RichTextField yerine RichTextUploadingField meta_description = models.CharField(max_length=160, blank=True) # Meta açıklama alanı main_description = models.TextField(blank=True) # Ana açıklama alanı created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title class NewsletterSubscriber(models.Model): email = models.EmailField(unique=True) subscribed_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email
-Usage: Usualy use two argument of main() to parse command, if have many argument, it's easy confuse to parse argument. On Linux, we can utilize "getopt()", "getopt_long" and "getopt_long_only" to parse many command argument. -Definition: #include <unistd.h> int getopt(int argc, char * const argv[], const char optstring); extern char *optarg; extern int optind, opterr, optopt; #include <getopt.h> int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex); int getopt_long_only(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex); -Illustrate: 1. getopt The getopt() has two arguments "argc" and "argv" which is from main() directly. And it has third argument "optstring". The format of "optstring" is "ab:cd" etc. After passing argument to getopt(), it will check firstly whether the command contain specify argument, like "-a", "-b", "-c" and "-d". In order to check argument, you should call getopt time and again. If the specify argument has colon on "optstring" and it need a specify value with passing argument. eg: optstring = "a:bcd:" command: ./execute -a=100 -b -c -d 200 2. getopt_long The "longopts" points a array that constitute the structure of "option", the definition of "otption" as follow: struct option { const char *name; int has_arg; int *flag; int val; }; "name": argument's name. "has_arg": points out whether argument has value. it's optional: no_argument: indicate argument has not value(eg --name) required_argument: indicate argument must has a vlaue(eg --name Buddy) optional_argument: indicate that value is optional(eg --name or --name Bud) "flag": when this pointer is null, getopt_long() will return value of "val" directly. But it is non-null, "val" will assigment its value to a integer value that is pointed by flag and getopt_long return zero. "val": used to indicate the return value when match correct option.
import React from "react"; import styled from "styled-components"; import { Link } from "react-router-dom"; const Container = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 50px 0px; width: 100vw; `; const Row = styled.div` width: 100%; `; const Col = styled.div` display: flex; flex-direction: column; &.Description { height: 250px; } `; const NameTitle = styled.p` font-weight: 700; font-size: 2.5em; text-align: center; padding: 20px; padding-top: 0; padding-bottom: 0; &.Subtitles { font-size: 1.8rem; text-align: start; } @media (max-width: 590px) { font-size: 2.5rem; } `; const Text = styled.p` font-weight: 300; font-size: 1.2rem; text-align: center; margin: 0; padding: 20px; padding-top: 0; padding-bottom: 0; &.Subtitle { color: #555; padding-bottom: 50px; } &.Description { color: #666666; text-align: left; margin: 10px auto; } &.ProjectTextTitle { font-weight: 700; font-size: 2rem; text-align: left; } &.ProjectTextSubTitle { text-align: left; } `; const Project = styled.div` width: 100%; height: 450px; display: flex; justify-content: center; align-items: center; gap: 20px; margin-bottom: 50px; @media (max-width: 950px) { flex-direction: column; height: auto; } `; const ImgBox = styled.div` height: 80%; width: 60%; display: flex; justify-content: center; align-items: center; @media (min-width: 960px) { min-width: 500px; } @media (max-width: 600px) { min-width: 400px; } `; const Img = styled.img` height: 100%; width: 100%; `; const DescriptionProject = styled.div` height: 400px; width: auto; display: flex; flex-direction: column; justify-content: center; align-items: start; gap: 20px; @media (max-width: 950px) { height: auto; width: 90%; } `; const Buttons = styled(Link)` font-size: 1rem; height: 50px; width: 150px; display: flex; align-items: center; justify-content: center; border-radius: 5px; background-color: #f25709; color: white; text-decoration: none; font-weight: 700; box-shadow: 5px 5px 15px 1px #bbb; margin: 20px; &:hover { transform: translateY(-3px); transition: transform 0.15s ease-in-out; } `; const Projects = () => { return ( <Container> <Row className="row"> <Col className="col-xl-8 col-lg-9 col-11 justify-content-center m-auto Description"> <NameTitle>PROJECTS</NameTitle> <Text className="Subtitle"> Here you will find some of the personal and clients projects that I created with each project containing its own link </Text> </Col> <Col className="col-xl-10 col-lg-11 col-12 justify-content-center m-auto"> <Project> <ImgBox> <Img alt="EDTA Learn" src={require("../files/EDTA Learn.png")} ></Img> </ImgBox> <DescriptionProject> <Text className="ProjectTextTitle">EDTA Learn</Text> <Text className="ProjectTextSubTitle"> This project is dedicated to a virtual learning object (VLO) centered on potentiometric assessments of chelation formation with EDTA. As a significant component of an undergraduate thesis, it delivers impactful educational content in this specialized field. </Text> <Buttons to="https://edtalearn.netlify.app" target="_blank"> SEE PROJECT </Buttons> </DescriptionProject> </Project> <Project> <ImgBox> <Img alt="Weather App" src={require("../files/Weather App.png")} ></Img> </ImgBox> <DescriptionProject> <Text className="ProjectTextTitle">Weather App</Text> <Text className="ProjectTextSubTitle"> The Real-Time Weather and Points of Interest Dashboard is a React.js web application designed to provide users with up-to-date weather information and interesting details about a diverse set of cities and towns worldwide. The application leverages weather APIs to fetch real-time weather data, including temperature, humidity, and wind speed, ensuring users have the latest meteorological information. </Text> <Buttons to="https://weatherglobalapp.netlify.app" target="_blank" > SEE PROJECT </Buttons> </DescriptionProject> </Project> </Col> </Row> </Container> ); }; export default Projects;
/*--------------------------------------------------------------------------------* Copyright (C)Nintendo All rights reserved. These coded instructions, statements, and computer programs contain proprietary information of Nintendo and/or its licensed developers and are protected by national and international copyright laws. They may not be disclosed to third parties or copied or duplicated in any form, in whole or in part, without the prior written consent of Nintendo. The content herein is highly confidential and should be handled accordingly. *--------------------------------------------------------------------------------*/ #pragma once #include <nn/font/font_Types.h> #include <nn/font/font_Util.h> namespace nn { namespace font { template <typename CharType> class TextWriterBase; template <typename CharType> class PrintContext { public:// TODO:アクセサ TextWriterBase<CharType>* writer; //!< 文字列描画に使用しているTextWriterへのポインタ。 const CharType* str; //!< 描画中の文字列へのポインタ。 const CharType* strEnd; //!< 描画中の文字列の終端のポインタ。 const float xOrigin; //!< 描画開始X座標。 const float yOrigin; //!< 描画開始Y座標。 const float hScale; //!< 描画開始時点の水平方向スケール。 const float vScale; //!< 描画開始時点の垂直方向スケール。 uint32_t flags; //!< TextWriter::ContextFlag のOR。 uint32_t prevCode; //!< ひとつ前の文字。カーニングの値を求めるために使用します。 PrintContext( TextWriterBase<CharType>* aWriter, const CharType* aStr, const CharType* aStrEnd, const float aXOrigin, const float aYOrigin, const float aHScale, const float aVScale, uint32_t aFlags ) : writer(aWriter), str(aStr), strEnd(aStrEnd), xOrigin(aXOrigin), yOrigin(aYOrigin), hScale(aHScale), vScale(aVScale), flags(aFlags), prevCode(0) {} private: // コピー演算子を禁止します。 const PrintContext& operator=( const PrintContext& rhs); }; #if defined( __CC_ARM ) || defined( __ARMCC_VERSION ) #pragma push #pragma diag_suppress 2819 // class XXX has an implicitly instantiated key function YYY #endif //--------------------------------------------------------------------------- //! @brief グリフグループが定義されているフォントリソースを扱うクラスです。 //! //! @tparam CharType 文字の型。 //--------------------------------------------------------------------------- template <typename CharType> class TagProcessorBase { public: //! 実行時型情報です。 NN_FONT_RUNTIME_TYPEINFO_ROOT(); /* ------------------------------------------------------------------------ 型 ------------------------------------------------------------------------ */ typedef PrintContext<CharType> ContextType; //! 呼び出し元 (TextWriter) が行うべき処理の列挙子です。 enum Operation { //! @brief 行頭では次の文字との間に文字間を開けません。 //! 行頭以外の位置では次の文字との間に文字間を開けます。 //! Operation_Default, //! @brief 行頭以外の位置でタグ処理が行われた場合、 //! デフォルトでは次の文字との間に文字間を空けますが、 //! これを空けないようにします。 //! Operation_NoCharSpace, //! @brief 行頭でタグ処理が行われた場合、 //! デフォルトでは次の文字との間に文字間を空けませんが、 //! これを空けるようにします。 //! Operation_CharSpace, //! @brief 改行時に必要な処理のうち X 座標の調整のみを行います。 //! Y 座標の調整は行いません。 //! また、次の文字との間に文字間を開けません。 //! Operation_NextLine, //! @brief 文字列の途中で文字列描画を終了する場合に使用します。 //! Operation_EndDraw, //! @brief 内部用機能のため使用禁止です。 Operation_MaxOperation }; /* ------------------------------------------------------------------------ 関数 ------------------------------------------------------------------------ */ //! @name コンストラクタ / デストラクタ //@{ //! コンストラクタです。 TagProcessorBase(); //! デストラクタです。 virtual ~TagProcessorBase(); //@} //! @name タグ処理 //@{ //! @brief タグに従って処理を行います。 //! //! @param[in] code タグ処理の起点となった制御文字コード。(0x0000 ~ 0x001F) //! @param[in] pContext 文字列の描画状態情報へのポインタ。 //! //! @return 呼び出し元 (TextWriter) が行うべき処理を返します。 //! virtual Operation Process( uint32_t code, PrintContext<CharType>* pContext); //! @brief タグの影響範囲を計算します。 //! //! @param[out] pRect タグの影響範囲を格納する矩形構造体へのポインタ。 //! @param[in] pContext 文字列の描画状態情報へのポインタ。 //! @param[in] code タグ処理の起点となった制御文字コード。(0x0000 ~ 0x001F) //! //! @return 呼び出し元 (TextWriter) が行うべき処理を返します。 //! 同じタグに対して Process() 関数が返す値と同じ値を返すべきです。 //! virtual Operation CalculateRect( nn::font::Rectangle* pRect, PrintContext<CharType>* pContext, uint32_t code); //! @brief 行の高さを返します。 //! //! @details //! デフォルトの実装では、「フォントが持つ改行幅 * スケール Y + 行間」で計算される値が返ります。 //! タグによって文字のスケールを変えたときに、想定よりも行の高さが空いてしまうときには //! このメソッドをオーバーライドすることで行の高さを調整することができます。 //! //! @param[in] pTextWriter TextWriter へのポインタ。 //! //! @return 行の高さです。 //! virtual float GetLineHeight(const TextWriterBase<CharType>* pTextWriter) const; //@} //! @name 処理開始/終了コールバック //@{ //! @brief テキスト全体のプリントを行う前に呼び出されるコールバックです。 //! //! @param[in] pContext 文字列の描画状態情報へのポインタ。 //! virtual void BeginPrint(PrintContext<CharType>* pContext); //! @brief テキスト全体のプリントを行った後に呼び出されるコールバックです。 //! //! @param[in] pContext 文字列の描画状態情報へのポインタ。 //! virtual void EndPrint(PrintContext<CharType>* pContext); //! @brief テキスト一行の占める領域の計算を行う前に呼び出されるコールバックです。 //! //! @param[in] pContext 文字列の描画状態情報へのポインタ。 //! virtual void BeginCalculateRect(PrintContext<CharType>* pContext); //! @brief テキスト一行の占める領域の計算を行った後に呼び出されるコールバックです。 //! //! @param[in] pContext 文字列の描画状態情報へのポインタ。 //! virtual void EndCalculateRect(PrintContext<CharType>* pContext); //! @brief テキスト全体のプリントを行う前に呼び出されるコールバックです。 //! //! @details //! nn::font::TagProcessorBase::BeginPrint は、改行位置を計算した後に呼ばれます。 //! 改行位置の計算に使うパラメータを設定しておくなど、 //! 改行位置を計算する前に呼びたい場合は本メソッドをお使いください。 //! //! @param[in] pTextWriter TextWriter へのポインタ。 //! @param[in] pString 文字列の先頭のポインタ。 //! @param[in] pEnd 文字列の終端のポインタ。 //! virtual void BeginPrintWhole(const TextWriterBase<CharType>* pTextWriter, const CharType* pString, const CharType* pEnd); //! @brief テキスト全体のプリントを行った後に呼び出されるコールバックです。 //! //! @details //! nn::font::TagProcessorBase::EndPrint と同じタイミングで呼ばれます。 //! //! @param[in] pTextWriter TextWriter へのポインタ。 //! @param[in] pString 文字列の先頭のポインタ。 //! @param[in] pEnd 文字列の終端のポインタ。 //! virtual void EndPrintWhole(const TextWriterBase<CharType>* pTextWriter, const CharType* pString, const CharType* pEnd); //! @brief テキスト全体の占める領域の計算を行う前に呼び出されるコールバックです。 //! //! @details //! nn::font::TagProcessorBase::BeginCalculateRect は、テキスト 1 行ごとにコールバックが呼び出されます。 //! テキスト全体に対して 1 回だけ呼び出されたい場合は本メソッドをお使いください。 //! //! @param[in] pTextWriter TextWriter へのポインタ。 //! @param[in] pString 文字列の先頭のポインタ。 //! @param[in] pEnd 文字列の終端のポインタ。 //! virtual void BeginCalculateRectWhole(const TextWriterBase<CharType>* pTextWriter, const CharType* pString, const CharType* pEnd); //! @brief テキスト全体の占める領域の計算を行った後に呼び出されるコールバックです。 //! //! @details //! nn::font::TagProcessorBase::EndCalculateRect は、テキスト 1 行ごとにコールバックが呼び出されます。 //! テキスト全体に対して 1 回だけ呼び出されたい場合は本メソッドをお使いください。 //! //! @param[in] pTextWriter TextWriter へのポインタ。 //! @param[in] pString 文字列の先頭のポインタ。 //! @param[in] pEnd 文字列の終端のポインタ。 //! virtual void EndCalculateRectWhole(const TextWriterBase<CharType>* pTextWriter, const CharType* pString, const CharType* pEnd); //! @brief 描画可能な文字の位置を返すコールバックです。 //! //! @details //! このメソッドは、呼び出し元が描画可能な文字を得るために使用します。 //! 与えられた position の位置の文字が描画可能かどうかを pIsPrintable に設定し、 //! position の次の文字の位置を返します。 //! //! @param[out] pIsPrintable position の位置の文字が描画可能かどうか。 //! @param[in] position 呼び出し元から与えられる位置。 //! //! @return position の次の文字の位置。 //! virtual const CharType* AcquireNextPrintableChar(bool* pIsPrintable, const CharType* position); //@} private: void ProcessLinefeed(ContextType* pContext) const; void ProcessTab(ContextType* pContext) const; }; #if defined( __CC_ARM ) || defined( __ARMCC_VERSION ) #pragma pop #endif } // namespace font } // namespace nn
import wollok.game.* import elementos.* class Animacion { // el nombre es requerido para poder deterner el evento automático const property nombreAnimacion = "animacion_" + 0.randomUpTo(999999).toString() const fotogramas = [] //velocidad en fotogramas por segundo var velocidad = 0 var fotogramaActual = 0 var animando = false const reproduccionContinua = true method velocidad() = velocidad method velocidad(nuevaVelocidad) { velocidad = nuevaVelocidad } method animando() = animando method agregarFotograma(img) { fotogramas.add(img) } method image() = if(fotogramas.isEmpty()) "" else fotogramas.get(fotogramaActual) // reinicia la secuencia de la animación method resetear() { fotogramaActual = 0 } // establece el siguiente fotograma method siguiente() { // solo muevo al siguiente fotograma si hay alguno if(!fotogramas.isEmpty()) { fotogramaActual = (fotogramaActual + 1) % fotogramas.size() } } // Inicia la animación method iniciar() { if(velocidad != 0) { animando = true game.onTick(1000 / velocidad, nombreAnimacion, { if (!reproduccionContinua and fotogramaActual == fotogramas.size()-1){ self.detener() // self.resetear() }else{ self.siguiente() } }) } } method detener() { if(animando) { animando = false game.removeTickEvent(nombreAnimacion) } } method irAFotograma(numeroFotograma) { fotogramaActual = numeroFotograma } } // representa una Animación Nula // se utiliza para inicializar personajes sin animación inicial object nullAnimacion inherits Animacion( velocidad=0, fotogramas=["nada.png"] ) { override method velocidad(nuevaVelocidad) {} override method agregarFotograma(img) { self.error("no se puede agregar fotogramas a esta animación") } }
import React, { useState, useEffect, useMemo } from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import AuthContext, { AuthProvider } from './services/AuthContext'; import LoginScreen from './components/LoginScreen'; import OfferScreen from './components/OfferScreen'; import ProfilePage from './components/ProfileScreen'; import CreateAccountScreen from './components/CreateAccount'; import ForgotPasswordScreen from './components/ForgotPassword'; import LoadingScreen from './components/LoadingScreen'; import Toast from 'react-native-toast-message'; const Stack = createStackNavigator(); export default function App() { return ( <AuthProvider> <NavigationContainer> <Stack.Navigator initialRouteName="AuthLoading" screenOptions={{ headerShown: false, // This will hide the header for all screens }}> <Stack.Screen name="AuthLoading" component={LoadingScreen} /> <Stack.Screen name="Login" component={LoginScreen} /> <Stack.Screen name="Profile" component={ProfilePage} /> <Stack.Screen name='CreateAccount' component={CreateAccountScreen} /> <Stack.Screen name='Offers' component={OfferScreen} /> <Stack.Screen name='forgotPassword' component={ForgotPasswordScreen} /> </Stack.Navigator> <Toast /> </NavigationContainer> </AuthProvider> ); }
package com.example.testSGCIB.model; import com.example.testSGCIB.exception.MowerDirectionException; import lombok.extern.slf4j.Slf4j; import java.awt.*; import java.util.List; import static com.example.testSGCIB.model.Direction.*; @Slf4j public class Mower { private Point position; private Direction direction; public Mower(String[] data) throws MowerDirectionException { this.position = new Point(Integer.parseInt(data[0]),Integer.parseInt(data[1])); this.direction = Direction.of(data[2]); } public Point getPosition() { return position; } public void setPosition(Point position) { this.position = position; } public Direction getDirection() { return direction; } public void setDirection(Direction direction) { this.direction = direction; } //this method return the mower position and direction as a String public String getMowerPosition() { return (int) position.getX() + " " + (int) position.getY() + " " + direction.prefix; } //this method switch by 90° the direction of the mower public void switchDirection(boolean leftRotation) throws MowerDirectionException { if(leftRotation) { switch (direction) { case NORTH -> direction = WEST; case WEST -> direction = SOUTH; case SOUTH -> direction = EAST; case EAST -> direction = NORTH; default -> throw new MowerDirectionException(); } } else { switch (direction) { case NORTH -> direction = EAST; case WEST -> direction = NORTH; case SOUTH -> direction = WEST; case EAST -> direction = SOUTH; default -> throw new MowerDirectionException(); } } } //this method advance the mower in the provided direction if it is possible public void advanceMower(Point mapSize, List<Point> mowersFinalPositions) throws MowerDirectionException { switch (direction) { case NORTH -> { if (position.getY() < mapSize.getY() && checkPossibleTranslation(position.getX(),position.getY()+1,mowersFinalPositions)) position.translate(0, 1); else log.warn("End of map reached or an already mower was fond"); } case EAST -> { if (position.getX() < mapSize.getX() && checkPossibleTranslation(position.getX()+1,position.getY(),mowersFinalPositions)) position.translate(1, 0); else log.warn("End of map reached or an already mower was fond"); } case WEST -> { if (position.getX() > 0 && checkPossibleTranslation(position.getX()-1,position.getY(),mowersFinalPositions)) position.translate(-1, 0); else log.warn("End of map reached or an already mower was fond"); } case SOUTH -> { if (position.getY() > 0 && checkPossibleTranslation(position.getX(),position.getY()-1,mowersFinalPositions)) position.translate(0, -1); else log.warn("End of map reached or an already mower was fond"); } default -> throw new MowerDirectionException(); } } //this method check if the translation of the mower is possible private boolean checkPossibleTranslation(double x,double y,List<Point> mowersFinalPositions){ return !mowersFinalPositions.contains(new Point((int) x,(int) y)); } @Override public String toString() { return "Mower{" + "Position=" + position + ", direction=" + direction + '}'; } }
--- marp: true theme: my-theme paginate: true header: 창의융합인재 프로그램 3기 footer: 공학도서관 --- ###### 창의융합인재 프로그램 3기 # 데이터를 읽고 쓰기 ###### 2024년 5월 9일 --- # 목차 - 데이터 통신: I2C - I2C 실습 - 조도센서 - 조도센서를 파일에 쓰기 --- <!--paginate: true --> ## 기술 도구를 사용한 읽고 쓰기는 ## 우리에게 어떤 의미인가? --- ## 사람 간의 언어 vs 기계 간의 언어 --- # 프로토콜 ![width:10000px](./img/I2C_Basic_Address_and_Data_Frames.jpg) --- # I2C ![width:1000px](./img/I2C-Block-Diagram.jpg) --- # 복습하기 ### Thonny의 실행하고 폴더 경로 맞추기 1. Thonny 실행 2. 이 컴퓨터 -> C 드라이브 -> Users -> 사용자명 -> Desktop(더블클릭) 3. 새로운 디렉토리 -> 'Project' 폴더 생성 4. Project 폴더 안 -> '0509_DataPi' 폴더 생성 5. 파일 -> 새 파일 --- ### Thonny의 실행하고 폴더 경로 맞추기 결과 ![width:10000px ](img/finaloutput.png) --- # 복습하기 2. 데이타 파이 보드 연결하기 3. micropython 연결하기 --- ### I2C 실습 -1 ``` python from machine import Pin from machine import I2C ``` : I2C 라이브러리 가져오기 --- ### I2C 실습 -2 ```python sdaPIN = Pin(4) sclPIN = Pin(5) i2c = I2C(0, sda=sdaPIN, scl=sclPIN) devices = i2c.scan() ``` : I2C 통신을 위한 준비 --- ### I2C 실습 -3 ```python if len(devices) == 0: print("No I2C device") else: print("I2C device found :", len(devices)) for device in devices: print(" Hexa address: ", hex(device)) ``` : 연결된 I2C 정보 확인하기 --- ### I2C 실습 -완료 ```python from machine import Pin from machine import I2C sdaPIN = Pin(4) sclPIN = Pin(5) i2c = I2C(0, sda=sdaPIN, scl=sclPIN) devices = i2c.scan() if len(devices) == 0: print("No I2C device") else: print("I2C device found :", len(devices)) for device in devices: print(" Hexa address: ", hex(device)) ``` ```bash MPY: soft reboot I2C device found : 2 #I2C 통신이 가능한 디바이스 Hexa address: 0x23 #조도센서 Hexa address: 0x68 #RTC 모듈 ``` --- # 통신하기 ## 조도센서 --- # 준비 1. bh1750 라이브러리 [다운로드](https://github.com/AntonSangho/Dreamscometrue_Lecture/blob/main/lib/bh1750.py) 2. Rasberry pi Pico에 lib 폴더 만들기 3. bh1750.py 파일을 업로드 하기 --- ### 조도센서 실습 -1 ```python from machine import Pin, I2C from utime import sleep from bh1750 import BH1750 ``` : 조도센서 라이브러리 가져오기 --- ### 조도센서 실습 -2 ```python i2c0_sda = Pin(4) i2c0_scl = Pin(5) i2c0 = I2C(0, sda=i2c0_sda, scl=i2c0_scl) bh1750 = BH1750(0x23, i2c0) ``` : 조도 센서에 I2C연결하기 --- ### 조도센서 실습 -3 ```python while True: print(bh1750.measurement) sleep(1) ``` : 조도 센서에 값 출력하기 --- ### 조도센서 실습 -완료 ```python from machine import Pin, I2C from utime import sleep from bh1750 import BH1750 i2c0_sda = Pin(4) i2c0_scl = Pin(5) i2c0 = I2C(0, sda=i2c0_sda, scl=i2c0_scl) bh1750 = BH1750(0x23, i2c0) while True: print(bh1750.measurement) sleep(1) ``` ```bash 2411.667 166.6667 165.8333 ``` --- # 파일 쓰기 ## 조도센서 --- ### 파일 쓰기 실습 -1 ```python led = Pin("LED", Pin.OUT) sdaPIN = Pin(4) sclPIN = Pin(5) i2c = I2C(0, sda=sdaPIN, scl=sclPIN) bh1750 = BH1750(0x23, i2c) def writeLine(text): file = open("log.txt", "a") file.write(text + "\n") file.close() ``` : I2C 연결하고 쓰기 함수 --- ### 파일 쓰기 실습 -2 ```python while True: light = bh1750.measurement print(light) writeLine(str(light)) led.value(1) sleep(0.5) led.value(0) sleep(0.5) #sleep(1800) # 30 minutes ``` - 조도센서 값을 반복해서 쓰기 --- ### 파일 쓰기 실습 -완료 ```python from time import sleep from machine import I2C, Pin from bh1750 import BH1750 led = Pin("LED", Pin.OUT) sdaPIN = Pin(4) sclPIN = Pin(5) i2c = I2C(0, sda=sdaPIN, scl=sclPIN) bh1750 = BH1750(0x23, i2c) def writeLine(text): file = open("log.txt", "a") file.write(text + "\n") file.close() while True: light = bh1750.measurement print(light) writeLine(str(light)) led.value(1) sleep(0.5) led.value(0) sleep(0.5) #sleep(1800) # 30 minutes ``` --- # 정리 - 통신하기 - 데이터 읽어오기 - 데이터 쓰기 --- <body> <h1 style="text-align: center; color: white;">감사합니다.<h1> <h2 style="text-align: center; color: cyan">공학도서관</h2> <h2 style="text-align: center;" >www.gongdo.kr<h2> </body>
import { Button, Box } from "@mui/material"; import { StyledInput } from "./styled-input"; import DeleteIcon from "@mui/icons-material/Delete"; import { useFieldArray, useFormContext, FieldArray } from "react-hook-form"; import { Maturity } from "@talentdigital/season"; import { FormInputs } from "../types"; import { StyledSectionWrapper } from "."; import { StyledMultilineInputWrapper } from "./styled-multiline-wrapper"; type MaturityCode = `${Maturity}`; const maturityOptions: MaturityCode[] = ["ALPHA", "BETA", "PENDING", "PUBLIC"]; export const Episodes = () => { const { register, control, getValues } = useFormContext<FormInputs>(); const { fields: episodeFields, append: appendEpisode, remove: removeEpisode, } = useFieldArray({ control, name: "episodes", }); const handleRemoveEpisode = (index: number, episodeId: string) => { const values = getValues(); const usedInTestItems = values.testItems.some( (item) => item.episode === episodeId ); const usedInFeedbackQuestion = values.feedbackQuestions.some( (item) => item.episode === episodeId ); if (usedInTestItems || usedInFeedbackQuestion) { alert( "Cannot delete episode because it is used in a test item or a feedback question." ); return; } removeEpisode(index); }; return ( <> {episodeFields.map((episode, index) => ( <StyledSectionWrapper key={episode.id} indented> <Box sx={{ display: "flex", flexDirection: "column" }}> <StyledMultilineInputWrapper> <StyledInput> <label>Id</label> <input type="text" {...register(`episodes.${index}.episodeId` as const)} /> </StyledInput> <StyledInput> <label>Maturity</label> <select {...register(`episodes.${index}.maturity` as const)}> {maturityOptions.map((option) => ( <option value={option} key={option}> {option} </option> ))} </select> </StyledInput> <StyledInput> <label>Image Url</label> <input type="text" {...register(`episodes.${index}.imageUrl` as const)} /> </StyledInput> <StyledInput> <label>Format</label> <input type="text" {...register(`episodes.${index}.format` as const)} /> </StyledInput> <StyledInput> <label>Format configuration</label> <input type="text" {...register( `episodes.${index}.formatConfiguration` as const )} /> </StyledInput> </StyledMultilineInputWrapper> <StyledInput> <label>Title</label> <input type="text" {...register(`episodes.${index}.title` as const)} /> </StyledInput> <StyledInput> <label>Description</label> <input type="text" {...register(`episodes.${index}.description` as const)} /> </StyledInput> </Box> <Box sx={{ display: "flex", justifyContent: "flex-end" }}> <Button startIcon={<DeleteIcon />} variant="contained" color="error" onClick={() => handleRemoveEpisode(index, episode.episodeId)} > Remove episode </Button> </Box> </StyledSectionWrapper> ))} <StyledSectionWrapper indented> <div> <Button variant="contained" type="button" onClick={() => appendEpisode({ episodeId: getNewEpisodeId(episodeFields), title: "", description: "", maturity: "PUBLIC", imageUrl: "", format: "", formatConfiguration: "", }) } > Add Episode </Button> </div> </StyledSectionWrapper> </> ); }; function getNewEpisodeId( episodeFields: FieldArray<FormInputs, "episodes">[] ): string { if (episodeFields.length === 0) { return "1"; } const highestEpisodeId = episodeFields .map((episode) => Number(episode.episodeId)) .sort((a, b) => b - a)[0]; const maybeEpisodeNumber = String(highestEpisodeId + 1); return maybeEpisodeNumber === "NaN" ? "0" : maybeEpisodeNumber; }
package com.trkj.tsm.vo; import com.trkj.tsm.entity.SysMenu; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import org.springframework.validation.annotation.Validated; import java.util.ArrayList; import java.util.List; @Validated @Data @NonNull @NoArgsConstructor @AllArgsConstructor public class MenuVo { private Integer id; /** * 父菜单ID */ private Integer menuPid; /** * 当前菜单所有父菜单 */ private String menuPids; /** * 0:不是叶子节点,1:是叶子节点 */ private Byte isLeaf; /** * 菜单名称 */ private String menuName; /** * 允许客户端提交的方法get查询/post添加/put修改/delete删除 */ private String method; /** * 跳转URL */ private String url; /** * 组件名称 */ private String componentName; /** * 组件地址 */ private String componentPath; private String icon; private String iconColor; /** * 排序 */ private Byte sort; /** * 菜单层级 */ private Byte level; /** * 0:启用,1:禁用 */ private Byte status; private static final long serialVersionUID = 1L; /** * 侧边栏子菜单 */ private List<SysMenu> asideChildren = new ArrayList<SysMenu>(); }
import React, { useState } from 'react'; import './styles/Fridge.css'; import { foodIcons, SelectFoodFunction } from '../types'; import { RiFridgeFill } from "react-icons/ri"; const foodItems = [ { id: 1, name: 'Apple', hungerValue: 10 }, { id: 2, name: 'Banana', hungerValue: 15 }, { id: 3, name: 'Carrot', hungerValue: 5 } ]; interface FridgeProps { onSelectFood: SelectFoodFunction; } const Fridge: React.FC<FridgeProps> = ({ onSelectFood }) => { const [isOpen, setIsOpen] = useState(false); return ( <div> <button className="fridge-button" onClick={() => setIsOpen(true)}><RiFridgeFill/></button> {isOpen && ( <div className="modal"> <div className="modal-content"> <span className="close" onClick={() => setIsOpen(false)}>&times;</span> {foodItems.map(food => ( <button key={food.id} onClick={() => { onSelectFood(food); setIsOpen(false); }}> {foodIcons[food.name]} </button> ))} </div> </div> )} </div> ); }; export default Fridge;
import { Product } from './Product'; import { v4 as uuidV4 } from 'uuid'; describe('Product.ts', () => { it('should get/set id', () => { const product = new Product(); const uuid = uuidV4(); product.setID(uuid); expect(product.getID()).toBe(uuid); }); it('should enable the product if greater than zero', () => { const product = new Product(); product.setPrice(2.5); product.enable(); expect(product.getStatus() === 'enabled'); }); it('should throw an error if enables a product with price of zero', () => { const product = new Product('My Product'); expect(() => { product.enable(); }).toThrowError('The price must be greater than 0 to enable the product'); }); it('should disable the product if equals to zero', () => { const product = new Product(); product.setPrice(0); product.disable(); expect(product.getStatus() === 'disabled'); }); it('should throw an error if disabled a product with greater than zero', () => { const product = new Product(); product.setPrice(2.5); expect(() => { product.disable(); }).toThrowError('The price must be zero in order to disable the product'); }); it('should validate to false if incorrect product', () => { const product = new Product(); product.setID('TESTE'); product.setPrice(-10); const result = product.isValid(); expect(result.valid).toBe(false); expect(result.errors.length).toBeGreaterThan(0); }); it('should validate to true if correct product', () => { const product = new Product('My Product'); product.setID(uuidV4()); product.setPrice(2.8); product.enable(); const result = product.isValid(); expect(result.valid).toBe(true); expect(result.errors.length).toBe(0); }); });
package toll_controller_demo_database; import java.awt.*; import java.awt.event.*; import java.sql.ResultSet; import javax.swing.*; import net.proteanit.sql.DbUtils; public class DatabaseOFOnlineUserRecord extends JFrame implements ActionListener { JScrollPane ScrollPanel; Choice License; JButton SearchButton, TablePrintButton, UpdateButton, backButton; JTable DataTable; //table public DatabaseOFOnlineUserRecord() { getContentPane().setBackground(new Color(136, 196, 245)); setLayout(null); setDefaultCloseOperation(EXIT_ON_CLOSE); ImageIcon icon = new ImageIcon("IMAGES/icon2.png"); // Set the icon image for the JFrame this.setIconImage(icon.getImage()); //heading JLabel heading = new JLabel("ONLINE USER RECORD DATABASE"); add(heading); heading.setBounds(450, 10, 500, 50); heading.setFont(new Font("serif", Font.BOLD, 20)); heading.setForeground(Color.BLACK); DataTable = new JTable(); try { Conn ccc = new Conn(); ResultSet AllData = ccc.s.executeQuery("select * from online_user_registration_record"); DataTable.setModel(DbUtils.resultSetToTableModel(AllData)); } catch (Exception e) { e.printStackTrace(); } //Search JLabel DateTimeSearch = new JLabel("Search by License Number:"); DateTimeSearch.setBounds(50, 75, 250, 35); DateTimeSearch.setFont(new Font("serif", Font.BOLD, 20)); add(DateTimeSearch); License = new Choice(); License.setBounds(300, 83, 250, 60); add(License); try { Conn ccc = new Conn(); ResultSet AllData = ccc.s.executeQuery("select * from online_user_registration_record"); while(AllData.next()){ License.add(AllData.getString("Vehicle_License_Number")); //find by } } catch (Exception e) { e.printStackTrace(); } //ScrollPanel ScrollPanel = new JScrollPane(DataTable); ScrollPanel.setBounds(10, 125, 1370, 600); add(ScrollPanel); //search SearchButton = new JButton(" Search "); SearchButton.setBounds(550, 80, 150, 25); add(SearchButton); SearchButton.setFont(new Font("serif", Font.BOLD, 15)); SearchButton.setBackground(Color.BLACK); SearchButton.setForeground(Color.WHITE); SearchButton.addActionListener(this); // action //Print TablePrintButton = new JButton(" Print "); TablePrintButton.setBounds(750, 80, 150, 25); add(TablePrintButton); TablePrintButton.setFont(new Font("serif", Font.BOLD, 15)); TablePrintButton.setBackground(Color.BLACK); TablePrintButton.setForeground(Color.WHITE); TablePrintButton.addActionListener(this); // action //Back backButton = new JButton(" Back "); backButton.setBounds(900, 80, 150, 25); add(backButton); backButton.setFont(new Font("serif", Font.BOLD, 15)); backButton.setBackground(Color.BLACK); backButton.setForeground(Color.WHITE); backButton.addActionListener(this); // action //fream setSize(1350, 600); setLocation(0, 60); setVisible(true); } @Override public void actionPerformed (ActionEvent ae) { if(ae.getSource() == SearchButton){ //setVisible(false); String SearchQuary = " select * from online_user_registration_record where Vehicle_License_Number = '"+ License.getSelectedItem()+"'"; try { Conn ccc = new Conn(); ResultSet Data = ccc.s.executeQuery(SearchQuary); DataTable.setModel(DbUtils.resultSetToTableModel(Data)); } catch (Exception e) { e.printStackTrace(); } } else if (ae.getSource() == TablePrintButton) { try { DataTable.print(); } catch (Exception e) { e.printStackTrace(); } } else if (ae.getSource() == backButton) { setVisible(false); new MoreOption(); // moreOption.setVisible(true); } } public static void main(String[] args){ new DatabaseOFOnlineUserRecord(); } }
#include <iostream> #include <vector> #include <cctype> #include <iterator> #include <cstddef> #include "trade_msg.h" #include "msg.h" #include "reader.h" #include "writer.h" using namespace binaryio; const size_t MsgBuf::MAX_SIZE = 2048; const uint32_t MsgBuf::MAX_TYPE = 100000; std::ostream& operator<<(std::ostream& os, const TradeMsg& msg) { os << "[" << msg.type_ << "," << msg.time_ << "," << msg.len_ << "," << msg.msg_ << "]"; return os; } void MsgBuf::read(Reader& in) { while(!in.eof()) { uint32_t type = in.get_binary<uint32_t>(); uint32_t time = in.get_binary<uint32_t>(); uint32_t len = in.get_binary<uint32_t>(); if(!in.eof()) { std::string str_msg = in.get_string(len); if(len == str_msg.size()) { const TradeMsg msg(type, time, len, str_msg); add(msg); } } } } void MsgBuf::write_type_map(Writer& out) { for(MsgTypeMap::const_iterator it = type_map.begin(); it != type_map.end(); ++it) { out.save_binary((*it).first); out.save_binary((*it).second.get_avg()); } } void MsgBuf::write_data(const std::vector<TradeMsg> messages, Writer& out) { for(std::vector<TradeMsg>::const_iterator it = messages.begin(); it != messages.end(); ++it) { out.save_binary((*it).get_type()); out.save_binary((*it).get_time()); out.save_binary((*it).get_len()); out.save_string((*it).get_msg()); } } std::ostream& operator<<(std::ostream& os, const MsgBufInfo& s) { os << s.get_avg(); return os; } void MsgBuf::add(const TradeMsg& m) { size_t sz = m.get_size() + this->get_size(m.get_type()); bool msg_fit = sz < MAX_SIZE; if(msg_fit && m.get_type() < MAX_TYPE) { MsgTypeMap::iterator it = type_map.find(m.get_type()); if(it == type_map.end()) { type_map.insert(std::make_pair(m.get_type(), MsgBufInfo(m.get_time(), m.get_size()))); } else { (*it).second.add(m); } messages.push_back(m); } } bool MsgBuf::is_full(const uint32_t type) const { return this->get_size(type) < MsgBuf::MAX_SIZE; } void MsgBufInfo::add(const TradeMsg& m) { time_set_.insert(m.get_time()); ++msg_count_; size_ += m.get_size(); } const std::vector<TradeMsg>& MsgBuf::get_messages() const { return messages; } const MsgTypeMap& MsgBuf::get_type_map() const { return type_map; } size_t MsgBuf::get_size(uint32_t const type) const { MsgTypeMap::const_iterator it = type_map.find(type); if(it == type_map.end()) return 0; return (*it).second.get_size(); }
const express = require('express'); const bcrypt = require('bcrypt-nodejs'); const cors = require('cors'); const knex = require('knex'); const signin = require('./controllers/signin'); const register = require('./controllers/register'); const profile = require('./controllers/profile'); const image = require('./controllers/image'); const db = knex({ client: 'pg', connection: { connectionString: process.env.DATABASE_URL, ssl: { rejectUnauthorized: false } } }); // user : 'postgres', // password : 'test', // database : 'smart-brain' const app = express(); app.use(express.json()); app.use(cors()); // ROOT app.get('/', (req,res) =>{ res.json('Success'); }) // SIGN IN app.post('/signin', (req,res)=>{signin.handleSignin(req,res,db,bcrypt)}) // REGISTER app.post('/register', (req,res)=>{register.handleRegister(req,res,db,bcrypt)}) // PROFILE app.get('/profile/:id', (req,res)=>{profile.handleProfile(req,res,db)}) // UPDATE USER ENTRIES app.put('/image', (req,res) =>{image.handleImage(req,res,db)}) // CLARIFAI API app.post('/imageurl', (req,res) =>{image.handleAPICall(req,res)}) app.listen(process.env.PORT || 3001, ()=>{ console.log(`Server is running on port ${process.env.PORT} `); })
import { useState } from 'react'; import './App.css'; function Header() { return(<div className='header'> <h1>Memo</h1> </div> ) } function MemoList(props) { return(<div className='memo-card'> <h4 className='memo-title'>{props.memo.title}</h4> <p className='memo-body'>{props.memo.body}</p> <p className='memo-date'>{props.memo.createdAt}</p> <div className='memo-btns'> <button className='memo-btn' onClick={()=>props.onEditHandler(props.memo)}>Edit</button> <button className='memo-btn' onClick={()=>props.onDelete()}>Delete</button> </div> </div> ) } function Create(props) { const [inputTitle, setInputTitle] = useState(""); const [inputBody, setInputBody] = useState(""); return(<> <form className='create-form' onSubmit={(e)=>{ e.preventDefault(); const currentDate = new Date(); const year = currentDate.getFullYear(); const month = currentDate.getMonth() + 1; const day = currentDate.getDate(); const hour = currentDate.getHours(); const minute = currentDate.getMinutes(); const timestamp = currentDate.getTime(); props.onCreate(timestamp, inputTitle, inputBody, `${month}/${day}/${year} ${hour}:${minute}`); setInputTitle(""); setInputBody(""); }}> <input type="text" name="title" placeholder='Title' value={inputTitle} onChange={(e) => setInputTitle(e.target.value)}></input> <textarea type="text" name="body" placeholder='Take a memo' value={inputBody} onChange={(e) => setInputBody(e.target.value)}></textarea> <input type="submit"></input> </form> </> ) } function Edit(props) { const [inputTitle, setInputTitle] = useState(props.memo.title); const [inputBody, setInputBody] = useState(props.memo.body); return (<div> <form className='edit-form' onSubmit={(e)=> { e.preventDefault(); props.onEdit(inputTitle, inputBody); setInputTitle(""); setInputBody(""); }}> <input type="text" name="title" placeholder='Title' value={inputTitle} onChange={(e) => setInputTitle(e.target.value)}></input> <textarea type="text" name="body" placeholder='Take a memo' value={inputBody} onChange={(e) => setInputBody(e.target.value)}></textarea> <input type="submit"></input> </form> </div>) } function App() { const [memos, setMemos] = useState([{id: 1, title: 'memo app', body: 'take a memo here', createdAt:'3/1/2024 14:40'}]); const [mode, setMode] = useState(null); const [editMemo, setEditMemo] = useState(); return ( <div className="App"> <Header></Header> <Create onCreate={(_id, _title, _body, _date) => { const newMemo = {id:_id, title: _title, body: _body, createdAt:_date}; const newMemos = [...memos]; newMemos.push(newMemo); setMemos(newMemos); }}></Create> <div className='memo-list'> {memos.map(memo => <> <MemoList key={memo.createdAt} memo={memo} onDelete={() => { const newMemos = memos.filter(m => m !== memo) setMemos(newMemos); }} onEditHandler={(memo) => { setMode('EDIT'); setEditMemo(memo); }} ></MemoList> </>)} </div> {mode === 'EDIT' ? <Edit memo={editMemo} onEdit={(_title, _body)=>{ const newMemos = memos.map(m => m === editMemo? Object.assign(m, {title:_title, body:_body}):m) setMemos(newMemos); setMode(null) }}></Edit>:null} </div> ); } export default App;
<?php namespace App\Http\Controllers\MasterData; use App\Models\Category; use Carbon\Carbon; use App\Http\Requests; use App\Http\Controllers\Controller; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Password; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\View; use Illuminate\Support\Facades\Hash; use Validator; use Auth; class CategoryController extends Controller { public function index(){ return view('masterData.category.index'); } public function create(){ $isActive = [ 1 => trans('message.yes') , 0 => trans('message.no') ]; return view('masterData.category.form',compact('isActive')); } public function store(Request $request){ $messages = [ 'categoryCode.required' => trans('Category Code is required'), 'categoryDesc.required' => trans('Category Description is required'), ]; $validation = [ 'categoryCode' => 'required', 'categoryDesc' => 'required', ]; $request->validate($validation, $messages); $category = Category::where('CGCode',$request->categoryCode)->first(); if ($category != null){ return response()->json([ 'error' => '1', 'message' => trans('message.invalid.category') ], 400); } try { DB::beginTransaction(); $category = new Category(); $category->CGCode = $request->categoryCode ?? ''; $category->CGDesc = $request->categoryDesc ?? ''; $category->CGActive = $request->isActive; $category->CGCB = Auth::user()->USCode; $category->save(); DB::commit(); }catch (\Throwable $e) { DB::rollback(); return response()->json([ 'error' => '1', 'message' => trans('Add new vaccine brand was failed !').$e->getMessage() ], 400); } return response()->json([ 'success' => '1', 'redirect' => route('masterData.category.index'), 'message' => trans('message.category.create') ]); } public function edit($id){ $isActive = [ 1 => trans('message.yes') , 0 => trans('message.no') ]; $category = Category::find($id); return view('masterData.category.form',compact('category','isActive')); } public function update(Request $request,$id) { $messages = [ 'categoryCode.required' => trans('Category Code is required'), 'categoryDesc.required' => trans('Category Description is required'), ]; $validation = [ 'categoryCode' => 'required', 'categoryDesc' => 'required', ]; $request->validate($validation, $messages); try { DB::beginTransaction(); $category = Category::find($id); $category->CGCode = $request->categoryCode ?? ''; $category->CGDesc = $request->categoryDesc ?? ''; $category->CGActive = $request->isActive; $category->CGMB = Auth::user()->USCode; $category->save(); DB::commit(); }catch (\Throwable $e) { DB::rollback(); return response()->json([ 'error' => '1', 'message' => trans('Update was failed !').$e->getMessage() ], 400); } return response()->json([ 'success' => '1', 'redirect' => route('masterData.category.index'), 'message' => trans('message.category.update') ]); } public function datatable(){ $categoryData = Category::orderby('CGID','asc')->get(); $data = []; if(isset($categoryData) && count($categoryData)>0) { foreach ($categoryData as $x => $category) { array_push($data, [ 'categoryID' => (float) $category->CGID , 'code' => $category->CGCode ?? '', 'desc' => $category->CGDesc ?? '', 'isActive' => $category->CGActive ?? 0, 'createdBy' => $category->CGCB ?? 0, 'createdDate' => isset($category->CGCD) ? carbon::parse($category->CGCD)->format('d-m-Y H:i') : null, 'modifyBy' => $category->CGMB ?? 0, 'modifyDate' => isset($category->CGMD) ? carbon::parse($category->CGMD)->format('d-m-Y H:i') : null, ]); } } return datatables()->of($data) ->addIndexColumn() ->editColumn('code', function ($row) { return '<a href="'.route('masterData.category.edit', [$row['categoryID'] ]).'">'.$row['code'] .'</a>'; }) ->addColumn('isActive', function ($row) { if($row['isActive'] == 1) { return '<a class="mb-6 btn-floating waves-effect waves-light gradient-45deg-green-teal"><i class="material-icons">check</i></a>'; }else{ return '<a class="btn-floating mb-6 btn-flat waves-effect waves-light red darken-4 white-text"><i class="material-icons">clear</i></a>'; } }) ->addColumn('action', function ($row) { $data = '<a type="button" class="btn-floating mb-1 btn-flat waves-effect waves-light red darken-4 white-text" id="delete" data-id="' . $row['categoryID'] . '" data-url="' . route('masterData.category.delete', [$row['categoryID']]) . '"> <i class="material-icons">delete</i> </a>'; return $data; }) ->rawColumns(['code','isActive', 'action']) ->make(true); } public function delete(Request $request){ try { DB::beginTransaction(); $category = Category::find($request->id); $category->delete(); DB::commit(); }catch (\Throwable $e) { DB::rollback(); return response()->json([ 'error' => '1', 'message' => trans('Category delete failed !').$e->getMessage() ], 400); } return response()->json([ 'success' => '1', 'redirect' => route('masterData.category.index'), 'message' => trans('message.category.delete') ]); } }
<ion-grid> <ion-row class="ion-text-center"> <!-- Sin productos --> <ion-col *ngIf="userOrderService.numProducts() == 0"> <ion-text>{{'label.no.products' | translate}}</ion-text> </ion-col> <!-- Con productos --> <ion-col *ngIf="userOrderService.numProducts() > 0"> <ion-list> <!-- Recorremos los productos --> <ng-container *ngFor="let quantityProduct of userOrderService.getProducts()"> <!-- Nombre del producto --> <ion-item> <ion-label class="ion-text-wrap">{{quantityProduct.product.name | translate}}</ion-label> </ion-item> <!-- Extras del producto --> <ion-item *ngIf="quantityProduct.product.extras"> <ul> <li *ngFor="let optionSelected of quantityProduct.product.extras | extrasSelected">{{optionSelected}}</li> </ul> </ion-item> <ion-card> <ion-card-content> <!-- Opciones de aumentar y decrementar --> <ion-item lines="none"> <ion-label>{{'label.quantity' | translate}}</ion-label> <ion-icon (click)="userOrderService.oneLessProduct(quantityProduct.product)" name="remove-circle-outline"></ion-icon> <ion-text class="ion-padding">{{quantityProduct.quantity}}</ion-text> <ion-icon (click)="userOrderService.oneMoreProduct(quantityProduct.product)" name="add-circle-outline"></ion-icon> </ion-item> <!-- Total del producto --> <ion-item lines="none"> <ion-label slot="end">{{('label.total' | translate) + userOrderService.totalPrice(quantityProduct) + ' €'}}</ion-label> </ion-item> </ion-card-content> </ion-card> </ng-container> </ion-list> </ion-col> </ion-row> <!-- Total de la orden --> <ion-row *ngIf="userOrderService.numProducts() > 0"> <ion-col> <ion-item lines="none"> <ion-label>{{('label.total.order' | translate) + userOrderService.totalOrder() + ' €'}}</ion-label> </ion-item> </ion-col> </ion-row> </ion-grid>
package eu.craftok.buildtionnary.manager.player; import eu.craftok.buildtionnary.BMain; import eu.craftok.buildtionnary.manager.player.stats.BStats; import eu.craftok.buildtionnary.manager.task.GameTask; import eu.craftok.utils.PlayerUtils; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.OfflinePlayer; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.scheduler.BukkitRunnable; import java.util.UUID; import static eu.craftok.buildtionnary.manager.BGame.STATE.LOBBY; import static eu.craftok.buildtionnary.manager.task.GameTask.selectBuilder; /** * Project buildtionnary Created by Sithey */ public class BPlayer { private final UUID uuid; private boolean playing; private int points; private BStats stats; public BPlayer(UUID uuid){ this.uuid = uuid; this.playing = false; this.points = 0; this.stats = new BStats(this); } public UUID getUniqueId() { return uuid; } public Player getPlayer() { return Bukkit.getPlayer(getUniqueId()); } public OfflinePlayer getOfflinePlayer() { return Bukkit.getOfflinePlayer(getUniqueId()); } public boolean isPlaying() { return playing; } public void setPlaying(boolean playing) { this.playing = playing; } public int getPoints() { return points; } public void addPoints(int value){ this.points = this.points + value; } public BStats getStats() { return stats; } public void login(PlayerJoinEvent event){ BPlayerManager.players.add(this); BMain.getInstance().getScoreboard().join(this); event.setJoinMessage(null); Player player = event.getPlayer(); if (BMain.getInstance().getGame().getState() != LOBBY) { player.setGameMode(GameMode.SPECTATOR); } else { playing = true; player.setAllowFlight(false); player.setGameMode(GameMode.ADVENTURE); if (GameTask.timer == 60) { GameTask.timer--; new GameTask().runTaskTimer(BMain.getInstance(), 0, 20); } if (BPlayerManager.getAllPlayers().size() == 8){ GameTask.timer = 3; } } if (isPlaying()) Bukkit.broadcastMessage("§c§lCRAFTOK §8§l» §c" + event.getPlayer().getName() + "§7 a rejoint la partie §a(" + BPlayerManager.getPlayingPlayers().size() + "/8)"); player.setMaxHealth(20.0D); player.setHealth(20.0D); player.setFoodLevel(20); player.setSaturation(12.8F); player.setMaximumNoDamageTicks(20); player.setFireTicks(0); player.setFallDistance(0.0F); player.setLevel(0); player.setExp(0.0F); player.setWalkSpeed(0.2F); player.getInventory().setHeldItemSlot(0); player.getInventory().clear(); player.getInventory().setArmorContents(null); player.closeInventory(); player.getActivePotionEffects().stream().map(PotionEffect::getType).forEach(player::removePotionEffect); ((CraftPlayer) player).getHandle().getDataWatcher().watch(9, (byte) 0); player.getInventory().setHeldItemSlot(0); player.updateInventory(); new BukkitRunnable() { @Override public void run() { player.teleport(BMain.getInstance().getGame().getSpawn()); } }.runTaskLater(BMain.getInstance(), 2); } public void logout(PlayerQuitEvent event){ BMain.getInstance().getScoreboard().leave(this); BPlayerManager.players.remove(this); BPlayerManager.playersbuildcache.remove(this); BPlayerManager.playerswordcache.remove(this); if (GameTask.builder == this){ BMain.getInstance().getGame().getTopPoints().forEach(s -> new PlayerUtils(BPlayerManager.getAllPlayers()).sendMessage(s)); selectBuilder(); } event.setQuitMessage(null); if (isPlaying()){ Bukkit.broadcastMessage("§c§lCRAFTOK §8§l» §c" + event.getPlayer().getName() + "§7 a quitté la partie §a(" + BPlayerManager.getPlayingPlayers().size() + "/8)"); } else if (BPlayerManager.getPlayingBPlayers().size() == 1) BMain.getInstance().getGame().setWin(); } }
/* * HEALPix Java code supported by the Gaia project. * Copyright (C) 2006-2011 Gaia Data Processing and Analysis Consortium * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ package healpix.plot3d.canvas3d; import javax.media.j3d.Appearance; import javax.media.j3d.Geometry; import javax.media.j3d.GeometryArray; import javax.media.j3d.IndexedLineArray; import javax.media.j3d.Shape3D; import javax.vecmath.Point3d; /** * A sphere shape, extending Shape3D, but drawn using longitude/latitude lines. * The radius of the sphere may also be given. * * @author ejoliet * @version $Id: Group3DSphere.java 49444 2008-05-07 10:23:02Z ejoliet $ */ public class Group3DSphere extends Shape3D { /** The long res. */ private int longRes = 12; /** The lat res. */ private int latRes = 24; /** The radius. */ private double radius = 1.0; /** * Construct default sphere: longitudinal resolution 12, latitude 24, radius * 1 */ public Group3DSphere() { this.setGeometry(createGeometry()); this.setAppearance(createAppearance()); } /** * Alternate constructor: specify radius */ public Group3DSphere(int rad) { radius = rad; this.setGeometry(createGeometry()); this.setAppearance(createAppearance()); } /** * Alternate constructor: specify longitudinal and latitude resolution */ public Group3DSphere(int loRes, int laRes) { longRes = loRes; latRes = laRes; this.setGeometry(createGeometry()); this.setAppearance(createAppearance()); } /** * Alternate constructor: specify resolutions and radius */ public Group3DSphere(int loRes, int laRes, int rad) { longRes = loRes; latRes = laRes; radius = rad; this.setGeometry(createGeometry()); this.setAppearance(createAppearance()); } /** * Creates the geometry. * * @return the geometry */ private Geometry createGeometry() { // create line for X axis int nVertex = (longRes * (latRes - 2)) + 2; int nLines = 4 * longRes * (latRes + 1); IndexedLineArray longitudes = new IndexedLineArray(nVertex, GeometryArray.COORDINATES, nLines); longitudes.setCoordinate(0, new Point3d(0.0d, 0.0d, radius)); longitudes.setCoordinate(1, new Point3d(0.0d, 0.0d, -radius)); int i; int j; int cc = 2; int ci = 0; double phi0 = Math.PI / longRes; double theta0 = (2.0 * Math.PI) / latRes; double phi; double theta; double x; double y; double z; for (i = 0; i < longRes; i++) { phi = i * phi0; longitudes.setCoordinateIndex(ci++, 0); for (j = 1; j < latRes; j++) { if (j == (latRes / 2)) { longitudes.setCoordinateIndex(ci++, 1); longitudes.setCoordinateIndex(ci++, 1); continue; } theta = j * theta0; x = radius * Math.sin(theta) * Math.cos(phi); y = radius * Math.sin(theta) * Math.sin(phi); z = radius * Math.cos(theta); longitudes.setCoordinate(cc, new Point3d(x, y, z)); longitudes.setCoordinateIndex(ci++, cc); longitudes.setCoordinateIndex(ci++, cc++); } longitudes.setCoordinateIndex(ci++, 0); } int idx0; int idx1; int half = 0; for (j = 1; j < latRes; j++) { if (j == (latRes / 2)) { continue; } if (j > (latRes / 2)) { half = 1; } else { half = 0; } for (i = 0; i < longRes; i++) { idx0 = ((i * (latRes - 2)) + j) - half + 1; idx1 = idx0 + (latRes - 2); if (idx1 >= nVertex) { idx1 = latRes - j + half; } longitudes.setCoordinateIndex(ci++, idx0); longitudes.setCoordinateIndex(ci++, idx1); } } return longitudes; } /** * Creates the appearance. * * @return the appearance */ private Appearance createAppearance() { Appearance app; app = new Appearance(); return app; } }
import { JomqlObjectTypeLookup, JomqlArgsError, RootResolverDefinition, JomqlInitializationError, JomqlRootResolverType, JomqlInputType, JomqlInputTypeLookup, JomqlObjectType, JomqlInputFieldType, } from "jomql"; import { NormalService, PaginatedService, EnumService } from "../core/services"; import { generatePaginatorPivotResolverObject } from "../helpers/typeDef"; import { capitalizeString, isObject } from "../helpers/shared"; type BaseRootResolverTypes = | "get" | "getMultiple" | "delete" | "create" | "update" | "created" | "deleted" | "updated" | "listUpdated"; export function generateBaseRootResolvers( service: NormalService, methods: BaseRootResolverTypes[] ): { [x: string]: JomqlRootResolverType } { const capitalizedClass = capitalizeString(service.typename); const rootResolvers = {}; methods.forEach((method) => { const capitalizedMethod = capitalizeString(method); let methodName; switch (method) { case "get": methodName = method + capitalizedClass; rootResolvers[methodName] = new JomqlRootResolverType({ name: methodName, restOptions: { method: "get", route: "/" + service.typename + "/:id", query: service.presets.default, }, type: service.typeDefLookup, allowNull: false, args: new JomqlInputFieldType({ required: true, type: service.inputTypeDefLookup, }), resolver: ({ req, query, args, fieldPath }) => { return service.getRecord({ req, query, args, fieldPath, }); }, }); break; case "getMultiple": if (service instanceof PaginatedService) { methodName = "get" + capitalizeString(service.paginator.typename); rootResolvers[ "get" + capitalizeString(service.paginator.typename) ] = new JomqlRootResolverType(<RootResolverDefinition>{ name: methodName, restOptions: { method: "get", route: "/" + service.typename, query: service.paginator.presets.default, }, ...generatePaginatorPivotResolverObject({ pivotService: service, }), }); } else { throw new JomqlInitializationError({ message: `Cannot getMultiple of a non-paginated type '${service.typename}'`, }); } break; case "delete": methodName = method + capitalizedClass; rootResolvers[methodName] = new JomqlRootResolverType({ name: methodName, restOptions: { method: "delete", route: "/" + service.typename + "/:id", query: service.presets.default, }, type: service.typeDefLookup, allowNull: false, args: new JomqlInputFieldType({ required: true, type: service.inputTypeDefLookup, }), resolver: ({ req, query, args, fieldPath }) => service.deleteRecord({ req, query, args, fieldPath, }), }); break; case "update": const updateArgs = {}; methodName = method + capitalizedClass; Object.entries(service.getTypeDef().definition.fields).forEach( ([key, typeDefField]) => { let typeField = typeDefField.type; // if typeField is JomqlObjectTypeLookup, convert to JomqlInputTypeLookup if (typeField instanceof JomqlObjectTypeLookup) { typeField = new JomqlInputTypeLookup( "get" + capitalizeString(typeField.name) ); } else if (typeField instanceof JomqlObjectType) { typeField = new JomqlInputTypeLookup( "get" + capitalizeString(typeField.definition.name) ); } if (typeDefField.updateable) { // generate the argDefinition for the string type updateArgs[key] = new JomqlInputFieldType({ type: typeField, required: false, allowNull: typeDefField.allowNull, arrayOptions: typeDefField.arrayOptions, }); } } ); rootResolvers[methodName] = new JomqlRootResolverType({ name: methodName, restOptions: { method: "put", route: "/" + service.typename + "/:id", query: service.presets.default, }, type: service.typeDefLookup, allowNull: false, args: new JomqlInputFieldType({ required: true, type: new JomqlInputType({ name: methodName, fields: { item: new JomqlInputFieldType({ type: service.inputTypeDefLookup, required: true, }), fields: new JomqlInputFieldType({ type: new JomqlInputType({ name: "update" + capitalizedClass + "Fields", fields: updateArgs, inputsValidator: (args, fieldPath) => { // check if at least 1 valid update field provided if (!isObject(args)) { throw new JomqlArgsError({ message: `Object args required`, fieldPath, }); } const { id, ...updateFields } = args; if (Object.keys(updateFields).length < 1) throw new JomqlArgsError({ message: `No valid fields to update`, fieldPath, }); }, }), required: true, }), }, }), }), resolver: ({ req, query, args, fieldPath }) => service.updateRecord({ req, query, args, fieldPath }), }); break; case "create": const createArgs = {}; methodName = method + capitalizedClass; Object.entries(service.getTypeDef().definition.fields).forEach( ([key, typeDefField]) => { let typeField = typeDefField.type; // if typeField is JomqlObjectTypeLookup, convert to JomqlInputTypeLookup if (typeField instanceof JomqlObjectTypeLookup) { typeField = new JomqlInputTypeLookup( "get" + capitalizeString(typeField.name) ); } else if (typeField instanceof JomqlObjectType) { typeField = new JomqlInputTypeLookup( "get" + capitalizeString(typeField.definition.name) ); } if (typeDefField.addable) { // generate the argDefinition for the string type createArgs[key] = new JomqlInputFieldType({ type: typeField, required: typeDefField.required, allowNull: typeDefField.allowNull, arrayOptions: typeDefField.arrayOptions, }); } } ); rootResolvers[methodName] = new JomqlRootResolverType({ name: methodName, restOptions: { method: "post", route: "/" + service.typename, query: service.presets.default, }, type: service.typeDefLookup, allowNull: false, args: new JomqlInputFieldType({ required: true, type: new JomqlInputType({ name: methodName, fields: createArgs, }), }), resolver: ({ req, query, args, fieldPath }) => service.createRecord({ req, query, args, fieldPath, }), }); break; case "created": methodName = service.typename + capitalizedMethod; rootResolvers[methodName] = new JomqlRootResolverType({ name: methodName, restOptions: { method: "post", route: "/subscribe/" + service.typename + capitalizedMethod, query: service.presets.default, }, type: service.typeDefLookup, allowNull: false, resolver: ({ req, query, args, fieldPath }) => service.subscribeToMultipleItem( service.typename + capitalizedMethod, { req, query, args, fieldPath, } ), }); break; case "deleted": methodName = service.typename + capitalizedMethod; rootResolvers[methodName] = new JomqlRootResolverType({ name: methodName, restOptions: { method: "post", route: "/subscribe/" + service.typename + capitalizedMethod, query: service.presets.default, }, type: service.typeDefLookup, allowNull: false, resolver: ({ req, query, args, fieldPath }) => service.subscribeToSingleItem( service.typename + capitalizedMethod, { req, query, args, fieldPath, } ), }); break; case "updated": methodName = service.typename + capitalizedMethod; rootResolvers[methodName] = new JomqlRootResolverType({ name: methodName, restOptions: { method: "post", route: "/subscribe/" + service.typename + capitalizedMethod, query: service.presets.default, }, type: service.typeDefLookup, allowNull: false, resolver: ({ req, query, args, fieldPath }) => service.subscribeToSingleItem( service.typename + capitalizedMethod, { req, query, args, fieldPath, } ), }); break; case "listUpdated": methodName = service.typename + capitalizedMethod; rootResolvers[methodName] = new JomqlRootResolverType({ name: methodName, restOptions: { method: "post", route: "/subscribe/" + service.typename + capitalizedMethod, query: service.presets.default, }, type: service.typeDefLookup, allowNull: false, resolver: ({ req, query, args, fieldPath }) => service.subscribeToMultipleItem( service.typename + capitalizedMethod, { req, query, args, fieldPath, } ), }); break; default: throw new Error(`Unknown root resolver method requested: '${method}'`); } }); return rootResolvers; } export function generateEnumRootResolver( enumService: EnumService ): { [x: string]: JomqlRootResolverType } { const capitalizedClass = capitalizeString(enumService.paginator.typename); const methodName = "get" + capitalizedClass; const rootResolvers = { [methodName]: new JomqlRootResolverType({ name: methodName, restOptions: { method: "get", route: "/" + enumService.paginator.typename, query: enumService.presets.default, }, allowNull: false, type: enumService.paginator.typeDef, resolver: ({ req, args, query, fieldPath }) => enumService.paginator.getRecord({ req, args, query, fieldPath, }), }), }; return rootResolvers; }
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.dvtd.pojo; import com.fasterxml.jackson.annotation.JsonIgnore; import java.io.Serializable; import java.util.Date; import java.util.Set; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.hibernate.annotations.CreationTimestamp; import org.springframework.format.annotation.DateTimeFormat; /** * * @author ACER */ @Entity @Table(name = "shippers") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Shippers.findAll", query = "SELECT s FROM Shippers s"), @NamedQuery(name = "Shippers.findByShipperID", query = "SELECT s FROM Shippers s WHERE s.shipperID = :shipperID"), @NamedQuery(name = "Shippers.findByCmnd", query = "SELECT s FROM Shippers s WHERE s.cmnd = :cmnd"), @NamedQuery(name = "Shippers.findByCreatedDate", query = "SELECT s FROM Shippers s WHERE s.createdDate = :createdDate")}) public class Shippers implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ShipperID") private Integer shipperID; @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "CMND") private String cmnd; @Basic(optional = false) @Column(name = "created_date", nullable = true) @DateTimeFormat(pattern = "yyyy-MM-dd") @Temporal(TemporalType.TIMESTAMP) @CreationTimestamp private Date createdDate; @JoinColumn(name = "UserID", referencedColumnName = "UserID") @ManyToOne(optional = false) private Users userID; @OneToMany(mappedBy = "chosenShipperID") @JsonIgnore private Set<Orders> ordersSet1; @OneToMany(cascade = CascadeType.ALL, mappedBy = "shipperID") @JsonIgnore private Set<Bid> bidSet; public Shippers() { } public Shippers(Integer shipperID) { this.shipperID = shipperID; } public Shippers(Integer shipperID, String cmnd, Date createdDate) { this.shipperID = shipperID; this.cmnd = cmnd; this.createdDate = createdDate; } public Integer getShipperID() { return shipperID; } public void setShipperID(Integer shipperID) { this.shipperID = shipperID; } public String getCmnd() { return cmnd; } public void setCmnd(String cmnd) { this.cmnd = cmnd; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Users getUserID() { return userID; } public void setUserID(Users userID) { this.userID = userID; } @XmlTransient public Set<Orders> getOrdersSet1() { return ordersSet1; } public void setOrdersSet1(Set<Orders> ordersSet1) { this.ordersSet1 = ordersSet1; } @XmlTransient public Set<Bid> getBidSet() { return bidSet; } public void setBidSet(Set<Bid> bidSet) { this.bidSet = bidSet; } @Override public int hashCode() { int hash = 0; hash += (shipperID != null ? shipperID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Shippers)) { return false; } Shippers other = (Shippers) object; if ((this.shipperID == null && other.shipperID != null) || (this.shipperID != null && !this.shipperID.equals(other.shipperID))) { return false; } return true; } @Override public String toString() { return "com.dvtd.pojo.Shippers[ shipperID=" + shipperID + " ]"; } }
class SearchModel { Data? data; String? message; int? code; String? errors; SearchModel({this.data, this.message, this.code, this.errors}); SearchModel.fromJson(Map<String, dynamic> json) { data = json['data'] != null ? new Data.fromJson(json['data']) : null; message = json['message']; code = json['code']; errors = json['errors']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); if (this.data != null) { data['data'] = this.data!.toJson(); } data['message'] = this.message; data['code'] = this.code; data['errors'] = this.errors; return data; } } class Data { List<Data2>? data; Links? links; Meta? meta; Data({this.data, this.links, this.meta}); Data.fromJson(Map<String, dynamic> json) { if (json['data'] != null) { data = <Data2>[]; json['data'].forEach((v) { data!.add(new Data2.fromJson(v)); }); } links = json['links'] != null ? new Links.fromJson(json['links']) : null; meta = json['meta'] != null ? new Meta.fromJson(json['meta']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); if (this.data != null) { data['data'] = this.data!.map((v) => v.toJson()).toList(); } if (this.links != null) { data['links'] = this.links!.toJson(); } if (this.meta != null) { data['meta'] = this.meta!.toJson(); } return data; } } class Data2 { int? id; String? name; String? dateOfBirth; String? diagnosis; String? address; String? visitTime; int? userId; String? createdAt; String? updatedAt; Data2( {this.id, this.name, this.dateOfBirth, this.diagnosis, this.address, this.visitTime, this.userId, this.createdAt, this.updatedAt}); Data2.fromJson(Map<String, dynamic> json) { id = json['id']; name = json['name']; dateOfBirth = json['date_of_birth']; diagnosis = json['diagnosis']; address = json['address']; visitTime = json['visit_time']; userId = json['user_id']; createdAt = json['created_at']; updatedAt = json['updated_at']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['name'] = this.name; data['date_of_birth'] = this.dateOfBirth; data['diagnosis'] = this.diagnosis; data['address'] = this.address; data['visit_time'] = this.visitTime; data['user_id'] = this.userId; data['created_at'] = this.createdAt; data['updated_at'] = this.updatedAt; return data; } } class Links { String? first; String? last; Null prev; Null next; Links({this.first, this.last, this.prev, this.next}); Links.fromJson(Map<String, dynamic> json) { first = json['first']; last = json['last']; prev = json['prev']; next = json['next']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['first'] = this.first; data['last'] = this.last; data['prev'] = this.prev; data['next'] = this.next; return data; } } class Meta { int? currentPage; int? from; int? lastPage; List<Links>? links; String? path; int? perPage; int? to; int? total; Meta( {this.currentPage, this.from, this.lastPage, this.links, this.path, this.perPage, this.to, this.total}); Meta.fromJson(Map<String, dynamic> json) { currentPage = json['current_page']; from = json['from']; lastPage = json['last_page']; if (json['links'] != null) { links = <Links>[]; json['links'].forEach((v) { links!.add(new Links.fromJson(v)); }); } path = json['path']; perPage = json['per_page']; to = json['to']; total = json['total']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['current_page'] = this.currentPage; data['from'] = this.from; data['last_page'] = this.lastPage; if (this.links != null) { data['links'] = this.links!.map((v) => v.toJson()).toList(); } data['path'] = this.path; data['per_page'] = this.perPage; data['to'] = this.to; data['total'] = this.total; return data; } } class Links2 { String? url; String? label; bool? active; Links2({this.url, this.label, this.active}); Links2.fromJson(Map<String, dynamic> json) { url = json['url']; label = json['label']; active = json['active']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['url'] = this.url; data['label'] = this.label; data['active'] = this.active; return data; return data; } }
import convertMarkdown from './markdown'; import { Component } from 'vue' import { defineSFC, File } from 'vue-sfc-component'; import Markdown from 'markdown-it-for-mdvc'; type MaybePromise<T> = T | Promise<T> type FileContent = string | ArrayBuffer | Blob | Response function ensureAsync(fn?: (...arg: any) => any) { if (!fn) return return async function(...arg: any) { const r = fn(...arg) if (r instanceof Promise) { return await r } return r } } export default async function( mainfile: string, options?: { imports?: Record<string, any>; files?: Record<string, FileContent | URL>; getFile?: (path: string) => MaybePromise<FileContent | URL>; renderStyles?: (css: string) => MaybePromise<(() => void)>; catch?: (errors: Array<string | Error>) => MaybePromise<void>; fileConvertRule?: (file: File) => MaybePromise<void>; markdown?: Markdown.Options; extend?: (md: Markdown) => void; } ) : Promise<Component> { options = options || {} options.fileConvertRule = ensureAsync(options.fileConvertRule) return defineSFC(mainfile, { ...options, async fileConvertRule(file: File) { if (file.filename.endsWith(".md") || file.filename.endsWith(".mdv")) { if (file.content instanceof URL) { const res = await fetch(file.content) file.content = await res.text() } else if (file.content instanceof ArrayBuffer) { const decoder = new TextDecoder() file.content = decoder.decode(file.content) } file.content = convertMarkdown(file.content, { markdown: options?.markdown, extend: options?.extend }) file.language = "vue" } if (options?.fileConvertRule) { await options.fileConvertRule(file) } } }) }
import type { PublicUserInformationDTO } from "@/models/user/PublicUserInformationDTO"; import axios from "axios"; import type { AxiosResponse } from "axios"; import type { UserStatsDTO } from "@/models/user/UserStatsDTO"; /** * Service class for user related operations. */ export class UserService { private static readonly api_url = "http://localhost:8080/api/v1/users"; public static async searchUserByUsername( username: string, page: number, pageSize: number, ): Promise<PublicUserInformationDTO[]> { const url = this.api_url + "/public?" + "search=" + username + "&page=" + page + "&size=" + pageSize; console.log("url: " + url); try { const response: AxiosResponse<PublicUserInformationDTO[]> = await axios.get(url); return response.data; } catch (err) { console.log("error in search service: " + err); throw err; } } /** * Fetches the user stats of the currently logged-in user. */ public static async getUserStats(): Promise<UserStatsDTO> { try { const response: AxiosResponse<UserStatsDTO> = await axios.get( this.api_url + "/stats", ); return response.data; } catch (err) { throw err; } } /** * Fetches the public user information of a user with the given username. * @param username The username of the user. */ public static async getPublicUserInformationFromUsername( username: string, ): Promise<PublicUserInformationDTO> { try { const request = this.api_url + "/public/" + username; console.log("request: " + request); const response: AxiosResponse<PublicUserInformationDTO> = await axios.get(request); return response.data; } catch (err) { throw err; } } }
/* * @Author: Beau pg.beau@outlook.com * @Date: 2023-04-12 03:14:50 * @LastEditors: Beau pg.beau@outlook.com * @LastEditTime: 2023-04-25 14:14:09 * @FilePath: \workspace\React-The-Complete-Guide\19-1-Advanced-Redux-Cart\src\components\UI\Notification.jsx * @Description: * * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. */ import classes from './Notification.module.css'; const Notification = (props) => { let specialClasses = ''; if (props.status === 'error') { specialClasses = classes.error; } if (props.status === 'success') { specialClasses = classes.success; } const cssClasses = `${classes.notification} ${specialClasses}`; return ( <section className={cssClasses}> <h2>{props.title}</h2> <p>{props.message}</p> </section> ); }; export default Notification;
package functions import ( "fmt" "io" "github.com/dwethmar/gosqle/expressions" "github.com/dwethmar/gosqle/util" ) var _ expressions.Expression = &Count{} // Count is a count aggregate function. // example: // // COUNT(column) type Count struct { Col *expressions.Column } // WriteTo implements Expression. func (c *Count) Write(sw io.StringWriter) error { if err := util.WriteStrings(sw, "COUNT("); err != nil { return fmt.Errorf("error writing COUNT function: %v", err) } if err := c.Col.Write(sw); err != nil { return fmt.Errorf("error writing COUNT expression: %v", err) } if err := util.WriteStrings(sw, ")"); err != nil { return fmt.Errorf("error writing COUNT closing parenthesis: %v", err) } return nil } // NewCount returns a new Count aggregate functions expression. func NewCount(column *expressions.Column) *Count { return &Count{ Col: column, } }
<template> <!-- 顶部导航 start --> <div class="topnav"> <div class="topnav_bd w1210 bc"> <div class="topnav_left"></div> <div class="topnav_right fr"> <ul> <li v-if="isLogin"> 您好,欢迎 {{name}} 来到商城! [<a href="#" @click.prevent="logout">退出</a>] </li> <li v-else> 您好,欢迎来到商城! [<a href="#" @click.prevent="login">登录</a>] [<a href="#" @click.prevent="regist">免费注册</a>] </li> <li class="line">|</li> <li>我的订单</li> <li class="line">|</li> <li>客户服务</li> </ul> </div> </div> </div> <!-- 顶部导航 end --> </template> <script> import {mapState,mapMutations} from 'vuex' export default { data() { return{ } }, methods: { ...mapMutations({ setName: 'loginStore/setName', setToken: 'loginStore/setToken', changeLoginState: 'loginStore/changeLoginState', }), login(){ this.$router.push("/login") }, regist(){ this.$router.push("/regist") }, logout(){ //清空数据 this.setName(null) this.setToken(null) this.changeLoginState() localStorage.removeItem('name') localStorage.removeItem('token') } }, computed: { // ...mapState(['name']) 以前在index.js中获取state的方式 //第一个参数,就是store文件夹中的文件名 ...mapState("loginStore",{ name: state => state.name, isLogin: state => state.isLogin }) }, mounted() { //从本地存储中获取数据,重新放回vuex let name = localStorage.getItem('name') let token = localStorage.getItem('token') //放回vuex this.setName(name) this.setToken(token) this.changeLoginState() } }; </script> <style> </style>
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>程序运行效率和浮点数的一种解决方法</title> <style></style> </head> <body> </body> <script> //那如何来避免这类 ` 1.0-0.9 != 0.1 ` 的非bug型问题发生呢?下面给出一种目前用的比较多的解决方案, 在判断浮点运算结果前对计算结果进行精度缩小,因为在精度缩小的过程总会自动四舍五入.方法二、三是对此方法的运用。 //(1.0-0.9).toFixed(digits) // toFixed() 精度参数须在 0 与20 之间 parseFloat((1.0-0.9).toFixed(10)) === 0.1 // 结果为True parseFloat((1.0-0.8).toFixed(10)) === 0.2 // 结果为True parseFloat((1.0-0.7).toFixed(10)) === 0.3 // 结果为True parseFloat((11.0-11.8).toFixed(10)) === -0.8 // 结果为True //用下面的方法可以测试两个程序谁的效率高 var date1 = new Date(); //获取开始时间 for(var i = 0; i < 10000; i++){ //运行程序 var result1 = (10.22 - 0.11).toFixed(2); } console.log(result1); console.log(new Date() - date1);//用现在的时间减去开始时间。 效率低 var date2 = new Date(); for(var j = 0; j < 10000; j++){ //方法一:乘以10的对应整数倍后在除以相应的倍数 var result2 = (10.22 * 1000 - 0.11 * 1000) / 1000; } console.log(result2); console.log(new Date() - date2);//效率高 console.log(0.1 + 0.2 == 0.3); //既然返回false console.log(0.1 + 0.2); //既然返回0.30000000000000004 console.log(parseFloat(0.1) + parseFloat(0.2)); //还是返回0.30000000000000004 var result3 = (1.0 - 0.8); console.log(result3); //方法二:通过isEqual工具方法判断数值是否相等,面向对象的风格 Number.prototype.isEqual = function(number,digits){ var digits = digits==undefined ? 10 : digits; //默认精度为10 return this.toFixed(digits) === number.toFixed(digits); } var result = (1.0 - 0.8).isEqual(0.2); console.log(result); //方法三:原生扩展方式 function isEqual(num1,num2,digits){ var digits = digits==undefined ? 10 : digits; return num1.toFixed(digits) === num2.toFixed(digits); } var result4 = isEqual((1.0-0.8),0.2); console.log(result4); </script> </html>
// Discord import { SlashCommandBuilder } from '@discordjs/builders' import { ButtonInteraction } from 'discord.js' // Globals import { games } from '..' import { validateUserRole } from '../utils/discord' import { getSettings } from '../utils/settings' const adminId = process.env.ADMIN_ID module.exports = { data: new SlashCommandBuilder() .setName('begin-game') .setDescription('begin the game'), /** * Triggers start of game if there are enough players * @param interaction {ButtonInteraction} * @returns {void``} */ async execute(interaction: ButtonInteraction) { const { user, channelId } = interaction const { minCapacity } = await getSettings(channelId) const game = games[channelId] const playerArr = Object.values(game.players) // Allow admins to trigger game start even if not registered in game if (!game.players[user.id]) { const isAdmin = validateUserRole(adminId, interaction, user.id) if (!isAdmin) { return interaction.reply({ content: 'You need to be registered in gameplay to start the game', ephemeral: true, }) } } // Trigger game and let channel know who started it if (playerArr.length >= minCapacity) { game.waitingRoom = false interaction.reply({ content: `${user.username} has started the game`, }) setTimeout(() => { interaction.deleteReply() }, 10000) } else { interaction.reply({ content: `You can't start with less than ${minCapacity} players`, ephemeral: true, }) } }, }
import { BaseEntity, BeforeInsert, BeforeUpdate, Check, Column, Entity, JoinColumn, ManyToOne, OneToMany, OneToOne, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm'; import { IsNotEmpty, MaxLength, validateOrReject } from 'class-validator'; import { Promotion } from './promotion.entity'; import { ProductSize } from './productSize.entity'; @Entity({ name: 'PromotionDetails' }) export class PromotionDetail extends BaseEntity { @PrimaryGeneratedColumn({ type: 'int' }) promotionDetailId: number; @IsNotEmpty() @Column({ type: 'int' , nullable: true}) promotionId: number; @Column({type: 'int', nullable: true}) productSizeId: number; @Column({type: 'int'}) @Check('"quantity" > 0') quantity: number; @Column({type: 'nvarchar', length: 255, nullable: true}) description: string; @ManyToOne(() => ProductSize, (ps) => ps.promotionDetails) @JoinColumn({ name: 'productSizeId', }) productSize: ProductSize; @ManyToOne(() => Promotion, (pm) => pm.promotionDetails) @JoinColumn({ name: 'promotionId' }) promotion: Promotion; // HOOKS (AUTO VALIDATE) @BeforeInsert() @BeforeUpdate() async validate() { await validateOrReject(this); } }
//! Simple memory allocation. //! //! TODO: more efficient use core::alloc::Layout; use core::num::NonZeroUsize; use crate::{AllocError, AllocResult, BaseAllocator, ByteAllocator}; pub struct SimpleByteAllocator { start: usize, //起始位置 next: usize, //可用空间起始位置 allocations: usize, //分配次数 end: usize, //全部空间的结尾 } impl SimpleByteAllocator { pub const fn new() -> Self { Self { start: 0, next: 0, allocations: 0, end: 0, } } } impl BaseAllocator for SimpleByteAllocator { fn init(&mut self, _start: usize, _size: usize) { self.start = _start; self.next = _start; self.end = _start + _size; self.allocations = 0; } fn add_memory(&mut self, _start: usize, _size: usize) -> AllocResult { Ok(()) } } impl ByteAllocator for SimpleByteAllocator { fn alloc(&mut self, layout: Layout) -> AllocResult<NonZeroUsize> { let need_size = layout.size(); let align = layout.align(); let tmp_start = (self.next + align) / align * align; //对齐内存 if (tmp_start + need_size) > self.end { Err(crate::AllocError::NoMemory) } else { self.allocations += 1; self.next = self.next + need_size; Ok(NonZeroUsize::new(tmp_start).unwrap()) } } fn dealloc(&mut self, _pos: NonZeroUsize, _layout: Layout) { self.allocations -= 1; if self.allocations == 0 { self.start = 0; } } fn total_bytes(&self) -> usize { self.end - self.start } fn used_bytes(&self) -> usize { self.next - self.start } fn available_bytes(&self) -> usize { self.end - self.next } }
# 带有 React |语义 UI | GraphQL | PostgresSQL 的 Slack 克隆(第 3 部分) > 原文:<https://blog.devgenius.io/slack-clone-with-react-semantic-ui-graphql-postgressql-part-3-f42515446c80?source=collection_archive---------11-----------------------> ## 之前,我们设置了我们的 Graphql 服务器。你可以在这里找到那篇文章。 ![](img/d314b898fe904b16398f9f545130dee7.png) Volodymyr Hryshchenko 在 [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral) 上拍摄的照片 今天,我们将着手启动我们的数据库。 我建议看我上一篇文章的安装视频,看看如何启动 Postgres 服务器。然后,我将通过一个名为 Postico 的 GUI 应用程序创建数据库,而不是通过命令行。然而,这只是我的一个偏好。您可以继续观看视频来学习命令行方式。 # 启动服务器并创建数据库 仅供参考:在与数据库交互时,一定要运行 Postgres 服务器。默认情况下,这些是他们给你的数据库。 ![](img/19742a5bc6264176a79f59236f91b9ad.png) # 使用 Postico 与数据库交互 当您第一次开始时,它会要求您连接到您试图使用的数据库/服务器。只需按照这些指示,连接到你在 Postgres 上运行的同一个服务器。完成后,创建一个名为 Chat 的数据库。我点击了下面的“+数据库”按钮来创建一个新的。 ![](img/d2304a00f056ccefce8b2ffd81bde666.png) 当它在顶部显示“已连接”时,那是您连接到的数据库。 # 在项目中配置我们的数据库。 既然我们已经设置了数据库,现在是时候在项目中配置所有这些了。在根项目文件夹的终端中,运行命令 ``` npx sequelize init ``` 该命令将创建一个 config 文件夹,其中有一个`config.json`文件,该文件包含一些默认的数据库连接信息,您需要更改这些信息,以便与您之前创建的数据库相匹配。它应该看起来像这样 ``` /** config/config.js */ { "development": { "username": "ajeas", "password": "", "database": "chat", "host": "127.0.0.1", "dialect": "postgres" }, "test": { "username": "root", "password": null, "database": "database_test", "host": "127.0.0.1", "dialect": "postgres" }, "production": { "username": "root", "password": null, "database": "database_production", "host": "127.0.0.1", "dialect": "postgres" } } ``` “用户名”将是你的名字,默认密码是一个空字符串,“数据库”将是聊天,并确保使“方言”Postgres(告诉我们使用哪个数据库,如果你想,你可以放一个不同的,如 MySQL。但是,我们现在使用 Postgres)忽略测试和生产。 # 使用序列创建模型(表) 配置完数据库信息后,就该通过命令行创建我们的第一个模型了。运行这段代码来生成一个用户模型(代表一个注册用户)。 ``` npx sequelize model:generate --name User --attributes username:string,email:string,password:string ``` 这将用我们需要指定数据类型的`username`、`email`和`password`字段(列)创建我们的用户模型(表),这就是为什么我们在最后添加了`:string`。你的模型应该是这样的 ``` const { Model } = require("sequelize"); module.exports = (sequelize, DataTypes) => { class User extends Model { /** * Helper method for defining associations. * This method is not a part of Sequelize lifecycle. * The `models/index` file will call this method automatically. */ static associate() { // define association here } } User.init( { username: DataTypes.STRING, email: DataTypes.STRING, password: DataTypes.STRING }, { sequelize, modelName: "User" } ); return User; }; ``` 它还将创建一个迁移文件夹和一个代表我们在数据库中的表结构的`xxxxxxxx-create-user.js`文件。每次创建模型时,都会在 migrations 文件夹中附加一个迁移文件。(还创建了一个我们在本系列中不会用到的 seeder 文件夹,所以现在可以忽略它。) 在我们进入其他部分之前,让我们在启动服务器时连接到数据库。添加这是`server.js`文件 ``` /** add this */ const { sequelize } = require("./models");server.listen(4000, () => { console.log(`🚀 Server ready at port 4000`); // Connecting to Database/** add this */ sequelize .authenticate() .then(() => { console.log("database connected"); }) .catch(err => console.log(err)); }); ``` 它使用序列和我们的`config.js`文件连接到我们的数据库。重启服务器(`npm run dev`),现在你应该在终端中看到这个 ![](img/b9af60da07e737497ea860eb4f739fec.png) 现在,让我们创建我们需要的其他模型。运行与之前相同的命令,创建一个`Team`、`Channel`、`Message`模型 仅供参考:这些命令将在模型文件夹中为您创建文件 ``` npx sequelize model:generate --name Team --attributes name:stringnpx sequelize model:generate --name Channel --attributes name:string,public:booleannpx sequelize model:generate --name Message --attributes text:string ``` 您的所有模型应该看起来与用户模型图像相似。在将模型迁移到数据库之前。我们需要在他们之间建立关系。 # 模型关系(关联) 我们将使用`belongsToMany`和`belongsTo`关系,我们必须在每个模型文件中手动完成。 “一个**用户**可以属于 slack 中的许多团队”,这将使他们通过一个名为`member`(我们将在后面创建)的不同表链接在一起,该表向`member`表添加了一个外键。(仅供参考,我对关系数据库和关系还是新手。所以我用我能理解的最好的方式来解释:)。 ``` /** User model */ static associate({ Team }) { // define association here this.belongsToMany(Team, { through: "member", foreignKey: "userId" }); } ``` “一个**团队**可以属于许多用户,它属于一个特定的用户”,用不同的外键链接到同一个`member`表。`belongsTo`没有创建另一个表,它只是向`team`添加了一个外键。外键`owner`将是拥有团队的用户(模型)的“id”。 ``` /** Team model */ static associate({ User }) { // define association here this.belongsToMany(User, { through: "member", foreignKey: "teamId"}); this.belongsTo(User, { foreignKey: "owner" }); } ``` “一个**消息**属于一个频道,它属于一个用户”,给消息添加两个外键。外键`channelId`将是消息所属通道的“id ”,外键`userId`将是创建该消息的用户(模型)的“id”。 ``` /** Message model */ static associate({ Channel, User }) { // define association here this.belongsTo(Channel, { foreignKey: "channelId" }); this.belongsTo(User, { foreignKey: "userId" }); } ``` 最后,我们的渠道模型。“一个渠道属于一个团队”,因为没有团队我们无法创建渠道`teamId`外键是该渠道所属团队(模型)的“id”。 ``` /** Channel model */ static associate({ Team }) { // define association here this.belongsTo(Team, { foreignKey: "teamId" }); } ``` 现在,让我们将它迁移到数据库中,这样它将具有相同的结构。运行此命令进行迁移。 ``` npx sequelize db:migrate ``` 如果一切顺利,您应该会在终端上看到一条类似于`xxxxxxxxxxx-create-user.js migrated`的消息以及其他迁移文件。 确保连接到您的聊天数据库,check-in Postico,您现在应该可以看到添加了所有外键的所有表。 ![](img/2e8dea1a55a51ca7f2e795c848a345b4.png) 到目前为止,您的文件夹结构应该是这样的 ![](img/3dfe1002b97149f60299cb7e9d46f03a.png) 这是所有这一个乡亲,请随时让我知道,如果你在这个过程中有任何问题,这是一个很大的工作量,所以我很乐意帮助如果你卡住了。干杯!
package ca.qc.cstj.premiereapplication import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.NumberPicker import android.widget.TextView import android.widget.Toast import com.google.android.material.snackbar.Snackbar import org.w3c.dom.Text import kotlin.reflect.typeOf class GameActivity : AppCompatActivity() { private var nbTries = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_game) val txvMessage = findViewById<TextView>(R.id.txvMessage) val nprNumber = findViewById<NumberPicker>(R.id.nprNumber) val btnValidate = findViewById<Button>(R.id.btnValidate) val txvTries = findViewById<TextView>(R.id.txvTries) txvMessage.text = getString(R.string.msgGame, intent.getStringExtra(PLAYER_NAME_EXTRA)) nprNumber.minValue = 0 nprNumber.maxValue = 100 //Xavier le code que tu as manqué val theGoodNumber = (0 .. 100).random() //Log.i("GameActivity", theGoodNumber.toString()) btnValidate.setOnClickListener { nbTries++ val choice = nprNumber.value // if(choice == theGoodNumber) { // Snackbar.make(btnValidate, "Bravo", Snackbar.LENGTH_LONG).show() // } else if (choice > theGoodNumber) { // Snackbar.make(btnValidate, "Le nombre recherché est plus petit.", Snackbar.LENGTH_LONG).show() // } else { // Snackbar.make(btnValidate, "Le nombre recherché est plus grand.", Snackbar.LENGTH_LONG).show() // } when { choice == theGoodNumber -> { Snackbar.make(btnValidate, "Bravo", Snackbar.LENGTH_INDEFINITE) finish() } choice > theGoodNumber -> { Snackbar.make(btnValidate, "Le nombre recherché est plus petit.", Snackbar.LENGTH_LONG).show() } else -> { Snackbar.make(btnValidate, "Le nombre recherché est plus grand.", Snackbar.LENGTH_LONG).show() } } txvTries.text = applicationContext.resources.getQuantityString(R.plurals.nbTries, nbTries, nbTries) } } //La partie statique de notre classe companion object { // public static Intent newIntent() { } const val PLAYER_NAME_EXTRA = "PLAYER_NAME" fun newIntent(context: Context, playerName: String): Intent { val intent = Intent(context, GameActivity::class.java) //En c# Extra serait de type Dictionnary<String, Object> intent.putExtra(PLAYER_NAME_EXTRA, playerName) return intent } } }
import time import random import operator def d4(amt=1): counter = 0 for _ in range(amt): counter += random.randint(1,5) return counter def d6(amt=1): counter = 0 for _ in range(amt): counter += random.randint(1,6) return counter def d8(amt=1): counter = 0 for _ in range(amt): counter += random.randint(1,8) return counter def d10(amt=1): counter = 0 for _ in range(amt): counter += random.randint(1,10) return counter def d12(amt=1): counter = 0 for _ in range(amt): counter += random.randint(1,12) return counter def d20(amt=1): counter = 0 for _ in range(amt): counter += random.randint(1,20) return counter def d100(amt=1): counter = 0 for _ in range(amt): counter += random.randint(1,100) return counter def genSheetTemplate(): """Returns the framework of a character sheet""" sheet = {"name" : "Teste", "class" : "testicle", "level" : 1, "background" : None, "player name" : None, "race" : None, "proficiency" : 2, "scores" : {"str" : {"assigned" : False, "val" : 0, "order" : 1, "mod" : 0}, "dex" : {"assigned" : False, "val" : 0, "order" : 2, "mod" : 0}, "con" : {"assigned" : False, "val" : 0, "order" : 3, "mod" : 0}, "int" : {"assigned" : False, "val" : 0, "order" : 4, "mod" : 0}, "wis" : {"assigned" : False, "val" : 0, "order" : 5, "mod" : 0}, "cha" : {"assigned" : False, "val" : 0, "order" : 6, "mod" : 0}}, "saves" : {"str" : 0, "dex" : 0, "con" : 0, "int" : 0, "wis" : 0, "cha" : 0}, "skills" : {"acrobatics" : {"base" : "dex", "mod" : 0, "proficient" : False}, "animal handling" : {"base" : "wis", "mod" : 0, "proficient" : False}, "arcana" : {"base" : "int", "mod" : 0, "proficient" : False}, "athletics" : {"base" : "str", "mod" : 0, "proficient" : False}, "deception" : {"base" : "cha", "mod" : 0, "proficient" : False}, "history" : {"base" : "int", "mod" : 0, "proficient" : False}, "insight" : {"base" : "wis", "mod" : 0, "proficient" : False}, "intimidation" : {"base" : "cha", "mod" : 0, "proficient" : False}, "investigation" : {"base" : "int", "mod" : 0, "proficient" : False}, "medicine" : {"base" : "wis", "mod" : 0, "proficient" : False}, "nature" : {"base" : "int", "mod" : 0, "proficient" : False}, "perception" : {"base" : "wis", "mod" : 0, "proficient" : False}, "performance" : {"base" : "cha", "mod" : 0, "proficient" : False}, "persuasion" : {"base" : "cha", "mod" : 0, "proficient" : False}, "religion" : {"base" : "int", "mod" : 0, "proficient" : False}, "sleight of hand" : {"base" : "dex", "mod" : 0, "proficient" : False}, "stealth" : {"base" : "dex", "mod" : 0, "proficient" : False}, "survival" : {"base" : "wis", "mod" : 0, "proficient" : False}}, "combat info" : {"ac" : 0, "initiative" : 0, "speed" : 0, "hp" : 0, "hit dice type" : None, "hit dice amt" : 0}, "passives" : {"perception" : 0, "investigation" : 0, "insight" : 0}, "languages" : [], "equipment" : {}, "spellcasting" : {}, "proficiencies" : {"weapons" : [], "armor" : [], "tools" : []}, "features" : {}, "attacks" : {}, "resistances" : [], "recommended" : {}} return sheet def printSheet(sheet): print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("******************************") print(sheet["name"] + ", " + sheet["race"] + " " + sheet["class"]) print("-----------------------------") print("Name:\n" + sheet["name"]) print("-----------------------------") print("Class:\n" + sheet["class"]) print("-----------------------------") print("Background:\n" + sheet["background"]) print("-----------------------------") print("Race:\n" + sheet["race"]) print("-----------------------------") #Scores print("Scores:" + "\n") current = 1 i = "scores" while current < 7: for s in sheet[i]: if sheet[i][s]["order"] == current: if(sheet[i][s]["mod"] >= 0): print(s + ": " + str(sheet[i][s]["val"]) + " (+" + str(sheet[i][s]["mod"]) + ")") else: print(s + ": " + str(sheet[i][s]["val"]) + " (" + str(sheet[i][s]["mod"]) + ")") current += 1 print("-----------------------------") #Combat info i = "combat info" print("Combat Info:\n") for a in sorted(sheet[i]): print(a + ": " + str(sheet[i][a])) print("-----------------------------") #Saves i = "saves" print("Saves:\n") for s in sheet[i]: if(sheet[i][s] >= 0): print(s + ": +" + str(sheet[i][s])) elif(sheet[i][s] < 0): print(s + ": " + str(sheet[i][s])) print("-----------------------------") if(sheet["resistances"] != []): #Resistances print("Resistances:") i = "resistances" for t in range(len(sheet[i])): if(t < len(sheet[i]) - 1): print(sheet[i][t] + ", ", end='') else: print(sheet[i][t]) print("-----------------------------") #Skills i = "skills" print("Skills:\n") for s in sorted(sheet[i]): if(sheet[i][s]["mod"] >= 0): print(s + ": " + "(+" + str(sheet[i][s]["mod"]) + ")") else: print(s + ": " + "(" + str(sheet[i][s]["mod"]) + ")") print("-----------------------------") #Passives i = "passives" print("Passives:\n") for p in sheet[i]: print(p + ": " + str(sheet[i][p])) print("-----------------------------") #Languages i = 'languages' print("Languages:\n") for t in range(len(sheet[i])): if(t < len(sheet[i]) - 1): print(sheet[i][t] + ", ", end='') else: print(sheet[i][t]) print("-----------------------------") #Attacks i = "attacks" print("Attacks:\n") for a in sorted(sheet[i]): print(a + ": " + str(sheet[i][a])) print("-----------------------------") #Spellcasting i = "spellcasting" if(sheet[i] != {}): print("Spellcasting:\n") print("Stats:\nSpell Save DC: " + str(sheet[i]["dc"]) + "\nSpell Attack Modifier: " + str(sheet[i]["mod"]) + "\n") print("Slots:") for s in sheet[i]["slots"]: print(s + ": " + str(sheet[i]["slots"][s])) print("\nSpells:") print("Cantrips: ", end='') for n in range(len(sheet[i][0])): if(n < len(sheet[i][0]) - 1): print(sheet[i][0][n] + ", ", end='') else: print(sheet[i][0][n]) print("Level 1: ", end='') for n in range(len(sheet[i][1])): if(n < len(sheet[i][1]) - 1): print(sheet[i][1][n] + ", ",end='') else: print(sheet[i][1][n]) print() print("-----------------------------") #Features i = "features" print("Features:\n") for f in sorted(sheet[i]): print(f + " - " + str(sheet[i][f]) + "\n") print("-----------------------------") #Proficiencies i = "proficiencies" print("Proficiencies:\n") for p in sheet[i]: if(sheet[i][p] != []): print(p + ": ", end='') for t in range(len(sheet[i][p])): if(t < len(sheet[i][p]) - 1): print(sheet[i][p][t] + ", ", end='') else: print(sheet[i][p][t]) print("-----------------------------") #Equipment i = "equipment" print("Equipment:\n") for e in sheet[i]: if(sheet[i][e] > 1): print(e + " (x" + str(sheet[i][e]) + ")") else: print(e) print("-----------------------------") print("******************************") return def doASI(sheet, score, amt): temp = sheet temp["scores"][score]["val"] += amt return temp def chooseOneTool(list): print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please choose one of the following to be proficient with: ") for i in list: print(i) chosen = input("") if not chosen in list: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid choice (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseOneTool(list) return chosen def chooseSubrace(sheet, subraces): temp = sheet print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please choose a subrace from the following options: ") for r in subraces: print("-----------------------------") print("Subrace: " + r) print("\nDescription: " + subraces[r]["desc"]) print("-----------------------------") subrace = input("Which subrace do you want to play as?\n") #Check to make sure the input race is valid if not subrace in subraces: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid subrace (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseSubrace(temp, subraces) else: #Update race temp["race"] = subrace #Update speed if "speed" in subraces[subrace]: temp["combat info"]["speed"] = subraces[subrace]["speed"] #Update ability scores for score in subraces[subrace]["asi"]: temp = doASI(temp, score, subraces[subrace]["asi"][score]) #Update resistances if "resistances" in subraces[subrace]: sheet["resistances"].extend(subraces[subrace]["resistances"]) #Update features if("features" in subraces[subrace]): temp["features"].update(subraces[subrace]["features"]) #Add 1 to hp max if the character is a dwarf if(subrace == "hill dwarf"): temp["combat info"]["hp"] += 1 #Update proficiencies if("proficiencies" in subraces[subrace]): #Update weapon proficiencies if "weapons" in subraces[subrace]["proficiencies"]: temp["proficiencies"]["weapons"].extend(subraces[subrace]["proficiencies"]["weapons"]) #Update armor proficiencies if "armor" in subraces[subrace]["proficiencies"]: temp["proficiencies"]["armor"].extend(subraces[subrace]["proficiencies"]["armor"]) #Update tool proficiencies if "tools" in subraces[subrace]["proficiencies"]: for t in subraces[subrace]["proficiencies"]["tools"]: if(t == "choose one"): chosen = chooseOneTool(subraces[subrace]["proficiencies"]["tools"][t]) temp["proficiencies"]["tools"].extend([chosen]) else: temp["proficiencies"]["tools"].extend([t]) return temp def chooseDraconicAncestry(sheet): """Chooses a draconic ancestry and updates the sheet accordingly. Should only be called for dragonborn.""" temp = sheet ancestry = {"black" : {"type" : "acid", "weapon" : "5x30 line (dex save)"}, "blue" : {"type" : "lightning", "weapon" : "5x30 line (dex save)"}, "brass" : {"type" : "fire", "weapon" : "5x30 line (dex save)"}, "bronze" : {"type" : "lightning", "weapon" : "5x30 line (dex save)"}, "copper" : {"type" : "acid", "weapon" : "5x30 line (dex save)"}, "gold" : {"type" : "fire", "weapon" : "15ft cone (dex save)"}, "green" : {"type" : "poison", "weapon" : "15ft cone (con save)"}, "red" : {"type" : "fire", "weapon" : "15ft cone (dex save)"}, "silver" : {"type" : "cold", "weapon" : "15ft cone (con save)"}, "white" : {"type" : "cold", "weapon" : "15ft cone (con save)"}} print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please select a draconic ancestry color from the following. You gain the associated breath attack, as well as resistance to the associated type of damage.") for a in ancestry: print("-----------------------------") print("Color: " + a + "\nType: " + ancestry[a]["type"] + "\nWeapon: " + ancestry[a]["weapon"]) print("-----------------------------") choice = input("Which ancestry do you want to choose?\n") #Check to make sure the input race is valid if not choice in ancestry: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid ancestry type (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseDraconicAncestry(temp) else: temp["attacks"].update({"Breath Weapon" : ancestry[choice]["type"] + " - " + ancestry[choice]["weapon"]}) temp["resistances"].extend([ancestry[choice]["type"]]) return temp def chooseTwoASI(sheet): """Increases two ability scores by one each.""" temp = sheet scores = ["str", "dex", "con", "int", "wis", "cha"] print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please select a score to increase by 1:") for s in scores: print("-----------------------------") print(s) print("-----------------------------") choice = input("Which ability would you like to increase?\n") if not choice in scores: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid ability score (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseTwoASI(sheet) else: temp["scores"][choice]["val"] += 1 scores.remove(choice) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please select a second score to increase by 1:") for s in scores: print("-----------------------------") print(s) print("-----------------------------") choice = input("Which ability would you like to increase?\n") if not choice in scores: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid ability score (capitalization matters). Start choosing two again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseTwoASI(sheet) else: temp["scores"][choice]["val"] += 1 return temp def chooseRace(sheet, rand): """Chooses a race and a subrace.""" races = {"dwarf" : {"desc" : "Kingdoms rich in ancient grandeur, halls carves into the roots of mountains, the echoing of picks and hammers in deep mines and blazing forges, a commitment to clan and tradition, and a burning hatred of goblins and orcs - these common threads unite all dwarves.", "asi" : {"con" : 2}, "speed" : 25, "resistances" : ["poison"], "features" : {"Darkvision" : "Accustomed to life underground, you have superior vision in dark and dim conditions. You can see in dim light within 60 feet of you as if it were bright light, and in darkness as if it were dim light. You can't discern colors in the dark, only shades of gray.", "Dwarven Resilience" : "You have advantage on saving throws against poison, and you have resistance against poison damage.", "Stonecunning" : "Whenever you make an Intelligence (History) check related to the origin of stonework, you are considered proficient in the History skill and add double your proficiency bonus to the check, instead of your normal proficiency."}, "proficiencies" : {"weapons" : ["battleaxe", "handaxe", "light hammer", "warhammer"], "tools" : {"choose one" : ["smith's tools", "brewer's supplies", "mason's tools"]}}, "languages" : ["common", "dwarvish"], "subraces" : {"hill dwarf" : {"desc" : "As a hill dwarf, you have keen senses, deep intuition, and remarkable resilience. The gold dwarves of Faerun in their mighty southern kingdom are hilll dwarves, as are the exiled Neidar and the debased Klar of Krynn in the Dragonlance setting.", "asi" : {"wis" : 1}, "features" : {"Dwarven Toughness" : "Your hit point maximum increases by 1, and it increases by 1 every time you gain a level."}}, "mountain dwarf" : {"desc" : "As a mountain dwarf, you're strong and hardy, accusstomed to a difficult life in rugged terrain. You're probably on the tall side (for a dwarf), and tend toward lighter coloration. The shield dwarves of northern Faerun, as well as the ruling Hylar clan and the noble Daewar clan of Dragonlance, are mountain dwarves.", "asi" : {"str" : 2}, "proficiencies" : {"armor" : ["light", "medium"]}}}}, "elf" : {"desc" : "Elves are magical people of people of otherworldly grace, living in the world but not entirely part of it. They live in places of ethereal beauty, in the midst of ancient forests or in silvery spires glittering with faerie light, where soft music drifts through the air and gentle fragrances waft on the breeze. Elves love nature and magic, art and artistry, music and poetry, and the good things of the world.", "asi" : {"dex" : 2}, "speed" : 30, "features" : {"Darkvision" : "Accustomed to life underground, you have superior vision in dark and dim conditions. You can see in dim light within 60 feet of you as if it were bright light, and in darkness as if it were dim light. You can't discern colors in the dark, only shades of gray.", "Fey Ancestry" : "You have advantage on saving throws against being charmed, and magic can't put you to sleep.", "Trance" : "Elves don't need to sleep. Instead, they meditate deeply, remaining semiconscious, for 4 hours a day. (The common word for such meditation is 'trance.') While meditating, you can dream after a fashion; such dreams are actually mental exercises that have become reflexive through years of practice. After resting in this way, you gain the same benefit that a human does from 8 hours of sleep."}, "proficiencies" : {"skills" : ["perception"]}, "languages" : ["common", "elvish"], "subraces" : {"high elf" : {"desc" : "As a high elf, you have a keen mind and a mastery of at least the basics of magic. In many of the world of D&D, there are twoo kinds of high elves. One type (which includes the gray elves and valley elves of Greyhawk, the Silvanesti of Dragonlance, and the sun elves of the Forgotten Realms) is haughty and reclusive, believing themselves to be superior to non-elves and even other elves. The other type (including the high elves of Greyhawk, the Qualinesti of Dragonlance, and the moon elves of the Forgotten Realms) are more common and more friendly, and often encountered among humans and other races.", "asi" : {"int" : 1}, "proficiencies" : {"weapons" : ["longsword", "shortsword", "shortbow", "longbow"]}, "features" : {"Cantrip" : "You know one extra cantrip of your choice from the wizard spell list. Intelligence is your spellcasting ability for it."}}, "wood elf" : {"desc" : "As a wood elf, you have keen senses and intuition, and your fleet feet carry you quickly and stealthily through your native forests. This category includes the wild elves (grugach) of Greyhawk and the Kagonesti of Dragonlance, as well as the races called wood elves in Greyhawk and the Forgotten Realms. In Faer�n, wood elves (also called wild elves, green elves, or forest elves) are reclusive and distrusting of non-elves.", "asi" : {"wis" : 1}, "proficiencies" : {"weapons" : ["longsword", "shortsword", "shortbow", "longbow"]}, "speed" : 35, "features" : {"Mask of the Wild" : "You can attempt to hide even when you are only lightly obscured by foliage, heavy rain, falling snow, mist, and other natural phenomena."}}, "dark elf" : {"desc" : "Descended from an earlier subrace of elves, the drow were banished from the surface world for following the goddess Lolth down the path of evil. Now they have built their own civilization in the depths of the Underdark, patterned after the Way of Lolth. Also called dark elves, the drow have skin that resembles charcoal or obsidian, as well as stark white or pale yellow hair. They commonly have very pale eyes (so pale as to be mistaken for white) in shades of lilac, silver, pink, red, and blue. They tend to be smaller and thinner than most elves.", "asi" : {"cha" : 1}, "features" : {"Superior Darkvision" : "Your darkvision has a range of 120 feet.", "Sunlight Sensitivity" : "You have disadvantage on attack rolls and Wisdom (Perception) checks that rely on sight when you, the target of the attack, or whatever you are trying to perceive is in direct sunlight.", "Drow Magic" : "You know the 'dancing lights' cantrip. When you reach 3rd level, you can cast the 'faerie fire' spell once with this trait and regain the ability to do so when you finish a long rest. When you reach 5th level, you can cast the 'darkness' spell once with this trait and regain the ability to do so once you finish a long rest. Charisma is your spellcasting ability for these spells."}, "proficiencies" : {"weapons" : ["rapiers", "shortswords", "hand crossbows"]}}}}, "halfling" : {"desc" : "The comforts of home are the goals of most halflings� lives: a place to settle in peace and quiet, far from marauding monsters and clashing armies; a blazing fire and a generous meal; fine drink and fine conversation. Though some halflings live out their days in remote agricultural communities, others form nomadic bands that travel constantly, lured by the open road and the wide horizon to discover the wonders of new lands and peoples. But even these wanderers love peace, food, hearth, and home, though home might be a wagon jostling along a dirt road or a raft floating downriver.", "asi" : {"dex" : 2}, "speed" : 25, "features" : {"Lucky" : "When you roll a 1 on the d20 for an attack roll, ability check, or saving throw, you can reroll the die and must use the new roll.", "Brave" : "You have advantage on saving throws against being frightened.", "Halfling Nimbleness" : "You can move through the space of any creature that is of a size larger than yours."}, "languages" : ["common", "halfling"], "subraces" : {"lightfoot" : {"desc" : "As a lightfoot halfling, you can easily hide from notice, even using other people as cover. You're inclined to be affable and get along well with others. In the Forgotten Realms lightfoot halflings have spread the farthest and thus are the most common variety. Lightfoots are prone to wanderlust than other halflings, and often dwell alongside other races or take up a nomadic life. In the world of Greyhawk, these halflings are called hairfeet or tallfellows", "asi" : {"cha" : 1}, "features" : {"Naturally Stealthy" : "You can attempt to hide even when you are obscured only by a creature that is at least one size larger than you."}}, "stout" : {"desc" : "As a stout halfling, you're hardier than average and have some resistance to poison. Some say that stouts have dwarven blood. In the Forgotten Realms, these halflings are colled stronghearts, and they're most common in the south.", "asi" : {"con" : 1}, "resistances" : ["poison"], "features" : {"Stout Resilience" : "You have advantage on saving throws against poison, and you have resistance against poison damage."}}}}, "human" : {"desc" : "In the reckonings of most worlds, humans are the youngest of the common races, late to arrive on the world scene and short-lived in comparison to dwarves, elves, and dragons. Perhaps it is because of their shorter lives that they strive to achieve as much as they can in the years they are given. Or maybe they feel they have something to prove to the elder races, and that�s why they build their mighty empires on the foundation of conquest and trade. Whatever drives them, humans are the innovators, the achievers, and the pioneers of the worlds.", "asi" : {"str" : 1, "dex" : 1, "con" : 1, "int" : 1, "wis" : 1, "cha" : 1}, "speed" : 30, "languages" : ["common", "choose 1"]}, "dragonborn" : {"desc" : "Born of dragons, as their name proclaims, the dragonborn walk proudly through a world that greets them with fearful incomprehension. Shaped by draconic gods or the dragons themselves, dragonborn originally hatched from dragon eggs as a unique race, combining the best attributes of dragons and humanoids. Some dragonborn are faithful servants to true dragons, others form the ranks of soldiers in great wars, and still others find themselves adrift, with no clear calling in life.", "asi" : {"str" : 2, "cha" : 1}, "speed" : 30, "languages" : ["common", "draconic"], "features" : {"Draconic Ancestry" : "You have draconic ancestry. Your breath weapon and damage resistance are determined by the dragon type.", "Breath Weapon" : "You can use your action to exhale destructive energy. Your draconic ancestry determines the size, shape, and damage type of the exhalation. When you use your breath weapon, each creature in the area of the exhalation must make a saving throw, the type of which is determined by your draconic ancestry. The DC for this saving throw equals 8 + your Constitution modifier + your proficiency bonus. A creature takes 2d6 damage on a failed save, and half as much damage on a successful one. The damage increases to 3d6 at 6th level, 4d6 at 11th level, and 5d6 at 16th level. After you use your breath weapon, you can�t use it again until you complete a short or long rest.", "Damage Resistance" : "You have resistance to the damage type associated with your draconic ancestry."}}, "gnome" : {"desc" : "A constant hum of busy activity pervades the warrens and neighborhoods where gnomes form their close-knit communities. Louder sounds punctuate the hum: a crunch of grinding gears here, a minor explosion there, a yelp of surprise or triumph, and especially bursts of laughter. Gnomes take delight in life, enjoying every moment of invention, exploration, investigation, creation, and play.", "asi" : {"int" : 2}, "speed" : 25, "languages" : ["common", "gnomish"], "features" : {"Darkvision" : "Accustomed to life underground, you have superior vision in dark and dim conditions. You can see in dim light within 60 feet of you as if it were bright light, and in darkness as if it were dim light. You can't discern color in darkness, only shades of gray.", "Gnome Cunning" : "You have advantage on all Intelligence, Wisdom, and Charisma saving throws against magic."}, "subraces" : {"forest gnome" : {"desc" : "As a forest gnome, you have a natural knack for illusion and inherent quickness and stealth. In the worlds of D&D, forest gnomes are rare and secretive. They gather in hidden communities in sylvan forests, using illusions and trickery to conceal themselves from threats or to mask their escape should they be detected. Forest gnomes tend to be friendly with other good-spirited woodland folk, and they regard elves and good fey as their most important allies. These gnomes also befriend small firest animals and rely on them for information about threats that might prowl their lands.", "asi" : {"dex" : 2}, "features" : {"Natural Illusionist" : "You know the 'minor illusion' cantrip. Intelligence is your spellcasting modifier for it.", "Speak with Small Beasts" : "Through sounds and gestures, you can communicate simple ideas with Small or smaller beasts. Forest gnomes love animals and often keep squirrels, badgers, rabbits, moles, woodpeckers, and other creatures as beloved pets."}}, "rock gnome" : {"desc" : "As a rock gnome, you have a natural inventiveness and hardiness beyond that of other gnomes. Most gnomes in the worlds of D&D are rock gnomes, including the tinker gnomes of the Dragonlance setting.", "asi" : {"con" : 1}, "features" : {"Artificer's Lore" : "Whenever you make an Intelligence (History) check related to magic items, alchemical objects, or technological devices, you can add twice your proficiency bonus, instead of any proficiency bonus you normally apply.", "Tinker" : "You have proficiency with artisan's tools (tinker's tools). Using those tools, you can spend 1 hour and 10 gp worth of materials to construct a Tiny clockwork device (AC 5, 1 hp). The device ceases to function after 24 hours (unless you spend 1 hour repairing it to keep the device functioning), or when you use your action to dismantle it; at that time, you can reclaim the materials used to create it. You can have up to three such devices active at a time.\n\nWhen you create a device, choose one of the following options:\n\nClockwork Toy. This toy is a clockwork animal, monster, or person, such as a frog, mouse, bird, dragon, or soldier. When placed on the ground, the toy moves 5 feet across the ground on each of your turns in a random direction. It makes noises as appropriate to the creature it represents.\n\nFire Starter. The device produces a miniature flame, which you can use to light a candle, torch, or campfire. Using the device requires your action.\n\nMusic Box. When opened, this music box plays a single song at a moderate volume. The box stops playing when it reaches the song�s end or when it is closed."}, "proficiencies" : {"tools" : ["artisan's tools (tinker tools)"]}}}}, "half-elf" : {"desc" : "Walking in two worlds but truly belonging to neither, half-elves combine what some say are the best qualities of their elf and human parents: human curiosity, inventiveness, and ambition tempered by the refined senses, love of nature, and artistic tastes of the elves. Some half-elves live among humans, set apart by their emotional and physical differences, watching friends and loved ones age while time barely touches them. Others live with the elves, growing restless as they reach adulthood in the timeless elven realms, while their peers continue to live as children. Many half-elves, unable to fit into either society, choose lives of solitary wandering or join with other misfits and outcasts in the adventuring life.", "asi" : {"cha" : 2, "choose two" : None}, "speed" : 30, "features" : {"Darkvision" : "Thanks to your elf blood, you have superior vision in dark and dim conditions. You can see in dim light within 60 feet of you as if it were bright light, and in darkness as if it were dim light. You can't discern color in darkness, only shades of gray.", "Fey Ancestry" : "You have advantage on saving throws against being charmed, and magic can't put you to sleep."}, "proficiencies" : {"skills" : ["choose 2"]}, "languages" : ["common", "elvish", "choose 1"]}, "half-orc" : {"desc" : "Whether united under the leadership of a mighty warlock or having fought to a standstill after years of conflict, orc and human tribes sometimes form alliances, joining forces into a larger horde to the terror of civilized lands nearby. When these alliances are sealed by marriages, half-orcs are born. Some half-orcs rise to become proud chiefs of orc tribes, their human blood giving them an edge over their full-blooded orc rivals. Some venture into the world to prove their worth among humans and other more civilized races. Many of these become adventurers, achieving greatness for their mighty deeds and notoriety for their barbaric customs and savage fury.", "asi" : {"str" : 2, "con" : 1}, "speed" : 30, "proficiencies" : {"skills" : ["intimidation"]}, "languages" : ["common", "orc"], "features" : {"Darkvision" : "Thanks to your orc blood, you have superior vision in dark and dim conditions. You can see in dim light within 60 feet of you as if it were bright light, and in darkness as if it were dim light. You can't discern colors in darkness, only shades of gray.", "Relentless Endurance" : "When you are reduced to 0 hit points but not killed outright, you can drop to 1 hit point instead. You can't use this feature again until you finish a long rest.", "Savage Attacks" : "When you score a critical hit with a melee weapon attack, you can roll one of the weapon's damage dice one additional time and add it to the extra damage of the critical hit."}}, "tiefling" : {"desc" : "To be greeted with stares and whispers, to suffer violence and insult on the street, to see mistrust and fear in every eye: this is the lot of the tiefling. And to twist the knife, tieflings know that this is because a pact struck generations ago infused the essence of Asmodeusoverlord of the Nine Hellsinto their bloodline. Their appearance and their nature are not their fault but the result of an ancient sin, for which they and their children and their children's children will always be held accountable.", "asi" : {"int" : 1, "cha" : 2}, "speed" : 30, "resistances" : ["fire"], "languages" : ["common", "infernal"], "features" : {"Darkvision" : "Thanks to your infernal heritage, you have superior vision in dark and dim conditions. You can see in dim light within 60 feet of you as if it were bright light, and in darkness as if it were dim light. You can't discern color in darkness, only shades of gray.", "Infernal Legacy" : "You know the 'thaumaturgy' cantrip. When you reach 3rd level, you can cast the 'hellish rebuke' spell as a 2nd-level spell once with this trait and regain the ability to do so when you finish a long rest. When you reach 5th level, you can cast the 'darkness' spell once with this trait and regain the ability to do so when you finish a long rest. Charisma is your spellcasting ability for these spells."}}} temp = sheet if not rand: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please choose a race from the following options: ") for r in sorted(races): print("-----------------------------") print("Race: " + r) print("\nDescription: " + races[r]["desc"]) print("-----------------------------") race = input("Which race do you want to play as?\n") #Check to make sure the input race is valid if not race in races: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid race (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseRace(sheet, rand) else: #Update race temp["race"] = race #Update ability scores for score in races[race]["asi"]: if(score == "choose two"): temp = chooseTwoASI(temp) else: temp = doASI(temp, score, races[race]["asi"][score]) #Update speed temp["combat info"]["speed"] = races[race]["speed"] #Update features if "features" in races[race]: temp["features"].update(races[race]["features"]) if "Draconic Ancestry" in races[race]["features"]: temp = chooseDraconicAncestry(temp) #Update languages for l in races[race]["languages"]: if(l.split(' ')[0] == "choose"): temp = chooseLanguages(temp, int(l.split(' ')[1])) else: if l in temp["languages"]: temp = chooseLanguages(temp, 1) else: temp["languages"].append(l) #Update resistances if "resistances" in races[race]: temp["resistances"].extend(races[race]["resistances"]) #Update weapon proficiencies if "proficiencies" in races[race]: if "weapons" in races[race]["proficiencies"]: temp["proficiencies"]["weapons"].extend(races[race]["proficiencies"]["weapons"]) #Update armor proficiencies if "armor" in races[race]["proficiencies"]: temp["proficiencies"]["armor"].extend(races[race]["proficiencies"]["armor"]) #Update skill proficiencies if "skills" in races[race]["proficiencies"]: for s in races[race]["proficiencies"]["skills"]: if(s.split(' ')[0] == "choose"): temp = chooseSkills(temp, int(s.split(' ')[1])) else: if(temp["skills"][s]["proficient"]): temp = chooseSkills(temp, 1) else: temp["skills"][s]["proficient"] = True temp["skills"][s]["mod"] += temp["proficiency"] #Update tool proficiencies if "tools" in races[race]["proficiencies"]: for t in races[race]["proficiencies"]["tools"]: if(t == "choose one"): chosen = chooseOneTool(races[race]["proficiencies"]["tools"][t]) temp["proficiencies"]["tools"].extend([chosen]) else: temp["proficiencies"]["tools"].extend([t]) #Choose a subrace if("subraces" in races[race] and races[race]["subraces"] != None): temp = chooseSubrace(temp, races[race]["subraces"]) return temp def chooseLanguages(sheet, amt): """Adds a number of languages to the sheet equal to amt.""" temp = sheet languages = ["dwarvish", "elvish", "giant", "gnomish", "goblin", "halfling", "orc", "abyssal", "celestial", "deep speech", "draconic", "infernal", "primordial", "sylvan", "undercommon"] options = [] for l in languages: if l not in temp["languages"]: options.append(l) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please choose a language from the following options: ") for o in sorted(options): print("-----------------------------") print(o) print("-----------------------------") choice = input("Which language would you like to be able to speak?\n") #Check to make sure the input race is valid if not choice in options: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid language (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseLanguages(sheet, amt) else: temp["languages"].append(choice) if(amt > 1): temp = chooseLanguages(temp, amt - 1) return temp def chooseSkills(sheet, amt, options=None): """Adds skills to the sheet equal to amt.""" temp = sheet if(options == None): skills = ["acrobatics", "animal handling", "arcana", "athletics", "deception", "history", "insight", "intimidation", "investigation", "medicine", "nature", "perception", "performance", "persuasion", "religion", "sleight of hand", "stealth", "survival"] else: skills = options temp_options = [] for s in skills: if not temp["skills"][s]["proficient"]: temp_options.append(s) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please choose a skill from the following options: ") for o in sorted(temp_options): print("-----------------------------") print(o) print("-----------------------------") choice = input("Which skill would you like to be proficient in?\n") #Check to make sure the input race is valid if not choice in temp_options: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid skill (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseSkills(sheet, amt, options) else: temp["skills"][choice]["proficient"] = True temp["skills"][choice]["mod"] += temp["proficiency"] if(amt > 1): temp = chooseSkills(temp, amt - 1, options) return temp def chooseBackground(sheet, rand): """Chooses a background for the sheet""" backgrounds = {"acolyte" : {"desc" : "You have spent your life in the service of a temple to a specific god or pantheon of gods. You act as an intermediary between the realm of the holy and the mortal world, performing sacred rites and offering sacrifices in order to conduct worshipers into the presence of the divine. You are not necessarily a clericperforming sacred rites is not the same thing as channeling divine power.", "proficiencies" : {"skills" : ["insight", "religion"]}, "languages" : ["choose 2"], "equipment" : {"a holy symbol" : 1, "a prayer book or prayer wheel" : 1, "stick of incense" : 5, "vestments" : 1, "a set of common clothes" : 1, "gp" : 15}, "features" : {"Shelter of the Faithful" : "As an acolyte, you Command the respect of those who share your faith, and you can perform the religious ceremonies of your deity. You and your Adventuring companions can expect to receive free Healing and care at a temple, shrine, or other established presence of your faith, though you must provide any material Components needed for Spells. Those who share your Religion will support you (but only you) at a modest lifestyle."}}, "charlatan" : {"desc" : "You have always had a way with people. You know what makes them tick, you can tease out their heart�s desires after a few minutes of conversation, and with a few leading questions you can read them like they were children's books. It�s a useful talent, and one that you�re perfectly willing to use for your advantage.", "proficiencies" : {"skills" : ["deception", "sleight of hand"], "tools" : ["disguise kit", "forgery kit"]}, "equipment" : {"a set of fine clothes" : 1, "a disguise kit" : 1, "tools of the con of your choice (ten stoppered bottles filled with colored liquid, a set of weighted dice, a deck of marked cards, or a signet ring of an imaginary duke)." : 1, "gp" : 15}, "features" : {"False Identity" : "You have created a second identity that includes documentation, established acquaintances, and disguises that allow you to assume that persona. Additionally, you can forge documents including official papers and personal letters, as long as you have seen an example of the kind of document or the handwriting you are trying to copy."}}, "criminal" : {"desc" : "You are an experienced criminal with a history of breaking the law. You have spent a lot of time among other criminals and still have contacts within the criminal underworld. You're far closer than most people to the world of murder, theft, and violence that pervades the underbelly of civilization, and you have survived up to this point by flouting the rules and regulations of society.", "proficiencies" : {"skills" : ["deception", "stealth"], "tools" : ["one type of gaming set", "thieve's tools"]}, "equipment" : {"a crowbar" : 1, "a set of dark common clothes including a hood" : 1, "gp" : 15}, "features" : {"Criminal Contact" : "You have a reliable and trustworthy contact who acts as your liason to a network of other criminals. You know how to get messages to and from your contact, even over great distances; specifically, you know the local messengers, corrupt caravan masters, and seedy sailors who can deliver messages for you."}}, "entertainer" : {"desc" : "You thrive in front of anaudience. You know how to entrance them, entertain then, and even inspire them. Your poetics can stir the hearts of those who hear you, awakening grief or joy, laughter or anger. Your music raises their spirits or captures their sorrow. Your dance steps captivate, your humor cuts to the quick. Whatever techniques you use, your art is your life.", "proficiencies" : {"skills" : ["acrobatics", "performance"], "tools" : ["disguise kit", "one kind of musical instrument"]}, "equipment" : {"a musical instrument (one of your choice)" : 1, "the favor of an admirer (love letter, lock of hair, or trinket)" : 1, "a costume" : 1, "gp" : 15}, "features" : {"By Popular Demand" : "You can always find a place to perform, usually in an inn or tavern but possibly with a circus, at a theater, or even in a noble's court. At such a place, you receive free lodging and food of a modest or comfortable standard (depending on the quality of the establishment), as long as you perform each night. In addition, your performance makes you something of a local figure. When strangers recognize you in a rown where you have performed, they typically take a liking to you."}}, "folk hero" : {"desc" : "You come from a humble social rank, but you are destined for so much more. Already the people of your hom e village regard you as their champion, and your destiny calls you to stand against the tyrants and monsters that threaten the common folk everywhere.", "proficiencies" : {"skills" : ["animal handling", "survival"], "tools" : ["one type of artisan's tools, vehicles (land)"]}, "equipment" : {"a set of artisan's tools (your choice)" : 1, "a shovel" : 1, "an iron pot" : 1, "a set of common clothes" : 1, "gp" : 10}, "features" : {"Rustic Hospitality" : "Since you come from the ranks of the common folk, you fit in among them with ease. You can find a place to hide, rest, or recuperate among other commoners, unless you have shown yourself to be a danger to them. They will shield you from the law or anyone else searching for you, though they will not risk their lives for you."}}, "guild artisan" : {"desc" : "You are a member of an artisan�s guild, skilled in a particular field and closely associated with other artisans. You are a well-established part of the mercantile world, freed by talent and wealth from the constraints of a feudal social order. You learned your skills as an apprentice to a master artisan, under the sponsorship of your guild, until you became a master in your own right.", "proficiencies" : {"skills" : ["insight", "persuasion"], "tools" : ["one type of artisan's tools"]}, "languages" : ["choose 1"], "equipment" : {"a set of artisan's tools (one of your choice)" : 1, "a letter of introduction from your guild" : 1, "a set of traveler's clothes" : 1, "gp" : 15}, "features" : {"Guild Membership" : "As an established and respected member of a guild, you can rely on certain benefits that membership provides. Your fellow guild members will provide you with lodging and food if necessary, and pay for your funeral if needed. In some cities and towns, a guildhall offers a central place to meet other members of your profession, which can be a good place to meet potential patrons, allies, or hirelings. Guilds often wield tremendous political power. If you are accused of a crime, your guild will support you if a good case can be made for your innocence or the crime is justifiable. You can also gain access to powerful political figures through the guild, if you are a member in good standing. Such connections might require the donation of money or magic items to the guild�s coffers. You must pay dues of 5 gp per month to the guild. If you miss payments, you must make up back dues to remain in the guild�s good graces."}}, "hermit" : {"desc" : "You lived in seclusion - either in a sheltered community such as a monastery, or entirely alone - for a formative part of your life. In your time apart from the clamor of society, you found quiet, solitude, and perhaps some of the answers you were looking for.", "proficiencies" : {"skills" : ["medicine", "religion"], "tools" : ["herbalism kit"]}, "languages" : ["choose 1"], "equipment" : {"a scroll case stuffed full of notes from your studies or prayers" : 1, "a winter blanket" : 1, "a set of common clothes" : 1, "an herbalism kit" : 1, "gp" : 5}, "features" : {"Discovery" : "The quiet seclusion of your extended hermitage gave you access to a unique and powerful discovery. The exact nature of this revelation depends on the nature of your seclusion. It might be a great truth about the cosmos, the deities, the powerful beings of the outer planes, or the forces of nature. It could be a site that no one else has ever seen. You might have uncovered a fact that has long been forgotten, or unearthed some relic of the past that could rewrite history. It might be information that would be damaging to the people who consigned you to exile, and hence the reason for your return to society. Work with your DM to determine the details of your discovery and its impact on the campaign."}}, "noble" : {"desc" : "You understand wealth, power, and privilege. You carry a noble title, and your family owns land, collects taxes, and wields significant political influence. You might be a pampered aristocrat unfamiliar with work or discomfort, a former merchant just elevated to the nobility, or a disinherited scoundrel with a disproportionate sense of entitlement. Or you could be an honest, hard-working landowner who cares deeply about the people who live and work on your land, keenly aware of your responsibility to them.", "proficiencies" : {"skills" : ["history", "persuasion"], "tools" : ["one type of gaming set"]}, "languages" : ["choose 1"], "equipment" : {"a set of fine clothes" : 1, "a signet ring" : 1, "a scroll of pedigree" : 1, "gp" : 25}, "features" : {"Position of Privilege" : "Thanks to your noble birth, people are inclined to think the best of you. You are welcome in high society, and people assume you have the right to be wherever you are. The common folk and merchants make every effort to accommodate you and avoid your displeasure, and other people of high birth treat you as a member of the same social sphere. You can secure an audience with a local noble if you need to."}}, "outlander" : {"desc" : "You grew up in the wilds, far from civilization and the comforts of town and technology. You�ve witnessed the migration of herds larger than forests, survived weather more extreme than any city-dweller could comprehend, and enjoyed the solitude of being the only thinking creature for miles in any direction. The wilds are in your blood, whether you were a nomad, an explorer, a recluse, a hunter-gatherer, or even a marauder. Even in places where you don�t know the specific features of the terrain, you know the ways of the wild.", "proficiencies" : {"skills" : ["athletics", "survival"], "tools" : ["one type of musical instrument"]}, "languages" : ["choose 1"], "equipment" : {"a staff" : 1, "a hunting trap" : 1, "a trophy from an animal you killed" : 1, "a set of traveler's clothes" : 1, "gp" : 10}, "features" : {"Wanderer" : "You have an excellent memory for maps and geography, and you can always recall the general layout of terrain, settlements, and other features around you. In addition, you can find food and fresh water for yourself and up to five other people each day, provided that the land offers berries, small game, water, and so forth."}}, "sage" : {"desc" : "You spent years learning the lore of the multiverse. You scoured manuscripts, studied scrolls, and listened to the greatest experts on the subjects that interest you. Your efforts have made you a master in your fields of study.", "proficiencies" : {"skills" : ["arcana", "history"]}, "languages" : ["choose 2"], "equipment" : {"a bottle of black ink" : 1, "a quill" : 1, "a small knife" : 1, "a letter from a dead colleague posing a question you have not been able to answer" : 1, "a set of common clothes" : 1, "gp" : 10}, "features" : {"Researcher" : "When you attempt to learn or recall a piece of lore, if you do not know that information, you often know where and from whom you can obtain it. Usually, this information comes from a library, scriptorium, university, or a sage or other learned person or creature. Your DM might rule that the knowledge you seek is secreted away in an almost inaccessible place, or that it simply cannot be found. Unearthing the deepest secrets of the multiverse can require an adventure or even a whole campaign."}}, "sailor" : {"desc" : "You sailed on a seagoing vessel for years. In that time, you faced down mighty storms, monsters of the deep, and those who wanted to sink your craft to the bottomless depths. Your first love is the distant line of the horizon, but the time has come to try your hand at something new.", "proficiencies" : {"skills" : ["athletics", "perception"], "tools" : ["navigator's tools", "vehicles (water)"]}, "equipment" : {"a belaying pin (club)" : 1, "50 feet of silk rope" : 1, "a lucky charm such as a rabbit foot or a small stone with a hole in the center" : 1, "a set of common clothes" : 1, "gp" : 10}, "features" : {"Ship's Passage" : "When you need to, you can secure free passage on a sailing ship for yourself and your adventuring companions. You might sail on the ship you served on, or another ship you have good relations with (perhaps one captained by a former crewmate). Because you�re calling in a favor, you can�t be certain of a schedule or route that will meet your every need. Your Dungeon Master will determine how long it takes to get where you need to go. In return for your free passage, you and your companions are expected to assist the crew during the voyage."}}, "soldier" : {"desc" : "War has been your life for as long as you care to remember. You trained as a youth, studied the use of weapons and armor, learned basic survival techniques, including how to stay alive on the battlefield. You might have been part of a standing national army or a mercenary company, or perhaps a member of a local militia who rose to prominence during a recent war.", "proficiencies" : {"skills" : ["athletics", "intimidation"], "tools" : ["one type of gaming set", "vehicles (land)"]}, "equipment" : {"an insignia of rank" : 1, "a trophy taken from a fallen enemy (a dagger, broken blade, or piece of banner" : 1, "a set of bone dice or deck of cards" : 1, "a set of common clothes" : 1, "gp" : 10}, "features" : {"Military Rank" : "You have a military rank from your career as a soldier. Soldiers loyal to your former military organization still recognize your authority and influence, and they defer to you if they are of a lower rank. You can invoke your rank to exert influence over other soldiers and requisition simple equipment or horses for temporary use. You can also usually gain access to friendly military encampments and fortresses where your rank is recognized."}}, "urchin" : {"desc" : "You grew up on the streets alone, orphaned, and poor. You had no one to watch over you or to provide for you, so you learned to provide for yourself. You fought fiercely over food and kept a constant watch out for other desperate souls who might steal from you. You slept on rooftops and in alleyways, exposed to the elements, and endured sickness without the advantage of medicine or a place to recuperate. You've survived despite all odds, and did so through cunning, strength, speed, or some combination of each.", "proficiencies" : {"skills" : ["sleight of hand", "stealth"], "tools" : ["disguise kit", "thieves' tools"]}, "equipment" : {"a small knife" : 1, "a map of the city you grew up in" : 1, "a pet mouse" : 1, "a token to remember your parents by" : 1, "a set of common clothes" : 1, "gp" : 10}, "features" : {"City Secrets" : "You know the secret patterns and flow to cities and can find passages through the urban sprawl that others would miss. When you are not in combat, you (and companions you lead) can travel between any two locations in the city twice as fast as your speed would normally allow."}}} temp = sheet print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please choose a background from the following options: ") if(temp["recommended"] != {}): print("(Suggested background based on your class is " + temp["recommended"]["background"] + ".)") for b in sorted(backgrounds): print("-----------------------------") print("Background: " + b) print("\nDescription: " + backgrounds[b]["desc"]) print("-----------------------------") background = input("Which background would you like to come from?\n") #Check to make sure the input race is valid if not background in backgrounds: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid background (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseBackground(sheet, rand) else: #Update background temp["background"] = background #Update features if "features" in backgrounds[background]: temp["features"].update(backgrounds[background]["features"]) #Update languages if "languages" in backgrounds[background]: for l in backgrounds[background]["languages"]: if(l.split(' ')[0] == "choose"): temp = chooseLanguages(temp, int(l.split(' ')[1])) else: temp["languages"].append(l) #Update proficiencies if "proficiencies" in backgrounds[background]: #Update weapon proficiencies if "weapons" in backgrounds[background]["proficiencies"]: temp["proficiencies"]["weapons"].extend(backgrounds[background]["proficiencies"]["weapons"]) #Update armor proficiencies if "armor" in backgrounds[background]["proficiencies"]: temp["proficiencies"]["armor"].extend(backgrounds[background]["proficiencies"]["armor"]) #Update skill proficiencies if "skills" in backgrounds[background]["proficiencies"]: for s in backgrounds[background]["proficiencies"]["skills"]: if(s.split(' ')[0] == "choose"): temp = chooseSkills(temp, int(s.split(' ')[1])) else: if(temp["skills"][s]["proficient"]): temp = chooseSkills(temp, 1) else: temp["skills"][s]["proficient"] = True temp["skills"][s]["mod"] += temp["proficiency"] #Update tool proficiencies if "tools" in backgrounds[background]["proficiencies"]: for t in backgrounds[background]["proficiencies"]["tools"]: if(t == "choose one"): chosen = chooseOneTool(backgrounds[background]["proficiencies"]["tools"][t]) temp["proficiencies"]["tools"].extend([chosen]) else: temp["proficiencies"]["tools"].extend([t]) if "equipment" in backgrounds[background]: for e in backgrounds[background]["equipment"]: if e in temp["equipment"]: temp["equipment"][e] += backgrounds[background]["equipment"][e] else: temp["equipment"][e] = backgrounds[background]["equipment"][e] return temp def randomScore(): """Rolls 4 d6, drops the lowest.""" scores = [] for _ in range(4): scores.append(d6()) my_min = min(scores) scores.remove(my_min) return sum(scores) def doAbilityScores(sheet, values=None): """Does the ability scores. Allows the user to choose between standard array and rolling for scores.""" methods = ["standard", "roll"] temp = sheet if(values != None): print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") if(values==None): method = input("Would you like to use the standard array, or roll for scores? Please type 'standard' or 'roll'.\n") if method not in methods: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid method - either 'standard' or 'roll' (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return doAbilityScores(sheet, values) else: if(method == "roll"): values = sorted([randomScore(), randomScore(), randomScore(), randomScore(), randomScore(), randomScore()], reverse=True) else: values = sorted([8, 10, 12, 13, 14, 15], reverse=True) return doAbilityScores(temp, values) else: if(values == []): return sheet else: #Get current options options = [] for s in temp["scores"]: if not temp["scores"][s]["assigned"]: options.append(s) #Get which score they want to assign to current_val = values[0] print("Your remaining values to assign are " + str(values)) print("Please select the ability to which you would like to assign " + str(current_val) + ".") if(temp["recommended"] != None and len(values) == 6): print("(Recommended ability based on your class is " + temp["recommended"]["first"] + ".)") elif(temp["recommended"] != None and len(values) == 5): print("(Recommended ability based on your class is " + temp["recommended"]["second"] + ".)") print("-----------------------------") current = 1 while current < 7: for o in options: if sheet["scores"][o]["order"] == current: print(o + " (currently " + str(temp["scores"][o]["val"]) + ")") current += 1 print("-----------------------------") choice = input("To which ability would you like to assign " + str(current_val) + "?\n") if choice not in options: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid ability. (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return doAbilityScores(sheet, values) else: temp["scores"][choice]["val"] += current_val temp["scores"][choice]["assigned"] = True return doAbilityScores(temp, values[1:]) def doAbilityMods(sheet): """Associates the appropriate modifiers with each ability score.""" mods = {1 : -5, 2 : -4, 3 : -4, 4 : -3, 5 : -3, 6 : -2, 7 : -2, 8 : -1, 9 : -1, 10 : 0, 11 : 0, 12 : 1, 13 : 1, 14 : 2, 15 : 2, 16 : 3, 17 : 3, 18 : 4, 19 : 4, 20 : 5, 21 : 5, 22 : 6, 23 : 6, 24 : 7, 25 : 7, 26 : 8, 27 : 8, 28 : 9, 29 : 9, 30 : 10} temp = sheet for s in temp["scores"]: temp["scores"][s]["mod"] = mods[temp["scores"][s]["val"]] return temp def doBarbarian(sheet): """This is called when the Barbarian class is chosen.""" temp = sheet #Update class temp["class"] = "barbarian" #Set the recommended scores and background temp["recommended"]["first"] = "str" temp["recommended"]["second"] = "con" temp["recommended"]["background"] = "outlander" _ = input("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nNow, we will choose your background. This will determine what kind of life your character led before they became an adventurer. Press enter to continue.\n") temp = chooseBackground(temp, False) #Do Ability Scores print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nNow we will assign your ability scores. These form the basis for your character's stats.") temp = doAbilityScores(temp) #Hit Points temp["combat info"]["hit dice amt"] = 1 temp["combat info"]["hit dice type"] = "d12" temp["combat info"]["hp"] = 12 + temp["scores"]["con"]["mod"] #Proficiencies temp["proficiencies"]["armor"].extend(["light armor", "medium armor", "shields"]) temp["proficiencies"]["weapons"].extend(["simple weapons", "martial weapons"]) #saving throws temp["saves"]["str"] += temp["proficiency"] temp["saves"]["con"] += temp["proficiency"] #skills temp = chooseSkills(temp, 2, ["animal handling", "athletics", "intimidation", "nature", "perception", "stealth"]) #Equipment #greataxe temp["equipment"].update({"a greataxe" : 1}) if(temp["scores"]["str"]["mod"] >= 0): temp["attacks"].update({"Greataxe" : "+" + str(temp["proficiency"] + temp["scores"]["str"]["mod"]) + " to hit, 1d12+" + str(temp["scores"]["str"]["mod"]) + " slashing"}) else: temp["attacks"].update({"Greataxe" : "+" + str(temp["proficiency"] + temp["scores"]["str"]["mod"]) + " to hit, 1d12" + str(temp["scores"]["str"]["mod"]) + " slashing"}) #handaxes temp["equipment"].update({"a handaxe" : 2}) if(temp["scores"]["str"]["mod"] >= 0): temp["attacks"].update({"Handaxe (melee)" : "+" + str(temp["proficiency"] + temp["scores"]["str"]["mod"]) + " to hit, 1d6+" + str(temp["scores"]["str"]["mod"]) + " slashing"}) else: temp["attacks"].update({"Handaxe (melee)" : "+" + str(temp["proficiency"] + temp["scores"]["str"]["mod"]) + " to hit, 1d6" + str(temp["scores"]["str"]["mod"]) + " slashing"}) if(temp["scores"]["dex"]["mod"] >= 0): temp["attacks"].update({"Handaxe (ranged 20/60)" : "+" + str(temp["proficiency"] + temp["scores"]["dex"]["mod"]) + " to hit, 1d6+" + str(temp["scores"]["dex"]["mod"]) + " slashing"}) else: temp["attacks"].update({"Handaxe (ranged 20/60)" : "+" + str(temp["proficiency"] + temp["scores"]["dex"]["mod"]) + " to hit, 1d6" + str(temp["scores"]["dex"]["mod"]) + " slashing"}) #javelins temp["equipment"].update({"javelin" : 4}) if(temp["scores"]["str"]["mod"] >= 0): temp["attacks"].update({"Javelin (melee)" : "+" + str(temp["proficiency"] + temp["scores"]["str"]["mod"]) + " to hit, 1d6+" + str(temp["scores"]["str"]["mod"]) + " piercing"}) else: temp["attacks"].update({"Javelin (melee)" : "+" + str(temp["proficiency"] + temp["scores"]["str"]["mod"]) + " to hit, 1d6" + str(temp["scores"]["str"]["mod"]) + " piercing"}) if(temp["scores"]["dex"]["mod"] >= 0): temp["attacks"].update({"Javelin (ranged 30/120)" : "+" + str(temp["proficiency"] + temp["scores"]["dex"]["mod"]) + " to hit, 1d6+" + str(temp["scores"]["dex"]["mod"]) + " piercing"}) else: temp["attacks"].update({"Javelin (ranged 30/120)" : "+" + str(temp["proficiency"] + temp["scores"]["dex"]["mod"]) + " to hit, 1d6" + str(temp["scores"]["dex"]["mod"]) + " piercing"}) #explorer's pack temp["equipment"].update({"backpack" : 1, "bedroll" : 1, "mess kit" : 1, "tinderbox" : 1, "torches" : 10, "one day of rations" : 10, "waterskin" : 1, "50 feet of hempen rope" : 1}) #Features temp["features"].update({"Rage" : "In battle, you fight with primal ferocity. On your turn, you can enter a rage as a bonus action. While raging, you gain the following benefits if you aren't wearing heavy armor:\n*You have advantage on strength checks and strength saving throws.\n*When you make a melee weapon attack using strength, you gain a +2 bonus to the damage roll. This bonus increases as you level.\n*You have resistance to bludgeoning, piercing, and slashing damage.\nIf you are able to cast spells, you can't cast them or concentrate on them while raging. Your rage lasts for 1 minute. It ends early if you are knocked unconscious or if your turn ends and you haven't attacked a hostile creature since your last turn or taken damage since then. You can also end your rage on Your Turn as a bonus action. Once you have raged the maximum number of times for your barbarian level, you must finish a long rest before you can rage again. You may rage 2 times at 1st level, 3 at 3rd, 4 at 6th, 5 at 12th, and 6 at 17th.", "Unarmored Defense" : "While you are not wearing any armor, your armor class equals 10 + your dexterity modifier + your constitution modifier. You can use a shield and still gain this benefit."}) #AC (accounting for unarmored defense) temp["combat info"]["ac"] += 10 + temp["scores"]["dex"]["mod"] + temp["scores"]["con"]["mod"] # initiative temp["combat info"]["initiative"] = "+" + str(temp["scores"]["dex"]["mod"] + temp["combat info"]["initiative"]) return temp def chooseBardCantrips(sheet, amt): """Adds bard cantrips equal to amt to the spellcasting section of sheet.""" temp = sheet cantrips = ["Blade Ward", "Dancing Lights", "Friends", "Light", "Mage Hand", "Mending", "Message", "Minor Illusion", "Prestidigitation", "True Strike", "Vicious Mockery"] temp_options = [] for c in cantrips: if not c in temp["spellcasting"][0]: temp_options.append(c) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please choose a cantrip from the following options: ") for o in sorted(temp_options): print("-----------------------------") print(o) print("-----------------------------") choice = input("Which cantrip would you like to learn?\n") #Check to make sure the input cantrip is valid if not choice in temp_options: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid cantrip (capitalization matters). Try again!***") time.sleep(2) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseBardCantrips(sheet, amt) else: temp["spellcasting"][0].append(choice) if(amt > 1): temp = chooseBardCantrips(temp, amt - 1) return temp return temp def chooseBardFirstLevel(sheet, amt): """Adds bard lvl 1 spells equal to amt to the spellcasting section of sheet.""" temp = sheet spells = ["Animal Friendship", "Bane", "Charm Person", "Comprehend Languages", "Cure Wounds", "Detect Magic", "Disguise Self", "Dissonant Whispers", "Faerie Fire", "Feather Fall", "Healing Word", "Heroism", "Identify", "Illusory Script", "Longstrider", "Silent Image", "Sleep", "Speak with Animals", "Tasha's Hideous Laughter", "Thunderwave", "Unseen Servant"] temp_options = [] for s in spells: if not s in temp["spellcasting"][1]: temp_options.append(s) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please choose a level one spell from the following options: ") for o in sorted(temp_options): print("-----------------------------") print(o) print("-----------------------------") choice = input("Which spell would you like to learn?\n") #Check to make sure the input cantrip is valid if not choice in temp_options: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid spell (capitalization matters). Try again!***") time.sleep(2) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseBardFirstLevel(sheet, amt) else: temp["spellcasting"][1].append(choice) if(amt > 1): temp = chooseBardFirstLevel(temp, amt - 1) return temp return temp def doBard(sheet): """This is called when the Bard class is chosen.""" temp = sheet skills = ["acrobatics", "animal handling", "arcana", "athletics", "deception", "history", "insight", "intimidation", "investigation", "medicine", "nature", "perception", "performance", "persuasion", "religion", "sleight of hand", "stealth", "survival"] #Update class temp["class"] = "bard" #Set the recommended scores and background temp["recommended"]["first"] = "cha" temp["recommended"]["second"] = "dex" temp["recommended"]["background"] = "entertainer" temp["recommended"]["spells"] = {"dancing lights" : 0, "vicious mockery" : 0, "charm person" : 1, "detect magic" : 1, "healing word" : 1, "thunderwave" : 1} _ = input("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nNow, we will choose your background. This will determine what kind of life your character led before they became an adventurer. Press enter to continue.\n") temp = chooseBackground(temp, False) #Do Ability Scores print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nNow we will assign your ability scores. These form the basis for your character's stats.") temp = doAbilityScores(temp) #Hit Points temp["combat info"]["hit dice amt"] = 1 temp["combat info"]["hit dice type"] = "d8" temp["combat info"]["hp"] = 8 + temp["scores"]["con"]["mod"] #Proficiencies temp["proficiencies"]["armor"].extend(["light armor"]) temp["proficiencies"]["weapons"].extend(["simple weapons", "hand crossbows", "longswords", "rapiers", "shortswords"]) temp["proficiencies"]["tools"].extend(["three musical instruments of your choice."]) #saving throws temp["saves"]["dex"] += temp["proficiency"] temp["saves"]["cha"] += temp["proficiency"] #skills temp = chooseSkills(temp, 3, skills) #Equipment #Rapier temp["equipment"].update({"a rapier" : 1}) if(temp["scores"]["str"]["mod"] > temp["scores"]["dex"]["mod"]): better = "str" else: better = "dex" if(temp["scores"][better]["mod"] >= 0): temp["attacks"].update({"Rapier" : "+" + str(temp["proficiency"] + temp["scores"][better]["mod"]) + " to hit, 1d8+" + str(temp["scores"][better]["mod"]) + " piercing"}) else: temp["attacks"].update({"Rapier" : "+" + str(temp["proficiency"] + temp["scores"][better]["mod"]) + " to hit, 1d8" + str(temp["scores"][better]["mod"]) + " piercing"}) #dagger temp["equipment"].update({"a dagger" : 1}) if(temp["scores"]["str"]["mod"] > temp["scores"]["dex"]["mod"]): better = "str" else: better = "dex" if(temp["scores"][better]["mod"] >= 0): temp["attacks"].update({"Dagger (melee)" : "+" + str(temp["proficiency"] + temp["scores"][better]["mod"]) + " to hit, 1d4+" + str(temp["scores"][better]["mod"]) + " piercing"}) else: temp["attacks"].update({"Dagger (melee)" : "+" + str(temp["proficiency"] + temp["scores"][better]["mod"]) + " to hit, 1d4" + str(temp["scores"][better]["mod"]) + " piercing"}) if(temp["scores"]["dex"]["mod"] >= 0): temp["attacks"].update({"Dagger (ranged 20/60)" : "+" + str(temp["proficiency"] + temp["scores"]["dex"]["mod"]) + " to hit, 1d4+" + str(temp["scores"]["dex"]["mod"]) + " piercing"}) else: temp["attacks"].update({"Dagger (ranged 20/60)" : "+" + str(temp["proficiency"] + temp["scores"]["dex"]["mod"]) + " to hit, 1d4" + str(temp["scores"]["dex"]["mod"]) + " piercing"}) #entertainer's pack temp["equipment"].update({"backpack" : 1, "bedroll" : 1, "costume" : 2, "candle" : 5, "one day of rations" : 5, "waterskin" : 1, "disguise kit" : 1}) #A musical instrument temp["equipment"].update({"one musical instrument of your choice." : 1}) #Leather Armor temp["equipment"].update({"leather armor" : 1}) #Features temp["features"].update({"Bardic Inspiration" : "You can use a bonus action on your turn to choose one creature other than yourself within 60 feet of you who can hear you. That creature gains one Bardic Inspiration die, a d6. Once within the next 10 minutes, the creature can roll the die and add the number rolled to one ability check, attack roll, or saving throw it makes. The creature can wait until after it rolls the d20 before deciding to use the Bardic Inspiration die, but must decide before the DM says whether the roll succeeds or fails. Once the Bardic Inspiration die is rolled, it is lost. A creature can have only one Bardic Inspiration die at a time. You can use this feature a number of times equal to your Charisma modifier (a minimum of once). You regain any expended uses when you finish a long rest. Your Bardic Inspiration die changes when you reach certain levels in this class. The die becomes a d8 at 5th level, a d10 at 10th level, and a d12 at 15th level."}) temp["features"].update({"Spellcasting" : "You have learned to untangle and reshape the fabric of reality in harmony with your wishes and music. Your spells are part of your vast repertiore, magic that you can tune to different situations."}) #Spellcasting temp["spellcasting"] = {0 : [], 1 : [], "slots" : {}} temp = chooseBardCantrips(temp, 2) temp = chooseBardFirstLevel(temp, 4) temp["spellcasting"]["slots"].update({"1st" : 2}) temp["spellcasting"]["dc"] = 8 + temp["proficiency"] + temp["scores"]["cha"]["mod"] temp["spellcasting"]["mod"] = temp["proficiency"] + temp["scores"]["cha"]["mod"] #AC (accounting for unarmored defense) temp["combat info"]["ac"] += 11 + temp["scores"]["dex"]["mod"] # initiative temp["combat info"]["initiative"] = "+" + str(temp["scores"]["dex"]["mod"] + temp["combat info"]["initiative"]) return temp def chooseClass(sheet, rand): """Chooses a class.""" classes = {"barbarian" : "A fierce warrior of a primitive background who can enter a battle rage", "bard" : "An inspiring magician whose power echoes the music of creation.", "cleric" : "A priestly champion who wields divine magic in service of a higher power.", "druid" : "A priest of the Old Faith, wielding the powers of nature - moonlight and plant growth, fire and lightning - and adopting animal forms." , "fighter" : "A master of martial combat, skilled with a variety of weapons and armors.", "monk" : "A master of martial arts, skilled with fighting hands and martial monk weapons.", "paladin" : "A holy warrior bound to a sacred oath.", "ranger" : "A master of ranged combat, one with nature.", "rogue" : "A scoundrel and agile warrior who uses stealth and trickery to overcome obstacles and enemies.", "sorceror" : "A spellcaster who draws on inherent magic from a gift or bloodline.", "warlock" : "A wielder of magic that is derived from a bargain with an extraplanar entity.", "wizard" : "A scholarly magic-user capable of manipulating the structures of reality."} temp = sheet print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("Please choose a class from the following options: ") for c in sorted(classes): print("-----------------------------") print("Class: " + c) print("\nDescription: " + classes[c]) print("-----------------------------") choice = input("Which class would you like to play as?\n") #Check to make sure the input race is valid if not choice in classes: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("***Please enter a valid class (capitalization matters). Try again!***") time.sleep(3) print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") return chooseClass(sheet, rand) else: if(choice == "barbarian"): temp = doBarbarian(temp) elif(choice == "bard"): temp = doBard(temp) return temp def updateSkillMods(sheet): """Takes a sheet and updates the skill modifiers.""" temp = sheet for s in temp["skills"]: temp["skills"][s]["mod"] += temp["scores"][temp["skills"][s]["base"]]["mod"] return temp def updateSaves(sheet): """Takes a sheet and updates the saving throws based on the ability mods.""" temp = sheet for s in temp["saves"]: temp["saves"][s] += temp["scores"][s]["mod"] return temp def updatePassives(sheet): """Takes a sheet and sets the passive insight, perception, and investigation.""" temp = sheet for p in temp["passives"]: temp["passives"][p] += 10 + temp["skills"][p]["mod"] return temp def setName(sheet): """Asks the player for their character's name and stores it in the sheet.""" temp = sheet name = input("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nLast but not least, please enter your character's name. Don't be afraid to get creative!\n") temp["name"] = name return sheet def main(): _ = input("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nWelcome to the DnD Character Creator! We will start by choosing your character's race. Press enter to continue.") sheet = genSheetTemplate() sheet = chooseRace(sheet, False) _ = input("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nNow, we will choose your character's class. This is the most defining aspect of your character, so choose wisely. Press enter to continue.\n") sheet = chooseClass(sheet, False) sheet = setName(updatePassives(updateSaves(updateSkillMods(doAbilityMods(sheet))))) printSheet(sheet) if __name__ == "__main__": main()
Shader "Custom/Scanlines" { Properties { _MainTex("Texture", 2D) = "white" {} _ScanlineIntensity("Scanline Intensity", Range(0, 1)) = 0.5 _ScanlineFrequency("Scanline Frequency", Range(0.1, 200.)) = 100.1 } SubShader { Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct v2f { float2 uv : TEXCOORD0; float4 vertex : SV_POSITION; }; sampler2D _MainTex; float _ScanlineIntensity; float _ScanlineFrequency; v2f vert(appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv = v.uv; return o; } fixed4 frag(v2f i) : SV_Target { float4 col = tex2D(_MainTex, i.uv); float scanline = (frac(i.vertex.y * _ScanlineFrequency) < 0.5) ? 1.0 : 0.0; col.rgb -= col.rgb * scanline * _ScanlineIntensity; return col; } ENDCG } } FallBack "Diffuse" }
// // Created by Ximena on 10-06-2024. // #ifndef THREAD_H #define THREAD_H #include <thread> #include <vector> #include <mutex> #include "Laberinto.h" using namespace std; class Thread { private: Laberinto &laberinto; mutex mtx; bool resuelto = false; vector<thread> threads; public: /** * Constructor de Thread * @param lab */ Thread(Laberinto &lab); /** * Destructor de Thread */ ~Thread(); /** * Metodo que se vuelve true si el recorrido llega a la salida * @return resuelto */ bool isResuelto(); /** * Metodo que resuelve el laberinto segun el hilo y sus coordenadas * @param x coordenada en x del laberinto * @param y coordenada en y del laberinto * @param hilo indica cual es el hilo que esta usando el metodo */ void resolverLab(int x, int y, int hilo); /** * Metodo con orden de verificacion con inicio desde la Izquierda * @param x coordenada en x del laberinto * @param y coordenada en y del laberinto */ void resolverIzquierdaPrimero(int x, int y); /** * Metodo con orden de verificacion con inicio desde Arriba * @param x coordenada en x del laberinto * @param y coordenada en y del laberinto */ void resolverArribaPrimero(int x, int y); /** * Metodo con orden de verificacion con inicio desde la Derecha * @param x coordenada en x del laberinto * @param y coordenada en y del laberinto */ void resolverDerechaPrimero(int x, int y); /** * Metodo con orden de verificacion con inicio desde Abajo * @param x coordenada en x del laberinto * @param y coordenada en y del laberinto */ void resolverAbajoPrimero(int x, int y); /** * Metodo que da inicio a la resolucion del laberinto, creando hilos para este objetivo */ void comienzaAResolver(); }; #endif //THREAD_H
import Image from "next/image" export async function generateStaticParams(){ const data = await fetch( `https://api.themoviedb.org/3/movie/popular?api_key=${process.env.API_KEY}` , {next: {revalidate: 0}} ) const res = await data.json() return res.results.map((movie) => ({ movie : toString(movie.id), })) } export default async function MovieDetail({params}) { const imagePath = 'https://image.tmdb.org/t/p/original/' const data = await fetch( `https://api.themoviedb.org/3/movie/${params.movie}?api_key=${process.env.API_KEY}` ) const res = await data.json() return( <div> <div> <h2 className="text-2xl">{res.title}</h2> <h2 className="text-lg">{res.release_date}</h2> <h2 className="">Runtime : {res.runtime} minutes</h2> <h2 className="text-sm bg-green-600 inline-block my-2 py-1 px-2 rounded-md">{res.status}</h2> <Image className="my-12 w-full" src={imagePath + res.backdrop_path} width={1000} height={1000} priority /> <p>{res.overview}</p> </div> </div> ) }
import { Injectable } from '@nestjs/common'; import { IDataServices } from 'src/core/abstracts/data-services.abstract'; import { Cat } from 'src/core/entities/cat.entity'; @Injectable() export class CatUseCases { constructor(private readonly dataServices: IDataServices) {} async getAllCats(): Promise<Cat[]> { const cats = await this.dataServices.cats.getAll(); return cats; } async getCatById(id: string): Promise<Cat> { const cat = await this.dataServices.cats.get(id); return cat; } async createCat(cat: Cat): Promise<Cat> { try { const createdCat = await this.dataServices.cats.create(cat); return createdCat; } catch (e) { throw e; } } async updateCat(catId: string, cat: Cat): Promise<boolean> { try { const isSucess = await this.dataServices.cats.update(catId, cat); return isSucess; } catch (e) { return false; } } }
package com.example.lastlastversiondiplom import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.* import com.example.lastlastversiondiplom.db.Painting import com.example.lastlastversiondiplom.db.PaintingDatabase import com.squareup.picasso.Picasso import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import kotlin.random.Random import kotlinx.coroutines.* class QuizActivity : AppCompatActivity() { private lateinit var painting: Painting private lateinit var answerOptions: MutableList<String> private lateinit var questionText: TextView private lateinit var questionImage: ImageView private lateinit var option1: RadioButton private lateinit var option2: RadioButton private lateinit var option3: RadioButton private lateinit var option4: RadioButton private lateinit var submitButton: Button private lateinit var progressBar: ProgressBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_quiz) // Находим все View по их id questionText = findViewById(R.id.question_text) questionImage = findViewById(R.id.question_image) option1 = findViewById(R.id.option1) option2 = findViewById(R.id.option2) option3 = findViewById(R.id.option3) option4 = findViewById(R.id.option4) submitButton = findViewById(R.id.submit_answer_button) progressBar = findViewById(R.id.progress_bar) // Показываем индикатор загрузки progressBar.visibility = View.VISIBLE // Получаем случайную картину из базы данных GlobalScope.launch(Dispatchers.Main) { painting = getRandomPaintingFromDatabase() // Получаем четыре случайных варианта ответа, включая правильный answerOptions = mutableListOf(painting.author) while (answerOptions.size < 4) { val randomOption = getRandomAuthorFromDatabase() if (!answerOptions.contains(randomOption)) { answerOptions.add(randomOption) } } // Случайным образом перемешиваем варианты ответов answerOptions.shuffle() // Загружаем изображение картины в ImageView с помощью библиотеки Picasso val file = withContext(Dispatchers.IO) { File.createTempFile("image", ".jpg", applicationContext.cacheDir) } withContext(Dispatchers.IO) { file.writeBytes(painting.image ?: return@withContext) } Picasso.get().load(file).into(questionImage) // Устанавливаем текст вопроса и вариантов ответов questionText.text = getString(R.string.question_template, painting.title) option1.text = answerOptions[0] option2.text = answerOptions[1] option3.text = answerOptions[2] option4.text = answerOptions[3] // Скрываем индикатор загрузки progressBar.visibility = View.GONE } // Устанавливаем обработчик клика на кнопку submitButton.setOnClickListener { checkAnswer() } } private suspend fun getRandomPaintingFromDatabase(): Painting { return withContext(Dispatchers.IO) { val paintings = PaintingDatabase.getInstance(this@QuizActivity).paintingDao().getAllPaintings() if (isActive && paintings.isNotEmpty()) { paintings[Random.nextInt(paintings.size)] } else { Painting() } } } private suspend fun getRandomAuthorFromDatabase(): String { return withContext(Dispatchers.IO) { val authors = PaintingDatabase.getInstance(this@QuizActivity).paintingDao().getAllAuthors() if (isActive && authors.isNotEmpty()) { authors[Random.nextInt(authors.size)] } else { "" } } } private fun checkAnswer() { // Находим выбранный вариант ответа val answerOptions = findViewById<RadioGroup>(R.id.answer_options) val selectedOption = findViewById<RadioButton>(answerOptions.checkedRadioButtonId) // Запускаем корутин для проверки ответа GlobalScope.launch { // Проверяем, является ли выбранный вариант ответа правильным if (selectedOption.text == painting.author) { withContext(Dispatchers.Main) { Toast.makeText(this@QuizActivity, R.string.correct_answer_message, Toast.LENGTH_SHORT).show() } } else { withContext(Dispatchers.Main) { Toast.makeText(this@QuizActivity, R.string.incorrect_answer_message, Toast.LENGTH_SHORT).show() } } // Задерживаем закрытие активити на 2 секунды delay(2000) // Закрываем активити withContext(Dispatchers.Main) { finish() } } } }
import dbConnect from "@/lib/dbConnect"; import UserModel from "@/model/User"; import bcrypt from "bcryptjs"; import { sendVerificationEmail } from "@/helpers/sendVerificationEmail"; export async function POST(request: Request) { await dbConnect() try { const {username, email, password} = await request.json() const existingUserVerifiedByUsername = await UserModel.findOne({ username, isVerified: true }) if (existingUserVerifiedByUsername){ return Response.json({ success: false, message: "Username is already taken" }, {status: 409, statusText: 'Username already taken (conflict)'}) } const existingUserByEmail = await UserModel.findOne({ email, }) const verifyCode = Math.floor(100000 + Math.random() * 900000).toString() if (existingUserByEmail){ if(existingUserByEmail.isVerified){ return Response.json({ success: false, message: "Email already exists" }, {status: 409, statusText: "Email Conflict"}) }else{ const hashedPassword = await bcrypt.hash(password, 10) existingUserByEmail.password = hashedPassword; existingUserByEmail.verifyCode = verifyCode; existingUserByEmail.verifyCodeExpiry = new Date(Date.now() + 3600000) await existingUserByEmail.save() } }else{ const hashedPassword = await bcrypt.hash(password, 10); const expiryDate = new Date() expiryDate.setHours(expiryDate.getHours() + 1) const newUser = new UserModel({ username, email, password: hashedPassword, verifyCode, verifyCodeExpiry: expiryDate, isVerified: false, isAcceptingMessage: true, messages: [] }) await newUser.save() } // send verification email const emailResponse = await sendVerificationEmail(email, username, verifyCode) if (!emailResponse.success){ return Response.json({ success: false, message: emailResponse.message }, {status: 500, statusText: 'Internal Server Error'}) } return Response.json({ success: true, message: "User Registered Successfully. Please verify your email" }, {status: 201, statusText: 'User Created'}) } catch (error) { console.error("Error registering user", error); return Response.json( { success: false, message: "Error registering user", }, { status: 500, statusText: "Internal Server Error", } ) } }
import { ApiProperty } from '@nestjs/swagger'; import { ColumnEntity } from 'src/columns/column.entity'; import { TaskField } from 'src/task-fields/entities/task-field.entity'; import { User } from 'src/users/user.entity'; import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, OneToMany } from 'typeorm'; @Entity() export class Project { @ApiProperty( { example: 1, description: "id" } ) @PrimaryGeneratedColumn() id: number; @ApiProperty( { example: "project", description: "name" } ) @Column() name: string; @ApiProperty( { example: "project description", description: "description" } ) @Column() description: string; @ApiProperty( { example: "2024-06-08T09:36:59.955Z", description: "created at" } ) @Column() createdAt: Date; @ApiProperty( { description: "user" } ) @ManyToOne(() => User, (user) => user.projects, { onDelete: 'CASCADE' }) user: User; @ApiProperty( { description: "columns" } ) @OneToMany(() => ColumnEntity, (column) => column.project, { cascade: true, onDelete: 'CASCADE' }) columns: ColumnEntity[]; @OneToMany(() => TaskField, field => field.project, { cascade: true, onDelete: 'CASCADE' }) fields: TaskField[]; }
package tn.esprit.demotransaction.Service; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import tn.esprit.demotransaction.Entity.UserLoginRequest; import tn.esprit.demotransaction.Entity.MessageResponse; import tn.esprit.demotransaction.Entity.Phoenix; import java.util.Objects; import java.util.concurrent.TimeUnit; @Slf4j @Service @Component public class ChatWebSocketHandler extends TextWebSocketHandler { @Autowired private ObjectMapper mapper; @Autowired private RestTemplate restTemplate; @Value("${chatbot.url}") private String chatbotUrl; @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { super.handleTextMessage(session, message); log.info("Payload: " + message.getPayload()); UserLoginRequest messageDto = mapper.readValue(message.getPayload(), UserLoginRequest.class); if (StringUtils.isEmpty(messageDto.getMessage())) return; ResponseEntity<MessageResponse> responseEntity; try { responseEntity = restTemplate.postForEntity(chatbotUrl, messageDto, MessageResponse.class); } catch (Exception e) { log.info("Session ID: " + session.getId()); log.error("Happened error", e); session.sendMessage(new TextMessage(mapper.writeValueAsString(UserLoginRequest.builder().message("Sorry the bot is not available at this time.").build()))); return; } MessageResponse messageResponse = responseEntity.getBody(); if (Objects.requireNonNull(messageResponse).getType().equalsIgnoreCase("riddles")) { Phoenix dto = mapper.convertValue(messageResponse.getData(), Phoenix.class); log.info("RiddlesDto:: " + dto); TextMessage question = new TextMessage(mapper.writeValueAsString(UserLoginRequest.builder().message(dto.getQuestion()).build())); TextMessage answer = new TextMessage(mapper.writeValueAsString(UserLoginRequest.builder().message(dto.getAnswer()).build())); session.sendMessage(question); TimeUnit.SECONDS.sleep(1); session.sendMessage(answer); } else { TextMessage response = new TextMessage(mapper.writeValueAsString(messageResponse.getData())); log.info("Response: " + response.getPayload()); session.sendMessage(response); } } }
import React, { useState } from "react"; import FurnitureList from "../FurnitureList"; import FurnitureDetails from "../FurnitureDetails"; import { furnitureFactory } from "../../PatternService/FactoryService"; const Factory = () => { const [furnitureList, setFurnitureList] = useState([]); const [selectedType, setSelectedType] = useState(""); const [color, setColor] = useState(""); const [note, setNote] = useState(""); const [price, setPrice] = useState(""); const handleCreateFurniture = () => { const newFurniture = furnitureFactory.create( selectedType, color, note, price ); setFurnitureList([...furnitureList, newFurniture]); setSelectedType(""); setColor(""); setNote(""); setPrice(""); }; const furnitureTypes = ["Chair", "Table", "Bed"]; return ( <div> <h2 className="mt-3">Factory Pattern - Furniture Creator</h2> <p> <strong>Polish:</strong> Wzorzec projektowy Factory definiuje interfejs do tworzenia obiektów w klasie, pozostawiając podklasom decyzję o zmianie typu tworzonego obiektu. </p> <p> <strong>English:</strong> The Factory design pattern defines an interface for creating objects in a class, allowing subclasses to alter the type of objects that will be created. </p> <FurnitureDetails selectedType={selectedType} color={color} note={note} price={price} furnitureTypes={furnitureTypes} handleCreateFurniture={handleCreateFurniture} setSelectedType={setSelectedType} setColor={setColor} setNote={setNote} setPrice={setPrice} /> <FurnitureList furnitureList={furnitureList} /> </div> ); }; export default Factory;
--- id: Adapter title: Adapter tags: - Adapter - https://github.com/ignatandrei/patterns - structural - design pattern - SQLiteDataAdapter - EncodingAdapter --- # Pattern: Adapter <!-- id : 4 --> Adapter design pattern allows the interface of an existing class to be used as another interface. <br /> It is often used to make existing classes work with others without modifying their source code. <br /> ## Purpose of .NET implementation You want to transfer data from a database Command to a DataTable. <br /> The SQLiteDataAdapter serves as an adapter between the SQLiteCommand object (which represents a SQL command or stored procedure to execute against a SQLite database) and the DataTable object (which represents in-memory data in a tabular format). <br /> ## Examples in .NET : ### SQLiteDataAdapter ```csharp showLineNumbers title="SQLiteDataAdapter example for Pattern Adapter" namespace Adaptor; internal class SQLiteDataAdapterDemo { /// <summary> ///Adaptee - Command ///Target - DataTable ///Adapter - SqlDataAdapter ///Target Method - Fill(Dataset instance) /// </summary> /// <returns></returns> public static async Task MainSqliteAdapterAsync() { //Target: Creates a DataTable instance to hold the data fetched from the database. var dataFormats = new DataTable(); Console.WriteLine(dataFormats.Rows.Count); Console.WriteLine(dataFormats.Columns.Count); using (var con = new SQLiteConnection()) { con.ConnectionString = "Data Source=CatalogRo.sqlite3"; await con.OpenAsync(); using (var cmd = new SQLiteCommand()) { // Adaptee: Sets the SQL command text to fetch all records from the 'Format' table. cmd.CommandText = "select * from Format"; cmd.Connection = con; using (var adapt = new SQLiteDataAdapter(cmd)) { // Adapter: Fills the DataTable (Target) with data fetched using the SQLiteCommand (Adaptee). adapt.Fill(dataFormats); } } } Console.WriteLine(dataFormats.Rows.Count); Console.WriteLine(dataFormats.Columns.Count); } } ``` ### EncodingAdapter ```csharp showLineNumbers title="EncodingAdapter example for Pattern Adapter" namespace Adaptor; internal class EncodingAdapterDemo { /// <summary> ///Adaptee - string ///Target - bytes ///Adapter - encoding ///Target Method - GetBytes /// </summary> public static void AdapterStringByte() { var url = "http://msprogrammer.serviciipeweb.ro"; Encoding e = new ASCIIEncoding(); var b = e.GetBytes(url); Console.WriteLine($"from {e.EncodingName} number bytes {b.Length}"); e = new UTF32Encoding(); b = e.GetBytes(url); Console.WriteLine($"from {e.EncodingName} number bytes {b.Length}"); } } ``` [Download source](/zipSourceCodes/adapter.zip) ## See Source Code for Microsoft implementation of Adapter <a href="https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs" target="_blank">SourceCode AsciiEncoding</a> <br /> <a href="https://github.com/mono/mono/blob/9bb01f57a126dab35f070ce238457931e9814c33/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0/SQLiteDataAdapter.cs#L20" target="_blank">SourceCode SqliteDataAdapter</a> <br /> <a href="https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs" target="_blank">SourceCode UTF32Encoding</a> <br /> ## Learn More <a href="http://wiki.c2.com/?AdapterPattern" target="_blank">C2Wiki</a> <br /> <a href="http://www.dofactory.com/net/Adapter-design-pattern" target="_blank">dofactory</a> <br /> <a href="https://github.com/kamranahmedse/design-patterns-for-humans?tab=readme-ov-file#-Adapter" target="_blank">DPH</a> <br /> <a href="https://en.wikipedia.org/wiki/Adapter_pattern" target="_blank">Wikipedia</a> <br /> ## Homework iPhone 7 does not have a headphone jack. <br /> Implement an adapter that will allow you to use your old headphones , that have jack, with the iPhone 7. <br />
import express, { json } from 'express' import pc from 'picocolors' import morgan from 'morgan' import 'dotenv/config' // Import utils import { corsMiddleware } from './middlewares/cors.js' import pool from './database/db.js' // Import routes import ProductRouter from './routes/products.routes.js' import CategoryRouter from './routes/categories.routes.js' import ProviderRouter from './routes/providers.routes.js' import SuggestionRouter from './routes/suggestion.routes.js' import UserRouter from './routes/users.routes.js' import ReservationStatusRouter from './routes/reservation_statuses.routes.js' import TMStatusRouter from './routes/tools_machines_statuses.routes.js' import ToolsMachinesRouter from './routes/tools_machines.routes.js' import ReservationRouter from './routes/reservation.routes.js' import SalesStatusRouter from './routes/sales_status.routes.js' import SalesRouter from './routes/sales.routes.js' import SalesDetailRouter from './routes/sales_details.routes.js' import ProviderHasCategoryRouter from './routes/providers_has_categories.routes.js' import SendEmailRouter from './routes/sendEmail.routes.js' const PORT = process.env.PORT ?? 3000 // get server port or use 3000 by default const app = express() app.disable('x-powered-by') // dissable header X-Powered-By app.use(json()) // enable json app.use(express.urlencoded({ extended: true })) // enable forms app.use(morgan('dev')) app.use(corsMiddleware()) // enables cors in all routes pool.getConnection() // connect to db .then(conection => { console.log(pc.green('[+] '), pc.white('Database connected to host: '), pc.yellow(process.env.DB_HOST)) conection.release() }) .catch(err => { console.log(pc.red('[-] '), pc.white('Database connection error: '), err) }) app.get('/', (req, res) => { res.send('<h1>Ferreteria Construmanta P</h1>') }) // ROUTES app.use('/api/productos', ProductRouter) app.use('/api/categorias', CategoryRouter) app.use('/api/proveedores', ProviderRouter) app.use('/api/proveedores_tienen_categorias', ProviderHasCategoryRouter) app.use('/api/sugerencias', SuggestionRouter) app.use('/api/usuarios', UserRouter) app.use('/api/estados_reserva', ReservationStatusRouter) app.use('/api/reservas', ReservationRouter) app.use('/api/estados_herramienta_maquina', TMStatusRouter) app.use('/api/herramientas_maquinas', ToolsMachinesRouter) app.use('/api/estados_venta', SalesStatusRouter) app.use('/api/ventas', SalesRouter) app.use('/api/detalles_ventas', SalesDetailRouter) app.use('/api/send_email', SendEmailRouter) // Initialize the server app.listen(PORT, () => { console.log(pc.green('[+] '), pc.white('Server running on port: '), pc.yellow(PORT)) })
// // Colors.swift // WordCounter // // Created by Arrr Park on 2022/05/01. // import UIKit enum Colors: String { case blueJay = "#2B547E" case darkStateBlue = "#2B3856" case deepGreen = "#235264" case deepSkyBlue = "#64AAFF" case skyBlue = "#CCE1FF" static func getColor(hex: String, alpht: Double = 1.0) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.count) != 6) { return UIColor.gray } var rgbValue:UInt64 = 0 Scanner(string: cString).scanHexInt64(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } }
import {Component} from 'react' import './index.css' class Feedback extends Component { state = {isFeedbackSelected: false} onEmojiChange = () => this.setState({isFeedbackSelected: true}) renderFeedBackQuestion = () => { const {resources} = this.props const {emojis} = resources return ( <div className="feedback-question-container"> <h1 className="heading"> How satisfied are you with our customer support performance? </h1> <ul className="emojis-list"> {emojis.map(emoji => ( <li key={emoji.id}> <button className="emoji-btn" type="button" onClick={this.onEmojiChange} > <img src={emoji.imageUrl} alt={emoji.name} className="emoji" /> <br /> <span className="emoji-name">{emoji.name}</span> </button> </li> ))} </ul> </div> ) } renderThankyouSection = () => { const {resources} = this.props const {loveEmojiUrl} = resources return ( <div className="thankyou-container"> <img src={loveEmojiUrl} alt="love emoji" className="love-emoji" /> <h1 className="Thankyou">Thank You!</h1> <p className="description"> we will use your feedback to improve our customer support performance </p> </div> ) } render() { const {isFeedbackSelected} = this.state return ( <div className="container"> <div className="sub-container"> {isFeedbackSelected ? this.renderThankyouSection() : this.renderFeedBackQuestion()} </div> </div> ) } } export default Feedback
/** * __ __ _ __ ___ * WellProdSim * * \ \ /\ / /| '_ \ / __| * @version 1.0 * * \ V V / | |_) |\__ \ * @since 2023 * * \_/\_/ | .__/ |___/ * * * | | * @author Jairo Serrano * * |_| * @author Enrique Gonzalez * * Social Simulator used to estimate productivity and well-being of peasant * * families. It is event oriented, high concurrency, heterogeneous time * * management and emotional reasoning BDI. * */ package wpsPeasantFamily.Goals.L6Leisure; import wpsPeasantFamily.Tasks.L6Leisure.LeisureActivitiesTask; import BESA.BDI.AgentStructuralModel.GoalBDI; import BESA.BDI.AgentStructuralModel.GoalBDITypes; import BESA.BDI.AgentStructuralModel.StateBDI; import BESA.Kernel.Agent.Event.KernellAgentEventExceptionBESA; import rational.RationalRole; import rational.mapping.Believes; import rational.mapping.Plan; import wpsPeasantFamily.Agent.PeasantFamilyBDIAgentBelieves; import wpsActivator.wpsStart; import wpsPeasantFamily.Data.PeasantActivityType; import wpsPeasantFamily.Data.PeasantLeisureType; import wpsPeasantFamily.Data.TimeConsumedBy; import wpsViewer.Agent.wpsReport; /** * * */ public class LeisureActivitiesGoal extends GoalBDI { /** * * @return */ public static LeisureActivitiesGoal buildGoal() { LeisureActivitiesTask leisureActivitiesTask = new LeisureActivitiesTask(); Plan leisureActivitiesPlan = new Plan(); leisureActivitiesPlan.addTask(leisureActivitiesTask); RationalRole leisureActivitiesRole = new RationalRole( "LeisureActivitiesTask", leisureActivitiesPlan); LeisureActivitiesGoal leisureActivitiesGoalBDI = new LeisureActivitiesGoal( wpsStart.getPlanID(), leisureActivitiesRole, "LeisureActivitiesTask", GoalBDITypes.LEISURE); return leisureActivitiesGoalBDI; } /** * * @param id * @param role * @param description * @param type */ public LeisureActivitiesGoal(long id, RationalRole role, String description, GoalBDITypes type) { super(id, role, description, type); } /** * * @param parameters * @return * @throws KernellAgentEventExceptionBESA */ @Override public double evaluateViability(Believes parameters) throws KernellAgentEventExceptionBESA { return 1; } /** * * @param parameters * @return * @throws KernellAgentEventExceptionBESA */ @Override public double detectGoal(Believes parameters) throws KernellAgentEventExceptionBESA { PeasantFamilyBDIAgentBelieves believes = (PeasantFamilyBDIAgentBelieves) parameters; if (believes.getCurrentPeasantLeisureType() == PeasantLeisureType.LEISURE) { //wpsReport.debug("Detectó"); return 1; } else { return 0; } } /** * * @param parameters * @return * @throws KernellAgentEventExceptionBESA */ @Override public double evaluatePlausibility(Believes parameters) throws KernellAgentEventExceptionBESA { PeasantFamilyBDIAgentBelieves believes = (PeasantFamilyBDIAgentBelieves) parameters; if (believes.haveTimeAvailable(TimeConsumedBy.LeisureActivitiesTask)) { //wpsReport.warn("SI ES POSIBLE"); return 1; } else { return 0; } } /** * * @param stateBDI * @return * @throws KernellAgentEventExceptionBESA */ @Override public double evaluateContribution(StateBDI stateBDI) throws KernellAgentEventExceptionBESA { //wpsReport.info("evaluateContribution " + stateBDI.getMachineBDIParams().getAttentionCycleThreshold()); return 1; } /** * * @param stateBDI * @return * @throws KernellAgentEventExceptionBESA */ @Override public boolean evaluateLegality(StateBDI stateBDI) throws KernellAgentEventExceptionBESA { PeasantFamilyBDIAgentBelieves believes = (PeasantFamilyBDIAgentBelieves) stateBDI.getBelieves(); return believes.getPeasantProfile().getHealth() > 0; } /** * * @param parameters * @return * @throws KernellAgentEventExceptionBESA */ @Override public boolean goalSucceeded(Believes parameters) throws KernellAgentEventExceptionBESA { wpsReport.debug("goalSucceededgoalSucceeded"); return true; } }
using MediatR; using Microsoft.Extensions.Logging; using System.Threading; using System.Threading.Tasks; namespace Pricing.API.PipelineBehaviors { public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> { private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger; public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger) { _logger = logger; } public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { _logger.LogInformation("Command execution started for {CommandName} ({@Command})", request.GetType().Name, request); var response = await next(); _logger.LogInformation("Command execution completed for {CommandName} with response: {@Response}", request.GetType().Name, response); return response; } } }
/* * Copyright 2023 teogor (Teodor Grigor) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.teogor.querent.structures import com.android.build.api.variant.Variant import dev.teogor.querent.api.codegen.Blueprint import dev.teogor.querent.api.codegen.FoundationData import dev.teogor.querent.api.impl.QuerentConfiguratorExtension import dev.teogor.querent.api.models.PackageDetails import dev.teogor.querent.tasks.GenerateValuesTask import dev.teogor.querent.tasks.SoakConfiguredValuesTask import dev.teogor.querent.utils.QuantityStrings import dev.teogor.querent.utils.StringArray import dev.teogor.querent.utils.StringValue import dev.teogor.querent.utils.Values import dev.teogor.querent.utils.bind import dev.teogor.querent.utils.isDefault import dev.teogor.querent.utils.resources import dev.teogor.querent.utils.strings import dev.teogor.querent.utils.values import dev.teogor.querent.utils.variant import org.gradle.configurationcache.extensions.capitalized import org.gradle.kotlin.dsl.get import org.gradle.kotlin.dsl.register /** * https://developer.android.com/guide/topics/resources/string-resource * https://developer.android.com/guide/topics/resources/available-resources */ class XmlResources(data: FoundationData) : Blueprint(data) { private val buildOptions by lazy { extension<QuerentConfiguratorExtension>()!! } private val buildFeatures by lazy { buildOptions.buildFeatures } override val packageNameSuffix: String get() = "res" override fun isEnabled() = buildFeatures.xmlResources override fun onVariants(variant: Variant) { super.onVariants(variant) val kotlin = kotlinSources val packageDetails = PackageDetails( packageName = packageName, namespace = namespace, ) val languageListTaskProvider = project.tasks.register<SoakConfiguredValuesTask>( "soakConfiguredValues${variant.name.capitalized()}", ) { val resValues = mutableListOf<Values>() project.values { strings?.resources { val resources = bind<StringValue>() + bind<StringArray>() + bind<QuantityStrings>() resValues.add( Values( default = isDefault, elements = resources, code = this@values.variant, ), ) } } val defaultResourceValue = resValues.firstOrNull { it.default } val elements = defaultResourceValue?.elements ?: emptyList() val finalResourceValues = elements.map { it.toString() } resourceValues.set(finalResourceValues) languageTagListOutput.set(intermediates.file("${variant.name}/soaked_values_list.txt")) } val generateSupportedLocalesTaskProvider = project.tasks.register<GenerateValuesTask>( "generateValues${variant.name.capitalized()}", ) { valuesListInput.set(languageListTaskProvider.flatMap { it.languageTagListOutput }) outputDir.set(kotlin) moduleName.set(project.name) packageName.set(this@XmlResources.packageName) this.packageDetails.set(packageDetails) } project.afterEvaluate { project.tasks["pre${variant.name.capitalized()}Build"].apply { dependsOn(generateSupportedLocalesTaskProvider) } } } }
#ifndef __SHADERSTORAGEBUFFER_H__ #define __SHADERSTORAGEBUFFER_H__ #include <glad/gl.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <vector> #include "vertex.h" #include <string> using namespace std; using namespace glm; class ShaderStorageBufferBase { protected: GLuint ssbo; GLuint bindPoint; bool isDynamic; bool isNew; bool dirty; public: ShaderStorageBufferBase(GLuint iBindPoint, bool iIsDynamic = false); ShaderStorageBufferBase(ShaderStorageBufferBase && iOther); virtual ~ShaderStorageBufferBase(); virtual size_t getCount() const = 0; virtual const BufferFormat &getBufferFormat() const = 0; virtual void update(bool iDeferUnbind = false); virtual void mark(); virtual void unmark(); virtual void bind(); virtual void unbind(); protected: virtual const void *getData() const = 0; virtual GLsizei getDataSize() const = 0; }; template <typename DataType, const BufferFormat &iBufferFormat, bool iIsFixedSize = false, GLsizei iBufferSize = 0> class ShaderStorageBuffer : public ShaderStorageBufferBase { protected: vector<DataType> data; public: ShaderStorageBuffer(GLuint iBindPoint, bool iIsDynamic = false) : ShaderStorageBufferBase(iBindPoint, iIsDynamic) { } ShaderStorageBuffer(ShaderStorageBuffer && iOther) : ShaderStorageBufferBase(iOther) { } virtual size_t getCount() const { return data.size(); } virtual const BufferFormat &getBufferFormat() const { return iBufferFormat; } vector<DataType> &getVertices() { return data; } void addVertex(DataType iVertex) { data.push_back(iVertex); } // protected: virtual const void *getData() const { return (const void *) &(data[0]) ; } virtual GLsizei getDataSize() const { return (GLsizei) (iIsFixedSize ? iBufferSize : data.size() * sizeof(DataType)); } virtual GLsizei getVertexSize() const { return (GLsizei) sizeof(DataType); } }; #endif
What’s up Emotet? | CERT Polska cert.pl/en/news/single/whats-up-emotet/ What’s up, Emotet? Emotet is one of the most widespread and havoc-wreaking malware families currently out there. Due to its modular structure, it’s able to easily evolve over time and gain new features without having to modify the core. 1/13 Its first version dates back to 2014. Back then it was primarily a banking trojan. These days Emotet is known mostly for its spamming capabilities and as a delivery mechanism of other malware strains. It has recently undergone a substantial change in communication protocol and obfuscation techniques. This might be a response to the release of tools allowing researchers to easily download payloads from the C2 servers1 and detect machines infected with Emotet2. In this article, we will go over the standard Emotet features and take a look at some of the changes that have been spotted. Sample analysed: 500221e174762c63829c2ea9718ca44f Unpacked Emotet core: e8143ef2821741cff199eeda513225d7 Table of Contents Anti-analysis features Code Flow Obfuscation In order to make reverse engineering more difficult for researchers, a VM-like obfuscation was implemented. To achieve this, every function was split into basic blocks which were then repositioned into a simple state machine. Demangling the functions back to their original form is nontrivial, although possible. However, it was found that reverse engineering obfuscated binaries is still possible. 2/13 Function graph of the main function Encrypted Strings All used strings are encrypted almost like in the previous versions. Most noticeable difference is related to the xor key – it’s not passed as a parameter anymore. Instead, it’s located at the beginning of the data to be decrypted. Example encrypted string 3/13 Encrypted string structure One can decrypt those strings pretty easily using a quick Python script. Python function used for decrypting strings WinAPI Another method of slowing down the analysis that the malware authors really like is hiding the Window API calls by replacing them with a custom lookup function. Executing API calls using hash lookups isn’t a new thing in Emotet. In contrast to previous versions however, the new version fetches them on a need-to-use basis instead of loading them all at once and storing them in a data section. Api lookup function being used 4/13 Simple hash function used for function name hashing It can be solved rather easily. All one has to do is just reimplement the hashing function, iterate over common WinAPI function names and create an enum with all recovered hashes. It’s very important to set the accepted type in find_api to the newly-created enum type. This will allow IDA to automatically place the enum values in function calls. Comparison of a single function before and after applying the enum type Deleting previous versions of itself While analysing the encrypted strings, one of lists of keywords present in earlier versions was noticed. It was used to generate random system paths in which to put the Emotet core binary. This seemed weird because this method was replaced with completely random file paths. After closer inspection and confirmation by @JRoosen3 it turned out that these keywords are used to delete Emotet binaries that were dropped there by previous versions. 5/13 Part of the function used for deleting older versions of Emotet Extracting static configuration Public key The RSA public key is stored as a regular encrypted string. It’s embedded in the binary in order to encrypt the AES keys used for secure communication with the C2. This will deter all communication eavesdropping attempts. The public key isn’t stored in plaintext, but fetched like rest of the encrypted strings. Thus, it can be decrypted using the same script: The resulting key is encoded using DER format and can be parsed using the following script: Result PEM-encoded public key C2 list The method of retrieving C2 hosts has not changed. They are still stored as 8-byte blocks containing packed IP address and port. 6/13 Communication Path generation Keyword-generated paths have been abandoned in favour of fully random ones. Each new path consists of a random amount of alphanumeric segments separated by slashes. 7/13 Path generation algorithm Additionally, instead of simply uploading the payload data inside the POST body, it is now sent as a file upload using multipart/form-data enctype. The method of generating random attachment names and filenames is quite similar to the one used in generating URL paths. Part of function responsible for encoding the data as a file 8/13 Example request and response dissected in Wireshark Request structure This the part that has gone under the most changes. Protocol buffers have been dropped in favour of a custom binary protocol. Packet encryption Just like in previous versions, all packets are encrypted using AES-CBC with 16 nullbytes as IV. The AES key is generated using the CryptGenKey function, encrypted using the decoded RSA public key and appended to each request. Additionally, an SHA-1 hash of the packets contents is also sent for integrity verification purposes. The packet encryption structure Packet structure 9/13 Command packets are compressed and encapsulated in a simple packet structure. Outer packet dissection presented using dissect.cstruct Packet compression Another change is the compression algorithm used for compressing and decompressing packet body. Historically, the zlib algorithm has been used for that. It’s hard to pinpoint the exact algorithm that is now used, but the procedure evolution_unpack4 from quickbms project was found to correctly uncompress the data received from the C2 servers 10/13 Pseudocode of the new algorithm used to uncompress packets It was decided to reimplement the uncompression procedure in Python, the resulting script is listed below. Register packet structure As mentioned earlier, the protobuf structures have been abandoned in favour of custom structures. One of the observed packet types is the command used to register the bot on the botnet and receive modules to execute. The register packet structure can be easily presented using the following c struct: 11/13 Register packet dissection presented using dissect.cstruct Summary The goal of this article was to help other researchers with their Emotet research after recent changes. Emotet has once again proven to be an advanced threat capable of adapting and evolving quickly in order to wreak more havoc. This article barely scratches the surface of the Emotet’s inner workings, and should be treated as a good entry point, not as a complete guide. We encourage everyone to use this information, and hopefully share further results and/or discrupt the botnet’s operations. Further reading References 1: https://d00rt.github.io/emotet_network_protocol/ 2: https://github.com/JPCERTCC/EmoCheck 3: https://twitter.com/JRoosen/status/1225188513584467968 12/13 4: https://github.com/mistydemeo/quickbms/blob/master/unz.c#L5501 13/13
@extends('layouts.main') @section('title', 'सामाजिक तालिम') @section('menu_open','menu-open') @section('s_child','block') @section('setting_social_training', 'active') @section('main_content') {{-- this is start of edit part --}} @if (isset($social_training)) <div class="card text-sm mt-1"> <div class="card-header"> <div class="card-text"> <p class="mb-0">{{ __('सामाजिक तालिम सच्याउने') }}</p> </div> <div class=" card-body"> <form method="post" action="{{ route('social-training.update', $social_training) }}"> @csrf @method('PUT') <div class="row" style="margin-left:-30px;"> <div class="col-6"> <div class="input-group input-group-sm"> <div class="input-group-prepend"> <span class="input-group-text"> {{ __('सामाजिक तालिम') }} <span class="text-danger px-1 font-weight-bold">*</span> </span> </div> <input type="text" value="{{ $social_training->name }}" name="name" class="form-control @error('name') is-invalid @enderror"> @error('name') <p class="invalid-feedback" style="font-size: 1rem"> {{ __('सामाजिक तालिमको फिल्ड खाली छ ') }} </p> @enderror </div> </div> <div class="col-4"> <button type="submit" class="btn btn-primary">पेश गर्नुहोस्</button> </div> </div> </form> </div> </div> </div> @endif {{-- this is end of edit part --}} <div class="card text-sm "> <div class="card-header my-2"> <div class="row my-1"> <div class="col-md-6" style="margin-bottom:-5px;"> <p class="">{{ __('सामाजिक तालिमको सुचिहरु') }}</p> </div> <div class=" col-md-6 text-right"> <a class="btn text-white btn-sm btn-primary" data-toggle="modal" data-target="#modal-lg"> {{ __('सामाजिक तालिम थप्नुहोस') }}</a> </div> </div> </div> <!-- /.card-header --> <div class="card-body"> <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th class="text-center">{{ __('क्र.स.') }}</th> <th class="text-center">{{ __('सामाजिक तालिम') }}</th> <th></th> </tr> </thead> <tbody> @php $i = 1; @endphp @foreach ($social_trainings as $social_training) <tr> <td class="text-center">{{ $i++ }}</td> <td class="text-center">{{ $social_training->name }} </td> <td class="text-center"><a href="{{ route('social-training.edit', $social_training) }}" class="btn-sm btn-success"><i class="fas fa-edit px-1"></i> {{ __('सच्याउने') }}</a> <a href="#" class="btn-sm btn-danger" onclick="event.preventDefault(); document.getElementById('delete_social_training{{ $i }}').submit();"> <i class="fas fa-trash-alt px-2"></i>{{ __('हटाउनुहोस्') }}</a> </td> <form id="delete_social_training{{ $i }}" action="{{ route('social-training.destroy', $social_training) }}" method="POST" class="d-none"> @method('DELETE') @csrf </form> </tr> @endforeach </table> </div> <!-- /.card-body --> </div> {{-- modal for adding social_training status --}} <div class="modal fade text-sm" id="modal-lg"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="">{{ __('सामाजिक तालिम थप्नुहोस') }}</h5> <button type=" button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="post" action="{{ route('social-training.store') }}"> @csrf <div class="row"> <div class="col-6"> <div class="input-group input-group-sm"> <div class="input-group-prepend"> <span class="input-group-text"> {{ __('सामाजिक तालिम') }} <span class="text-danger px-1 font-weight-bold">*</span> </span> </div> <input type="text" value="{{ old('name') }}" name="name" class="form-control @error('name') is-invalid @enderror"> @error('name') <p class="invalid-feedback" style="font-size: 1rem"> {{ __('सामाजिक तालिमको फिल्ड खाली छ ') }} </p> @enderror </div> </div> <div class="col-4"> <button type="submit" class="btn btn-primary">पेश गर्नुहोस्</button> </div> </div> </form> </div> <div class="modal-footer justify-content-between"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> {{-- <button type="submit" class="btn btn-primary">पेश गर्नुहोस्</button> --}} </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> {{-- end of modal for adding social_training status --}} @endsection @section('scripts') <script> $(function() { $("#example1").DataTable({ "responsive": true, "autoWidth": false, }); }); </script> <script> window.onload = function() { if ({{ $errors->any() }}) { $('#modal-lg').modal('show'); } } </script> @endsection
import React, { useEffect } from "react"; import Highcharts from "highcharts"; import HighchartsReact from "highcharts-react-official"; const DonutChart = () => { const availableMargin=11000000 const marginUsed= 80000 const withdrawal=10920000 useEffect(() => { // Calculate percentage of available margin const percentage = ((marginUsed / availableMargin) * 100).toFixed(2); Highcharts.chart("donut-chart", { chart: { type: "pie", }, title: { text: "Margin Overview", }, tooltip: { pointFormat: "{series.name}: <b>{point.percentage:.1f}%</b>", }, plotOptions: { pie: { innerSize: "80%", allowPointSelect: true, cursor: "pointer", dataLabels: { enabled: true, format: "<b>{point.name}</b>: {point.percentage:.1f} %", }, }, }, series: [ { name: "Share", data: [ { name: "Available Margin", y: availableMargin }, { name: "Margin Used", y: marginUsed }, { name: "Withdrawal", y: parseFloat(percentage) }, // Include withdrawal percentage as data point { name: "Withdrawal Value", y: withdrawal, color: "red" }, // Include withdrawal value as data point and color it red ], }, ], }); }, [availableMargin, marginUsed, withdrawal]); return ( <div id="donut-chart"> <HighchartsReact highcharts={Highcharts} /> </div> ); }; export default DonutChart;
import { Controller, Get, Param, Post, Body, HttpCode, HttpStatus, Res, Patch, Delete, Query} from '@nestjs/common'; import { response } from 'express'; import { CoffeesService } from './coffees.service'; import { CreateCoffeeDto } from './dto/create-coffee.dto'; import { UpdateCoffeeDto } from './dto/update-coffee.dto'; @Controller('coffees') export class CoffeesController { constructor(private readonly coffeeService: CoffeesService) {} @Get() findAll(@Query() paginationQuery){ //const { limit, offset } = paginationQuery return this.coffeeService.findAll(); } @Get(':id') findOne(@Param('id') id: string){ return this.coffeeService.findOne(id); } @Post() create(@Body() createCoffeeDto: CreateCoffeeDto){ console.log(createCoffeeDto instanceof CreateCoffeeDto) return this.coffeeService.create(createCoffeeDto); } @Patch(':id') update(@Param('id') id: string, @Body() updateCoffeeDto: UpdateCoffeeDto){ return this.coffeeService.update(id, updateCoffeeDto); } @Delete(':id') remove(@Param('id') id: string){ return this.remove(id); } }
import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { ToastrService } from 'ngx-toastr'; import { HttpCode } from 'src/app/common/HttpCode'; import { HttpErrorCode } from 'src/app/common/HttpErrorCode'; import { whiteSpaceValidator } from 'src/app/validator/white-space.validator'; import { ConfirmDialogComponent } from 'src/app/confirm-dialog/confirm-dialog.component'; import { AcademicYear } from 'src/app/model/AcademicYear'; import { ApiResponse } from 'src/app/model/ApiResponse'; import { Class } from 'src/app/model/Class'; import { Grade } from 'src/app/model/Grade'; import { AcademicYearService } from 'src/app/service/academic-year.service'; import { ClassService } from 'src/app/service/class.service'; import { GradeService } from 'src/app/service/grade.service'; import { SaveAnotherDialogComponent } from 'src/app/save-another-dialog/save-another-dialog.component'; @Component({ selector: 'app-class-create', templateUrl: './class-create.component.html', styleUrls: ['./class-create.component.css'] }) export class ClassCreateComponent implements OnInit { submitted = false; academicYearList!: AcademicYear[]; gradeList!: Grade[]; form: FormGroup = new FormGroup({ academicYear: new FormControl('', [ Validators.required ]), grade: new FormControl('', [ Validators.required ]), name: new FormControl('', [ Validators.required, Validators.maxLength(100), Validators.pattern("^[^<>~`!\\[\\]{}|@#^*+=:;/?%$\"\\\\]*$"), whiteSpaceValidator() ]) }); constructor( private academicYearService: AcademicYearService, private classService: ClassService, private gradeService: GradeService, private toastrService: ToastrService, private router: Router, private matDialog: MatDialog ) { } ngOnInit(): void { this.academicYearService.fetchAllByAuthorizedStatus().subscribe(data => { this.academicYearList = data; }); this.gradeService.fetchAllByAuthorizedStatus().subscribe(data => { this.gradeList = data; }); } save() { this.submitted = true; if(this.form.invalid) { return; } const dialogRef = this.matDialog.open(ConfirmDialogComponent, { width: '300px' }); dialogRef.afterClosed().subscribe(result => { if(result) { let requestBody: Class = new Class(); requestBody.name = this.form.get('name')!.value.trim(); requestBody.academicYear.id = this.form.get('academicYear')!.value; requestBody.grade.id = this.form.get('grade')!.value; this.classService.save(requestBody).subscribe({ next: (res: ApiResponse) => { if(res.status == HttpCode.CREATED) { const dialogRef = this.matDialog.open(SaveAnotherDialogComponent, { width: '300px' }); dialogRef.afterClosed().subscribe(result => { if(result) { this.router.navigate(['/app/class/create']).then(() => { this.reset(); }); } else { this.back(); } }); this.toastrService.success("Successfully Created."); } }, error: (err) => { if(err.status == HttpErrorCode.CONFLICT) { this.toastrService.warning("Duplicate record.", "Record already exists."); } else if(err.status == HttpErrorCode.FORBIDDEN) { this.toastrService.error("Forbidden", "Failed action"); } else { this.toastrService.error("Failed to save new record", "Failed action"); } } }); } else { this.matDialog.closeAll(); } }); } reset() { this.form.reset(); this.form.get('academicYear')!.setValue(''); this.form.get('grade')!.setValue(''); this.submitted = false; } back() { this.router.navigate(['/app/class/list']); } }
<?php namespace App\Controller; use App\Entity\Categoria; use App\Repository\CategoriaRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use OpenApi\Attributes as OA; use Nelmio\ApiDocBundle\Annotation\Model; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpFoundation\Request; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Component\HttpFoundation\JsonResponse; #[OA\Tag(name: 'Categorias')] #[Route("/api", "api_", format: "json")] class CategoriaController extends AbstractController { #[OA\Response( response: 200, description: 'Retorna todos los Categorias', content: new OA\JsonContent( type: 'array', items: new OA\Items(ref: new Model(type: Categoria::class)) ) )] #[Route('/categoria', name: 'app_categoria', methods: ["GET"])] public function getCategorias(CategoriaRepository $cr): Response { $categorias = $cr->findAll(); if(count($categorias) == 0) { return $this->json([Response::HTTP_NO_CONTENT, "No se encontraron categorias"]); }else{ return $this->json($categorias, Response::HTTP_OK,[], [ ObjectNormalizer::ATTRIBUTES => [ 'id', 'nombre' ]]); } } #[OA\Response( response: 200, description: 'Retorna un Categoria', content: new OA\JsonContent( ref: new Model(type: Categoria::class) ) )] #[OA\Parameter( name: 'id', in: 'path', description: 'ID del Categoria', required: true, schema: new OA\Schema(type: 'integer') )] #[Route('/categoria/{id}', name: 'get_categoria', methods: ["GET"])] public function getCategoria(Categoria $categoria): JsonResponse { try{ return $this->json($categoria, Response::HTTP_OK,[], [ ObjectNormalizer::ATTRIBUTES => [ 'id', 'nombre' ] ]); } catch(\Exception $e){ //return $this->json([Response::HTTP_NOT_FOUND, "No se encontró el categoria"]); throw new BadRequestHttpException($e->getMessage()); } } #[OA\Response( response: 201, description: 'Retorna la Categoria creada', content: new OA\JsonContent( ref: new Model(type: Categoria::class) ) )] #[OA\RequestBody( description: 'Datos del Categoria', required: true, content: new OA\JsonContent( ref: new Model(type: Categoria::class, groups: ["create"]) ) )] #[Route("/categoria", name:'create_categoria', methods: ["POST"])] public function createCategoria( Request $request, EntityManagerInterface $em, ValidatorInterface $validator): JsonResponse { $requestBody = json_decode($request->getContent(), true); $categoria = new Categoria(); $categoria->setNombre($requestBody['nombre']); $errores = $validator->validate($categoria); if (count($errores) > 0) { return $this->json([Response::HTTP_BAD_REQUEST, $errores]); } $em->persist($categoria); $em->flush(); return $this->json([Response::HTTP_CREATED, $categoria]); } #[OA\Response( response: 202, description: 'Retorna el Categoria actualizada', content: new OA\JsonContent( ref: new Model(type: Categoria::class) ) )] #[OA\RequestBody( description: 'Datos del Categoria a actualizar', required: true, content: new OA\JsonContent( ref: new Model(type: Categoria::class, groups: ["update"]) ) )] #[Route("/categoria/{id}", name:'update_categoria', methods: ["PUT"])] public function updateCategoria( Categoria $categoria, Request $request, EntityManagerInterface $em ): JsonResponse { $requestBody = json_decode($request->getContent(), true); if(isset($requestBody['nombre'])) { $categoria->setNombre($requestBody['nombre']); } $em->persist($categoria); $em->flush(); return $this->json([Response::HTTP_ACCEPTED, $categoria]); } #[OA\Response( response: 204, description: 'Retorna un 204 si el Categoria fue eliminado' )] #[OA\Parameter( name: 'id', in: 'path', description: 'ID del Categoria', required: true, schema: new OA\Schema(type: 'integer') )] #[Route("/categoria/{id}", name:'delete_categoria', methods: ["DELETE"])] public function deleteCategoria( Categoria $categoria, EntityManagerInterface $em): JsonResponse { $em->remove($categoria); $em->flush(); return $this->json([Response::HTTP_NO_CONTENT, "Categoria eliminado"]); } }
--- title: "Exploiting Misconfigurations and Authorization Vulnerabilities in a Multinational Company's Content Management System" layout: post date: 2023-03-25 12:00 image: /assets/images/blogs/IDOR/access-control.svg headerImage: false tag: - JavaScript Files Analysis - Privilege Escalation - Fuzzing - Misconfiguration category: blog author: Naveen description: This blog discusses the exploitation of misconfigurations and authorization vulnerabilities in a Multinational Company's Content Management System (CMS) application. --- ## Target Background The target of this analysis is a prominent Multinational Company (MNC) with a significant market value and stock presence. The company utilizes a Content Management System (CMS) application built with ReactJS to create, edit, and update the content for their products and services. Once the content is published, it is pushed to the live website associated with the corresponding product or service. ## Overview The CMS application lacks a sign-up page, and only the application administrator has the privilege to create user accounts and assign roles. The home page exclusively presents a login form, with no sign-up buttons. ### Reconnaissance During the reconnaissance phase, the following technologies and components were identified: - ReactJS - Amazon CDN (Content Delivery Network) - REST APIs ### Analysis of Loaded Source Files After thoroughly analyzing the loaded source files, it became evident that legitimate user credentials are required to access the application. No REST API endpoints were explicitly mentioned in the JavaScript files. To proceed further, a URL fuzzing technique was employed, leading to the discovery of the signup endpoint: **https://abc.com/abc/xyz/signup.html**. ## Misconfiguration - 1 ### Sign-up Process Due to the application's design, the sign-up functionality is not accessible from the home page. It appears that the developer might have intentionally kept it separate, possibly for internal use or as a legacy feature that was not removed. By signing up for an account, it was observed that no additional confirmation steps, such as email verification, were required. The account creation process was successful without any validation of the provided information. However, upon attempting to log in with the newly created account, it was redirected back to the login page. Since the account lacked proper authorization and assigned roles, the application denied access to its contents. Nonetheless, by examining the page, embedded REST API locations were identified, indicating that successful authentication was achieved. The only issue pertained to incorrect permissions preventing access to application pages. To understand the flow and identify potential missing elements, a detailed analysis of the login request was conducted. Upon successful login, the application provided an authorization token (JWT) in the Location header. Decoding the JWT revealed that it did not contain any values for Cognito permissions, thereby explaining the unavailability of application contents. ```json { "at_hash": "ry3UaTl8rD1IPBffLSyQ7w", "sub": "e03f561e-9392-437d-abf7-48715fde4a4e", "cognito:groups": [ "" ], "iss": "https://cognito-idp.abc.com", "cognito:username": "test", "origin_jti": "", "cognito:roles": [ "" ], "aud": "2kp93i4kj1ump55lid961qm7bv", "event_id": "65f7336b-1b89-45e6-b9f9-be466f24207b", "token_use": "id", "auth_time": "", "phone_number": "", "exp": "", "iat": "", "jti": "66d3189d-e26e-454f-9b8d-7863ac4de102", "email": "nj@tvhsecurity.com" } ``` The decoded JWT revealed that the user did not possess any assigned roles to access the application pages. ### Fuzzing the JWT In an attempt to identify the correct "Cognito groups," the JWT payload was fuzzed by adding random role permission keywords. However, encoding and sending the modified JWT in the request did not yield any successful results. Nevertheless, utilizing the obtained token, the page source was downloaded using curl and the "authorization header." A personal one-liner script was then utilized to extract embedded URL locations from the application. Alternatively, the tool [URLScrapy](https://github.com/thevillagehacker/urlscrapy) could also be employed to achieve this. ## HTTP Response Codes All extracted URLs were compiled into a text file, and the tool **[HTTPX](https://github.com/projectdiscovery/httpx)** was utilized to check the status codes and content lengths. Fortunately, one of the pages returned a different content length. Upon visiting the page, static content related to user roles within the application was revealed. This reconnaissance effort revealed the presence of two user roles: "editor" and "publisher." Editors possess the ability to edit contents, while publishers can approve new content submissions made by editors. ## Checkpoint At this stage, the following elements are available for accessing the application contents: - A newly signed-up account without any assigned roles - Knowledge of user roles within the application - A functioning JWT token (Authorization) With these resources in hand, the next step is to find a way to assign user roles to the token and gain access to the application contents. Through experimentation with the browser's developer tools, it was discovered that a local storage variable, "user_role," was present but had no value assigned for our user account. By setting its value to "editor" and refreshing the page, the application started utilizing the local storage variables to determine content access. As a result, the ability to add and edit application contents was obtained. ## Misconfiguration - 2 Having gained access to the application, it was determined that the application exclusively employs AWS Cognito groups for authentication, without utilizing them for authorization. This was evident from the fact that by merely adding the value "editor" to the local storage variable "user_role," one could assume the role of an editor within the application. Therefore, the only requirement to access the REST APIs was a legitimate authentication token, as authorization was not properly implemented. ### Privilege Escalation Privilege escalation was achieved by modifying the "user_role" local storage variable to "publisher." Upon refreshing the page, access to publisher content pages was obtained, enabling the approval or rejection of contents created by editor users in the application. It should be noted that due to non-disclosure agreements, only limited information could be shared in this blog post. Thank you for reading! For more insights and updates, follow me on Twitter: [@thevillagehacker](https://twitter.com/thevillagehackr).
% Starburst Algorithm % % This function implements the Starburst Algorithm, a feature-based approach % for detecting the contour of the pupil in eye-tracking applications. It uses % a radial search pattern emanating from an initial guess point to locate edge % points that are likely part of the pupil boundary. The algorithm iteratively % refines these points to converge on the pupil contour. % % Usage: % [epx, epy, edge_thresh, epx_init, epy_init] = starburstPupilContourDetection(I, cx, cy, edge_thresh, radii_pupil, min_features, min_edge_thresh) % % Inputs: % - I: Input image (grayscale) in which pupil contour is to be detected. % - cx, cy: Initial guess for the pupil center (x and y coordinates). % - edge_thresh: Initial threshold for edge detection. The algorithm adjusts this % threshold dynamically based on feature detection. Default: 30 % - radii_pupil: Expected radii range of the pupil. Only the first value is used. It is scaled % to set the distance at which to start searching for an edge. % - min_features: Minimum fraction of total features (relative to the number of rays) % required to proceed with the detection. % - min_edge_thresh: Minimum allowable edge threshold to limit the adjustment of % edge_thresh during detection. Default: 2 % % Outputs: % - epx, epy: Coordinates (x and y) of the detected feature points that likely % belong to the pupil contour. % - edge_thresh: The final edge threshold value used for detecting the feature points. % - epx_init, epy_init: Initial sets of feature points detected before iterative refinement. % % % This source code is part of the starburst algorithm. % Starburst algorithm is free; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % Starburst algorithm is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with cvEyeTracker; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % % Starburst Algorithm - Version 1.0.0 % Part of the openEyes ToolKit -- http://hcvl.hci.iastate.edu/openEyes % Release Date: % Authors : Dongheng Li <donghengli@gmail.com> % Derrick Parkhurst <derrick.parkhurst@hcvl.hci.iastate.edu> % Edited by Hannah Payne, 2021 % Copyright (c) 2005 % All Rights Reserved. function [epx, epy, edge_thresh, epx_init, epy_init] = starburstPupilContourDetection(I, cx, cy, edge_thresh, radii_pupil, min_features, min_edge_thresh) if ~exist('min_edge_thresh', 'var') || isempty(min_edge_thresh) min_edge_thresh = 2; end if isempty(edge_thresh) || edge_thresh<= min_edge_thresh edge_thresh = 30; % edge_threshold = best guess for the pupil contour threshold (30) end N = 100; % Number of rays to use to detect feature points. Edited from 50 min_candidate_features = N*min_features; % Minimum number of pupil feature candidates min_distance = radii_pupil(1)*.5; % Distance from pupil center guess to start searching for edge angle_spread = 60*pi/180; min_change = 6; % Stop if sum of change in mean x and y over previous iteration is smaller than this (distance in pixels) loop_count = 0; max_loop_count = 10; tcx(loop_count+1) = cx; tcy(loop_count+1) = cy; angle_step= 2*pi/N; while edge_thresh > min_edge_thresh && loop_count <= max_loop_count epx = []; epy = []; while length(epx) < min_candidate_features && edge_thresh > min_edge_thresh [epx, epy, epd] = locate_edge_points(I, cx, cy, min_distance, angle_step, 0, 2*pi, edge_thresh); if length(epx) < min_candidate_features edge_thresh = edge_thresh - 1; end epx_init = epx; epy_init = epy; end angle_normal = atan2(cy-epy, cx-epx); for i = 1:length(epx) [tepx, tepy, ~] = locate_edge_points(I, epx(i), epy(i), ... min_distance*1.5, angle_step*(edge_thresh/epd(i)), ... angle_normal(i), angle_spread, edge_thresh); epx = [epx tepx]; epy = [epy tepy]; end loop_count = loop_count+1; tcx(loop_count+1) = mean(epx); tcy(loop_count+1) = mean(epy); if sqrt((tcx(loop_count+1)-cx).^2 + (tcy(loop_count+1)-cy).^2) < min_change % threshold change in pupil position over loops break; end cx = mean(epx); cy = mean(epy); end function [epx, epy, dir] = locate_edge_points(I, cx, cy, dis, angle_step, angle_normal, angle_spread, edge_thresh) [height, width] = size(I); epx = []; epy = []; dir = []; ep_num = 0; % ep stands for edge point step = 2; maxDist = 2; maxstep = round(dis*maxDist/step); dists = dis + step*(0:maxstep)'; for angle=(angle_normal-angle_spread/2+0.0001):angle_step:(angle_normal+angle_spread/2) cosangle = cos(angle); sinangle = sin(angle); % Generate candidate points ps = [round(cx + dists*cosangle) round(cy + dists*sinangle)]; % Make sure points are within image bounds mask = ps(:,2) < height & ps(:,2) > 1 & ps(:,1) < width & ps(:,1) > 1; ps = ps(mask,:); inds = ps(:,2) + (ps(:,1) - 1).*height; vals = I(inds); d = diff(vals); ind = find(d>edge_thresh,1); if ~isempty(ind) ep_num = ep_num+1; epx(ep_num) = ps(ind,1)+step/2; % Edge point x coordinate epy(ep_num) = ps(ind,2)+step/2; % Edge point y coordinate dir(ep_num) = d(ind); end end
import React, { useState, useEffect } from "react"; import "./bootcampSlider.css"; import data from "../person.json"; function BootcampSlider() { const [activeState, setActiveState] = useState("tanya"); const [activePerson, setActivePerson] = useState(""); useEffect(() => { if (activeState === "tanya") { setActivePerson(data[0]); } else { setActivePerson(data[1]); } }, [activeState]); return ( <div className="bootcampSlider"> <img src="assets/images/pattern-curve.svg" className="leftBottomBg" alt="leftBottomBg" /> <div className="bootcampSliderWrapper"> <div className="bootcampSliderLeft"> <img src="assets/images/pattern-quotes.svg" className="textBg" alt="textBg" /> <p className="bootcampSliderLeftContent">{activePerson.desc}</p> <div className="bootcampSliderLeftBottom"> <p className="bootcampSliderLeftBottomTitle"> {activePerson.fullName} </p> <p className="bootcampSliderLeftBottomDesc">{activePerson.job}</p> </div> </div> <div className="bootcampSliderRight"> <img src="assets/images/pattern-bg.svg" alt="photoBg" className="photoBg" /> <div className="sliderControl"> <img src="assets/images/icon-prev.svg" className="sliderControlIcon" alt="sliderPrev" onClick={() => setActiveState(activeState === "tanya" ? "john" : "tanya") } /> <img src="assets/images/icon-next.svg" className="sliderControlIcon" alt="sliderNext" onClick={() => setActiveState(activeState === "tanya" ? "john" : "tanya") } /> </div> <img src={activePerson.img} alt="personPhoto" className="bootcampSliderRightImg" /> </div> </div> </div> ); } export default BootcampSlider;
/* * VCAI.h, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * * License: GNU General Public License v2.0 or later * Full text of license available in license.txt file, in main folder * */ #pragma once #include "AIUtility.h" #include "Goals.h" #include "../../lib/AI_Base.h" #include "../../CCallback.h" #include "../../lib/CThreadHelper.h" #include "../../lib/GameConstants.h" #include "../../lib/VCMI_Lib.h" #include "../../lib/CBuildingHandler.h" #include "../../lib/CCreatureHandler.h" #include "../../lib/CTownHandler.h" #include "../../lib/mapObjects/MiscObjects.h" #include "../../lib/spells/CSpellHandler.h" #include "../../lib/CondSh.h" struct QuestInfo; class AIStatus { boost::mutex mx; boost::condition_variable cv; BattleState battle; std::map<QueryID, std::string> remainingQueries; std::map<int, QueryID> requestToQueryID; //IDs of answer-requests sent to server => query ids (so we can match answer confirmation from server to the query) std::vector<const CGObjectInstance*> objectsBeingVisited; bool ongoingHeroMovement; bool ongoingChannelProbing; // true if AI currently explore bidirectional teleport channel exits bool havingTurn; public: AIStatus(); ~AIStatus(); void setBattle(BattleState BS); void setMove(bool ongoing); void setChannelProbing(bool ongoing); bool channelProbing(); BattleState getBattle(); void addQuery(QueryID ID, std::string description); void removeQuery(QueryID ID); int getQueriesCount(); void startedTurn(); void madeTurn(); void waitTillFree(); bool haveTurn(); void attemptedAnsweringQuery(QueryID queryID, int answerRequestID); void receivedAnswerConfirmation(int answerRequestID, int result); void heroVisit(const CGObjectInstance *obj, bool started); template <typename Handler> void serialize(Handler &h, const int version) { h & battle; h & remainingQueries; h & requestToQueryID; h & havingTurn; } }; enum {NOT_VISIBLE = 0, NOT_CHECKED = 1, NOT_AVAILABLE}; struct SectorMap { //a sector is set of tiles that would be mutually reachable if all visitable objs would be passable (incl monsters) struct Sector { int id; std::vector<int3> tiles; std::vector<int3> embarkmentPoints; //tiles of other sectors onto which we can (dis)embark std::vector<const CGObjectInstance *> visitableObjs; bool water; //all tiles of sector are land or water Sector() { id = -1; water = false; } }; typedef unsigned short TSectorID; //smaller than int to allow -1 value. Max number of sectors 65K should be enough for any proper map. typedef boost::multi_array<TSectorID, 3> TSectorArray; bool valid; //some kind of lazy eval std::map<int3, int3> parent; TSectorArray sector; //std::vector<std::vector<std::vector<unsigned char>>> pathfinderSector; std::map<int, Sector> infoOnSectors; std::shared_ptr<boost::multi_array<TerrainTile*, 3>> visibleTiles; SectorMap(); SectorMap(HeroPtr h); void update(); void clear(); void exploreNewSector(crint3 pos, int num, CCallback * cbp); void write(crstring fname); bool markIfBlocked(TSectorID &sec, crint3 pos, const TerrainTile *t); bool markIfBlocked(TSectorID &sec, crint3 pos); TSectorID & retrieveTile(crint3 pos); TSectorID & retrieveTileN(TSectorArray & vectors, const int3 & pos); const TSectorID & retrieveTileN(const TSectorArray &vectors, const int3 &pos); TerrainTile* getTile(crint3 pos) const; std::vector<const CGObjectInstance *> getNearbyObjs(HeroPtr h, bool sectorsAround); void makeParentBFS(crint3 source); int3 firstTileToGet(HeroPtr h, crint3 dst); //if h wants to reach tile dst, which tile he should visit to clear the way? int3 findFirstVisitableTile(HeroPtr h, crint3 dst); }; class VCAI : public CAdventureAI { public: //internal methods for town development //try build an unbuilt structure in maxDays at most (0 = indefinite) /*bool canBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=7);*/ bool tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=7); //try build ANY unbuilt structure BuildingID canBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=7); bool tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=7); //try build first unbuilt structure bool tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=7); friend class FuzzyHelper; std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > knownTeleportChannels; std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates; ObjectInstanceID destinationTeleport; int3 destinationTeleportPos; std::vector<ObjectInstanceID> teleportChannelProbingList; //list of teleport channel exits that not visible and need to be (re-)explored //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs std::map<HeroPtr, std::set<const CGTownInstance *> > townVisitsThisWeek; std::map<HeroPtr, Goals::TSubgoal> lockedHeroes; //TODO: allow non-elementar objectives std::map<HeroPtr, std::set<const CGObjectInstance *> > reservedHeroesMap; //objects reserved by specific heroes std::set<HeroPtr> heroesUnableToExplore; //these heroes will not be polled for exploration in current state of game //sets are faster to search, also do not contain duplicates std::set<const CGObjectInstance *> visitableObjs; std::set<const CGObjectInstance *> alreadyVisited; std::set<const CGObjectInstance *> reservedObjs; //to be visited by specific hero std::map <HeroPtr, std::shared_ptr<SectorMap>> cachedSectorMaps; //TODO: serialize? not necessary TResources saving; AIStatus status; std::string battlename; std::shared_ptr<CCallback> myCb; std::unique_ptr<boost::thread> makingTurn; VCAI(); virtual ~VCAI(); //TODO: use only smart pointers? void tryRealize(Goals::Explore & g); void tryRealize(Goals::RecruitHero & g); void tryRealize(Goals::VisitTile & g); void tryRealize(Goals::VisitHero & g); void tryRealize(Goals::BuildThis & g); void tryRealize(Goals::DigAtTile & g); void tryRealize(Goals::CollectRes & g); void tryRealize(Goals::Build & g); void tryRealize(Goals::Invalid & g); void tryRealize(Goals::AbstractGoal & g); int3 explorationBestNeighbour(int3 hpos, int radius, HeroPtr h); int3 explorationNewPoint(HeroPtr h); int3 explorationDesperate(HeroPtr h); bool isTileNotReserved(const CGHeroInstance * h, int3 t); //the tile is not occupied by allied hero and the object is not reserved void recruitHero(); virtual std::string getBattleAIName() const override; virtual void init(std::shared_ptr<CCallback> CB) override; virtual void yourTurn() override; virtual void heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID) override; //pskill is gained primary skill, interface has to choose one of given skills and call callback with selection id virtual void commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO virtual void showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel) override; //Show a dialog, player must take decision. If selection then he has to choose between one of given components, if cancel he is allowed to not choose. After making choice, CCallback::selectionMade should be called with number of selected component (1 - n) or 0 for cancel (if allowed) and askID. virtual void showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID) override; //all stacks operations between these objects become allowed, interface has to call onEnd when done virtual void showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override; void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override; virtual void saveGame(BinarySerializer & h, const int version) override; //saving virtual void loadGame(BinaryDeserializer & h, const int version) override; //loading virtual void finish() override; virtual void availableCreaturesChanged(const CGDwelling *town) override; virtual void heroMoved(const TryMoveHero & details) override; virtual void stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute) override; virtual void heroInGarrisonChange(const CGTownInstance *town) override; virtual void centerView(int3 pos, int focusTime) override; virtual void tileHidden(const std::unordered_set<int3, ShashInt3> &pos) override; virtual void artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst) override; virtual void artifactAssembled(const ArtifactLocation &al) override; virtual void showTavernWindow(const CGObjectInstance *townOrTavern) override; virtual void showThievesGuildWindow (const CGObjectInstance * obj) override; virtual void playerBlocked(int reason, bool start) override; virtual void showPuzzleMap() override; virtual void showShipyardDialog(const IShipyard *obj) override; virtual void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override; virtual void artifactPut(const ArtifactLocation &al) override; virtual void artifactRemoved(const ArtifactLocation &al) override; virtual void stacksErased(const StackLocation &location) override; virtual void artifactDisassembled(const ArtifactLocation &al) override; virtual void heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start) override; virtual void availableArtifactsChanged(const CGBlackMarket *bm = nullptr) override; virtual void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town) override; virtual void tileRevealed(const std::unordered_set<int3, ShashInt3> &pos) override; virtual void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override; virtual void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) override; virtual void showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level) override; virtual void heroMovePointsChanged(const CGHeroInstance * hero) override; virtual void stackChangedType(const StackLocation &location, const CCreature &newType) override; virtual void stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count) override; virtual void newObject(const CGObjectInstance * obj) override; virtual void showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor) override; virtual void playerBonusChanged(const Bonus &bonus, bool gain) override; virtual void newStackInserted(const StackLocation &location, const CStackInstance &stack) override; virtual void heroCreated(const CGHeroInstance*) override; virtual void advmapSpellCast(const CGHeroInstance * caster, int spellID) override; virtual void showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID) override; virtual void requestRealized(PackageApplied *pa) override; virtual void receivedResource() override; virtual void stacksSwapped(const StackLocation &loc1, const StackLocation &loc2) override; virtual void objectRemoved(const CGObjectInstance *obj) override; virtual void showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor) override; virtual void heroManaPointsChanged(const CGHeroInstance * hero) override; virtual void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override; virtual void battleResultsApplied() override; virtual void objectPropertyChanged(const SetObjectProperty * sop) override; virtual void buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) override; virtual void heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain) override; virtual void showMarketWindow(const IMarket *market, const CGHeroInstance *visitor) override; void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions) override; virtual void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) override; virtual void battleEnd(const BattleResult *br) override; void makeTurn(); void makeTurnInternal(); void performTypicalActions(); void buildArmyIn(const CGTownInstance * t); void striveToGoal(Goals::TSubgoal ultimateGoal); Goals::TSubgoal striveToGoalInternal(Goals::TSubgoal ultimateGoal, bool onlyAbstract); void endTurn(); void wander(HeroPtr h); void setGoal(HeroPtr h, Goals::TSubgoal goal); void evaluateGoal(HeroPtr h); //evaluates goal assigned to hero, if any void completeGoal (Goals::TSubgoal goal); //safely removes goal from reserved hero void striveToQuest (const QuestInfo &q); void recruitHero(const CGTownInstance * t, bool throwing = false); bool isGoodForVisit(const CGObjectInstance *obj, HeroPtr h, SectorMap &sm); void buildStructure(const CGTownInstance * t); //void recruitCreatures(const CGTownInstance * t); void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter); bool canGetArmy (const CGHeroInstance * h, const CGHeroInstance * source); //can we get any better stacks from other hero? void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack void pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other = nullptr); void moveCreaturesToHero(const CGTownInstance * t); bool goVisitObj(const CGObjectInstance * obj, HeroPtr h); void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h); bool moveHeroToTile(int3 dst, HeroPtr h); void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on) void waitTillFree(); void addVisitableObj(const CGObjectInstance *obj); void markObjectVisited (const CGObjectInstance *obj); void reserveObject (HeroPtr h, const CGObjectInstance *obj); //TODO: reserve all objects that heroes attempt to visit void unreserveObject (HeroPtr h, const CGObjectInstance *obj); void markHeroUnableToExplore (HeroPtr h); void markHeroAbleToExplore (HeroPtr h); bool isAbleToExplore (HeroPtr h); void clearPathsInfo(); void validateObject(const CGObjectInstance *obj); //checks if object is still visible and if not, removes references to it void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it void validateVisitableObjs(); void retrieveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned = false) const; void retrieveVisitableObjs(); std::vector<const CGObjectInstance *> getFlaggedObjects() const; const CGObjectInstance *lookForArt(int aid) const; bool isAccessible(const int3 &pos); HeroPtr getHeroWithGrail() const; const CGObjectInstance *getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> &predicate); bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const; //optimization - use one SM for every hero call std::shared_ptr<SectorMap> getCachedSectorMap(HeroPtr h); const CGTownInstance *findTownWithTavern() const; bool canRecruitAnyHero(const CGTownInstance * t = NULL) const; Goals::TSubgoal getGoal (HeroPtr h) const; bool canAct(HeroPtr h) const; std::vector<HeroPtr> getUnblockedHeroes() const; HeroPtr primaryHero() const; TResources freeResources() const; //owned resources minus gold reserve TResources estimateIncome() const; bool containsSavedRes(const TResources &cost) const; void checkHeroArmy (HeroPtr h); void requestSent(const CPackForServer *pack, int requestID) override; void answerQuery(QueryID queryID, int selection); //special function that can be called ONLY from game events handling thread and will send request ASAP void requestActionASAP(std::function<void()> whatToDo); template <typename Handler> void registerGoals(Handler &h) { //h.template registerType<Goals::AbstractGoal, Goals::BoostHero>(); h.template registerType<Goals::AbstractGoal, Goals::Build>(); h.template registerType<Goals::AbstractGoal, Goals::BuildThis>(); //h.template registerType<Goals::AbstractGoal, Goals::CIssueCommand>(); h.template registerType<Goals::AbstractGoal, Goals::ClearWayTo>(); h.template registerType<Goals::AbstractGoal, Goals::CollectRes>(); h.template registerType<Goals::AbstractGoal, Goals::Conquer>(); h.template registerType<Goals::AbstractGoal, Goals::DigAtTile>(); h.template registerType<Goals::AbstractGoal, Goals::Explore>(); h.template registerType<Goals::AbstractGoal, Goals::FindObj>(); h.template registerType<Goals::AbstractGoal, Goals::GatherArmy>(); h.template registerType<Goals::AbstractGoal, Goals::GatherTroops>(); h.template registerType<Goals::AbstractGoal, Goals::GetArtOfType>(); h.template registerType<Goals::AbstractGoal, Goals::GetObj>(); h.template registerType<Goals::AbstractGoal, Goals::Invalid>(); //h.template registerType<Goals::AbstractGoal, Goals::NotLose>(); h.template registerType<Goals::AbstractGoal, Goals::RecruitHero>(); h.template registerType<Goals::AbstractGoal, Goals::VisitHero>(); h.template registerType<Goals::AbstractGoal, Goals::VisitTile>(); h.template registerType<Goals::AbstractGoal, Goals::Win>(); } template <typename Handler> void serializeInternal(Handler &h, const int version) { h & knownTeleportChannels; h & knownSubterraneanGates; h & destinationTeleport; h & townVisitsThisWeek; h & lockedHeroes; h & reservedHeroesMap; //FIXME: cannot instantiate abstract class h & visitableObjs; h & alreadyVisited; h & reservedObjs; h & saving; h & status; h & battlename; h & heroesUnableToExplore; //myCB is restored after load by init call } }; class cannotFulfillGoalException : public std::exception { std::string msg; public: explicit cannotFulfillGoalException(crstring _Message) : msg(_Message) { } virtual ~cannotFulfillGoalException() throw () { }; const char *what() const throw () override { return msg.c_str(); } }; class goalFulfilledException : public std::exception { std::string msg; public: Goals::TSubgoal goal; explicit goalFulfilledException(Goals::TSubgoal Goal) : goal(Goal) { msg = goal->name(); } virtual ~goalFulfilledException() throw () { }; const char *what() const throw () override { return msg.c_str(); } }; void makePossibleUpgrades(const CArmedInstance *obj);
<script lang="ts"> import type { FormFields, Poll } from "src/types"; import Button from "./ui/Button.svelte"; import InputWrapper from "./ui/InputWrapper.svelte"; export let createHandler: (data: Poll) => void; let valid = false; let fields: FormFields = { question: "", answerA: "", answerB: "" }; let errors: FormFields = { question: "", answerA: "", answerB: "" }; let submitHandler = () => { valid = true; if (fields.question.trim().length < 5) { valid = false; errors.question = "Question must be at least 5 characters long"; } else { errors.question = ""; } if (fields.answerA.trim().length < 1) { valid = false; errors.answerA = "Answer A cannot be empty"; } else { errors.answerA = ""; } if (fields.answerB.trim().length < 1) { valid = false; errors.answerB = "Answer B cannot be empty"; } else { errors.answerB = ""; } if (valid) { errors = { question: "", answerA: "", answerB: "" }; let poll = { ...fields, voteA: 0, voteB: 0, id: Math.random() } as Poll; createHandler(poll); } }; </script> <form on:submit|preventDefault={submitHandler}> <InputWrapper title="Question" error={errors.question}> <input type="text" id="question" class="shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light" required bind:value={fields.question} /> </InputWrapper> <InputWrapper title="Answer A" error={errors.answerA}> <input type="text" id="answer A" class="shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light" required bind:value={fields.answerA} /> </InputWrapper> <InputWrapper title="Answer B" error={errors.answerB}> <input type="text" id="answer B" class="shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light" required bind:value={fields.answerB} /> </InputWrapper> <Button>Add Poll</Button> </form> <style> form { width: 400px; margin: 0 auto; text-align: center; } </style>
import 'zone.js/node'; import { ngExpressEngine } from '@nguniversal/express-engine'; import * as express from 'express'; import { join } from 'path'; import * as dotenv from 'dotenv'; import helmet from 'helmet'; import { AppServerModule } from './src/main.server'; import { APP_BASE_HREF } from '@angular/common'; import { existsSync, readFileSync } from 'fs'; import { Express } from 'express'; // eslint-disable-next-line @typescript-eslint/no-var-requires const domino = require('domino'); // eslint-disable-next-line @typescript-eslint/no-var-requires const path = require('path'); const template = readFileSync(path.join('dist/browser', 'index.html')).toString(); const win = domino.createWindow(template); dotenv.config(); win.Object = Object; win.Math = Math; // tslint:disable-next-line global['window'] = win; // tslint:disable-next-line global['document'] = win.document; process.env.NODE_TLS_REJECT_UNAUTHORIZED = '1'; // The Express app is exported so that it can be used by serverless Functions. const server: Express = express(); server.use(helmet({ hsts: true, hidePoweredBy: true, contentSecurityPolicy: false })); const distFolder = join(process.cwd(), 'dist/browser'); const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index'; // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine) server.engine( 'html', ngExpressEngine({ bootstrap: AppServerModule }) ); server.set('view engine', 'html'); server.set('views', distFolder); // Example Express Rest API endpoints // server.get('/api/**', (req, res) => { }); // Serve static files from /browser server.get('*.*', express.static(distFolder, { maxAge: '1y' })); // All regular routes use the Universal engine server.get('*', (req, res) => { res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }); }); server.set('port', process.env.PORT || 4000); server.listen(server.get('port'), () => { // tslint:disable-next-line:no-console console.log(`Node Express server listening on port ${server.get('port')}`); }); export * from './src/main.server';
package com.shopme.admin.user.export; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class ExcelDuplicateFinder { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("C:\\Users\\mahpawar\\Desktop\\demoExcel.xlsx"); Workbook workbook = new XSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); List<String> rows = new ArrayList<>(); for (Row row : sheet) { StringBuilder rowContent = new StringBuilder(); for (Cell cell : row) { rowContent.append(cell.toString()).append(","); } rows.add(rowContent.toString()); } Set<String> duplicateRows = new HashSet<>(); Set<String> uniqueRows = new HashSet<>(); for (String row : rows) { if (!uniqueRows.add(row)) { duplicateRows.add(row); } } if (duplicateRows.isEmpty()) { System.out.println("No duplicate rows found."); } else { System.out.println("Duplicate rows:"); for (String row : duplicateRows) { System.out.println(row); } } workbook.close(); } catch (IOException e) { e.printStackTrace(); } } } //public class ExcelDuplicateFinder { // // public static void main(String[] args) { // try { // // Load Excel file // FileInputStream fis = new FileInputStream("C:\\Users\\mahpawar\\Desktop\\demo.xlsx"); // Workbook workbook = new XSSFWorkbook(fis); // Sheet sheet = workbook.getSheetAt(0); // // // Store rows in a set to remove duplicates // Set<String> rows = new HashSet<>(); // for (Row row : sheet) { // StringBuilder rowContent = new StringBuilder(); // for (Cell cell : row) { // rowContent.append(cell.toString()).append(","); // } // String trimmedRow = rowContent.toString().replaceAll(",$", ""); // Remove trailing comma // rows.add(trimmedRow); // } // // // Print duplicate rows // Set<String> duplicates = findDuplicates(rows); // if (!duplicates.isEmpty()) { // System.out.println("Duplicate rows found:"); // for (String duplicate : duplicates) { // System.out.println(duplicate); // } // } else { // System.out.println("No duplicate rows found."); // } // // workbook.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // private static Set<String> findDuplicates(Set<String> rows) { // Set<String> duplicateRows = new HashSet<>(); // Set<String> uniqueRows = new HashSet<>(); // // for (String row : rows) { // if (!uniqueRows.add(row)) { // duplicateRows.add(row); // } // } // // return duplicateRows; // } //} //public class ExcelDuplicateFinder { // // public static void main(String[] args) { // try { // // Load Excel file // FileInputStream fis = new FileInputStream("C:\\Users\\mahpawar\\Desktop\\demoExcel.xlsx"); // Workbook workbook = new XSSFWorkbook(fis); // Sheet sheet = workbook.getSheetAt(0); // // // Map to store row content and count // Map<String, Integer> rowMap = new HashMap<>(); // // // Iterate through rows // for (Row row : sheet) { // StringBuilder rowContent = new StringBuilder(); // for (Cell cell : row) { // rowContent.append(cell.toString()).append(","); // } // String rowString = rowContent.toString(); // // // Increment count for this row content in the map // rowMap.put(rowString, rowMap.getOrDefault(rowString, 0) + 1); // } // // // Print duplicate rows // for (Map.Entry<String, Integer> entry : rowMap.entrySet()) { // if (entry.getValue() > 1) { // System.out.println("Duplicate Row: " + entry.getKey()); // } // } // // workbook.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } //}
package com.staler2019.iotsocket; import android.os.Handler; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; public class ServerThread extends Thread { private final ArrayList<Socket> clients = new ArrayList<>(); private int connCount = 0; private ServerSocket serverSocket; private final int SERVER_PORT = Constant.SERVER_PORT; private Handler handler; // thread control @Override public void run() { try { serverSocket = new ServerSocket(SERVER_PORT); handlerSendMsg(MsgObj.NAME + " started.(" + ServerActivity.getIPAddress() + ":" + Integer.valueOf(SERVER_PORT) + ")"); while (!serverSocket.isClosed()) { waitNewClient(); } } catch (IOException e) { e.printStackTrace(); } finally { handlerSendMsg("serverSocketClose"); } } public void terminate() { try { handlerSendMsg("leaving..."); leaveMsg(); Thread.sleep(2000); serverSocket.close(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } public void setHandler(Handler handler) { this.handler = handler; } // my functions private void waitNewClient() { try { Socket socket = serverSocket.accept(); ++connCount; addNewClient(socket); } catch (IOException e) { e.printStackTrace(); } } private void addNewClient(final Socket socket) { new Thread(() -> { try { clients.add(socket); String ipPort = socket.getInetAddress().getHostAddress() + ":" + socket.getPort(); BufferedReader br = new BufferedReader(new InputStreamReader((socket.getInputStream()))); recvFirstMsg(br, ipPort); while (socket.isConnected()) { if (!recvMsg(br)) { break; } } } catch (IOException e) { e.getStackTrace(); } finally { clients.remove(socket); --connCount; Log.d("users amount", String.valueOf(connCount)); } }).start(); } // handler private void handlerSendMsg(String msg) { handler.sendMessage(handler.obtainMessage(0, msg)); } // send msg public void sendMsg(String msg) { handlerSendMsg("You: " + msg); castMsg(MsgObj.NAME, msg); Log.d("SendMsg", msg); } private void castMsg(String name, String msg) { Socket[] clientArrays = new Socket[clients.size()]; clients.toArray(clientArrays); for (Socket socket : clientArrays) { new Thread(() -> { try { BufferedWriter bw; bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); JSONObject writeObj = new JSONObject(); writeObj.put(MsgObj.LABEL_NAME, name); writeObj.put(MsgObj.LABEL_MSG, msg); bw.write(writeObj + "\n"); bw.flush(); } catch (JSONException | IOException e) { e.printStackTrace(); } }).start(); } } private void leaveMsg() { castMsg(MsgObj.NAME, "Server closed. Please press leave button."); Log.d("SendMsg", "Server closed. Please press leave button."); } // receive msg private boolean recvMsg(BufferedReader br) { try { String rl; rl = br.readLine(); if (rl != null && !rl.equals("")) { JSONObject readObj = new JSONObject(rl); if (readObj.has(MsgObj.LABEL_ACTION)) { if (readObj.getInt(MsgObj.LABEL_ACTION) == 1) { sendMsg(readObj.getString(MsgObj.LABEL_NAME) + " has left."); return false; } } String name = readObj.getString(MsgObj.LABEL_NAME); String msg = readObj.getString(MsgObj.LABEL_MSG); handlerSendMsg(name + ": " + msg); castMsg(name, msg); } } catch (IOException | JSONException e) { e.printStackTrace(); } return true; } private void recvFirstMsg(BufferedReader br, String ipPort) { while (true) { try { String rl = br.readLine(); if (rl != null && !rl.equals("")) { JSONObject readObj = new JSONObject(rl); String name = readObj.getString(MsgObj.LABEL_NAME); handlerSendMsg("\n" + name + "(" + ipPort + ") connected.\n"); handlerSendMsg(MsgObj.NAME + ": Welcome " + name + " join us!"); castMsg(MsgObj.NAME, "Welcome " + name + " join us!"); break; } } catch (IOException | JSONException e) { e.printStackTrace(); } } } }
import { BottomTabNavigationProp } from "@react-navigation/bottom-tabs"; import { Alert } from "react-native"; import { AppMode } from "../components/AppContext"; import { TabParamList } from "../components/AppStack"; import { postFinishTimes } from "./APICalls"; import CreateAPIError from "./CreateAPIError"; import { AddToStorage } from "./FLAddToStorage"; type ScreenNavigationProp = BottomTabNavigationProp<TabParamList>; // Post Times to API export const SaveResults = async ( raceID: number, eventID: number, appMode: AppMode, time: number, finishTimesRef: React.MutableRefObject<Array<number>>, checkerBibsRef: React.MutableRefObject<Array<number>>, setLoading: (value: React.SetStateAction<boolean>) => void, navigation: ScreenNavigationProp ): Promise<void> => { try { // Post Finish Times data if (finishTimesRef.current.length < 1) { // Alert if no finishing times have been recorded Alert.alert("No Results", "You have not recorded any results. Please try again."); } else { try { if (appMode === "Online") { await postFinishTimes(raceID, eventID, finishTimesRef.current); } AddToStorage( raceID, eventID, appMode, time, finishTimesRef.current, checkerBibsRef.current, true, setLoading, navigation ); } catch (error) { if (error instanceof Error && error.message.toLowerCase().includes("out of order")) { Alert.alert("Results Error", "Results have already been posted for this event! You cannot re-post results."); } else { CreateAPIError("Post Times", error); } setLoading(false); } } } catch (error) { CreateAPIError("Start Time", error); } };
package com.example.flixsterpart2 import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide const val MOVIE_EXTRA = "MOVIE_EXTRA" private const val TAG = "MovieAdapter" class MovieAdapter(private val context: Context, private val movies: List<Movie>) : RecyclerView.Adapter<MovieAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.item_movie, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { // TODO: Get the individual article and bind to holder val movie = movies[position] holder.bind(movie) } override fun getItemCount() = movies.size inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { private val mediaImageView = itemView.findViewById<ImageView>(R.id.mediaImage) private val titleTextView = itemView.findViewById<TextView>(R.id.mediaTitle) private val rateTextView = itemView.findViewById<TextView>(R.id.mediaRate) init { itemView.setOnClickListener(this) } // TODO: Write a helper method to help set up the onBindViewHolder method override fun onClick(v: View?) { // TODO: Get selected article val movie = movies[absoluteAdapterPosition] // TODO: Navigate to Details screen and pass selected article val intent = Intent(context, MovieDetailActivity::class.java) intent.putExtra(MOVIE_EXTRA, movie) context.startActivity(intent) } fun bind(movie: Movie) { titleTextView.text = movie.title.toString() rateTextView.text = "Rate: " + movie.vote.toString() Glide.with(context) .load("https://image.tmdb.org/t/p/w500" + movie.poster_path) .into(mediaImageView) } } }
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; import { DataService } from '../../data.service'; @Component({ selector: 'app-adminadd', templateUrl: './adminadd.component.html', styleUrls: ['./adminadd.component.css'] }) export class AdminaddComponent implements OnInit { menuForm: FormGroup = new FormGroup({}); aliments = [ { id: 1, nom: 'California Saumon Avocat' }, { id: 2, nom: 'Sushi Saumon' }, { id: 3, nom: 'Spring Avocat Cheese' }, {id:4, nom: 'California pacific'}, {id:5, nom:'Edamame/Salade de chou'}, {id:6, nom:'Maki Salmon Roll'}, {id:7, nom:'Spring Saumon Avocat'}, {id:8, nom:'Maki Cheese Avocat'}, {id:9, nom:'California Thon Cuit Avocat'}, {id:10, nom:'Sushi Thon'}, {id:11, nom:'California Thon Avocat'}, {id:12, nom:'Sando Chicken Katsu'}, {id:13, nom:'Sando Salmon Aburi'}, {id:14, nom:'Maki Salmon'}, {id:15, nom:'California Crevette'}, {id:16, nom:'California Chicken Katsu'}, {id:18, nom:'Spring tataki Saumon'}, {id:19, nom:'Signature Dragon Roll'}, {id:20, nom:'California French Touch'}, {id:21, nom:'California French salmon'}, {id:22, nom:'California Yellowtail Ponzu'}, {id:23, nom:"Signature Rock'n Roll"}, {id:24, nom:"Sushi Salmon"}, {id:24, nom:"Sushi Saumon Tsukudani"}, ]; saveurs = [ { id: 1, nom: 'Saumon' }, { id: 2, nom: 'Avocat' }, { id: 3, nom: 'cheese' }, {id:4, nom: 'coriandre'}, {id:5, nom:'thon'}, {id:6, nom:'viande'}, {id:7, nom:'crevette'}, {id:8, nom:'spicy'}, {id:9, nom:'seriole lalandi'} ]; constructor(private fb: FormBuilder, private dataService: DataService) { } ngOnInit() { this.menuForm = this.fb.group({ nom: '', img: '', pieces: '', prix: '', aliments: this.fb.array([]), saveurs: this.fb.array([]) }); this.addCheckboxes(); } private addCheckboxes() { this.aliments.map((o, i) => { const control = this.fb.control(false); (this.menuForm.controls['aliments'] as FormArray).push(control); }); this.saveurs.map((o, i) => { const control = this.fb.control(false); (this.menuForm.controls['saveurs'] as FormArray).push(control); }); } submit() { const selectedAlimentIds = this.menuForm.value.aliments .map((v: boolean, i: number) => v ? this.aliments[i].id : null) .filter((v: any) => v !== null) const selectedSaveurIds = this.menuForm.value.saveurs .map((v: boolean, i: number) => v ? this.saveurs[i].id : null) .filter((v: any) => v !== null) const data = { nom: this.menuForm.value.nom, img: this.menuForm.value.img, pieces: Number(this.menuForm.value.pieces), prix: Number(this.menuForm.value.prix), aliments: selectedAlimentIds, saveurs: selectedSaveurIds }; console.log(data) this.dataService.createMenu(data).subscribe( res => { console.log(res); alert('Menu créé avec succès'); }, err => { console.error(err); alert('Menu non créé. Erreur : ' + err.message); } ); }}
package com.example.assignmentdistributed.user; import com.example.assignmentdistributed.Game; import com.example.assignmentdistributed.Rank; import com.example.assignmentdistributed.SocketMessage; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; import javafx.util.Duration; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; public class UserAplication extends Application { private Socket userSocket; private ObjectInputStream input; private ObjectOutputStream output; private String username; private int mode; public UserAplication() {} public void connectToServer() { String hostname = "localhost"; try { InetAddress ip = InetAddress.getByName(hostname); userSocket = new Socket(ip, 12345); output = new ObjectOutputStream(userSocket.getOutputStream()); input = new ObjectInputStream(userSocket.getInputStream()); userSocket.setSoTimeout(200); System.out.println("USER - CONNECTION WAS SUCCESSFULLY SET UP"); } catch (Exception e) { e.printStackTrace(); } } public void authentication() { launch(); } @Override public void start(Stage primaryStage) { connectToServer(); drawLoginMenu(primaryStage); } public void drawLoginMenu(Stage stage) { // Create UI controls Label usernameLabel = new Label("Username:"); TextField usernameField = new TextField(); Label passwordLabel = new Label("Password:"); PasswordField passwordField = new PasswordField(); Button loginButton = new Button("Login"); Button registerButton = new Button("Register"); // Create layout panes and add controls GridPane root = new GridPane(); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(10)); root.setHgap(10); root.setVgap(10); root.add(usernameLabel, 0, 0); root.add(usernameField, 1, 0); root.add(passwordLabel, 0, 1); root.add(passwordField, 1, 1); HBox buttonBox = new HBox(); buttonBox.setAlignment(Pos.CENTER); buttonBox.setSpacing(10); buttonBox.getChildren().addAll(loginButton, registerButton); root.add(buttonBox, 0, 2, 2, 1); // Create scene and add layout pane Scene scene = new Scene(root, 300, 200); // Set stage properties and show stage.setScene(scene); stage.setTitle("Authentication Menu"); stage.show(); loginButton.setOnAction(event -> { sendLoginRequest(usernameField.getText(), passwordField.getText()); SocketMessage response = getServerMessageResponse(); if (response.getCode() == SocketMessage.LOGIN_SUCCESSFUL) { stage.close(); username = usernameField.getText(); Object[] arguments = response.getArguments(); String game = (String) arguments[0]; if (game.equals("game")) draw_success_message("Login succeded! Game is starting.", stage, "startGame"); else draw_success_message("Login succeded! Choose Game Mode.", stage, "login"); } else { // show error stage.close(); draw_error("Invalid username or password.", stage); } }); registerButton.setOnAction(event -> { if(usernameField.getText().isEmpty()) { stage.close(); draw_error("Username cannot be empty!", stage); } else if(passwordField.getText().isEmpty()){ stage.close(); draw_error("Password cannot be empty!", stage); } else { sendRegistrationRequest(usernameField.getText(), passwordField.getText()); SocketMessage response = getServerMessageResponse(); if (response.getCode() == SocketMessage.REGISTER_SUCCESSFUL) { stage.close(); draw_success_message("Register Succeeded! Please Login.", stage, "register"); } else { // show error stage.close(); draw_error("Username already exists.", stage); } } }); } public void draw_error(String error, Stage stage) { // Create UI controls Label errorLabel = new Label(error); Button okayButton = new Button("I understand"); GridPane root = new GridPane(); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(10)); root.setHgap(10); root.setVgap(10); root.add(errorLabel, 0, 0); HBox buttonBox = new HBox(); buttonBox.setAlignment(Pos.CENTER); buttonBox.setSpacing(10); buttonBox.getChildren().addAll(okayButton); root.add(buttonBox, 0, 2, 2, 1); // Create scene and add layout pane Scene scene = new Scene(root, 300, 200); // Set stage properties and show Stage errorStage = new Stage(); errorStage.setScene(scene); errorStage.setTitle("Error"); errorStage.show(); okayButton.setOnAction(event -> { errorStage.close(); drawLoginMenu(stage); }); } public void draw_success_message(String msg, Stage stage, String etapa) { // Create UI controls Label messageLabel = new Label(msg); Button nextButton = new Button("Next"); GridPane root = new GridPane(); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(10)); root.setHgap(10); root.setVgap(10); root.add(messageLabel, 0, 0); HBox buttonBox = new HBox(); buttonBox.setAlignment(Pos.CENTER); buttonBox.setSpacing(10); buttonBox.getChildren().addAll(nextButton); root.add(buttonBox, 0, 2, 2, 1); // Create scene and add layout pane Scene scene = new Scene(root, 400, 200); Stage successStage = new Stage(); successStage.setScene(scene); successStage.setTitle("Success"); successStage.show(); nextButton.setOnAction(event -> { successStage.close(); switch (etapa) { case "login" -> askGameMode(stage); case "register" -> drawLoginMenu(stage); case "gameMode" -> { sendGameMode(mode); inQueue(stage); } case "startGame" -> { SocketMessage response = getServerMessageResponse(); Object[] arguments = response.getArguments(); Game game = (Game) arguments[0]; mode = game.mode; Integer rank = (Integer) arguments[1]; startGame(stage, game, rank); } default -> { } } }); } public SocketMessage getServerMessageResponse(){ SocketMessage response = null; try { response = (SocketMessage) input.readObject(); } catch (SocketException se) { // handle socket closed exception System.out.println("Socket closed: " + se.getMessage()); } catch (IOException | ClassNotFoundException e) { //e.printStackTrace(); } return response; } public void sendLoginRequest(String name, String pass) { try { SocketMessage loginInfo = new SocketMessage(SocketMessage.LOGIN_REQUEST, name, pass); output.writeObject(loginInfo); output.flush(); System.out.println("USER - WRITING login info"); } catch (IOException e) { e.printStackTrace(); } } public void sendRegistrationRequest(String name, String pass) { try { SocketMessage loginInfo = new SocketMessage(SocketMessage.REGISTER_REQUEST, name, pass); output.writeObject(loginInfo); output.flush(); System.out.println("USER - WRITING registration info"); } catch (IOException e) { e.printStackTrace(); } } public void askGameMode(Stage stage) { System.out.println("ASKING GAME MODE"); GameModeView.run(stage, mode -> { setMode(mode); if(mode == 1) draw_success_message("Simple Mode chosen Successfully! Click next to enter the queue", stage, "gameMode"); else draw_success_message("Ranked Mode chosen Successfully! Click next to enter the queue", stage, "gameMode"); }); } public void sendGameMode(int mode) { try { SocketMessage gameMode = new SocketMessage(SocketMessage.GAME_MODE, mode); output.writeObject(gameMode); output.flush(); } catch (IOException e) { e.printStackTrace(); } } public void inQueue(Stage stage){ stage.setOnCloseRequest(event -> { // code to run when the window is closed System.out.println("Window closed - exiting queue"); sendExitQueueRequest(); }); System.out.println("IN QUEUE"); SocketMessage posGameMode = getServerMessageResponse(); Object[] arguments = posGameMode.getArguments(); Integer queueLength = (Integer) arguments[0]; Integer rank; if (mode == 1) { rank = null; QueueView.run(stage, username, queueLength, ""); } else { // ranking rank = (Integer) arguments[1]; QueueView.run(stage, username, queueLength, Rank.getRankByLevel(rank).toString()); } Timeline timeline = new Timeline(); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(1), event -> { SocketMessage response = getServerMessageResponse(); if (response != null && response.getCode() == SocketMessage.UPDATE_QUEUE_LENGTH) { System.out.println("SUCCESS"); Object[] arguments2 = response.getArguments(); Integer queueLength2 = (Integer) arguments2[0]; QueueView.updateView(stage, queueLength2); } if (response != null && response.getCode() == SocketMessage.START_GAME) { System.out.println("Received START_GAME"); Object[] arguments2 = response.getArguments(); Game game = (Game) arguments2[0]; stage.close(); timeline.stop(); startGame(stage, game, rank); } })); timeline.setCycleCount(Timeline.INDEFINITE); timeline.play(); } public void sendExitQueueRequest() { try { SocketMessage exitRequest = new SocketMessage(SocketMessage.EXIT_QUEUE, username); output.writeObject(exitRequest); output.flush(); System.out.println("USER - Sending Queue Exit request"); } catch (IOException e) { e.printStackTrace(); } } private void startGame(Stage stage, Game game, Integer rank) { stage.setOnCloseRequest(event -> { System.out.println("Window closed - Game went down"); sendReconnectionMessage(); }); System.out.println("Game started! Mode: " + mode); GameView.run(stage, game, username , mode, rank, output); Timeline timeline = new Timeline(); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(1), event -> { SocketMessage response = getServerMessageResponse(); if (response != null && response.getCode() == SocketMessage.UPDATE_GAME) { Object[] arguments = response.getArguments(); String turn = (String) arguments[0]; String tooltip = (String) arguments[1]; String attack_effectiveness = (String) arguments[2]; int P1_health = (int) arguments[3]; int P2_health = (int) arguments[4]; boolean player_turn = turn.equals(username); GameView.updateView(player_turn, tooltip, attack_effectiveness, P1_health, P2_health); } if(response != null && response.getCode() == SocketMessage.GAME_OVER) { System.out.println("Game is Over"); Object[] arguments = response.getArguments(); String winner = (String) arguments[0]; String tooltip = (String) arguments[1]; stage.close(); timeline.stop(); draw_winner(stage, winner, tooltip); } sendConfirmationMessage(); })); timeline.setCycleCount(Timeline.INDEFINITE); timeline.play(); } private void sendReconnectionMessage() { try { SocketMessage exitRequest = new SocketMessage(SocketMessage.GAME_RECONNECTION); output.writeObject(exitRequest); output.flush(); System.out.println("USER - Sending Queue Exit request"); } catch (IOException e) { e.printStackTrace(); } } private void sendConfirmationMessage() { try { SocketMessage gameMode = new SocketMessage(SocketMessage.STILL_HERE); output.writeObject(gameMode); output.flush(); } catch (IOException e) { e.printStackTrace(); } } private void draw_winner(Stage stage, String winner, String tooltip) { GameOverView.run(stage, winner, tooltip, mode -> { switch (mode) { case 1 -> { stage.close(); askGameMode(stage); } case 2 -> { try { SocketMessage logoutRequest = new SocketMessage(SocketMessage.LOGOUT_REQUEST); output.writeObject(logoutRequest); output.flush(); } catch (IOException e) { e.printStackTrace(); } stage.close(); try { userSocket.close(); } catch (IOException e) { e.printStackTrace(); } start(stage); } case 3 -> { try { SocketMessage logoutRequest = new SocketMessage(SocketMessage.LOGOUT_REQUEST); output.writeObject(logoutRequest); output.flush(); } catch (IOException e) { e.printStackTrace(); } stage.close(); } } }); } private void setMode(int m) { mode = m; } }
package com.skylightapp.Bookings; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.skylightapp.Classes.Profile; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.adapter.guava.GuavaCallAdapterFactory; @SuppressWarnings("UnstableApiUsage") public class LocalProviderService { private static final String TAG = "LocalProviderService"; public static final int GET_TRIP_RETRY_INTERVAL_MILLIS = 5000; private final RestProvider provider; private final Executor executor; TripResponse trip ; private final ScheduledExecutorService scheduledExecutor; public LocalProviderService( RestProvider provider, Executor executor, ScheduledExecutorService scheduledExecutor) { this.provider = provider; this.executor = executor; this.scheduledExecutor = scheduledExecutor; } public ListenableFuture<TripResponse> createTrip(TaxiTrip createTripRequest) { return provider.createTrip(createTripRequest); } public ListenableFuture<TokenResponse> fetchAuthToken(String tripId) { return provider.getProfileToken(tripId); } public ListenableFuture<Profile> fetchMatchedTrip(String tripName) { String tripId = null; if (TripName.create(tripName) != null) { if (TripName.create(tripName) != null) { tripId = TripName.create(tripName).getTripId(); } } ListenableFuture<GetTripResponse> getTripResponseFuture = fetchMatchedTripWithRetries(tripId); String finalTripId = tripId; return Futures.transform( getTripResponseFuture, getTripResponse -> { if (getTripResponse != null) { trip = getTripResponse.getTrip(); } if (trip != null) { if (TripData.newBuilder() != null) { return TripData.newBuilder() .setTripId(finalTripId) .setTripName(trip.getTripName()) .setVehicleId(trip.getVehicleId()) .setTripStatus(TripStatus.parse(trip.getTripStatus())) .setWaypoints(Lists.newArrayList(trip.getWaypoints())) .build(); } } return null; }, executor); } private ListenableFuture<GetTripResponse> fetchMatchedTripWithRetries(String tripId) { return new RetryingFuture(scheduledExecutor) .runWithRetries( () -> provider.getTrip(tripId), RetryingFuture.RUN_FOREVER, GET_TRIP_RETRY_INTERVAL_MILLIS, LocalProviderService::isTripValid); } private static boolean isTripValid(GetTripResponse response) { return response != null && response.getTrip() != null && response.getTrip().getVehicleId() != null && !response.getTrip().getVehicleId().isEmpty(); } public static RestProvider createRestProvider(String baseUrl) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addCallAdapterFactory(GuavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(RestProvider.class); } }
import tkinter as tk from tkinter import filedialog from PIL import Image, ImageTk, ImageDraw import requests import io import shutil class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() def create_widgets(self): self.upload = tk.Button(self) self.upload["text"] = "Upload Image" self.upload["command"] = self.upload_image self.upload.pack(side="top") self.quit = tk.Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="bottom") def upload_image(self): filepath = filedialog.askopenfilename() self.send_request(filepath) def send_request(self, filepath): token = "rest_api_token" project_id = "project_id" model = "model_name" headers = {"X-Auth-token": token, "Content-Type": "application/octet-stream"} with open(filepath, 'rb') as handle: r = requests.post('https://platform.sentisight.ai/api/predict/{}/{}/'.format(project_id,model), headers=headers, data=handle) if r.status_code == 200: print('Response from REST API:') response = r.json() print(response) # Print the JSON response self.display_image(filepath, response) else: print('Error occurred with REST API.') print('Status code: {}'.format(r.status_code)) print('Error message: ' + r.text) def display_image(self, filepath, response): image = Image.open(filepath) draw = ImageDraw.Draw(image) for obj in response: x0, y0, x1, y1 = obj['x0'], obj['y0'], obj['x1'], obj['y1'] label = obj['label'] draw.rectangle(((x0, y0), (x1, y1)), outline="red", width=5) draw.text((x0, y0 - 10), label, fill="black") image.save("output.png") photo = ImageTk.PhotoImage(image) new_window = tk.Toplevel(self) label = tk.Label(new_window, image=photo) label.image = photo label.pack() root = tk.Tk() app = Application(master=root) app.mainloop()
import './Common.css'; import './ItemList.css'; import { useMoreButtonFunction } from './MoreFunction'; import { useSnapFunction } from './SnapFunction'; import data from "../itemList.json"; function ItemGroup({ items }) { return ( <div className="item"> {items.map(item => ( <div key={item.id}> <div className='itemimg'><img src={item.img} alt={item.title} /></div> <p>{item.title}</p> </div> ))} </div> ); } function ItemDataList() { // 콘텐츠 8개씩 보기 const { displayItems, moreButtonVisible, closeButtonVisible, showMore, close } = useMoreButtonFunction(data.itemData, 8); // 스냅 기능 useSnapFunction('#section02 .content'); // dataList를 두 부분으로 나눔 const halfLength = Math.ceil(displayItems.length / 2); const itemFirstHalf = displayItems.slice(0, halfLength); const itemSecondHalf = displayItems.slice(halfLength); return ( <div id="main"> <section id="section02"> <div className="inner padding"> <div className="title"> <div> <h3>참여품목</h3> <p>입주를 위한<br />모든 것이 한곳에!</p> </div> </div> {moreButtonVisible && <button onClick={showMore}><i className="bi bi-plus-circle-fill" id="moreButton02"></i></button>} {closeButtonVisible && <button onClick={() => close('section02')}><i className="bi bi-dash-circle-fill" id="closeButton02"></i></button>} <div className="content"> <div> <ItemGroup items={itemFirstHalf} /> <ItemGroup items={itemSecondHalf} /> </div> </div> </div> </section> </div> ); } export default ItemDataList;
#include "search.h" /** * linear_skip - searches for a value in a sorted skip list of integers * * @list: Pointer to the head node of the list * @value: the value to search for * * Return: a pointer to the node with the value */ skiplist_t *linear_skip(skiplist_t *list, int value) { skiplist_t *search_pointer; if (!list) return (NULL); search_pointer = list->express; printf("Value checked at index [%lu] = [%d]\n", search_pointer->index, search_pointer->n); while (search_pointer && search_pointer->n < value) { list = search_pointer; search_pointer = search_pointer->express; if (!search_pointer) break; printf("Value checked at index [%lu] = [%d]\n", search_pointer->index, search_pointer->n); } if (!search_pointer) { search_pointer = list; while (search_pointer->next) search_pointer = search_pointer->next; } printf("Value found between indexes [%lu] and [%lu]\n", list->index, search_pointer->index); while (list && list->n <= search_pointer->n) { printf("Value checked at index [%lu] = [%d]\n", list->index, list->n); if (list->n == value) return (list); list = list->next; } return (NULL); }
package com.restful.springrest.entities; import java.util.Date; import java.util.UUID; import jakarta.persistence.Entity; import jakarta.persistence.Id; @Entity public class Loads { @Id private int loadId; private String loadingPoint; private String unloadingPoint; private String productType; private String truckType; private int noOfTrucks; private double weight; private UUID shipperId; private Date date; public Loads() { super(); // TODO Auto-generated constructor stub } public Loads(int loadId, String loadingPoint, String unloadingPoint, String productType, String truckType, int noOfTrucks, double weight, UUID shipperId, Date date) { super(); this.loadId=loadId; this.loadingPoint = loadingPoint; this.unloadingPoint = unloadingPoint; this.productType = productType; this.truckType = truckType; this.noOfTrucks = noOfTrucks; this.weight=weight; this.shipperId = shipperId; this.date = date; } public int getLoadId() { return loadId; } public void setLoadId(int loadId) { this.loadId = loadId; } public UUID getShipperId() { return shipperId; } public void setShipperId(UUID shipperId) { this.shipperId = shipperId; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getLoadingPoint() { return loadingPoint; } public void setLoadingPoint(String loadingPoint) { this.loadingPoint = loadingPoint; } public String getUnloadingPoint() { return unloadingPoint; } public void setUnloadingPoint(String unloadingPoint) { this.unloadingPoint = unloadingPoint; } public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; } public String getTruckType() { return truckType; } public void setTruckType(String truckType) { this.truckType = truckType; } public int getNoOfTrucks() { return noOfTrucks; } public void setNoOfTrucks(int noOfTrucks) { this.noOfTrucks = noOfTrucks; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } @Override public String toString() { return "Load [loadId=" +loadId +"loadingPoint=" +loadingPoint +", unloadingPoint=" +unloadingPoint +", productType=" +productType +", truckType" +truckType +", noOfTrucks=" +noOfTrucks +", weight=" +weight +", shipperId=" +shipperId +", Date=" +date +"]"; } }
#include "Bees.hpp" #include <utility> #include <limits> #include <chrono> std::string_view CriterionToString(criterion c) { switch (c) { case max_transported: return "Maksymalny przewóz"; case max_distance: return "Maksymalny dystans"; case most_efficient: return "Największa efetywność"; case CRITERION_NR_ITEMS: break; } return ""; } std::string_view NeighborhoodToString(Neighborhood neighborhood) { switch (neighborhood) { case RANDOM_TRAM_RANDOM_PATH: return "Losowy tramwaj, losowa trasa"; case RANDOM_TRAM_RANDOM_AFTER: return "Losowy tramwaj, losowa zmiana końca trasy"; case NEIGHBORHOOD_NR_ITEMS: break; } return ""; } Bees::Bees( AlgorithmParameters parameters, uint32_t seed, Point2D depot, ProblemParameters problemParameters) : seed_(seed), depot_(depot), problemParameters_(std::move(problemParameters)), parameters_(parameters), generator_{seed_} { tram_amount = problemParameters_.tramCount; solutions.reserve(parameters.solutionsNumber); // Initialize rest of solutions bees randomly for (int i=0; i != parameters.solutionsNumber; i ++) { // generate random solutions Bee bee; bee.trams.gen_rand_unique(problemParameters_.stations, tram_amount, tram_length, depot_, generator_); bee.quality = calculateFitness(bee.trams); bee.age = 0; solutions.push_back(bee); } std::sort(solutions.begin(), solutions.end(), std::greater<>()); best_bee_ = solutions[0]; bestValueIteration_.push_back(best_bee_.quality); } Bee Bees::run() { for (int iteration = 0; iteration != parameters_.maxIterations; iteration++) { elites_search(); best_search(); scouts_search(); age(); std::sort(solutions.begin(), solutions.end(), std::greater<>()); if (solutions[0].quality > best_bee_.quality) best_bee_ = solutions[0]; bestValueIteration_.push_back(best_bee_.quality); // For debug only // bestValueIteration_.push_back(solutions[0].quality); } return best_bee_; } void Bees::elites_search() { for (int i=0; i != parameters_.eliteCount; i ++) { Bee &newBee = solutions[i]; std::vector<BeeLocal> vec; vec.reserve(parameters_.eliteRecruits); for (auto z : std::views::iota(0, parameters_.eliteRecruits)) vec.push_back(CreatLocalBee(newBee)); bool has_changed_bee = false; // szukaj lokalnie dopóki czas życia, sąsiectwo dla elitranych nie jest adaptacyjne for (int j = 0; j < parameters_.beeLifeTime; ++j) { for (auto &localBee: vec) { if (localBee.distance_from_original > parameters_.neighborhoodSize) localBee = CreatLocalBee(newBee); if (problemParameters_.neighborhood == RANDOM_TRAM_RANDOM_PATH) // Sąsiectwo 1 { localBee.trams.deleteTram(generator_() % tram_amount); localBee.trams.gen_rand_unique(problemParameters_.stations, 1, tram_length, depot_, generator_); localBee.quality = calculateFitness(localBee.trams); localBee.distance_from_original += 1; } else if (problemParameters_.neighborhood == RANDOM_TRAM_RANDOM_AFTER) // Sąsiectwo 2 { localBee.trams.gen_rand_after(problemParameters_.stations, problemParameters_.neighborhood, tram_length, depot_, generator_); localBee.quality = calculateFitness(localBee.trams); // dystans nie ma znaczenia, nie będzie większy niż rozmiar otoczenia } if (localBee.quality > newBee.quality) { newBee.trams = localBee.trams; newBee.quality = localBee.quality; newBee.age = 0; has_changed_bee = true; } } // Jeśli polepszono - przeszukanie lokalne na nowo if (has_changed_bee) { has_changed_bee = false; j = 0; auto localBee = CreatLocalBee(newBee); std::fill(vec.begin(), vec.end(), localBee); } } newBee.age = parameters_.beeLifeTime + 1; } // for (int i=0; i != parameters_.eliteCount; i ++) { // Bee newBee(solutions[i]); // // for (int j=0; j != parameters_.eliteRecruits; j ++) { // Bee tempBee(solutions[i]); // // tempBee.trams.deleteTram(generator_() % tram_amount); // tempBee.trams.gen_rand_unique(problemParameters_.stations, 1, tram_length, depot_, generator_); // tempBee.quality = calculateFitness(tempBee.trams); // tempBee.age = 0; // // if (tempBee.quality > newBee.quality){ // newBee = tempBee; // } // } // if (newBee.quality > solutions[i].quality){ // solutions[i] = newBee; // } // } } void Bees::best_search() { for (int i=parameters_.eliteCount; i != parameters_.bestCount; i ++) { Bee &newBee = solutions[i]; std::vector<BeeLocal> vec; vec.reserve(parameters_.bestRecruits); for (auto z : std::views::iota(0, parameters_.bestRecruits)) vec.push_back(CreatLocalBee(newBee)); bool has_changed_bee = false; int neighborhood_size = parameters_.neighborhoodSize; int iter_without_change = 0; // szukaj lokalnie dopóki czas życia i sąsiectwo nie jest zerowe for (int j = 0; j < parameters_.beeLifeTime && neighborhood_size > 0; ++j) { for (auto &localBee: vec) { if (localBee.distance_from_original > neighborhood_size) localBee = CreatLocalBee(newBee); if (problemParameters_.neighborhood == RANDOM_TRAM_RANDOM_PATH) // Sąsiectwo 1 { localBee.trams.deleteTram(generator_() % tram_amount); localBee.trams.gen_rand_unique(problemParameters_.stations, 1, tram_length, depot_, generator_); localBee.quality = calculateFitness(localBee.trams); localBee.distance_from_original += 1; } else if (problemParameters_.neighborhood == RANDOM_TRAM_RANDOM_AFTER) // Sąsiectwo 2 { localBee.trams.gen_rand_after(problemParameters_.stations, problemParameters_.neighborhood, tram_length, depot_, generator_); localBee.quality = calculateFitness(localBee.trams); // dystans nie ma znaczenia, nie będzie większy niż rozmiar otoczenia } ++iter_without_change; if (localBee.quality > newBee.quality) { newBee.trams = localBee.trams; newBee.quality = localBee.quality; newBee.age = 0; has_changed_bee = true; } if (parameters_.adaptive_size > 0 && iter_without_change >= parameters_.adaptive_size) { neighborhood_size /= 2; // TODO - add parameter } } // Jeśli polepszono - przeszukanie lokalne na nowo if (has_changed_bee) { has_changed_bee = false; j = 0; neighborhood_size = parameters_.neighborhoodSize; iter_without_change = 0; auto localBee = CreatLocalBee(newBee); std::fill(vec.begin(), vec.end(), localBee); } } newBee.age = parameters_.beeLifeTime + 1; } // for (int j=0; j != parameters_.eliteRecruits; j ++) { // BeeLocal tempBee = CreatLocalBee(newBee); // // // tempBee.trams.deleteTram(generator_() % tram_amount); // tempBee.trams.gen_rand_unique(problemParameters_.stations, 1, tram_length, depot_, generator_); // tempBee.quality = calculateFitness(tempBee.trams); // tempBee.distance_from_original += 1; // // // } // for (int i=parameters_.eliteCount; i != parameters_.bestCount; i ++) { // Bee newBee(solutions[i]); // // for (int j=0; j != parameters_.bestRecruits; j ++) { // Bee tempBee(solutions[i]); // // tempBee.trams.deleteTram(generator_() % tram_amount); // tempBee.trams.gen_rand_unique(problemParameters_.stations, 1, tram_length, depot_, generator_); // tempBee.quality = calculateFitness(tempBee.trams); // tempBee.age = 0; // // if (tempBee.quality > newBee.quality){newBee = tempBee;} // } // if (newBee.quality > solutions[i].quality){solutions[i] = newBee;} // } } void Bees::scouts_search() { for (int i=parameters_.bestCount; i != parameters_.solutionsNumber; i ++) { Bee &bee = solutions[i]; bee.trams.gen_rand_unique(problemParameters_.stations, tram_amount, tram_length, depot_, generator_); bee.quality = calculateFitness(bee.trams); bee.age = 0; solutions[i] = bee; } } float Bees::calculateFitness(TramList trams) { objectiveFunCalls += 1; // Calculate the fitness (quality) of a Trams std::tuple<float, uint32_t, float> objective = problemParameters_.tramProblem.run(trams); switch (problemParameters_.problemCriterion) { case max_transported: return std::get<0>(objective); case max_distance: return float(std::get<1>(objective)); case most_efficient: return std::get<2>(objective); case CRITERION_NR_ITEMS: break; } return std::numeric_limits<float>::min(); } void Bees::age() { for (int i=0; i != parameters_.bestCount; i ++) { Bee &bee = solutions[i]; if (bee.age > parameters_.beeLifeTime){ bee.trams.gen_rand_unique(problemParameters_.stations, tram_amount, tram_length, depot_, generator_); bee.quality = calculateFitness(bee.trams); bee.age = 0; } else bee.age ++; } } ProblemParameters::ProblemParameters(const int i, Graph<struct Point2D> graph, TramProblem problem, StationList list, criterion criterion1, Neighborhood neighborhood) :tramCount(i), stations(std::move(graph)), tramProblem(std::move(problem)), stationList(std::move(list)), problemCriterion(criterion1), neighborhood{neighborhood} { } //Bee::Bee(const TramList& trams, double quality, uint8_t age): trams{trams}, quality{quality}, age{age} //{ //} BeeLocal CreatLocalBee(const Bee& bee) { return { .trams = bee.trams, .quality = bee.quality, .distance_from_original = 0 }; }
--- tags: ALL aliase: created: 2023-04-15 20:44 modified: 星期六 15日 四月 2023 20:44:09 --- # Q 函式進階 *** 1. 請問以下C++程式碼是否正確? ```cpp linenos void (*ptr)(int a=3,int b=4) = &test; ``` >[!note]- Ans >函式指標只能指向函式本身,而不是函式的參數,因此無法給函式參數設置默認值。 2. 請問以下C++程式碼是否正確? ```cpp linenos add(int a=2, int b);//最右邊開始 ``` >[!note]- Ans >默認參數應從最右邊開始指派 3. 請問以下C++程式碼在第5行出錯,為什麼? ```cpp linenos void test(int a, int b=3){     cout << "2"; } int main(){     void (*ptr)(double, int) = test;// compilation error } ``` >[!note]- Ans >函式指標參數與指定函式的參數類型不一致 4. 請問以下C++程式碼是否正確? ```cpp linenos void (*ptr)(int a,int b) = &test(int a,int b); ``` >[!note]- Ans >test不需要加參數 5. 請問以下C++程式碼是否正確? ```cpp title:"宣告與定義" int add(); int add(int a, int b=2); int add(){return 0;} int add(int a, int b=2){return a+b;} ``` >[!note]- Ans >第5行程式碼,宣告-定義分開式結構,(define)不能使用默認參數
import { DecisionIntegration, DecisionRequest, DecisionResponse, HealthCheckResponse, IntegrationInfoResponse, StatusCode, } from '@indent/base-integration' const pkg = require('../package.json') export class NewIntegration implements DecisionIntegration { _name?: string constructor(opts?: { name: string }) { if (opts) { this._name = opts.name } } HealthCheck(): HealthCheckResponse { return { status: { code: 0 }, } } GetInfo(): IntegrationInfoResponse { return { name: ['indent-example-webhook', this._name].filter(Boolean).join('#'), capabilities: ['Apply', 'Pull'], version: pkg.version, } } MatchDecision(_req: DecisionRequest): boolean { return true } async GetDecision(req: DecisionRequest): Promise<DecisionResponse> { const { events } = req const reqEvent = events[0] // process request event return { status: { code: StatusCode.OK }, claims: [ { event: 'access/approve', actor: { id: 'auto-approval', displayName: 'On-call Auto Approval' }, }, ], } } }
<template> <div> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="/home">CNS-Vue</a> <div v-if="isLogin" class="row"> <button class="btn btn-secondary mx-3" id="create_btn" data-toggle="modal" data-target="#create_post_modal" @click="openModal">Create Post</button> <button @click="logout" class="btn" id="header_logout_btn">Logout</button> </div> <div v-else class="row"> <router-link to="/signup"> <button class="btn btn-secondary mr-3" id="header_signup_btn">Sign Up</button> </router-link> <router-link to="/login"> <button class="btn btn-secondary" id="header_login_btn">Login</button> </router-link> </div> </div> </nav> <!-- <div class="modal fade" id="create_post_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Create Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="create_title_text">Title</label> <input type="text" class="form-control" id="create_title_text" placeholder="Title"> </div> <div class="form-group"> <label for="create_content_text">Content</label> <textarea class="form-control" rows="3" id="create_content_text"></textarea> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary" id="save_post_btn">Save Post</button> </div> </div> </div> </div> --> <!-- Button trigger modal --> <!-- <div class="example-modal-window"> <p>버튼을 누르면 모달 대화 상자가 열립니다.</p> <button @click="openModal">열기</button> --> <!-- 컴포넌트 MyModal --> <MyModal @close="closeModal" v-if="modal" class=" modal-dialog-centered"> <template slot="header"> <!-- <div> --> <h5 class="modal-title" id="exampleModalLongTitle">Create Post</h5> <button @click="closeModal" type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <!-- </div> --> </template> <template> <!-- <p>Vue.js Modal Window!</p> --> <div> <!-- <input v-model="message"> --> <form> <div class="form-group"> <label for="create_title_text">Title</label> <input v-model="title" type="text" class="form-control" id="create_title_text" placeholder="Title"> </div> <div class="form-group"> <label for="create_content_text">Content</label> <textarea v-model="content" class="form-control" rows="3" id="create_content_text"></textarea> </div> </form> </div> </template> <!-- default 슬롯 콘텐츠 --> <!-- <p>Vue.js Modal Window!</p> <div> <input v-model="message"> <form> <div class="form-group"> <label for="create_title_text">Title</label> <input type="text" class="form-control" id="create_title_text" placeholder="Title"> </div> <div class="form-group"> <label for="create_content_text">Content</label> <textarea class="form-control" rows="3" id="create_content_text"></textarea> </div> </form> </div> --> <!-- /default --> <!-- footer 슬롯 콘텐츠 --> <template slot="footer"> <button @click="doSend">제출</button> <button @click="closeModal" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button @click="createPost" type="button" class="btn btn-primary" id="save_post_btn">Save Post</button> </template> <!-- /footer --> </MyModal> <!-- </div> --> </div> </template> <script> import MyModal from './TestModal.vue' export default { data() { return { // showModal: false, isLogin: false, // 임시 // is_show: false, modal: false, message: '', title: "", content: "", } }, components:{ MyModal, }, created() { console.log("baseheader created "); if(this.$cookies.get('accesstoken')){ console.log("isLogin = ",this.isLogin); this.isLogin = true; } }, methods: { // handle_toggle: function(){ // this.is_show = !this.is_show; // #2, #3 // }, logout(){ this.$cookies.remove("accesstoken"); this.$router.go() }, openModal() { this.modal = true }, closeModal() { this.modal = false }, doSend() { if (this.message.length > 0) { alert(this.message) this.message = '' this.closeModal() } else { alert('메시지를 입력해주세요.') } }, createPost(){ console.log("create post"); var vm = this var data = { title : this.title, content : this.content, } var config = { headers: { accesstoken: vm.$cookies.get('accesstoken'), } } this.axios.post("/post",data,config) .then(function(response) { console.log("success ",response.data); vm.closeModal() vm.$router.go() }) .catch(function(error) { console.log(error); }) } }, } </script> <style> /* .modal-mask { position: fixed; z-index: 9998; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, .5); display: table; transition: opacity .3s ease; } .modal-wrapper { display: table-cell; vertical-align: middle; } .modal-container { width: 300px; margin: 0px auto; padding: 20px 30px; background-color: #fff; border-radius: 2px; box-shadow: 0 2px 8px rgba(0, 0, 0, .33); transition: all .3s ease; font-family: Helvetica, Arial, sans-serif; } .modal-header h3 { margin-top: 0; color: #42b983; } .modal-body { margin: 20px 0; } .modal-default-button { float: right; } */ /* * The following styles are auto-applied to elements with * transition="modal" when their visibility is toggled * by Vue.js. * * You can easily play with the modal transition by editing * these styles. */ /* .modal-enter { opacity: 0; } .modal-leave-active { opacity: 0; } .modal-enter .modal-container, .modal-leave-active .modal-container { -webkit-transform: scale(1.1); transform: scale(1.1); } */ </style>
# ON_PLAY_HANGUP_SOUND L'event `ON_PLAY_HANGUP_SOUND` se déclenche lorsqu'un appel est raccroché. ```js Wazo.Phone.on(Wazo.Phone.ON_PLAY_HANGUP_SOUND, onPlayHangupSound); ``` <div class="useless-tab-container"> - **Déclenchement** L'event `ON_PLAY_HANGUP_SOUND` se déclenche lorsqu'un appel est raccroché. ```js Wazo.Phone.hangup(callSession) ``` Plus d'informations sur la page [hangup](../phone/actions/hangup) - **Data** ```js // ne retourne pas de donnée ``` - **Logique** Permet d'obtenir l'information qu'il faut jouer le son pour signaler que l'appel est raccroché. - **Exemple** voici un exemple dans un projet avec React : ```js import React, { useState } from "react"; export const myComponent = () => { const [callSession, setCallSession] = useState({}); // contient l'appel actif const [callSessions, setCallSessions] = useState({}); // contient l'ensemble des appels (en cours et disponible) let audioTune; // définit la variable pour jouer le fichier audio const initializeWebRtc = async () => { // connexion à la ligne SIP await Wazo.Phone.connect({ audio: true, video: true }); // écoute de l'évènement ON_PLAY_HANGUP_SOUND Wazo.Phone.on(Wazo.Phone.ON_PLAY_HANGUP_SOUND, onPlayHangupSound); }; const onPlayHangupSound = () => { audioTune = new Audio('./sounds/HangUp.mp3') audioTune.play(); }; }; ``` </div>
import React, { useEffect, useState } from "react"; import LeftMenu from "./components/LeftMenu"; import RightTaskDesc from "./components/RightTaskDesc"; import Task from "./components/Task"; import { useAppDispatch, useAppSelector } from "./hooks/redux"; import Auth from "./components/auth/login/Auth"; import { Route, Routes } from "react-router-dom"; import ForgotPass from "./components/auth/forgot/ForgotPass"; import Register from "./components/auth/register/Register"; import { taskSlice } from "./hooks/reducers/taskSlice"; import { getUser } from "./services/auth/auth.helper"; import ListPage from "./pages/ListPage/ListPage"; import ListMain from "./pages/ListMain/ListMain"; import ListControl from "./pages/ListControl/ListControl"; function App() { //local vars const isLogined = useAppSelector((state) => state.taskReducer.isLogined); let userR = useAppSelector((state) => state.taskReducer.User); const dispatch = useAppDispatch(); const [indentUser, setIndentUser] = useState(0); const { pushCurrentUser } = taskSlice.actions; const isLogged = async () => { if (Object.keys(await getUser().then((res) => res)).length !== 0) { const user = await getUser(); userR = user; dispatch(pushCurrentUser(user)); setIndentUser((indentUser) => (indentUser = user.id)); } }; useEffect(() => { isLogged(); }, [isLogined]); if (isLogined === true) { if (userR!.role === "admin") { return ( <Routes> <Route path={`/workspace/${indentUser}`} element={ <main className="App"> <LeftMenu /> <Task /> <RightTaskDesc /> </main> } /> <Route path={`/workspace/${indentUser}/admin`} element={ <main className="App"> <ListPage /> <ListMain /> <ListControl /> </main> } /> <Route path="/" element={ <main className="App"> <Auth /> </main> } /> <Route path="/" element={ <main className="App"> <Auth /> </main> } /> <Route path="/register" element={ <main className="App"> {" "} <Register />{" "} </main> } /> <Route path="/login/access-token" element={<main className="App"></main>} /> <Route path="/forgot-password" element={ <main className="App"> {" "} <ForgotPass />{" "} </main> } /> </Routes> ); } else { return ( <Routes> <Route path={`/workspace/${indentUser}`} element={ <main className="App"> <LeftMenu /> <Task /> <RightTaskDesc /> </main> } /> <Route path="/" element={ <main className="App"> <Auth /> </main> } /> <Route path="/" element={ <main className="App"> <Auth /> </main> } /> <Route path="/register" element={ <main className="App"> {" "} <Register />{" "} </main> } /> <Route path="/login/access-token" element={<main className="App"></main>} /> <Route path="/forgot-password" element={ <main className="App"> {" "} <ForgotPass />{" "} </main> } /> </Routes> ); } } else { return ( <Routes> <Route path="/" element={ <main className="App"> <Auth /> </main> } /> <Route path="/register" element={ <main className="App"> {" "} <Register />{" "} </main> } /> <Route path="/login/access-token" element={<main className="App"></main>} /> <Route path="/forgot-password" element={ <main className="App"> {" "} <ForgotPass />{" "} </main> } /> </Routes> ); } } export default App;