text
stringlengths
184
4.48M
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddValueAndTimestampsToCurrencyTypesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('currency_types', function (Blueprint $table) { $table->decimal('value', 12, 6); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('currency_types', function (Blueprint $table) { $table->dropColumn('value'); $table->dropColumn('created_at'); $table->dropColumn('updated_at'); }); } }
package 双指针 /* 对双指针的理解: left从左向右遍历,right从右向左遍历; 则对left来说,leftMax一定准确,rightMax不一定准确,因为区间(left, right)的值还没有遍历, 但是left的rightMax一定 >= right的rightMax,所以只要leftMax < rightMax时, 我们不关心left的rightMax是多少了,因为它肯定比leftMax大,我们可以直接计算出left的存水量leftMax - nums[left]; 对right来说,rightMax一定准确,leftMax不一定准确,因为区间(left, right)的值还没有遍历, 但是right的leftMax一定 >= left的leftMax,所以只要leftMax >= rightMax时, 我们不关心right的leftMax是多少了,因为它肯定比rightMax大,我们可以直接计算出right的存水量rightMax - nums[right]; */ /* */ func trap(height []int) (ans int) { left, right := 0, len(height)-1 leftMax, rightMax := 0, 0 for left < right { leftMax = max(leftMax, height[left]) rightMax = max(rightMax, height[right]) if height[left] < height[right] { ans += leftMax - height[left] left++ } else { ans += rightMax - height[right] right-- } } return }
// // PlayHistory.swift // TenTunes // // Created by Lukas Tenbrink on 24.02.18. // Copyright © 2018 ivorius. All rights reserved. // import Cocoa extension Array { mutating func removeAll(keepTrackOf index: inout Int, where remove: (Element) -> Bool) { let realisticIndex = (0...count).clamp(index) self[0..<realisticIndex].removeAll { let removed = remove($0) if removed { index -= 1 } return removed } self[realisticIndex..<count].removeAll(where: remove) } } class PlayHistory { var playlist: AnyPlaylist var order: [Track] var shuffled: [Track]? var playingIndex: Int = -1 var queueEndIndex: Int = -1 init(playlist: AnyPlaylist) { self.playlist = playlist self.order = Array(playlist.tracksList) } init(from: PlayHistory) { playlist = from.playlist order = from.order playingIndex = from.playingIndex } var isUntouched: Bool { return order == Array(playlist.tracksList) } var isUnsorted: Bool { return order.sharesOrder(with: playlist.tracksList) } func convert(to mox: NSManagedObjectContext) { playlist = playlist.convert(to: mox) ?? PlaylistEmpty() order = mox.compactConvert(order) shuffled = shuffled.map(mox.compactConvert) } // Order, Filter func filter(by filter: @escaping (Track) -> Bool) { queueEndIndex = -1 if shuffled != nil { shuffled!.removeAll(keepTrackOf: &playingIndex) { !filter($0) } order.removeAll { !filter($0) } } else { order.removeAll(keepTrackOf: &playingIndex) { !filter($0) } } } func sort(by sort: (Track, Track) -> Bool) { queueEndIndex = -1 let playing = order[safe: playingIndex] order = order.sorted(by: sort) if shuffled == nil, let playing = playing { playingIndex = order.firstIndex(of: playing)! } } func unshuffle() { queueEndIndex = -1 let playing = playingTrack shuffled = nil if let playing = playing { playingIndex = order.firstIndex(of: playing)! } // Else we were at start or end } func shuffle() { queueEndIndex = -1 let playing = playingTrack shuffled = order shuffled!.shuffle() if let playing = playing { let idx = shuffled!.firstIndex(of: playing)! shuffled?.swapAt(0, idx) playingIndex = 0 } } func insert(tracks: [Track], before: Int) { queueEndIndex = -1 if shuffled != nil { shuffled!.insert(contentsOf: tracks, at: min(shuffled!.count, before)) } else { order.insert(contentsOf: tracks, at: min(order.count, before)) } } enum QueueLocation { case start, end } func enqueue(tracks: [Track], at: QueueLocation) { let queueStart = playingIndex + 1 let queueEnd = queueEndIndex > playingIndex ? queueEndIndex : queueStart insert(tracks: tracks, before: at == .start ? queueStart : queueEnd) queueEndIndex = queueEnd + tracks.count } func rearrange(tracks: [Track], before: Int) { queueEndIndex = -1 // TODO Doesn't work with the same track being in the playlist twice let playing = playingTrack if shuffled != nil { shuffled!.rearrange(elements: tracks, to: before) } else { order.rearrange(elements: tracks, to: before) } if let previous = playing { playingIndex = indexOf(track: previous)! } } func remove(indices: [Int]) { queueEndIndex = -1 if shuffled != nil { shuffled!.remove(at: indices) } else { order.remove(at: indices) } } // Query var count: Int { return tracks.count } var tracks: [Track] { return shuffled ?? order } func track(at: Int) -> Track? { return tracks[safe: at] } func indexOf(track: Track) -> Int? { return tracks.firstIndex(of: track) } func move(to: Int) { playingIndex = (-1...(tracks.count > 0 ? tracks.count : -1)).clamp(to) } func move(by: Int) -> Track? { move(to: playingIndex + by) return track(at: playingIndex) } var playingTrack: Track? { return track(at: playingIndex) } }
package co.lepelaka.controller; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import co.lepelaka.domain.AttachFileDTO; import co.lepelaka.service.BoardService; import lombok.Getter; import lombok.extern.log4j.Log4j; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.geometry.Positions; import net.coobird.thumbnailator.tasks.UnsupportedFormatException; @Controller @Log4j public class UploadController { @Getter private static final String PATH = "c:/upload"; @Autowired private BoardService boardService; @GetMapping("upload") public void upload() { log.info("upload"); } @PostMapping("upload") public void upload(MultipartFile[] files) throws IllegalStateException, IOException { log.info("upload post"); for(MultipartFile m : files) { log.info(m.getOriginalFilename()); log.info(m.getSize()); // 실제 스트림 전송 m.transferTo(new File("c:/upload", m.getOriginalFilename())); } } @GetMapping("uploadAjax") public void uploadAjax() { log.info("uploadAjax"); } @PostMapping(value="uploadAjax", produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody @PreAuthorize("isAuthenticated()") public List<AttachFileDTO> uploadAjax(MultipartFile[] files){ log.info("uploadAjax post"); List<AttachFileDTO> list = new ArrayList<>(); File uploadPath = new File(PATH, getFolder()); if(!uploadPath.exists()) { uploadPath.mkdirs(); } for(MultipartFile m : files) { log.info(m.getOriginalFilename()); // 실제 스트림 전송 String uuidStr = UUID.randomUUID().toString(); String tName = uuidStr + "_" + m.getOriginalFilename(); File f = new File(uploadPath, tName); boolean image = false; try { image = isImage(f); m.transferTo(f); if(image) { // 섬네일 처리 File f2 = new File(uploadPath, "s_" + tName); Thumbnails.of(f).crop(Positions.CENTER).size(200,200).toFile(f2); } } catch (UnsupportedFormatException e) { image = false; } catch (IOException e) { e.printStackTrace(); } AttachFileDTO dto = new AttachFileDTO(); dto.setUuid(uuidStr); dto.setPath(getFolder()); dto.setImage(image); dto.setName(m.getOriginalFilename()); list .add(dto); } return list; } @GetMapping("deleteFile") @ResponseBody @PreAuthorize("isAuthenticated()") public String deleteFile(AttachFileDTO dto) { return boardService.deleteFile(dto); } @GetMapping("display") @ResponseBody public ResponseEntity<byte[]> getFile(AttachFileDTO dto, Boolean thumb) { // fileName : path + uuid + name String s = PATH + "/" + dto.getPath() + "/" + (thumb != null && thumb ? "s_" : "") + dto.getUuid() + "_" + dto.getName(); File file = new File(s); ResponseEntity<byte[]> result = null; try { HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", Files.probeContentType(file.toPath())); result = new ResponseEntity<>(FileCopyUtils.copyToByteArray(file), headers, HttpStatus.OK); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } @GetMapping("download") @ResponseBody public ResponseEntity<byte[]> download(AttachFileDTO dto) { // fileName : path + uuid + name String s = PATH + "/" + dto.getPath() + "/" + dto.getUuid() + "_" + dto.getName(); File file = new File(s); ResponseEntity<byte[]> result = null; try { HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE); headers.add("Content-Disposition", "attachment; filename=" + new String(dto.getName().getBytes("utf-8"), "iso-8859-1")); result = new ResponseEntity<>(FileCopyUtils.copyToByteArray(file), headers, HttpStatus.OK); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } @GetMapping("list") @ResponseBody public List<String> test() { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); return list; } @GetMapping(value="dto", produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public AttachFileDTO getDto() { AttachFileDTO dto = new AttachFileDTO(); dto.setImage(true); dto.setName("파일명.png"); return dto; } private String getFolder() { return new SimpleDateFormat("yyyy/MM/dd").format(new Date()); } // file >> mime private boolean isImage(File file) throws IOException { List<String> excludes = Arrays.asList("ico", "webp"); int idx = file.toString().lastIndexOf("."); if(idx == -1) { return false; } String ext = file.toString().substring(idx+1); if(excludes.contains(ext)) { return false; } String mime = Files.probeContentType(file.toPath()); return mime != null && mime.startsWith("image"); } @PostMapping("/ckImage") @ResponseBody public Map<String, Object> uploadAjax(MultipartHttpServletRequest request) throws IllegalStateException, IOException { log.info(request); MultipartFile multipartFile = request.getFile("upload"); String origin = multipartFile.getOriginalFilename(); String uuidStr = UUID.randomUUID().toString(); String tName = uuidStr + "_" + origin; File f = new File(PATH, tName); AttachFileDTO dto = new AttachFileDTO(); dto.setUuid(uuidStr); dto.setPath(""); dto.setName(origin); multipartFile.transferTo(f); Map<String, Object> map = new HashMap<>(); map.put("uploaded", true); map.put("url", "/display"+dto.getUrl()); log.info(map); return map; } }
@extends('base.base') @section('start') <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel c нуля</title> <link href="https://unpkg.com/tailwindcss@2.0.3/dist/tailwind.min.css" rel="stylesheet"> </head> <body> <div class="h-screen bg-white flex flex-col space-y-10 justify-center items-center"> <div class="bg-white w-96 shadow-xl rounded p-5"> <h1 class="text-3xl font-medium">Регистрация</h1> <form action="{{route('register_process')}}" class="space-y-5 mt-5" method="POST"> @csrf <input name="name" class="w-full h-12 border border-gray-800 rounded px-3" placeholder="Name" /> @error('name') <p> {{$message}}</p> @enderror <input name="email" class="w-full h-12 border border-gray-800 rounded px-3" placeholder="Email" /> @error('email') <p> {{$message}}</p> @enderror <input name="password" class="w-full h-12 border border-gray-800 rounded px-3" placeholder="Пароль" /> @error('password') <p> {{$message}}</p> @enderror <input name="password_confirmation" class="w-full h-12 border border-gray-800 rounded px-3" placeholder="Подтверждение пароля" /> @error('password_confirmation') <p> {{$message}}</p> @enderror <div> <a href="{{route('login')}}" class="font-medium text-blue-900 hover:bg-blue-300 rounded-md p-2">Есть аккаунт?</a> </div> <button type="submit" class="text-center w-full bg-blue-900 rounded-md text-white py-3 font-medium">Зарегистрироваться</button> </form> </div> </div> </body> </html> @endsection
#ifndef DATABASE_H #define DATABASE_H // STL #include <map> // Local #include "AbstractTableFactory.h" #include "VirtualDatabase.h" #include "CustomSaveLoadStrategy.h" #include "MongoDbSaveLoadStrategy.h" namespace core { namespace save_load { class CustomFileStrategy; } class Database: public VirtualDatabase { public: explicit Database(std::wstring name, std::unique_ptr<const AbstractTableFactory> factory); // Database operations const std::wstring& name() const final; bool changeName(std::wstring name) final; void saveDatabase(const save_load::Information& saveInfo) final; const save_load::Information& lastSaveInfo() const final; void deleteDatabase() final; // Table operations VirtualTable& table(TableId id) final; const VirtualTable& table(TableId id) const final; size_t tableCount() const final; void forAllTable(const std::function<void(const VirtualTable&)>& worker) const final; core::TableId createTable(std::wstring name) final; void deleteTable(TableId id) final; void createCartesianProduct(TableId firstId, TableId secondId) final; // VirtualValidator bool validateTableName(const std::wstring& name) const final; bool validateColumnName(const std::wstring& name) const final; private: friend class save_load::CustomFileStrategy; std::wstring fName; const std::unique_ptr<const AbstractTableFactory> fTableFactory; std::map<TableId, std::unique_ptr<VirtualTable>> fTables; save_load::Information fLastSaveInfo; }; } // core #endif //DATABASE_H
const { uploadFile, getFileListPerBucket, deleteFile, getFileById, } = require("../services/fileService"); const response = require("responsify-requests"); const { messages, status } = require("../constants/messages"); const { convertLocalFileToUrl } = require("../helpers/fileHelpers"); const uploadFileController = async (req, res) => { try { let files = req.files; let fileData; let fileUrl = convertLocalFileToUrl(files[0]?.filename); if (files.length == 1 && files[0].fieldname == "file") { fileData = { fileName: files[0]?.filename, fileType: files[0]?.mimetype, fileSize: files[0]?.size, bucketId: req.body.bucketId, }; let fileUploadService = await uploadFile(fileData, req.userId); if (fileUploadService == 2) { return response( res, {}, 0, messages.BUCKETS_NOT_FOUND, status.BAD_REQUEST ); } else if (fileUploadService == 0) { return response( res, {}, 0, messages.FILE_UPLOAD_FAILURE, status.BAD_REQUEST ); } else { return response( res, { fileUrl: fileUrl }, 1, messages.FILE_UPLOAD_SUCCESS, status.SUCCESS ); } } else { return response(res, {}, 0, messages.ONLY_ONE_FILE, status.BAD_REQUEST); } } catch (error) { console.log("error in uploadFileCotroller ", error); return response(res, {}, 0, messages.INTERNAL_SERVER_ERROR); } }; const getFileListController = async (req, res) => { try { const getListService = await getFileListPerBucket(req.body, req.userId); if (getListService == 2) { return response( res, {}, 0, messages.BUCKETS_NOT_FOUND, status.BAD_REQUEST ); } else if (getListService == 1) { return response(res, [], 1, messages.FILE_FETCH_FAILURE, status.SUCCESS); } else { return response( res, getListService, 1, messages.FILE_FETCH_SUCCESS, status.SUCCESS ); } } catch (error) { console.log("error in get file list controller ", error); return response(res, {}, 0, messages.INTERNAL_SERVER_ERROR); } }; const deleteFileController = async (req, res) => { try { const deleteFileService = await deleteFile(req.body, req.userId); if (deleteFileService == 0) { return response( res, {}, 0, messages.FILE_DELETE_FAILURE, status.BAD_REQUEST ); } else if (deleteFileService == 2) { return response( res, {}, 0, messages.BUCKETS_NOT_FOUND, status.BAD_REQUEST ); } else if (deleteFileService == 3) { return response( res, {}, 0, messages.FILE_ALREADY_DELETED, status.BAD_REQUEST ); } else { return response(res, {}, 1, messages.FILE_DELETE_SUCCESS, status.SUCCESS); } } catch (error) { console.log("error in deleteFileController ", error); return response(res, {}, 0, messages.INTERNAL_SERVER_ERROR); } }; const getFileByIdController = async (req, res) => { try { const getFileService = await getFileById(req.body, req.userId); if (getFileService == 2) { return response( res, {}, 0, messages.BUCKETS_NOT_FOUND, status.BAD_REQUEST ); } else if (getFileService == 0) { return response(res, {}, 0, messages.FILES_NOT_FOUND, status.BAD_REQUEST); } else { return response( res, getFileService, 1, messages.FILE_FETCH_SUCCESS, status.SUCCESS ); } } catch (error) { console.log("error in getFileById ", error); return response(res, {}, 0, messages.INTERNAL_SERVER_ERROR); } }; module.exports = { uploadFileController, getFileListController, deleteFileController, getFileByIdController, };
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCandidateQuestionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('candidate_questions', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('candidate_id'); $table->foreign('candidate_id')->references('id')->on('candidates')->constrained(); $table->unsignedBigInteger('job_id'); $table->foreign('job_id')->references('id')->on('recruter_job')->constrained(); $table->unsignedBigInteger('question_id'); $table->foreign('question_id')->references('id')->on('job_questions')->constrained(); $table->text('answer'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('candidate_questions'); } }
import React, { lazy, Suspense } from 'react'; import { Route, Routes } from 'react-router-dom'; import Container from './Container'; import HomeView from '../views/HomeView'; import SharedLayout from './SharedLayout'; const Tweets = lazy(() => import('../views/Tweets')); export default function App() { return ( <Container> <Routes> <Route path="/" element={<SharedLayout />}> <Route index element={<HomeView />} /> <Route path="*" element={<HomeView />} /> <Route path="/tweets" element={ <Suspense fallback={<div>Loading...</div>}> <Tweets /> </Suspense> } /> </Route> </Routes> </Container> ); }
package data_structures.tuple.mutable; import com.google.common.primitives.Longs; import data_structures.tuple.iterators.TupleIteratorLong; import org.apache.commons.lang3.ArrayUtils; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class TupleLong implements Iterable<Long>, Comparable<TupleLong> { private long[] elems; public int length; public TupleLong(long... elements) { this.elems = elements; this.length = ArrayUtils.getLength(this.elems); } public void set(int index, long elem){ elems[index] = elem; } public long get(int index){ return elems[index]; } @Override public int compareTo(@NotNull TupleLong o) { return Arrays.compare(elems, o.elems); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TupleLong that = (TupleLong) o; return Arrays.equals(elems, that.elems); } @Override public int hashCode() { return Arrays.hashCode(elems); } @Override public String toString() { return Arrays.toString(elems); } public long[] toArray(){ return elems.clone(); } public List<Long> toList(){ return Longs.asList(elems); } @NotNull @Override public Iterator<Long> iterator() { return new TupleIteratorLong(this); } /// static methods public static TupleLong TupleLongEmpty = new TupleLong(); public static TupleLong valueOf(long... elements){ if (elements == null) return TupleLongEmpty; else return new TupleLong(elements); } }
import {createGlobalStyle} from "styled-components"; const globalStyles = createGlobalStyle` body { background: ${({theme}) => theme.body}; color: ${({theme}) => theme.text}; transition: background 0.2s ease-in, color 0.2s ease-in; } *, *::before, *::after { box-sizing: border-box; } body, h1, h2, h3, h4, p, figure, blockquote, dl, dd { margin: 0; } ul[role='list'], ol[role='list'], li, ul { margin: 0; padding: 0; list-style: none; } p { color: ${({theme}) => theme.textParagraph}; line-height: 30px; } html:focus-within { scroll-behavior: smooth; } body { min-height: 100vh; text-rendering: optimizeSpeed; line-height: 1.5; font-family: 'Inter', sans-serif; } a:not([class]) { text-decoration-skip-ink: auto; } a { text-decoration: none; color: ${({theme}) => theme.text}; transition: color 0.2s ease-in; &:hover { color: ${({theme}) => theme.textSecondary}; } } img, picture { max-width: 100%; display: block; } input, button, textarea, select { font: inherit; } @media (prefers-reduced-motion: reduce) { html:focus-within { scroll-behavior: auto; } *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; } } `; export default globalStyles;
import React, { useState } from 'react'; import { View, Text, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native'; import StarRating from 'react-native-star-rating-widget' import styles from "./styles"; import { getDatabase, ref, push, set} from "firebase/database"; import Toast from '../../components/Toast/Toast'; const WriteReviewScreen = (props) => { const { navigation, route } = props; const item = route.params?.item; const user = route.params?.user; const db = getDatabase(); const [rating, setRating] = useState(0); const [reviewText, setReviewText] = useState(''); const [isLoading, setIsLoading] = useState(false); const [toast, setToast] = useState(null); const showToast = (message, type, duration) => { setToast({ message, type, duration }); setTimeout(() => { setToast(null); }, 1000); }; const handleRatingChange = (newRating) => { setRating(newRating); }; const handleSaveReview = async () => { setIsLoading(true); const reviewsRef = ref(db, 'Reviews'); const newReviewItemRef = push(reviewsRef); const newReviewItemKey = newReviewItemRef.key; const reviewData = { id:newReviewItemKey, user_id: user.id, user_name:user.first_name, product_id: item.product_id, rating: rating, review_text: reviewText, review_date: new Date().toISOString(), }; try{ await set(newReviewItemRef, reviewData); setIsLoading(false); showToast('Review saved successfully','success'); navigation.navigate("Order Details"); } catch(error){ setIsLoading(false) showToast('Error saving review:', 'error'); } }; return ( <View style={styles.reviewcontainer}> <Text style={styles.ratingLabel}>Rate this product:</Text> <StarRating maxStars={5} rating={rating} enableHalfStar={false} onChange={(newRating) => handleRatingChange(newRating)} size={100} activeColor="#FFD700" /> <Text style={styles.reviewLabel}>Write a review:</Text> <TextInput style={styles.reviewInput} multiline numberOfLines={4} placeholder="Write your review here..." value={reviewText} onChangeText={(text) => setReviewText(text)} /> <TouchableOpacity style={styles.saveButton} onPress={handleSaveReview}> <Text style={styles.saveButtonText}>Save</Text> </TouchableOpacity> { isLoading? <ActivityIndicator />:null } {toast && ( <Toast message={toast.message} type={toast.type} duration={toast.duration} /> )} </View> ); }; export default WriteReviewScreen;
""" File of metrics computations """ import numpy as np from scipy.signal import butter, filtfilt, find_peaks, fftconvolve import sys def sum_torques(joints_data, sim_fraction=1.0): """Compute sum of torques""" nsteps = joints_data.shape[0] nsteps_considered = round(nsteps * sim_fraction) return np.sum(np.abs(joints_data[-nsteps_considered:, :])) def cost_of_transport(network, sim_fraction=0.3): """ Compute the cost of transport = torque / speed """ mass = 0.00005022324522733332 #[kg] (fspeed,lspeed) = compute_speed_cycle(network, sim_fraction=sim_fraction) torque = sum_torques(network.joints_active_torques, sim_fraction=sim_fraction) speed = np.sqrt(np.mean(fspeed)**2 + np.mean(lspeed)**2) # compute the Distance Traveled with the speed distance = speed * network.times[-1] return torque / (distance*mass) def compute_speed_cycle( network, sim_fraction: float = 1.0, ): """ Compute forward and lateral speeds using the xy joint positions sampled across cycles using the frequency computed using the treshold crossing method """ n_steps = network.links_positions.shape[0] n_steps_considered = round(n_steps * sim_fraction) links_pos_xy = network.links_positions[-n_steps_considered:, :, :2] # compute freq based on the state times = network.times[-n_steps_considered:] state = network.state[-n_steps_considered:] muscle_diff = state[:, network.muscle_l]-state[:, network.muscle_r] frequency, _ = compute_frequency_treshold_crossings( times, muscle_diff.T, theta=0.0) if frequency > 0: sampling_rate = int(1/(frequency*network.pars.timestep)) sampling_idxs = np.arange(0, n_steps_considered, sampling_rate) sampled_pos = links_pos_xy[sampling_idxs, 0, :] # head pos vel = frequency*(sampled_pos[1:]-sampled_pos[:-1]) # head velocity nsamples = len(sampling_idxs) v_fwd = np.zeros(nsamples-1) v_lat = np.zeros(nsamples-1) for idx in range(nsamples-2): # p_head_fwd0 = links_pos_xy[sampling_idxs[idx], 0, :]-links_pos_xy[sampling_idxs[idx], 1, :] move_direction0 = p_head_fwd0/np.linalg.norm(p_head_fwd0) angles = [] theta = np.arctan2(move_direction0[1], move_direction0[0]) for idx2 in range(sampling_idxs[idx]+1, sampling_idxs[idx+1]): # to avoid the bias from the arctan switching sign at theta=pi # we sum across small dthetas in each iteration p_head_fwd = links_pos_xy[idx2, 0, :]-links_pos_xy[idx2, 1, :] move_direction = p_head_fwd/np.linalg.norm(p_head_fwd) cos_dtheta = np.dot(move_direction0, move_direction) sin_dtheta = np.cross(move_direction0, move_direction) dtheta = np.arctan2(sin_dtheta, cos_dtheta) theta = theta + dtheta angles.append(theta) move_direction0 = move_direction mean_angle = np.mean(angles) ht_direction = np.array([np.cos(mean_angle), np.sin(mean_angle)]) ht_direction = ht_direction/np.linalg.norm(ht_direction) vec_left = np.cross( [0, 0, 1], [ht_direction[0], ht_direction[1], 0] )[:2] v_fwd[idx+1] = np.dot(vel[idx+1], ht_direction) v_lat[idx+1] = np.dot(vel[idx+1], vec_left) return v_fwd[1:], v_lat[1:] else: return 0.0, 0.0 def compute_speed_PCA(links_positions, links_vel, sim_fraction=1.0): ''' Computes the axial and lateral speed based on the PCA of the links positions ''' n_steps = links_positions.shape[0] n_steps_considered = round(n_steps * sim_fraction) links_pos_xy = links_positions[-n_steps_considered:, :, :2] joints_vel_xy = links_vel[-n_steps_considered:, :, :2] time_idx = links_pos_xy.shape[0] speed_forward = [] speed_lateral = [] for idx in range(time_idx): x = links_pos_xy[idx, :, 0] y = links_pos_xy[idx, :, 1] pheadtail = links_pos_xy[idx][0]-links_pos_xy[idx][-1] # head - tail vcom_xy = np.mean(joints_vel_xy[idx], axis=0) covmat = np.cov([x, y]) eig_values, eig_vecs = np.linalg.eig(covmat) largest_index = np.argmax(eig_values) largest_eig_vec = eig_vecs[:, largest_index] ht_direction = np.sign(np.dot(pheadtail, largest_eig_vec)) largest_eig_vec = ht_direction * largest_eig_vec v_com_forward_proj = np.dot(vcom_xy, largest_eig_vec) left_pointing_vec = np.cross( [0, 0, 1], [largest_eig_vec[0], largest_eig_vec[1], 0] )[:2] v_com_lateral_proj = np.dot(vcom_xy, left_pointing_vec) speed_forward.append(v_com_forward_proj) speed_lateral.append(v_com_lateral_proj) return np.mean(speed_forward), np.mean(speed_lateral) # ------= SIGNAL PROCESSING TOOLS ------= def filter_signals( signals: np.ndarray, signal_dt: float, fcut_hp: float = None, fcut_lp: float = None, filt_order: int = 5, ): ''' Butterwort, zero-phase filtering ''' # Nyquist frequency fnyq = 0.5 / signal_dt # Filters if fcut_hp is not None: num, den = butter(filt_order, fcut_hp/fnyq, btype='highpass') signals = filtfilt(num, den, signals) if fcut_lp is not None: num, den = butter(filt_order, fcut_lp/fnyq, btype='lowpass') signals = filtfilt(num, den, signals) return signals def remove_signals_offset(signals: np.ndarray): ''' Removed offset from the signals ''' return (signals.T - np.mean(signals, axis=1)).T def compute_frequency_treshold_crossings( times: np.ndarray, signals: np.ndarray, theta=0.1 ): """ Compute the frequency of a signal oscillating around a predefined treshold """ onset_idxs = (signals[:, 1:] >= theta) * (signals[:, :-1] < theta) last_spikes = np.zeros(onset_idxs.shape[0]) prec_spikes = np.zeros(onset_idxs.shape[0]) for idx, onsets in enumerate(onset_idxs): onsets = onset_idxs[idx] all_spikes = times[:-1][onsets] # check if 1) all neurons have fired and 2) the last spike happened # after tstop/2 (or no oscillations at st) if len(all_spikes) > 1 and all_spikes[-1] > times[-1]/2: last_spikes[idx] = all_spikes[-1] prec_spikes[idx] = all_spikes[-2] periods = last_spikes - prec_spikes if all(periods): # make sure that all neurons are oscillating period = np.mean(periods) phase_diffs = np.zeros(onset_idxs.shape[0]-1) for i in range(len(last_spikes)-1): dphi = last_spikes[i+1]-last_spikes[i] if dphi < -period/2: phase_diffs[i] = period+dphi elif dphi > period/2: phase_diffs[i] = dphi-period else: phase_diffs[i] = dphi frequency = 1/period else: frequency = 0.0 phase_diffs = np.zeros(onset_idxs.shape[0]) return frequency, phase_diffs def compute_ptcc( times: np.ndarray, signals: np.ndarray, discard_time: float = 0, filtering: bool = True, ) -> np.ndarray: ''' Computes the peak-to-through correlatio coefficient based on the difference between the the maximum and the minimum of the auto-correlogram of smoothened pools' oscillations ''' sig_dt = times[1] - times[0] smooth_signals = signals.copy() if filtering: smooth_signals = filter_signals(smooth_signals, sig_dt, fcut_lp=10) # Remove offset and initial transient smooth_signals = remove_signals_offset(smooth_signals) istart = round(float(discard_time)/float(sig_dt)) chopped_signals = smooth_signals[:, istart:] ptccs = [] for ind, sig in enumerate(chopped_signals): # Auto-correlogram power = np.correlate(sig, sig) autocorr = fftconvolve(sig, sig[::-1], 'full') if power > 0: autocorr = autocorr / power else: autocorr = np.zeros(autocorr.shape) siglen = len(autocorr)//2 # Computed in [-n//2,+n//2-1] sig_maxs = find_peaks(+autocorr[siglen:]) sig_mins = find_peaks(-autocorr[siglen:]) if sig_maxs[0].size == 0 or sig_mins[0].size == 0: ptccs.append(0) else: first_max_ind = sig_maxs[0][0] + siglen first_min_ind = sig_mins[0][0] + siglen ptccs.append(autocorr[first_max_ind] - autocorr[first_min_ind]) return np.array(ptccs) def compute_controller( network ): """ Compute all the metrics of the firing rate controller """ metrics = {} n_iterations = network.pars.n_iterations sim_fraction = 0.3 nsteps_considered = round(n_iterations * sim_fraction) # consider sim_fraction number of steps, for the difference between left # and right muscle cells times = network.times[-nsteps_considered:] signals = network.state[-nsteps_considered:, network.muscle_r]-network.state[-nsteps_considered:, network.muscle_l] frequency, iplss = compute_frequency_treshold_crossings( times, signals.transpose(), theta=0.001 ) # adding one element to consider the full body length iplss = np.append(iplss, iplss[-1]) metrics["frequency"] = frequency metrics["ipls"] = np.sum(iplss) metrics["wavefrequency"] = metrics["ipls"]*metrics["frequency"] ptcc = compute_ptcc( times, signals.transpose(), ) metrics["ptcc"] = np.min(ptcc) # ------ amplitude of the limbs at steady-state ------ metrics["amp"] = np.max(signals)-np.min(signals) return metrics def compute_mechanical( network ): """ compute all mechanical metrics """ metrics = {} sim_fraction = 0.3 # ------ COMPUTE FORWARD AND LATERAL SPEEDS ------ links_positions = network.links_positions link_velocities = network.links_velocities joints_active_torques = network.joints_active_torques # method 1 (fspeed, lspeed) = compute_speed_PCA( links_positions, link_velocities, sim_fraction=sim_fraction ) metrics["fspeed_PCA"] = fspeed metrics["lspeed_PCA"] = lspeed # method 2 (fspeed, lspeed) = compute_speed_cycle( network, sim_fraction=sim_fraction ) metrics["fspeed_cycle"] = np.mean(fspeed) metrics["lspeed_cycle"] = np.mean(lspeed) # ------ Mechanical metrics ------ torque = sum_torques(joints_active_torques, sim_fraction=sim_fraction) metrics["torque"] = torque if network.mujoco_error: metrics = dict.fromkeys(metrics, np.nan) # ------ Cost of transport ------ cost = cost_of_transport(network, sim_fraction=sim_fraction) metrics["cost_of_transport"] = cost return metrics def compute_all(network): """ compute and joint all controller and mechanical metrics """ if sys.version_info[1] <= 8: # for python3.8 or lower metrics = { **compute_controller(network), **compute_mechanical(network)} else: metrics = compute_controller(network) | compute_mechanical(network) return metrics
"use client" import {useQuery, useQueryClient} from "@tanstack/react-query"; import {fetchProjects} from "@/services/project-service"; import {DataTable} from "@/components/ui/data-table/data-table"; import {projectColumns} from "@/types/project-types"; import {ApiQueryParams, defaultApiQueryParams} from "@/types/request-types"; import {Button} from "@/components/ui/button"; import {ArrowRight, Copy, Plus, Share, Trash2} from "lucide-react"; import React, {useState} from "react"; import {ProjectStatus} from "@prisma/client"; import Link from "next/link"; interface ProjectsContentProps { searchTerm?: string; } export default function ExplorerProjectsContent({searchTerm}: ProjectsContentProps) { const [queryParams, setQueryParams] = useState({ ...defaultApiQueryParams, filter: searchTerm, fieldFilters: [{name: "status", value: ProjectStatus.validated}] }) const {status, data, error} = useQuery({ queryKey: ['projects', queryParams], queryFn: () => fetchProjects(queryParams), }) if (status === 'pending') { return <span>Loading...</span> } if (status === 'error') { return <span>Error: {error.message}</span> } const hasData = (data?.data?.length ?? 0) > 0 function getColumns() { let filter = projectColumns.filter((column) => column.id !== "actions"); filter.push( { id: "actions", cell: ({row}) => { return ( <div className={"flex"}> <Link href={"/explorer/" + row.original.id + "/data-scope/"}> <Button variant="ghost" size={"md"} className="h-8 w-8 m-2"> <ArrowRight className="h-4 w-4"/> </Button> </Link> </div> ); }, }, ); return filter; } return ( <div className="container mx-auto py-10"> <div className="rounded-md border bg-white"> <div className={"text-xl font-bold p-4"}>Validated Projects</div> {(hasData) ? <DataTable title={"Projects"} columns={getColumns()} data={data.data!}/> : <div className="flex flex-col items-center justify-center"> <div className="text-gray-500">You don&apos;t have any Validated projects right now</div> <div className={"py-5 pr-5"}> <Button variant={"primary"} className={"w-44"}><Plus className={"pr-2"}/>Create now</Button> </div> </div>} </div> </div> ) }
use anyhow::{anyhow, Context, Result}; use nand2tetris::jack::tokenizer::TokenIterator; use nand2tetris::jack::xml_analyzer::XMLAnalyzer; use std::fs::{self, File}; use std::io::{BufReader, BufWriter, Write}; use std::path::{Path, PathBuf}; const JACK_EXT: &str = ".jack"; const XML_EXT: &str = ".xml"; fn main() -> Result<()> { let mut args = std::env::args(); args.next() .with_context(|| "First arg should be the program name...")?; let input_path = args .next() .with_context(|| "This program expects an argument but non was given")?; if args.next().is_some() { return Result::Err(anyhow!("This program expects at most one argument")); } let jack_files = if fs::metadata(&input_path) .with_context(|| format!("Unable to read {}", input_path))? .is_dir() { fs::read_dir(&input_path) .with_context(|| format!("Unable to read {}", input_path))? .map(|r| { r.with_context(|| format!("Unable to read an entry in {}", input_path)) .map(|e| { let jack_name = e .path() .file_name() .map::<&Path, _>(|p| p.as_ref()) .and_then(|p| p.to_str()) .map_or(false, |p| p.ends_with(JACK_EXT)); if jack_name && e.path().is_file() { Some(e.path().to_path_buf()) } else { None } }) }) .collect::<Result<Vec<_>>>()? .into_iter() .flat_map(|x| x) .collect::<Vec<PathBuf>>() } else { if !input_path.ends_with(JACK_EXT) { return Result::Err(anyhow!("Input file must be suffixed by {}", JACK_EXT)); } vec![PathBuf::from(&input_path)] }; for jack_file in jack_files { let jack = File::open(&jack_file) .map(BufReader::new) .with_context(|| format!("Unable to open file {}", jack_file.to_string_lossy()))?; let token_iterator = TokenIterator::from(jack); let mut analyzer = XMLAnalyzer::from(token_iterator); let result = analyzer .compile() .with_context(|| format!("Unable to analyze {}", jack_file.to_string_lossy()))?; let output_file = jack_file.with_extension(&XML_EXT[1..]); let mut xml = File::create(&output_file) .map(BufWriter::new) .with_context(|| format!("Unable to open file {}", output_file.to_string_lossy()))?; xml.write(result.as_bytes()).with_context(|| { format!("Failed to write to file {}", output_file.to_string_lossy()) })?; } Result::Ok(()) }
<%@page import="com.bus.booking.dto.Bus"%> <%@page import="java.util.List"%> <%@page import="com.bus.booking.dao.BusDataBase"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>BUS BOOKING</title> </head> <body> <% String busName = request.getParameter("busname"); BusDataBase base = new BusDataBase(); List<Bus> buses = base.searchBus(busName); if (buses != null) { request.getRequestDispatcher("/dashboard").include(request, response); %> <div class="container"> <table class="table table-bordered"> <thead> <tr> <th>BUS NAME</th> <th>FROM</th> <th>--</th> <th>TO</th> <th>SEATS</th> <th>TICKET</th> <th colspan="2" align="center">ACTION</th> </tr> </thead> <tbody> <% for (Bus bb : buses) { %> <tr> <td><%=bb.getName()%></td> <td><%=bb.getFrom()%></td> <td>To</td> <td><%=bb.getTo()%></td> <td><%=bb.getSeats()%></td> <td><%=bb.getTicketRate()%></td> <td><button class="btn btn-primary"> <a href="./edit?id=<%=bb.getBusId()%>">EDIT</a> </button></td> <td><button class="btn btn-danger"> <a href="./delete?id=<%=bb.getBusId()%>">DELETE</a> </button></td> </tr> <% } } else { request.getRequestDispatcher("/admin").forward(request, response); } %> </tbody> </table> <button type="submit" class="btn btn-primary mb-2"> <a href="./route">BACK</a> </button> </div> <style> a:visited { color: white; } a:active { color: white; } a { color: white; text-decoration: none; } </style> </body> </html>
import React, { useState, useEffect, useRef } from "react"; import { Link } from "react-router-dom"; import styles from "./Navbar.module.css"; import RegisterModal from "../RegisterModal/RegisterModal"; import LoginModal from "../LoginModal/LoginModal"; import StoryModal from "../StoryModal/StoryModal"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faBookmark } from "@fortawesome/free-solid-svg-icons"; export default function Navbar() { // const navigate = useNavigate(); const [isRegisterModalOpen, setIsRegisterModalOpen] = useState(false); const [isLoginModalOpen, setIsLoginModalOpen] = useState(false); const [isStoryModalOpen, setIsStoryModalOpen] = useState(false); const [username, setUsername] = useState(""); const [isLoggedIn, setIsLoggedIn] = useState(false); // const [isBookmarksClicked, setIsBookmarksClicked] = useState(false); const dropdownRef = useRef(); useEffect(() => { const loggedIn = localStorage.getItem("isLoggedIn"); setIsLoggedIn(loggedIn === "true"); const storedUsername = localStorage.getItem("username"); setUsername(storedUsername || ""); }, [username, isLoggedIn]); const openStoryModal = () => { setIsStoryModalOpen(true); }; const closeStoryModal = () => { setIsStoryModalOpen(false); }; const openRegisterModal = () => { setIsRegisterModalOpen(true); }; const closeRegisterModal = () => { setIsRegisterModalOpen(false); }; const openLoginModal = () => { setIsLoginModalOpen(true); }; const closeLoginModal = () => { setIsLoginModalOpen(false); }; const handleSuccessfulRegistration = () => { setIsLoggedIn(true); localStorage.setItem("isLoggedIn", true); // setUsername(username); // localStorage.setItem("username", username); closeRegisterModal(); }; const handleSuccessfulLogin = () => { setIsLoggedIn(true); localStorage.setItem("isLoggedIn", true); // setUsername(username); // localStorage.setItem("username", username); closeLoginModal(); }; const handleLogout = () => { setIsLoggedIn(false); localStorage.removeItem("isLoggedIn"); // localStorage.removeItem("token"); setUsername(""); localStorage.removeItem("username"); }; const dropDownHandler = () => { if (dropdownRef.current.style.display === "none") { dropdownRef.current.style.display = "block"; } else { dropdownRef.current.style.display = "none"; } }; // const handleBookmarkClick = () => { // navigate("/userbookmarks"); // Step 3: Navigate to the desired route // document.body.requestFullscreen(); // Step 4: Enter full-screen mode // }; // const handleBookmarkClick = () => { // setIsBookmarksClicked(true); // Set the state to true when bookmarks are clicked // navigate("/userbookmarks"); // }; return ( <div> {/* {!isBookmarksClicked && ( */} <nav className={styles.navbar}> <div className={styles.logo}>SwipTory</div> <div className={styles.navBtns}> {isLoggedIn ? ( <> <div className={styles.storyBtns}> <Link to="/bookmarks" className={styles.bookmarkBtn} // onClick={() => { // navigate("/userbookmarks"); // }} // onClick={handleBookmarkClick} > <FontAwesomeIcon icon={faBookmark} /> &nbsp; Bookmarks </Link> <button className={styles.addstoryBtn} onClick={openStoryModal}> Add Story </button> </div> <img src="https://cdn-icons-png.flaticon.com/512/3135/3135715.png" alt="" className={styles.profileIcon} /> <div className={styles.navItem}> <div className={styles.hamburgerMenu} onClick={dropDownHandler}> <div className={styles.bar}></div> <div className={styles.bar}></div> <div className={styles.bar}></div> </div> <div style={{ display: "none" }} className={styles.dropdownContent} ref={dropdownRef} > <p style={{ fontWeight: "600", overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis", }} > {username} </p> <Link to="/" className={styles.logoutBtn} onClick={handleLogout}> Logout </Link> </div> </div> </> ) : ( <> <button className={styles.registerBtn} onClick={openRegisterModal} > Register Now </button> <button className={styles.loginBtn} onClick={openLoginModal}> Sign In </button> </> )} </div> </nav> {/* )} */} <RegisterModal isOpen={isRegisterModalOpen} onClose={closeRegisterModal} onSuccess={handleSuccessfulRegistration} /> <LoginModal isOpen={isLoginModalOpen} onClose={closeLoginModal} onSuccess={handleSuccessfulLogin} /> <StoryModal isOpen={isStoryModalOpen} onClose={closeStoryModal} /> <br /> </div> ); }
import { injectable, inject } from 'tsyringe'; import { isBefore } from 'date-fns'; import AppError from '@shared/errors/AppError'; import IAppointmentsRepository from '@modules/appointments/repositories/IAppointmentsRepository'; import IUsersRepository from '@modules/users/repositories/IUsersRepository'; import ICreateAppointmentDTO from '../dtos/ICreateAppointmentDTO'; import Appointment from '../infra/typeorm/entities/Appointment'; @injectable() class CreateAppointmentService { constructor( @inject('AppointmentsRepository') private appointmentsRepository: IAppointmentsRepository, @inject('UsersRepository') private usersRepository: IUsersRepository, ) {} public async execute({ teacher_id, laboratory_number, year, month, day, time, subject, classroom, status, observations, }: ICreateAppointmentDTO): Promise<Appointment> { const checkTeacherExists = await this.usersRepository.findById(teacher_id); if (!checkTeacherExists) { throw new AppError('Informed teacher does not exists.'); } else if (!checkTeacherExists.subjects.split(', ').includes(subject)) { throw new AppError('Informed subject is not from the teacher.'); } const appointmentDate = new Date(year, month - 1, day, 23, 59, 59); if (isBefore(appointmentDate, Date.now())) { throw new AppError('You can not create an appointment on a past date.'); } const existingAppointments = await this.appointmentsRepository.findAllAppointmentsByDate( year, month, day, ); existingAppointments.map(existingAppointment => { time.split(', ').map(specificTime => { if ( existingAppointment.time.split(', ').includes(specificTime) && existingAppointment.laboratory_number === laboratory_number ) { throw new AppError('This appointment is already booked.'); } }); }); const appointment = await this.appointmentsRepository.create({ teacher_id, laboratory_number, year, month, day, time, subject, classroom, status, observations, }); return appointment; } } export default CreateAppointmentService;
import React, { useState } from 'react'; import './Cadastro.css'; import "react-datepicker/dist/react-datepicker.css"; import AlertComponent from '../template/Alert'; import { Form } from 'react-bootstrap'; import { Row, Col } from 'react-bootstrap'; import Modal from 'react-bootstrap/Modal'; import { BsFillCloudDownloadFill } from "react-icons/bs"; import { saveAs } from 'file-saver'; import * as XLSX from 'xlsx'; import db from '../../database'; import { Button } from 'react-bootstrap'; import { FcCheckmark } from "react-icons/fc"; import { useEffect } from 'react'; function DataFile({ fetchDespesas, openModal2, closeModal, idEdit, atualizarTabela }) { const [cadastroSucesso, setCadastroSucesso] = useState(null); const [cadastroErro, setCadastroErro] = useState(false); const [dados, setDados] = useState(null); const [importedDataInfo, setImportedDataInfo] = useState({ importDate: null, backupDate: null, rowCount: 0, dateRange: null }); useEffect(() => { return () => { setCadastroSucesso(null); }; }, []); const handleSubmit = () => { atualizarTabela(); }; const fecharModal = () => { closeModal(); } // const exportData = async () => { // try { // const dataAtual = new Date().toLocaleString('pt-br') // const tableData = await db.expenses.toArray(); // Recupere os dados da tabela 'expenses' // const worksheet = XLSX.utils.json_to_sheet(tableData); // Converta os dados para o formato do XLSX // const workbook = XLSX.utils.book_new(); // XLSX.utils.book_append_sheet(workbook, worksheet, 'Expenses'); // Adicione a planilha ao livro de trabalho // const fileContent = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' }); // Converta o livro de trabalho para um array de bytes // const fileBlob = new Blob([fileContent], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); // Crie um Blob com o conteúdo do arquivo // saveAs(fileBlob, 'expenses' + '-' + dataAtual + '.xlsx'); // Faça o download do arquivo com o nome 'expenses.xlsx' // } catch (error) { // console.error('Erro ao exportar os dados:', error); // } // }; const exportData = async () => { try { const dataAtual = new Date().toLocaleString('pt-br'); const tableData = await db.expenses.toArray(); const worksheet = XLSX.utils.json_to_sheet(tableData); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, 'Expenses'); const fileContent = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' }); const fileBlob = new Blob([fileContent], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); saveBackupToDevice(fileBlob, 'expenses' + '-' + dataAtual + '.xlsx'); } catch (error) { console.error('Erro ao exportar os dados:', error); } }; const saveBackupToDevice = (fileBlob, fileName) => { if (window.cordova && window.cordova.file && window.cordova.file.externalDataDirectory) { const fileDir = window.cordova.file.externalDataDirectory; const filePath = fileDir + fileName; window.resolveLocalFileSystemURL(fileDir, function (dirEntry) { dirEntry.getFile(fileName, { create: true }, function (fileEntry) { fileEntry.createWriter(function (fileWriter) { fileWriter.onwriteend = function() { // Arquivo salvo com sucesso // Adicione aqui o código para notificar o usuário ou realizar outras ações setCadastroSucesso(true); setTimeout(handleSubmit, 1500); }; fileWriter.onerror = function(e) { console.error('Erro ao salvar o arquivo:', e); handleError(e); }; // Converta o Blob para ArrayBuffer const fileReader = new FileReader(); fileReader.onloadend = function() { const arrayBuffer = this.result; // Escreva o ArrayBuffer no arquivo fileWriter.write(arrayBuffer); }; fileReader.onerror = function(e) { console.error('Erro ao ler o arquivo:', e); handleError(e); }; fileReader.readAsArrayBuffer(fileBlob); }, handleError); }, handleError); }, handleError); } else { // Salvar o arquivo usando a biblioteca file-saver (apenas para a web) saveAs(fileBlob, fileName); setCadastroSucesso(true); setTimeout(handleSubmit, 1500); } }; const handleError = (error) => { console.error('Erro ao salvar o arquivo:', error); }; function getDatos(event) { setDados(event.target.files[0]); } const importData = async (event) => { try { const file = dados; const reader = new FileReader(); reader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array' }); const worksheet = workbook.Sheets[workbook.SheetNames[0]]; const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, range: 1 }); // const [, ...rows] = jsonData; // Processar os dados importados e inserir na tabela 'expenses' jsonData.forEach(async (row) => { const [descricao, tipo, typePayment, valor, date] = row; await db.expenses.add({ descricao, tipo, typePayment, valor, date }); }); setCadastroSucesso(true); setTimeout(() => { handleSubmit(); }, 1500); const importDate = new Date().toLocaleString('pt-br'); let backupDate = file.name.split('-')[1].replace('.xlsx', ''); backupDate = backupDate.replace(/_/g, "/").replace(/,/g, " "); const rowCount = jsonData.length; const dateRange = [jsonData[0][4], jsonData[jsonData.length - 1][4]]; // Assume que a data está na coluna 4 // Atualizar as informações do estado setImportedDataInfo({ importDate, backupDate, rowCount, dateRange }); // setCadastroSucesso(true); }; reader.readAsArrayBuffer(file); } catch (error) { setCadastroSucesso(false); console.error('Erro ao importar os dados:', error); } }; return ( <> <Modal show={openModal2} onHide={closeModal}> <Modal.Header closeButton> <Modal.Title>Importar/Exportar Dados</Modal.Title> </Modal.Header> <Modal.Body> <Form> {cadastroSucesso && ( <AlertComponent variant="success" content="Dados importados com sucesso!" show={cadastroSucesso} /> )} {cadastroErro && ( <AlertComponent variant="success" content="Aconteceu um erro" show={cadastroErro} /> )} <div> <Row className="mb-4"> <Col sm={3}> <Form.Label>Backup:</Form.Label> </Col> <Col sm={8}> <Button variant="primary" onClick={exportData} style={{ background: '', border: 'none', boxShadow: 'none' }}> {/* <FcCheckmark size={35} /> */} <BsFillCloudDownloadFill ></BsFillCloudDownloadFill> </Button> </Col> </Row> <Row > <Col sm={2} className="mb-4"> <Form.Label>Importar: </Form.Label> </Col> <Col sm={8} className="mb-4"> <Form.Control type="file" accept=".xlsx" onChange={getDatos} /> </Col> <Col sm={2} className="mb-4"> <Button variant="primary" onClick={importData} style={{ background: 'transparent', border: 'none', boxShadow: 'none' }}> <FcCheckmark size={35} /> </Button> </Col> </Row> <div> </div> </div> </Form> <div> {importedDataInfo.importDate && ( <p>Data da última importação: {importedDataInfo.importDate}</p> )} {importedDataInfo.backupDate && ( <p>Data do backup importado: {importedDataInfo.backupDate}</p> )} {importedDataInfo.rowCount > 0 && ( <p>Registros importados: {importedDataInfo.rowCount}</p> )} {importedDataInfo.dateRange && ( <p>Intervalo de datas: {importedDataInfo.dateRange[0]} - {importedDataInfo.dateRange[1]}</p> )} </div> <Col sm={2} className="mb-4"> <Button variant="primary" onClick={fecharModal}> OK</Button> </Col> </Modal.Body> </Modal> </> ); } export default DataFile;
import torch import torch.nn.functional as F import torchvision.transforms.functional as TF import os from runpy import run_path from skimage import img_as_ubyte from natsort import natsorted from glob import glob import cv2 from tqdm import tqdm import argparse from pdb import set_trace as stx import numpy as np parser = argparse.ArgumentParser(description='Test on your own images') parser.add_argument('--input_dir', default='./test/input/', type=str, help='Directory of input images or path of single image') parser.add_argument('--result_dir', default='./test/output/', type=str, help='Directory for restored results') parser.add_argument('--task', required=True, type=str, help='Task to run', choices=['Deraining']) parser.add_argument('--tile', type=int, default=None, help='Tile size (e.g 720). None means testing on the original resolution image') parser.add_argument('--tile_overlap', type=int, default=32, help='Overlapping of different tiles') args = parser.parse_args() def load_img(filepath): return cv2.cvtColor(cv2.imread(filepath), cv2.COLOR_BGR2RGB) def save_img(filepath, img): cv2.imwrite(filepath,cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) def load_gray_img(filepath): return np.expand_dims(cv2.imread(filepath, cv2.IMREAD_GRAYSCALE), axis=2) def save_gray_img(filepath, img): cv2.imwrite(filepath, img) def get_weights_and_parameters(task, parameters): if task == 'Deraining': weights = os.path.join('pretrained_models', 'deraining.pth') return weights, parameters task = args.task inp_dir = args.input_dir out_dir = os.path.join(args.result_dir, task) os.makedirs(out_dir, exist_ok=True) extensions = ['jpg', 'JPG', 'png', 'PNG', 'jpeg', 'JPEG', 'bmp', 'BMP'] if any([inp_dir.endswith(ext) for ext in extensions]): files = [inp_dir] else: files = [] for ext in extensions: files.extend(glob(os.path.join(inp_dir, '*.'+ext))) files = natsorted(files) if len(files) == 0: raise Exception(f'No files found at {inp_dir}') # Get model weights and parameters parameters = {'inp_channels':3, 'out_channels':3, 'dim':48, 'num_blocks':[4,6,6,8], 'heads':[1,2,4,8], 'ffn_expansion_factor':2.66, 'bias':False, 'LayerNorm_type':'WithBias'} weights, parameters = get_weights_and_parameters(task, parameters) load_arch = run_path(os.path.join('basicsr', 'models', 'archs', 'DRSformer_arch.py')) model = load_arch['DRSformer'](**parameters) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) checkpoint = torch.load(weights) model.load_state_dict(checkpoint['params']) model.eval() img_multiple_of = 8 print(f"\n ==> Running {task} with weights {weights}\n ") with torch.no_grad(): for file_ in tqdm(files): if torch.cuda.is_available(): torch.cuda.ipc_collect() torch.cuda.empty_cache() if task == 'Deraining': img = load_img(file_) input_ = torch.from_numpy(img).float().div(255.).permute(2,0,1).unsqueeze(0).to(device) # Pad the input if not_multiple_of 8 height,width = input_.shape[2], input_.shape[3] H,W = ((height+img_multiple_of)//img_multiple_of)*img_multiple_of, ((width+img_multiple_of)//img_multiple_of)*img_multiple_of padh = H-height if height%img_multiple_of!=0 else 0 padw = W-width if width%img_multiple_of!=0 else 0 input_ = F.pad(input_, (0,padw,0,padh), 'reflect') if args.tile is None: ## Testing on the original resolution image restored = model(input_) else: # test the image tile by tile b, c, h, w = input_.shape tile = min(args.tile, h, w) assert tile % 8 == 0, "tile size should be multiple of 8" tile_overlap = args.tile_overlap stride = tile - tile_overlap h_idx_list = list(range(0, h-tile, stride)) + [h-tile] w_idx_list = list(range(0, w-tile, stride)) + [w-tile] E = torch.zeros(b, c, h, w).type_as(input_) W = torch.zeros_like(E) for h_idx in h_idx_list: for w_idx in w_idx_list: in_patch = input_[..., h_idx:h_idx+tile, w_idx:w_idx+tile] out_patch = model(in_patch) out_patch_mask = torch.ones_like(out_patch) E[..., h_idx:(h_idx+tile), w_idx:(w_idx+tile)].add_(out_patch) W[..., h_idx:(h_idx+tile), w_idx:(w_idx+tile)].add_(out_patch_mask) restored = E.div_(W) restored = torch.clamp(restored, 0, 1) # Unpad the output restored = restored[:,:,:height,:width] restored = restored.permute(0, 2, 3, 1).cpu().detach().numpy() restored = img_as_ubyte(restored[0]) f = os.path.splitext(os.path.split(file_)[-1])[0] # stx() if task == 'Deraining': save_img((os.path.join(out_dir, f+'.png')), restored) print(f"\nRestored images are saved at {out_dir}")
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Categoria } from '../core/model'; import { environment } from 'src/environments/environment'; export class CategoriaFiltro { nome: string; pagina = 0; itensPorPagina = 5; } @Injectable({ providedIn: 'root' }) export class CategoriaService { categoriasUrl: string; constructor(private http: HttpClient) { this.categoriasUrl = `${environment.apiUrl}/categorias` } pesquisar(filtro: CategoriaFiltro): Promise<any> { let params = new HttpParams(); params = params.set('page', filtro.pagina.toString()); params = params.set('size', filtro.itensPorPagina.toString()); if (filtro.nome) { params = params.set('nome', filtro.nome); } return this.http.get(`${this.categoriasUrl}`, { params }) .toPromise() .then(response => { const categorias = response['content'] const resultado = { categorias, total: response['totalElements'] } return resultado; }); } listarTodas(){ return this.http.get<any>(`${this.categoriasUrl}/listar`) .toPromise() .then(response => response); } salvar(categoria: Categoria): Promise<Categoria> { return this.http.post<Categoria>(this.categoriasUrl, categoria) .toPromise(); } atualizar(categoria: Categoria): Promise<any> { return this.http.put<Categoria>(`${this.categoriasUrl}/${categoria.codigo}`, categoria) .toPromise() .then(response => { const categoriaAlterada = response; return categoriaAlterada; }); } buscaPorCodigo(codigo: number): Promise<Categoria> { return this.http.get<Categoria>(`${this.categoriasUrl}/${codigo}`) .toPromise() .then(response => { const categoria = response return categoria; }); } mudarStatus(codigo: number, ativo: boolean): Promise<void> { const headers = new HttpHeaders().append('Content-Type', 'application/json'); return this.http.put(`${this.categoriasUrl}/${codigo}/ativo`, ativo, { headers }) .toPromise() .then(() => null); } excluir(codigo: number): Promise<void> { return this.http.delete(`${this.categoriasUrl}/${codigo}`) .toPromise() .then(() => null); } }
import pygame, sys, asyncio from pygame.locals import * import defs import button import menu pygame.init() p1 = defs.PLAYER e1 = defs.ENEMY pygame.time.set_timer(defs.MORE_SPEED, 1000) #Collision Checker def checkIfCollision(p1,e1): if(p1.rect.colliderect(e1.rect)): return True #Score Counter Font font = pygame.font.Font('freesansbold.ttf', 32) #Settings Button gear_img = pygame.image.load('assets/gear.png').convert_alpha() settings_button = button.Button(380 ,580, gear_img, 1) #Main loop begins async def main(): print("starting main") while True: #Run Menu if(defs.GAME_PAUSED): menu.menu() #Run Game else: p1.update() e1.move() #Event Checker for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: defs.GAME_PAUSED=True if event.type == defs.MORE_SPEED: defs.SPEED += 1 print(defs.SPEED) if event.type == QUIT: pygame.quit() sys.exit() # For Mobile Devices if event.type == pygame.FINGERDOWN: print("debug:event.type=FINGERDOWN") x = event.x * defs.SCREEN_WIDTH y = event.y * defs.SCREEN_HEIGHT p1.finger_move(x,y) if event.type == pygame.FINGERUP: print("debug:event.type=FINGERUP") #fingers.pop(event.finger_id, None) SCORE = font.render(str(defs.SCORE), True, "green", "white") SCORE_rect = SCORE.get_rect() SCORE_rect.center = (20,20) HIGH_SCORE_text = font.render(str(defs.HIGH_SCORE), True, "green", "white") HIGH_SCORE_textRect = HIGH_SCORE_text.get_rect() HIGH_SCORE_textRect.center = (370, 20) defs.DISPLAYSURF.fill("white") #Chech for collisision if(checkIfCollision(p1,e1)): print("Game Over") if(defs.SCORE > defs.HIGH_SCORE): defs.HIGH_SCORE = defs.SCORE #Restart Game defs.GAME_PAUSED=True defs.MENU_STATE="main" e1.__init__() p1.__init__() defs.SPEED=0 defs.SCORE=0 print(f"skin set to {defs.CURRENT_SKIN}") #Draw Content To Screen if settings_button.draw(defs.DISPLAYSURF): defs.GAME_PAUSED = True p1.draw(defs.DISPLAYSURF) e1.draw(defs.DISPLAYSURF) defs.DISPLAYSURF.blit(SCORE, SCORE_rect) defs.DISPLAYSURF.blit(HIGH_SCORE_text, HIGH_SCORE_textRect) pygame.display.update() defs.FRAMES_PER_SEC.tick(defs.FPS) await asyncio.sleep(0) asyncio.run(main())
package cleanups import ( "context" "github.com/docker/docker/internal/multierror" ) type Composite struct { cleanups []func(context.Context) error } // Add adds a cleanup to be called. func (c *Composite) Add(f func(context.Context) error) { c.cleanups = append(c.cleanups, f) } // Call calls all cleanups in reverse order and returns an error combining all // non-nil errors. func (c *Composite) Call(ctx context.Context) error { err := call(ctx, c.cleanups) c.cleanups = nil return err } // Release removes all cleanups, turning Call into a no-op. // Caller still can call the cleanups by calling the returned function // which is equivalent to calling the Call before Release was called. func (c *Composite) Release() func(context.Context) error { cleanups := c.cleanups c.cleanups = nil return func(ctx context.Context) error { return call(ctx, cleanups) } } func call(ctx context.Context, cleanups []func(context.Context) error) error { var errs []error for idx := len(cleanups) - 1; idx >= 0; idx-- { c := cleanups[idx] errs = append(errs, c(ctx)) } return multierror.Join(errs...) }
import Head from 'next/head'; import type { GetStaticProps } from 'next'; import { TopChampionsByLane } from '@/components'; interface PageProps { title: string; description: string; } export const getStaticProps: GetStaticProps<PageProps> = async () => { return { props: { title: 'LoL DataHub', description: 'Informações sobre build, items e habilidade de campeões do League of Legends.' } }; }; export default function Home ({title, description}: PageProps) { return ( <> <Head> <title>{title}</title> <meta name='description' content={description} /> </Head> <TopChampionsByLane /> </> ); }
import React, { ReactNode, createContext, useContext } from "react"; import { Theme, pageThemes } from "./themes"; interface ThemeContextProps { theme: Theme; } const ThemeContext = createContext<ThemeContextProps | undefined>(undefined); export const ThemeProvider: React.FC<{ page: string; children: ReactNode }> = ({ page, children, }) => { const theme = pageThemes[page as keyof typeof pageThemes]; return ( <ThemeContext.Provider value={{ theme }}>{children}</ThemeContext.Provider> ); }; export const useTheme = () => { const context = useContext(ThemeContext); if (!context) { throw new Error("useTheme must be used within a ThemeProvider"); } return context.theme; };
#ifndef FEUP_DA1_STATION_H #define FEUP_DA1_STATION_H #include <string> /** * @brief Represents a station */ class Station { private: /** * @brief Station name */ std::string _name; /** * @brief Station district */ std::string _district; /** * @brief Station municipality */ std::string _municipality; /** * @brief Station township */ std::string _township; /** * @brief Station line */ std::string _line; public: Station( const std::string& name, const std::string& district, const std::string& municipality, const std::string& township, const std::string& line ); Station(); /** * @brief Get the station name * * @return std::string stationName */ std::string getName() const; /** * @brief Get the station district * * @return std::string stationDistrict */ std::string getDistrict() const; /** * @brief Get the station municipality * * @return std::string stationMunicipality */ std::string getMunicipality() const; /** * @brief Get the station township * * @return std::string stationTownship */ std::string getTownship() const; /** * @brief Get the stationLine * * @return std::string stationLine */ std::string getLine() const; /** * @brief Checks stations equality * * @param other station * @return true are the same station * @return false are not the same station */ bool operator==(const Station& other) const; }; #endif // FEUP_DA1_STATION_H
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { NavbarComponent } from './navbar/navbar.component'; import { BrandsComponent } from './brands/brands.component'; import { NotfoundComponent } from './notfound/notfound.component'; import { FooterComponent } from './footer/footer.component'; import { MycartComponent } from './mycart/mycart.component'; import { SignupComponent } from './signup/signup.component'; import { SigninComponent } from './signin/signin.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ProductDetailsComponent } from './product-details/product-details.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { CarouselModule } from 'ngx-owl-carousel-o'; import { MainsliderComponent } from './mainslider/mainslider.component'; import { ForgotPasswordComponent } from './forgot-password/forgot-password.component'; import { ResetPasswordComponent } from './reset-password/reset-password.component'; import { CheckoutComponent } from './checkout/checkout.component'; import { AddHeaderInterceptor } from './interceptor/add-header.interceptor'; import { AddTitlePipe } from './add-title.pipe'; import { SearchPipe } from './search.pipe'; import { LoaderComponent } from './loader/loader.component'; import { LoaderInterceptor } from './loader.interceptor'; @NgModule({ declarations: [ AppComponent, HomeComponent, NavbarComponent, NotfoundComponent, FooterComponent, MycartComponent, SignupComponent, SigninComponent, ProductDetailsComponent, MainsliderComponent, ForgotPasswordComponent, ResetPasswordComponent, CheckoutComponent, AddTitlePipe, SearchPipe, LoaderComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ReactiveFormsModule, BrowserAnimationsModule, CarouselModule, FormsModule ], providers: [ { provide:HTTP_INTERCEPTORS, useClass:AddHeaderInterceptor, multi: true }, { provide:HTTP_INTERCEPTORS, useClass:LoaderInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
import { Vector2D } from '../utils' /** * Check if a polygon and a point intersect * * Source: https://www.jeffreythompson.org/collision-detection/poly-point.php * * @param vertices polygon verticies * @param px point x position * @param py point y position * @returns * * @example * ```js * import { polyPoint } from 'jt-collision-detection' * * const poly = [ * // triangle * { x: 10, y: 10 }, * { x: 20, y: 20 }, * { x: 30, y: 10 }, * ] * * const point = { * x: 10, * y: 10, * } * * const haveCollided = polyPoint( * poly, * * point.x, * point.y, * ) * ``` */ export const polyPoint = ( vertices: Vector2D[], px: number, py: number, ): boolean => { let collision = false // go through each of the vertices, plus // the next vertex in the list let next = 0 for (let current = 0; current < vertices.length; current++) { // get next vertex in list // if we've hit the end, wrap around to 0 next = current + 1 if (next == vertices.length) next = 0 // get the PVectors at our current position // this makes our if statement a little cleaner const vc: Vector2D = vertices[current] // c for "current" const vn: Vector2D = vertices[next] // n for "next" // compare position, flip 'collision' variable // back and forth if ( ((vc.y >= py && vn.y < py) || (vc.y < py && vn.y >= py)) && px < ((vn.x - vc.x) * (py - vc.y)) / (vn.y - vc.y) + vc.x ) { collision = !collision } } return collision }
import tensorflow as tf import numpy as np from tensorflow import keras xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float) model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer='sgd', loss='mean_squared_error') model.fit(xs, ys, epochs=500, verbose=0) print(model.predict([10.0])) def my_huber_loss_self(y_pred, y_true): #https: // en.wikipedia.org / wiki / Huber_loss threshold = 1 error = y_pred - y_true if tf.abs(error) <= threshold: loss = tf.square(error)/2.0 else: loss = threshold*(tf.abs(error)-(0.5*threshold)) return loss def my_huber_loss(y_pred, y_true): # This is the standardized code from coursera, above function is how I implemented. threshold = 1 error = y_pred - y_true is_small_error = tf.abs(error)<threshold small_error_loss = tf.square(error)/2 big_error_loss = threshold * (tf.abs(error)-(0.5*threshold)) return tf.where(is_small_error, small_error_loss, big_error_loss) model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer='sgd', loss=my_huber_loss) model.fit(xs, ys, epochs=500, verbose=0) print(model.predict([10.0]))
// import logo from './logo.svg'; import "./App.css"; import React, { useState } from "react"; function App() { const [value, setValue] = useState(""); const [results, setResults] = useState([]); const fetchImages = () => { fetch( `https://api.unsplash.com/search/photos?client_id=mtmVjlZVowBLDttrAKdnfNw3HbJ4AhFHfGufiNWaYKM&query=${value}&orientation=squarish&username&html` ) .then((res) => res.json()) .then((data) => { console.log(data); setResults(data.results); }); }; return ( <> <div className="App"> <div className="myDiv"> <span className="heading">Search</span> <input style={{ width: "100%" }} type="text" value={value} onChange={(e) => setValue(e.target.value)} /> <br/> <br/> <button className="btn btn-primary" onClick={() => fetchImages()} > Send </button> </div> <div className="container mt-3"> <div className="row mb-5"> {results.map((item) => { return ( <div className="col-md-4 mb-5"> <div className="card"> <img className="card-img-top" alt="image not found" key={item.id} src={item.urls.regular} /> <div className="card-body"> <h5 className="card-title user-1"> Photographer: {item.user.username} </h5> <h5 className="card-text user-2"> Username: {item.user.username} </h5> <h5 className="card-text user-3"> User Profile: <a href="..." className="link-1"> {item.user.links.html} </a> </h5> </div> </div> </div> ); })} </div> </div> </div> </> ); } export default App;
pragma solidity 0.5.11; contract Votacion { address ine; struct Votante { bool votante_autorizado; bool voto_emitido; } modifier onlyINE() { require(ine == msg.sender, 'No tienes permiso para autorizar'); _; } bytes32[] candidatos; mapping (address => Votante) votantes; mapping (uint => uint ) votos_recibidos; constructor(bytes32[] memory _candidatos) public { ine = msg.sender; votantes[ine].votante_autorizado = true; candidatos = _candidatos; } function autorizarVotantes(address _votante) public onlyINE{ require(!votantes[_votante].votante_autorizado,'Usuario previamente autorizado'); votantes[_votante].votante_autorizado = true; } function votar(uint _candidato) public { Votante storage elector = votantes[msg.sender]; require(elector.votante_autorizado,'Votante no autorizado'); require(!elector.voto_emitido, 'Voto emitido previamente'); require(_candidato < candidatos.length,'Opcion no valida'); elector.voto_emitido = true; votos_recibidos[_candidato]+=1; } }
import * as React from 'react'; import renderer, { act } from 'react-test-renderer'; import { ActivityIndicator, Platform } from 'react-native'; import { Input, Button } from 'react-native-elements'; import { KeyboardAvoidingContainer } from '@core/styled'; import { AUTH_TYPES } from '@core/models'; import { _Auth } from './auth'; describe('Auth', () => { const signIn = jest.fn(); describe('when Auth was mounted with all needed props', () => { describe('and isPending prop equals true', () => { const wrapper = renderer.create( <_Auth signIn={signIn} isPending={true} type={AUTH_TYPES.JOIN} />, ); it('should render ActivityIndicator component', () => { expect(wrapper.root.findByType(ActivityIndicator)) .toBeTruthy(); }); }); describe('and isPending prop equals false', () => { const wrapper = renderer.create( <_Auth signIn={signIn} isPending={false} type={AUTH_TYPES.JOIN} />, ); it('should render email input component', () => { expect(wrapper.root.findByType(Input)) .toBeTruthy(); }); describe('and provided email address does not match email pattern', () => { act(() => { wrapper.root.findByType(Button).props.onPress(); }); it('should not call signIn prop after press on Button', () => { expect(signIn) .not.toHaveBeenCalled(); }); }); describe('and provided email address match email pattern', () => { act(() => { wrapper.root.findByType(Input).props.onChangeText('test@example.com') }); it('should call signIn prop with provided email after press on Button', () => { act(() => { wrapper.root.findByType(Button).props.onPress(); }); expect(signIn) .toHaveBeenCalledWith('test@example.com'); }); }); }); describe('and current Platform is android', () => { beforeEach(() => { Platform.OS = 'android'; }); it('should render KeyboardAvoidingContainer with 90 keyboardVerticalOffset', () => { const wrapper = renderer.create( <_Auth signIn={signIn} isPending={false} type={AUTH_TYPES.JOIN} />, ); expect(wrapper.root.findByType(KeyboardAvoidingContainer).props.keyboardVerticalOffset) .toEqual(90); }); }); describe('and current Platform is iOS', () => { beforeEach(() => { Platform.OS = 'ios'; }); const wrapper = renderer.create( <_Auth signIn={signIn} isPending={false} type={AUTH_TYPES.JOIN} />, ); it('should render KeyboardAvoidingContainer with 70 keyboardVerticalOffset', () => { expect(wrapper.root.findByType(KeyboardAvoidingContainer).props.keyboardVerticalOffset) .toEqual(70); }); }); }); });
import { AnimatePresence, motion } from "framer-motion"; import { DateTime } from "luxon"; import { Header } from "./Header"; import { InlineLoader } from "~/components/InlineLoader"; import { isNil, isNull } from "shared/lib/identity"; import { locationToUrl } from "~/lib/maps"; import { ReloadButton } from "../components/ReloadButton"; import { useScrollPosition } from "~/lib/scroll"; import CarIcon from "~/static/images/icons/solid/car.svg"; import clsx from "clsx"; import MapIcon from "~/static/images/icons/solid/map-marker.svg"; import ParkingIcon from "~/static/images/icons/solid/parking.svg"; import React, { ReactElement, ReactNode, useEffect, useRef, useState, } from "react"; import WSDOTIcon from "~/static/images/icons/wsdot.svg"; import type { Camera } from "shared/contracts/cameras"; import type { Terminal } from "shared/contracts/terminals"; interface Props { terminal: Terminal | null; } export const Cameras = ({ terminal }: Props): ReactElement => { if (!terminal) { return <InlineLoader>Loading cameras...</InlineLoader>; } const { cameras } = terminal; const [cameraTime, setCameraTime] = useState<number>( DateTime.local().toSeconds() ); const [cameraInterval, setCameraInterval] = useState<number | null>(null); const wrapper = useRef<HTMLDivElement | null>(null); const { y } = useScrollPosition(wrapper); // Update images ever 10 seconds useEffect(() => { setCameraInterval( window.setInterval(() => { setCameraTime(DateTime.local().toSeconds()); }, 10 * 1000) ); return () => { if (cameraInterval) { clearInterval(cameraInterval); } }; }, []); const reload = () => setCameraTime(DateTime.local().toSeconds()); const renderCamera = (camera: Camera, index: number): ReactNode => { const { id, title, image, spacesToNext, location, owner } = camera; const isFirst = index === 0; let totalToBooth: number | null; const mapsUrl = locationToUrl(location); if (isNil(cameras[0]?.spacesToNext)) { totalToBooth = null; } else { totalToBooth = 0; cameras.find((candidate) => { const { spacesToNext } = candidate; if (isNull(spacesToNext)) { return true; } totalToBooth = Number(totalToBooth) + (candidate?.spacesToNext ?? 0); return candidate === camera; }); } return ( <li className={clsx("flex flex-col", "relative", !isFirst && "pt-8")} key={id} > <div className="bg-lighten-lower w-full relative" style={{ paddingTop: `${(image.height / image.width) * 100}%`, }} > <img src={`${image.url}?${cameraTime}`} className={clsx( "absolute inset-0 w-full", owner?.name && "border border-black" )} alt={`Traffic Camera: ${title}`} /> </div> <span className="font-bold text-lg mt-2"> <a href={mapsUrl} target="_blank" className="link" rel="noopener noreferrer" > {title} </a> {Boolean(totalToBooth) && ( <span className={clsx("ml-4 font-normal text-sm")}> <CarIcon className="inline-block mr-2" /> {totalToBooth} to tollbooth </span> )} {totalToBooth === 0 && ( <span className={clsx("ml-4 font-normal text-sm")}> <ParkingIcon className="inline-block mr-2" /> Past tollbooth </span> )} </span> {isFirst && ( <div className={clsx( "bg-green-dark", "w-12 h-full", "absolute bottom-0 left-0 -ml-12 z-10" )} /> )} <div className={clsx( "bg-green-dark text-lighten-medium", "w-12 py-2", "absolute bottom-0 left-0 -ml-12 -mb-2 z-10", "text-center" )} > <MapIcon className="text-2xl inline-block ml-1" /> </div> {Boolean(spacesToNext) && ( <div className={clsx( "bg-green-dark", "w-12 py-1", "absolute top-0 left-0 -ml-12 mt-1/3 z-10", "text-center" )} > <div className="flex flex-col ml-1 items-center"> <CarIcon className="inline-block" /> <span className="text-sm">{spacesToNext}</span> </div> </div> )} </li> ); }; return ( <> <Header reload={reload} share={{ shareButtonText: "Share Cameras", sharedText: `Cameras for ${terminal.name} Ferry Terminal`, }} items={[ ...(terminal.terminalUrl ? [ { Icon: WSDOTIcon, label: "WSF Cameras Page", url: terminal.terminalUrl, isBottom: true, }, ] : []), ]} > <span className="text-center flex-1">{terminal.name} Cameras</span> <ReloadButton onClick={() => reload()} ariaLabel="Reload Cameras" isReloading={false} /> </Header> <main className="flex-grow overflow-y-scroll scrolling-touch text-white" ref={wrapper} > <div className={clsx("my-4 pl-12 relative max-w-lg")}> <div className={clsx( "bg-green-dark", "border-l-4 border-dotted border-lighten-medium", "w-1 h-full", "absolute inset-y-0 left-0 ml-6" )} /> {/* Top shadow on scroll */} <AnimatePresence> {y > 0 && ( <motion.div className={clsx( "fixed top-16 left-0 w-full h-2", "pointer-events-none z-20", "bg-gradient-to-b from-darken-medium to-transparent" )} initial={{ opacity: 0.5 }} animate={{ opacity: 1 }} exit={{ opacity: 0.5 }} transition={{ duration: 0.1 }} /> )} </AnimatePresence> <ul>{cameras.map(renderCamera)}</ul> </div> </main> </> ); };
import numpy as np from numpy import polyval import matplotlib.pyplot as plt import os import pandas as pd import math from scipy import interpolate, signal from tqdm import tqdm from astropy.stats.sigma_clipping import sigma_clip import itertools, json from sklearn.metrics import mean_squared_error from scipy.optimize import minimize, curve_fit v_virial = 250 c = 2.9979e5 comb_path = '/home/dataadmin/GBTData/SharedDataDirectory/lband/data_info/polynomial_normalized_comb_new.npy' def filtr(ys, cell_size): """ Removes center DC spike :param ys: powers :type ys: 1darray :param cell_size: number of points in a coarse channel based on the data type (medium resolution, high spectral resolution, high time resolution) :type cell_size: int :param window: number of points to fit polynomial to :type window: int :return: filtered powers :rtype: 1darray """ for i in range(cell_size//2-1, len(ys), cell_size): ys[i] = np.mean([ys[i-1], (ys[i+2])]) return ys def rebin(xs, ys, cell_size=16): """ Rebins data to a smaller number of points per coarse channel :param xs: frequencies :type xs: 1d array :param ys: powers :type ys: 1darray :param cell_size: number of desired points in a coarse channel (16 for this analysis) :type cell_size: int :return: rebinned frequency array, rebinned power array :rtype: tuple """ rebin_size=1024//cell_size rebinned_spec = [] for i in range(len(ys)//rebin_size): average = np.mean(ys[i*rebin_size:i*rebin_size+rebin_size]) rebinned_spec.append(average) rebinned_freq = [] for i in range(len(xs)//rebin_size): average = np.mean(xs[i*rebin_size:i*rebin_size+rebin_size]) rebinned_freq.append(average) return rebinned_freq, rebinned_spec def normalize(xs, ys, order, window): """ Normalizes spectra by fitting and dividing by an unweighted polynomial :param xs: frequencies :type xs: 1darray :param ys: powers :type ys: 1darray :param order: order of polynomial :type order: int :param window: number of points to fit polynomial to :type window: int :return: normalized powers :rtype: 1darray """ xs, ys = np.array(xs), np.array(ys) ys = ys / ys.mean() ys_mean = ys / ys.mean() for i in range(0, len(ys)-16, 16): # Excise the 4 unstable valley points in each coarse channel ys_mean[i] = np.NaN ys_mean[i+15] = np.NaN ys_mean[i+1] = np.NaN ys_mean[i+14] = np.NaN normalized_spectrum = [] ind_xs = np.arange(-(window//2), window//2+1) lower = (window - 1) // 2 upper = (window + 1) // 2 for i in range(0,len(xs)): if i <= lower: # For points in the first 50 MHz, fit a polynomial to the right of the point current_ys = ys_mean[i:i+window] idx = np.isfinite(current_ys) c_w = np.polyfit(ind_xs[idx], current_ys[idx], order) normalized_spectrum.append(ys[i] / np.polyval(c_w,ind_xs)[0]) elif i >= len(xs) - upper: # For points in the last 50 MHz, fit a polynomial to the left of the point current_ys = ys_mean[i-window+1:i+1] idx = np.isfinite(current_ys) c_w = np.polyfit(ind_xs[idx], current_ys[idx], order) normalized_spectrum.append(ys[i] / np.polyval(c_w,ind_xs)[-1]) else: current_ys = ys_mean[i-lower:i+upper] # For points in the middle, fit a polynomial to 25 MHz on either side idx = np.isfinite(current_ys) c_w = np.polyfit(ind_xs[idx], current_ys[idx], order) normalized_spectrum.append(ys[i] / np.polyval(c_w,ind_xs)[lower]) return normalized_spectrum def comb_spec(ys, comb): """ Removes the bandpass structure from data :param ys: powers :type ys: 1darray :param comb: 16-point comb :type ys: 1darray :return: combed powers :rtype: 1darray """ ys = np.array(ys) return ys / np.resize(comb, ys.shape) def clean(xs, ys, cell_size, low_freq, high_freq): """ Removes noisiest regions of the band corresponding to the notch filter :param xs: frequencies :type xs: 1darray :param ys: powers :type ys: 1darray :param cell_size: number of points per coarse channel after rebinning :type cell_size: int :param low_freq: the lowest frequency to keep for the desired region :type low_freq: float :param high_freq: the highest frequency to keep for the desired region :type high_freq: float :return: array of frequencies to keep, array of powers to keep :rtype: tuple """ xs = np.array(xs) i1 = np.argmin(np.abs(xs - low_freq)) // cell_size * cell_size i2 = np.argmin(np.abs(xs - high_freq)) // cell_size * cell_size i1, i2 = min(i1, i2), max(i1, i2) xs_cut = xs[i1:i2].copy() ys_cut = ys[i1:i2].copy() return xs_cut, ys_cut def main(worker_id, filepath, out_filepath, template): if 'freqs' not in filepath: # The file is a power array try: ys_injected = np.load(filepath) xs_injected = np.load(filepath[:-4]+ "_freqs.npy") filtered = filtr(ys_injected, 1024) xs, ys = rebin(xs_injected, filtered,16) # To calculate window: # points/coarse channel * frequency range of window [MHz] * 2.9 MHz/channel # Example: 16 [points/channel] * 53 [MHz] / 2.9 [MHz/channel] = 293 points # Note: window size must be odd in order to have an exact center normed = normalize(xs, ys, 5, 293) best_comb = np.load(comb_path) if len(ys) == 4928: # File contains all 308 coarse channels ys_new = comb_spec(normed,best_comb) xs_1, ys_1 = clean(xs, ys_new, 16, 1024.01, 1229.1) xs_2, ys_2 = clean(xs, ys_new, 16, 1302.4, 1525) xs_3, ys_3 = clean(xs, ys_new, 16, 1560.2, 1923.25) xs, ys = np.concatenate((xs_1, xs_2, xs_3)), np.concatenate((ys_1, ys_2, ys_3)) data = np.array([xs, ys]) np.save(out_filepath, data) except Exception as e: print(e)
import React, {ReactNode} from 'react'; import {Link} from 'gatsby'; import {AnchorLink} from 'gatsby-plugin-anchor-links'; // import AnimatedLink from '@app/components/AnimatedLink'; import AnimatedUnderline from '@app/components/AnimatedUnderline'; type MenuItemsProps = { href: string, anchorLink: boolean, animatedLink?: boolean, className?: string, children: ReactNode, } & React.HTMLAttributes<HTMLSpanElement> const MenuItem = ({ href = '/', animatedLink = false, anchorLink = false, className = '', children, ...rest }: MenuItemsProps) => { const RawLink = animatedLink ? <AnimatedUnderline className={className} {...rest}> {children} </AnimatedUnderline> : <span className={`text-primary ${className}`} {...rest}> {children} </span>; return ( <> {anchorLink ? (<AnchorLink to={href}>{RawLink}</AnchorLink>) : (<Link to={href}>{RawLink}</Link>) } </> ); }; export default MenuItem;
import {createSlice, PayloadAction} from '@reduxjs/toolkit'; import {signIn, signUp} from './actions'; export type UserState = { token: string | null; }; const initialState: UserState = { token: null, }; const slice = createSlice({ name: 'user', initialState, reducers: {}, extraReducers: builder => { builder.addCase(signUp.fulfilled, (state, action: PayloadAction<any>) => { state.token = action.payload.token; }); builder.addCase(signIn.fulfilled, (state, action: PayloadAction<any>) => { state.token = action.payload.token; }); }, }); type InStoreType = { user: UserState; }; export const selectors = { selectUser: (state: InStoreType) => state.user, selectToken: (state: InStoreType) => state.user.token, }; export const actions = { ...slice.actions, signUp, signIn, }; export const reducer = slice.reducer;
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 5.0 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. Class fixedValueCorrectedFvPatchField Description SourceFiles fixedValueCorrectedFvPatchField.C \*---------------------------------------------------------------------------*/ #ifndef fixedValueCorrectedFvPatchField_H #define fixedValueCorrectedFvPatchField_H #include "correctedFvPatchField.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class fixedValueCorrectedFvPatch Declaration \*---------------------------------------------------------------------------*/ template<class Type> class fixedValueCorrectedFvPatchField : public correctedFvPatchField<Type> { public: //- Runtime type information TypeName("fixedValueCorrected"); // Constructors //- Construct from patch and internal field fixedValueCorrectedFvPatchField ( const fvPatch&, const DimensionedField<Type, volMesh>& ); //- Construct from patch, internal field and dictionary fixedValueCorrectedFvPatchField ( const fvPatch&, const DimensionedField<Type, volMesh>&, const dictionary& ); //- Construct by mapping the given fixedValueCorrectedFvPatchField<Type> // onto a new patch fixedValueCorrectedFvPatchField ( const fixedValueCorrectedFvPatchField<Type>&, const fvPatch&, const DimensionedField<Type, volMesh>&, const fvPatchFieldMapper& ); //- Construct and return a clone virtual tmp<fvPatchField<Type> > clone() const { return tmp<fvPatchField<Type> > ( new fixedValueCorrectedFvPatchField<Type>(*this) ); } //- Construct as copy setting internal field reference fixedValueCorrectedFvPatchField ( const fixedValueCorrectedFvPatchField<Type>&, const DimensionedField<Type, volMesh>& ); //- Construct and return a clone setting internal field reference virtual tmp<fvPatchField<Type> > clone(const DimensionedField<Type, volMesh>& iF)const { return tmp<fvPatchField<Type> > ( new fixedValueCorrectedFvPatchField<Type>(*this, iF) ); } // Member functions // Access //- Return true if this patch field fixes a value. // Needed to check if a level has to be specified while solving // Poissons equations. virtual bool fixesValue() const { return true; } // Evaluation functions //- Return the matrix diagonal coefficients corresponding to the // evaluation of the value of this patchField with given weights virtual tmp<Field<Type> > valueInternalCoeffs ( const tmp<scalarField>& ) const; //- Return the matrix source coefficients corresponding to the // evaluation of the value of this patchField with given weights virtual tmp<Field<Type> > valueBoundaryCoeffs ( const tmp<scalarField>& ) const; //- Return the matrix diagonal coefficients corresponding to the // evaluation of the gradient of this patchField virtual tmp<Field<Type> > gradientInternalCoeffs() const; //- Return the matrix source coefficients corresponding to the // evaluation of the gradient of this patchField virtual tmp<Field<Type> > gradientBoundaryCoeffs() const; //- Write virtual void write(Ostream&) const; // Member operators virtual void operator=(const UList<Type>&) {} virtual void operator=(const fvPatchField<Type>&) {} virtual void operator+=(const fvPatchField<Type>&) {} virtual void operator-=(const fvPatchField<Type>&) {} virtual void operator*=(const fvPatchField<scalar>&) {} virtual void operator/=(const fvPatchField<scalar>&) {} virtual void operator+=(const Field<Type>&) {} virtual void operator-=(const Field<Type>&) {} virtual void operator*=(const Field<scalar>&) {} virtual void operator/=(const Field<scalar>&) {} virtual void operator=(const Type&) {} virtual void operator+=(const Type&) {} virtual void operator-=(const Type&) {} virtual void operator*=(const scalar) {} virtual void operator/=(const scalar) {} }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "fixedValueCorrectedFvPatchField.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
// // Copyright (C) University College London, 2007-2012, all rights reserved. // // This file is part of HemeLB and is provided to you under the terms of // the GNU LGPL. Please see LICENSE in the top level directory for full // details. // #ifndef HEMELB_UNITTESTS_LBTESTS_STREAMERTESTS_H #define HEMELB_UNITTESTS_LBTESTS_STREAMERTESTS_H #include <cppunit/TestFixture.h> #include <iostream> #include <sstream> #include "lb/streamers/Streamers.h" #include "geometry/SiteData.h" #include "unittests/helpers/FourCubeBasedTestFixture.h" namespace hemelb { namespace unittests { namespace lbtests { static const distribn_t allowedError = 1e-10; /** * StreamerTests: * * This class tests the streamer implementations. We assume the collision operators are * correct (as they're tested elsewhere), then compare the post-streamed values with * the values we expect to have been streamed there. */ class StreamerTests : public helpers::FourCubeBasedTestFixture { CPPUNIT_TEST_SUITE( StreamerTests); CPPUNIT_TEST( TestSimpleCollideAndStream); CPPUNIT_TEST( TestFInterpolation); CPPUNIT_TEST( TestSimpleBounceBack); CPPUNIT_TEST( TestRegularised); CPPUNIT_TEST( TestGuoZhengShi); CPPUNIT_TEST( TestRegularisedIolet); CPPUNIT_TEST( TestNashBB); CPPUNIT_TEST( TestJunkYangEquivalentToBounceBack);CPPUNIT_TEST_SUITE_END(); public: void setUp() { FourCubeBasedTestFixture::setUp(); propertyCache = new lb::MacroscopicPropertyCache(*simState, *latDat); normalCollision = new lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> >(initParams); } void tearDown() { delete propertyCache; delete normalCollision; FourCubeBasedTestFixture::tearDown(); } void TestSimpleCollideAndStream() { lb::streamers::SimpleCollideAndStream<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > simpleCollideAndStream(initParams); // Initialise fOld in the lattice data. We choose values so that each site has // an anisotropic distribution function, and that each site's function is // distinguishable. LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(latDat); // Use the streaming operator on the entire lattice. simpleCollideAndStream.StreamAndCollide<false> (0, latDat->GetLocalFluidSiteCount(), lbmParams, latDat, *propertyCache); // Now, go over each lattice site and check each value in f_new is correct. for (site_t streamedToSite = 0; streamedToSite < latDat->GetLocalFluidSiteCount(); ++streamedToSite) { geometry::Site streamedSite = latDat->GetSite(streamedToSite); distribn_t* streamedToFNew = latDat->GetFNew(lb::lattices::D3Q15::NUMVECTORS * streamedToSite); for (unsigned int streamedDirection = 0; streamedDirection < lb::lattices::D3Q15::NUMVECTORS; ++streamedDirection) { site_t streamerIndex = streamedSite.GetStreamedIndex<lb::lattices::D3Q15> (lb::lattices::D3Q15::INVERSEDIRECTIONS[streamedDirection]); // If this site streamed somewhere sensible, it must have been streamed to. if (streamerIndex >= 0 && streamerIndex < (lb::lattices::D3Q15::NUMVECTORS * latDat->GetLocalFluidSiteCount())) { site_t streamerSiteId = streamerIndex / lb::lattices::D3Q15::NUMVECTORS; // Calculate streamerFOld at this site. distribn_t streamerFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(streamerSiteId, streamerFOld); // Calculate what the value streamed to site streamedToSite should be. lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > streamerHydroVars(streamerFOld); normalCollision->CalculatePreCollision(streamerHydroVars, streamedSite); normalCollision->Collide(lbmParams, streamerHydroVars); // F_new should be equal to the value that was streamed from this other site // in the same direction as we're streaming from. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SimpleCollideAndStream, StreamAndCollide", streamerHydroVars.GetFPostCollision()[streamedDirection], streamedToFNew[streamedDirection], allowedError); } } } } void TestFInterpolation() { // Initialise fOld in the lattice data. We choose values so that each site has // an anisotropic distribution function, and that each site's function is // distinguishable. LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(latDat); lb::streamers::FInterpolation<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > fInterpolation(initParams); fInterpolation.StreamAndCollide<false> (0, latDat->GetLocalFluidSiteCount(), lbmParams, latDat, *propertyCache); fInterpolation.PostStep<false> (0, latDat->GetLocalFluidSiteCount(), lbmParams, latDat, *propertyCache); // Now, go over each lattice site and check each value in f_new is correct. for (site_t streamedToSite = 0; streamedToSite < latDat->GetLocalFluidSiteCount(); ++streamedToSite) { const geometry::Site streamedSite = latDat->GetSite(streamedToSite); distribn_t* streamedToFNew = latDat->GetFNew(lb::lattices::D3Q15::NUMVECTORS * streamedToSite); for (unsigned int streamedDirection = 0; streamedDirection < lb::lattices::D3Q15::NUMVECTORS; ++streamedDirection) { unsigned int oppDirection = lb::lattices::D3Q15::INVERSEDIRECTIONS[streamedDirection]; site_t streamerIndex = streamedSite.GetStreamedIndex<lb::lattices::D3Q15> (oppDirection); geometry::Site streamerSite = latDat->GetSite(streamerIndex); // If this site streamed somewhere sensible, it must have been streamed to. if (streamerIndex >= 0 && streamerIndex < (lb::lattices::D3Q15::NUMVECTORS * latDat->GetLocalFluidSiteCount())) { site_t streamerSiteId = streamerIndex / lb::lattices::D3Q15::NUMVECTORS; // Calculate streamerFOld at this site. distribn_t streamerFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(streamerSiteId, streamerFOld); // Calculate what the value streamed to site streamedToSite should be. lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > streamerHydroVars(streamerFOld); normalCollision->CalculatePreCollision(streamerHydroVars, streamerSite); normalCollision->Collide(lbmParams, streamerHydroVars); // F_new should be equal to the value that was streamed from this other site // in the same direction as we're streaming from. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SimpleCollideAndStream, StreamAndCollide", streamerHydroVars.GetFPostCollision()[streamedDirection], streamedToFNew[streamedDirection], allowedError); } else if (streamedSite.GetSiteType() == geometry::INLET_TYPE || streamedSite.GetSiteType() == geometry::OUTLET_TYPE) { // No reason to further test an inlet/outlet site. // Pass. } else { std::stringstream message; message << "Site: " << streamedToSite << " Direction " << oppDirection << " Data: " << streamedSite.GetSiteData().GetIntersectionData() << std::flush; CPPUNIT_ASSERT_MESSAGE("Expected to find a boundary" "opposite an unstreamed-to direction " + message.str(), streamedSite.HasBoundary(oppDirection)); // Test disabled due to RegressionTests issue, see discussion in #87 CPPUNIT_ASSERT_MESSAGE("Expect defined cut distance opposite an unstreamed-to direction " + message.str(), streamedSite.GetWallDistance<lb::lattices::D3Q15> (oppDirection) != -1.0); // To verify the operation of the f-interpolation boundary condition, we'll need: // - the distance to the wall * 2 distribn_t twoQ = 2.0 * streamedSite.GetWallDistance<lb::lattices::D3Q15> (oppDirection); // - the post-collision distribution at the current site. distribn_t streamedToSiteFOld[lb::lattices::D3Q15::NUMVECTORS]; // (initialise it to f_old). LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(streamedToSite, streamedToSiteFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > hydroVars(streamedToSiteFOld); normalCollision->CalculatePreCollision(hydroVars, streamedSite); // (find post-collision values using the collision operator). normalCollision->Collide(lbmParams, hydroVars); // - finally, the post-collision distribution at the site which is one further // away from the wall in this direction. distribn_t awayFromWallFOld[lb::lattices::D3Q15::NUMVECTORS]; site_t awayFromWallIndex = streamedSite.GetStreamedIndex<lb::lattices::D3Q15> (streamedDirection) / lb::lattices::D3Q15::NUMVECTORS; // If there's a valid index in that direction, use f-interpolation if (awayFromWallIndex >= 0 && awayFromWallIndex < latDat->GetLocalFluidSiteCount()) { const geometry::Site awayFromWallSite = latDat->GetSite(awayFromWallIndex); // (initialise it to f_old). LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(awayFromWallIndex, awayFromWallFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > awayFromWallsHydroVars(awayFromWallFOld); normalCollision->CalculatePreCollision(awayFromWallsHydroVars, awayFromWallSite); // (find post-collision values using the collision operator). normalCollision->Collide(lbmParams, awayFromWallsHydroVars); distribn_t toWallOld = hydroVars.GetFPostCollision()[oppDirection]; distribn_t toWallNew = awayFromWallsHydroVars.GetFPostCollision()[oppDirection]; distribn_t oppWallOld = hydroVars.GetFPostCollision()[streamedDirection]; // The streamed value should be as given below. distribn_t streamed = (twoQ < 1.0) ? (toWallNew + twoQ * (toWallOld - toWallNew)) : (oppWallOld + (1. / twoQ) * (toWallOld - oppWallOld)); std::stringstream msg(std::stringstream::in); msg << "FInterpolation, PostStep: site " << streamedToSite << " direction " << streamedDirection; // Assert that this is the case. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(msg.str(), streamed, * (latDat->GetFNew(streamedToSite * lb::lattices::D3Q15::NUMVECTORS + streamedDirection)), allowedError); } // With no valid lattice site, simple bounce-back will be performed. else { std::stringstream msg(std::stringstream::in); msg << "FInterpolation, PostStep by simple bounce-back: site " << streamedToSite << " direction " << streamedDirection; CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(msg.str(), hydroVars.GetFPostCollision()[oppDirection], * (latDat->GetFNew(streamedToSite * lb::lattices::D3Q15::NUMVECTORS + streamedDirection)), allowedError); } } } } } void TestSimpleBounceBack() { // Initialise fOld in the lattice data. We choose values so that each site has // an anisotropic distribution function, and that each site's function is // distinguishable. LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(latDat); site_t firstWallSite = latDat->GetMidDomainCollisionCount(0); site_t wallSitesCount = latDat->GetMidDomainCollisionCount(1) - firstWallSite; // Check that the lattice has sites labeled as wall (otherwise this test is void) CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of non-wall sites", wallSitesCount, (site_t) 16); site_t offset = 0; // Mid-Fluid sites use simple collide and stream lb::streamers::SimpleCollideAndStream<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > simpleCollideAndStream(initParams); simpleCollideAndStream.StreamAndCollide<false> (offset, latDat->GetMidDomainCollisionCount(0), lbmParams, latDat, *propertyCache); offset += latDat->GetMidDomainCollisionCount(0); // Wall sites use simple bounce back lb::streamers::SimpleBounceBack<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > simpleBounceBack(initParams); simpleBounceBack.StreamAndCollide<false> (offset, latDat->GetMidDomainCollisionCount(1), lbmParams, latDat, *propertyCache); offset += latDat->GetMidDomainCollisionCount(1); // Consider inlet/outlets and their walls as mid-fluid sites simpleCollideAndStream.StreamAndCollide<false> (offset, latDat->GetLocalFluidSiteCount() - offset, lbmParams, latDat, *propertyCache); offset += latDat->GetLocalFluidSiteCount() - offset; // Sanity check CPPUNIT_ASSERT_EQUAL_MESSAGE("Total number of sites", offset, latDat->GetLocalFluidSiteCount()); /* * Loop over the wall sites and check whether they got properly streamed on or bounced back * depending on where they sit relative to the wall. We ignore mid-Fluid sites since * StreamAndCollide was tested before. */ for (site_t wallSiteLocalIndex = 0; wallSiteLocalIndex < wallSitesCount; wallSiteLocalIndex++) { site_t streamedToSite = firstWallSite + wallSiteLocalIndex; const geometry::Site streamedSite = latDat->GetSite(streamedToSite); distribn_t* streamedToFNew = latDat->GetFNew(lb::lattices::D3Q15::NUMVECTORS * streamedToSite); for (unsigned int streamedDirection = 0; streamedDirection < lb::lattices::D3Q15::NUMVECTORS; ++streamedDirection) { unsigned oppDirection = lb::lattices::D3Q15::INVERSEDIRECTIONS[streamedDirection]; // Index of the site streaming to streamedToSite via direction streamedDirection site_t streamerIndex = streamedSite.GetStreamedIndex<lb::lattices::D3Q15> (oppDirection); // Is streamerIndex a valid index? if (streamerIndex >= 0 && streamerIndex < (lb::lattices::D3Q15::NUMVECTORS * latDat->GetLocalFluidSiteCount())) { // The streamer index is a valid index in the domain, therefore stream and collide has happened site_t streamerSiteId = streamerIndex / lb::lattices::D3Q15::NUMVECTORS; // Calculate streamerFOld at this site. distribn_t streamerFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(streamerSiteId, streamerFOld); // Calculate what the value streamed to site streamedToSite should be. lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > streamerHydroVars(streamerFOld); normalCollision->CalculatePreCollision(streamerHydroVars, streamedSite); normalCollision->Collide(lbmParams, streamerHydroVars); // F_new should be equal to the value that was streamed from this other site // in the same direction as we're streaming from. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SimpleCollideAndStream, StreamAndCollide", streamerHydroVars.GetFPostCollision()[streamedDirection], streamedToFNew[streamedDirection], allowedError); } else { // The streamer index shows that no one has streamed to streamedToSite direction // streamedDirection, therefore bounce back has happened in that site for that direction // Initialise streamedToSiteFOld with the original data distribn_t streamerToSiteFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(streamedToSite, streamerToSiteFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > hydroVars(streamerToSiteFOld); normalCollision->CalculatePreCollision(hydroVars, streamedSite); // Simulate post-collision using the collision operator. normalCollision->Collide(lbmParams, hydroVars); // After streaming FNew in a given direction must be f post-collision in the opposite direction // following collision std::stringstream msg(std::stringstream::in); msg << "Simple bounce-back: site " << streamedToSite << " direction " << streamedDirection; CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(msg.str(), streamedToFNew[streamedDirection], hydroVars.GetFPostCollision()[oppDirection], allowedError); } } } } void TestRegularised() { // Initialise fOld in the lattice data. We choose values so that each site has // an anisotropic distribution function, and that each site's function is // distinguishable. LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(latDat); site_t firstWallSite = latDat->GetMidDomainCollisionCount(0); site_t wallSitesCount = latDat->GetMidDomainCollisionCount(1) - firstWallSite; // Check that the lattice has sites labeled as wall (otherwise this test is void) CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of non-wall sites", wallSitesCount, (site_t) 16); site_t offset = 0; // Mid-Fluid sites use simple collide and stream lb::streamers::SimpleCollideAndStream<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > simpleCollideAndStream(initParams); simpleCollideAndStream.StreamAndCollide<false> (offset, latDat->GetMidDomainCollisionCount(0), lbmParams, latDat, *propertyCache); offset += latDat->GetMidDomainCollisionCount(0); // Wall sites use regularised BC lb::streamers::Regularised<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > regularised(initParams); regularised.StreamAndCollide<false> (offset, latDat->GetMidDomainCollisionCount(1), lbmParams, latDat, *propertyCache); offset += latDat->GetMidDomainCollisionCount(1); // Inlet/outlets and their walls use regularised BC regularised.StreamAndCollide<false> (offset, latDat->GetLocalFluidSiteCount() - offset, lbmParams, latDat, *propertyCache); offset += latDat->GetLocalFluidSiteCount() - offset; // Sanity check CPPUNIT_ASSERT_EQUAL_MESSAGE("Total number of sites", offset, latDat->GetLocalFluidSiteCount()); /* * Loop over the wall sites and check whether they got properly streamed on or bounced back * depending on where they sit relative to the wall. We ignore mid-Fluid sites since * StreamAndCollide was tested before. */ for (site_t wallSiteLocalIndex = 0; wallSiteLocalIndex < wallSitesCount; wallSiteLocalIndex++) { site_t streamedToSite = firstWallSite + wallSiteLocalIndex; const geometry::Site streamedSite = latDat->GetSite(streamedToSite); distribn_t* streamedToFNew = latDat->GetFNew(lb::lattices::D3Q15::NUMVECTORS * streamedToSite); for (unsigned int streamedDirection = 0; streamedDirection < lb::lattices::D3Q15::NUMVECTORS; ++streamedDirection) { unsigned oppDirection = lb::lattices::D3Q15::INVERSEDIRECTIONS[streamedDirection]; // Index of the site streaming to streamedToSite via direction streamedDirection site_t streamerIndex = streamedSite.GetStreamedIndex<lb::lattices::D3Q15> (oppDirection); // Is streamerIndex a valid index? if (streamerIndex >= 0 && streamerIndex < (lb::lattices::D3Q15::NUMVECTORS * latDat->GetLocalFluidSiteCount())) { // The streamer index is a valid index in the domain, therefore stream and collide has happened site_t streamerSiteId = streamerIndex / lb::lattices::D3Q15::NUMVECTORS; const geometry::Site streamingSite = latDat->GetSite(streamerSiteId); // Calculate streamerFOld at this site. distribn_t streamerFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(streamerSiteId, streamerFOld); // Calculate what the value streamed to site streamedToSite should be. lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > streamerHydroVars(streamerFOld); normalCollision->CalculatePreCollision(streamerHydroVars, streamingSite); normalCollision->Collide(lbmParams, streamerHydroVars); // If the streamer is a mid-fluid site, normal stream and collide has happened. Otherwise, regularised-type stream and collide if (streamingSite.GetCollisionType() == FLUID) { // F_new should be equal to the value that was streamed from this other site // in the same direction as we're streaming from. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Regularised", streamerHydroVars.GetFPostCollision()[streamedDirection], streamedToFNew[streamedDirection], allowedError); } else { distribn_t streamerFPostColl[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::CalculateRegularisedCollision(latDat, lbmParams, streamerSiteId, streamerHydroVars, streamerFPostColl); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Regularised", streamerFPostColl[streamedDirection], streamedToFNew[streamedDirection], allowedError); } } else { // The streamer index shows that no one has streamed to streamedToSite along direction // streamedDirection, therefore regularised-type bounce back has happened in that site // for that direction // Initialise streamedToSiteFOld with the original data distribn_t streamerToSiteFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(streamedToSite, streamerToSiteFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > hydroVars(streamerToSiteFOld); normalCollision->CalculatePreCollision(hydroVars, streamedSite); // Compute the post-collision step at the streamer node distribn_t streamerFPostColl[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::CalculateRegularisedCollision(latDat, lbmParams, streamedToSite, hydroVars, streamerFPostColl); // After streaming FNew in a given direction must be f post-collision in the opposite direction CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Regularised", streamerFPostColl[oppDirection], streamedToFNew[streamedDirection], allowedError); } } } } void TestGuoZhengShi() { lb::streamers::GuoZhengShi<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > guoZhengShi(initParams); for (double assignedWallDistance = 0.4; assignedWallDistance < 1.0; assignedWallDistance += 0.5) { // Initialise fOld in the lattice data. We choose values so that each site has // an anisotropic distribution function, and that each site's function is // distinguishable. LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(latDat); // Make some fairly arbitrary choices early on. const site_t chosenSite = 0; const geometry::Site& streamer = latDat->GetSite(chosenSite); const Direction chosenUnstreamedDirection = 5; const Direction chosenWallDirection = lb::lattices::D3Q15::INVERSEDIRECTIONS[chosenUnstreamedDirection]; const Direction chosenDoubleWallDirection1 = 7; const Direction chosenDoubleWallDirection2 = 8; // Calculate the next site out from the wall. const site_t nextSiteAwayFromWall = streamer.GetStreamedIndex<lb::lattices::D3Q15> (chosenUnstreamedDirection) / lb::lattices::D3Q15::NUMVECTORS; const geometry::Site& nextSiteAway = latDat->GetSite(nextSiteAwayFromWall); // Enforce that there's a boundary in the wall direction. latDat->SetHasBoundary(chosenSite, chosenWallDirection); latDat->SetHasBoundary(chosenSite, chosenDoubleWallDirection1); latDat->SetHasBoundary(chosenSite, chosenDoubleWallDirection2); latDat->SetBoundaryDistance(chosenSite, chosenWallDirection, assignedWallDistance); latDat->SetBoundaryDistance(chosenSite, chosenDoubleWallDirection1, assignedWallDistance); latDat->SetBoundaryDistance(chosenSite, chosenDoubleWallDirection2, assignedWallDistance); // Perform the collision and streaming. guoZhengShi.StreamAndCollide<false> (chosenSite, 1, lbmParams, latDat, *propertyCache); // Check each streamed direction. for (Direction streamedDirection = 0; streamedDirection < lb::lattices::D3Q15::NUMVECTORS; ++streamedDirection) { // Calculate the distributions at the chosen site up to post-collision. distribn_t streamerFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(chosenSite, streamerFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > streamerHydroVars(streamerFOld); normalCollision->CalculatePreCollision(streamerHydroVars, streamer); normalCollision->Collide(lbmParams, streamerHydroVars); // Calculate the streamed-to index. const site_t streamedIndex = streamer.GetStreamedIndex<lb::lattices::D3Q15> (streamedDirection); // Check that simple collide and stream has happened when appropriate. // Is streamerIndex a valid index? (And is it not in one of the directions // that has been meddled with for the test)? if (!streamer.HasBoundary(streamedDirection) && streamedIndex >= 0 && streamedIndex < (lb::lattices::D3Q15::NUMVECTORS * latDat->GetLocalFluidSiteCount())) { distribn_t streamedToFNew = *latDat->GetFNew(streamedIndex); // F_new should be equal to the value that was streamed from this other site // in the same direction as we're streaming from. CPPUNIT_ASSERT_DOUBLES_EQUAL(streamerHydroVars.GetFPostCollision()[streamedDirection], streamedToFNew, allowedError); } bool isDoubleWallDirection = ( (streamedDirection == chosenDoubleWallDirection1) || (streamedDirection == chosenDoubleWallDirection2)); // Next, handle the case where this is the direction where we're checking for // behaviour with a wall. I.e. are we correctly filling distributions that aren't // streamed-to by simple streaming? if (streamedDirection == chosenUnstreamedDirection || isDoubleWallDirection) { // Get f old at the two sites that may be relevant, and calculate their hydrodynamic // vars. distribn_t streamerFOld[lb::lattices::D3Q15::NUMVECTORS], nextSiteOutFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(chosenSite, streamerFOld); LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(nextSiteAwayFromWall, nextSiteOutFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > streamerHydroVars(streamerFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > nextSiteOutHydroVars(nextSiteOutFOld); normalCollision->CalculatePreCollision(streamerHydroVars, streamer); normalCollision->CalculatePreCollision(nextSiteOutHydroVars, nextSiteAway); // Next we calculate the velocity and f_neq at the hypothetical wall site. util::Vector3D<distribn_t> velocityWall; distribn_t fNeqWall; if (assignedWallDistance < 0.75 && !isDoubleWallDirection) { // This is the first means of estimating from the source paper: only // use the nearest fluid site. util::Vector3D<distribn_t> velocityEstimate1 = streamerHydroVars.momentum * (1. - 1. / assignedWallDistance) / streamerHydroVars.density; distribn_t fNeqEstimate1 = streamerHydroVars.GetFNeq()[streamedDirection]; // This is the second method for estimating: using the next fluid site // away from the wall. util::Vector3D<distribn_t> velocityEstimate2 = nextSiteOutHydroVars.momentum * (assignedWallDistance - 1.) / ( (1. + assignedWallDistance) * nextSiteOutHydroVars.density); distribn_t fNeqEstimate2 = nextSiteOutHydroVars.GetFNeq()[streamedDirection]; // The actual value is taken to be an interpolation between the two // estimates. velocityWall = velocityEstimate1 * assignedWallDistance + velocityEstimate2 * (1. - assignedWallDistance); fNeqWall = assignedWallDistance * fNeqEstimate1 + (1. - assignedWallDistance) * fNeqEstimate2; } else { velocityWall = streamerHydroVars.momentum * (1. - 1. / assignedWallDistance) / streamerHydroVars.density; fNeqWall = streamerHydroVars.GetFNeq()[streamedDirection]; } // Get the value to compare against, calculate eqm distribn. distribn_t streamedFNew = latDat->GetFNew(lb::lattices::D3Q15::NUMVECTORS * chosenSite)[streamedDirection]; util::Vector3D<distribn_t> momentumWall = velocityWall * streamerHydroVars.density; distribn_t fEqm[lb::lattices::D3Q15::NUMVECTORS]; lb::lattices::D3Q15::CalculateFeq(streamerHydroVars.density, momentumWall.x, momentumWall.y, momentumWall.z, fEqm); CPPUNIT_ASSERT_DOUBLES_EQUAL(streamedFNew, fEqm[streamedDirection] + (1.0 + lbmParams->GetOmega()) * fNeqWall, allowedError); } } } } /** * Junk&Yang should behave like simple bounce back when fluid sites are 0.5 lattice length units away * from the domain boundary. */ void TestJunkYangEquivalentToBounceBack() { // Initialise fOld in the lattice data. We choose values so that each site has // an anisotropic distribution function, and that each site's function is // distinguishable. LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(latDat); // Setting all the wall distances to 0.5 will make Junk&Yang behave like Simple Bounce Back LbTestsHelper::SetWallAndIoletDistances<lb::lattices::D3Q15>(*latDat, 0.5); site_t firstWallSite = latDat->GetMidDomainCollisionCount(0); site_t wallSitesCount = latDat->GetMidDomainCollisionCount(1) - firstWallSite; // Check that the lattice has sites labeled as wall (otherwise this test is void) CPPUNIT_ASSERT_EQUAL_MESSAGE("Number of non-wall sites", wallSitesCount, (site_t) 16); site_t offset = 0; // Mid-Fluid sites use simple collide and stream lb::streamers::SimpleCollideAndStream<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > simpleCollideAndStream(initParams); simpleCollideAndStream.StreamAndCollide<false> (offset, latDat->GetMidDomainCollisionCount(0), lbmParams, latDat, *propertyCache); offset += latDat->GetMidDomainCollisionCount(0); // Wall sites use junk and yang lb::streamers::JunkYang<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > junkYang(initParams); junkYang.StreamAndCollide<false> (offset, latDat->GetMidDomainCollisionCount(1), lbmParams, latDat, *propertyCache); junkYang.PostStep<false> (offset, latDat->GetMidDomainCollisionCount(1), lbmParams, latDat, *propertyCache); offset += latDat->GetMidDomainCollisionCount(1); // Consider inlet/outlets and their walls as mid-fluid sites simpleCollideAndStream.StreamAndCollide<false> (offset, latDat->GetLocalFluidSiteCount() - offset, lbmParams, latDat, *propertyCache); offset += latDat->GetLocalFluidSiteCount() - offset; // Sanity check CPPUNIT_ASSERT_EQUAL_MESSAGE("Total number of sites", offset, latDat->GetLocalFluidSiteCount()); /* * Loop over the wall sites and check whether they got properly streamed on or bounced back * depending on where they sit relative to the wall. We ignore mid-Fluid sites since * StreamAndCollide was tested before. */ for (site_t wallSiteLocalIndex = 0; wallSiteLocalIndex < wallSitesCount; wallSiteLocalIndex++) { site_t streamedToSite = firstWallSite + wallSiteLocalIndex; const geometry::Site streamedSite = latDat->GetSite(streamedToSite); distribn_t* streamedToFNew = latDat->GetFNew(lb::lattices::D3Q15::NUMVECTORS * streamedToSite); for (unsigned int streamedDirection = 0; streamedDirection < lb::lattices::D3Q15::NUMVECTORS; ++streamedDirection) { unsigned oppDirection = lb::lattices::D3Q15::INVERSEDIRECTIONS[streamedDirection]; // Index of the site streaming to streamedToSite via direction streamedDirection site_t streamerIndex = streamedSite.GetStreamedIndex<lb::lattices::D3Q15> (oppDirection); // Is streamerIndex a valid index? if (streamerIndex >= 0 && streamerIndex < (lb::lattices::D3Q15::NUMVECTORS * latDat->GetLocalFluidSiteCount())) { // The streamer index is a valid index in the domain, therefore stream and collide has happened site_t streamerSiteId = streamerIndex / lb::lattices::D3Q15::NUMVECTORS; // Calculate streamerFOld at this site. distribn_t streamerFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(streamerSiteId, streamerFOld); // Calculate what the value streamed to site streamedToSite should be. lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > streamerHydroVars(streamerFOld); normalCollision->CalculatePreCollision(streamerHydroVars, streamedSite); normalCollision->Collide(lbmParams, streamerHydroVars); // F_new should be equal to the value that was streamed from this other site // in the same direction as we're streaming from. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SimpleCollideAndStream, StreamAndCollide", streamerHydroVars.GetFPostCollision()[streamedDirection], streamedToFNew[streamedDirection], allowedError); } else { // The streamer index shows that no one has streamed to streamedToSite direction // streamedDirection, therefore bounce back has happened in that site for that direction // Initialise streamedToSiteFOld with the original data distribn_t streamerToSiteFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(streamedToSite, streamerToSiteFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > hydroVars(streamerToSiteFOld); normalCollision->CalculatePreCollision(hydroVars, streamedSite); // Simulate post-collision using the collision operator. normalCollision->Collide(lbmParams, hydroVars); // After streaming FNew in a given direction must be f post-collision in the opposite direction // following collision std::stringstream msg; msg << "Junk&Yang bounce-back equivalent: site " << streamedToSite << " direction " << streamedDirection; CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(msg.str(), streamedToFNew[streamedDirection], hydroVars.GetFPostCollision()[oppDirection], allowedError); } } } } void TestRegularisedIolet() { lb::boundaries::BoundaryValues inletBoundary(geometry::INLET_TYPE, latDat, simConfig->GetInlets(), simState, unitConverter); initParams.boundaryObject = &inletBoundary; lb::streamers::RegularisedIolet<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > regularisedIolet(initParams); for (double assignedWallDistance = 0.4; assignedWallDistance < 1.0; assignedWallDistance += 0.5) { // Initialise fOld in the lattice data. We choose values so that each site has // an anisotropic distribution function, and that each site's function is // distinguishable. LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(latDat); // Make some fairly arbitrary choices early on. const site_t chosenSite = 0; const int chosenBoundaryId = 0; const geometry::Site& streamer = latDat->GetSite(chosenSite); const Direction chosenUnstreamedDirection = 5; const Direction chosenIoletDirection = lb::lattices::D3Q15::INVERSEDIRECTIONS[chosenUnstreamedDirection]; const util::Vector3D<distribn_t> ioletNormal = inletBoundary.GetLocalIolet(chosenBoundaryId)->GetNormal(); // Enforce that there's a boundary in the iolet direction. latDat->SetHasIolet(chosenSite, chosenIoletDirection); latDat->SetBoundaryDistance(chosenSite, chosenIoletDirection, assignedWallDistance); latDat->SetBoundaryNormal(chosenSite, ioletNormal); latDat->SetBoundaryId(chosenSite, chosenBoundaryId); // Perform the collision and streaming. regularisedIolet.StreamAndCollide<false> (chosenSite, 1, lbmParams, latDat, *propertyCache); // Check each streamed direction. for (Direction streamedDirection = 0; streamedDirection < lb::lattices::D3Q15::NUMVECTORS; ++streamedDirection) { // Calculate the distributions at the chosen site up to post-collision. distribn_t streamerFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(chosenSite, streamerFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > streamerHydroVars(streamerFOld); normalCollision->CalculatePreCollision(streamerHydroVars, streamer); normalCollision->Collide(lbmParams, streamerHydroVars); // Calculate the streamed-to index. const site_t streamedIndex = streamer.GetStreamedIndex<lb::lattices::D3Q15> (streamedDirection); // Check that simple collide and stream has happened when appropriate. // Is streamerIndex a valid index? (And is it not in one of the directions // that has been meddled with for the test)? if (!streamer.HasIolet(streamedDirection) && streamedIndex >= 0 && streamedIndex < (lb::lattices::D3Q15::NUMVECTORS * latDat->GetLocalFluidSiteCount())) { distribn_t streamedToFNew = *latDat->GetFNew(streamedIndex); // F_new should be equal to the value that was streamed from this other site // in the same direction as we're streaming from. CPPUNIT_ASSERT_DOUBLES_EQUAL(streamerHydroVars.GetFPostCollision()[streamedDirection], streamedToFNew, allowedError); } // Next, handle the case where this is the direction where we're checking for // behaviour with a wall. I.e. are we correctly filling distributions that aren't // streamed-to by simple streaming? if (streamedDirection == chosenUnstreamedDirection) { // The streamer works by assuming the presence of a 'ghost' site, just beyond the // iolet. The density of the ghost site is extrapolated from the iolet density // and the density of the fluid site. distribn_t ghostSiteDensity = inletBoundary.GetBoundaryDensity(chosenBoundaryId); // The velocity of the ghost site is the component of the fluid site's velocity // along the iolet normal. util::Vector3D<distribn_t> ghostSiteVelocity = ioletNormal * (streamerHydroVars.momentum / streamerHydroVars.density).Dot(ioletNormal); util::Vector3D<distribn_t> ghostSiteMomentum = ghostSiteVelocity * ghostSiteDensity; distribn_t ghostPostCollision[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::CalculateLBGKEqmF<lb::lattices::D3Q15>(ghostSiteDensity, ghostSiteMomentum.x, ghostSiteMomentum.y, ghostSiteMomentum.z, ghostPostCollision); CPPUNIT_ASSERT_DOUBLES_EQUAL(latDat->GetFNew(chosenSite * lb::lattices::D3Q15::NUMVECTORS)[chosenUnstreamedDirection], ghostPostCollision[chosenUnstreamedDirection], allowedError); } } } } void TestNashBB() { lb::boundaries::BoundaryValues inletBoundary(geometry::INLET_TYPE, latDat, simConfig->GetInlets(), simState, unitConverter); initParams.boundaryObject = &inletBoundary; lb::streamers::NashBB<lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> > > regularisedIolet(initParams); for (double assignedIoletDistance = 0.4; assignedIoletDistance < 1.0; assignedIoletDistance += 0.5) { // Initialise fOld in the lattice data. We choose values so that each site has // an anisotropic distribution function, and that each site's function is // distinguishable. LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(latDat); // Make some fairly arbitrary choices early on. const site_t chosenSite = 0; const int chosenBoundaryId = 0; const geometry::Site& streamer = latDat->GetSite(chosenSite); const Direction chosenWallDirection = 11; const Direction chosenUnstreamedDirection = 5; const Direction chosenIoletDirection = lb::lattices::D3Q15::INVERSEDIRECTIONS[chosenUnstreamedDirection]; const util::Vector3D<distribn_t> ioletNormal = inletBoundary.GetLocalIolet(chosenBoundaryId)->GetNormal(); // Enforce that there's a boundary in the iolet direction. latDat->SetHasIolet(chosenSite, chosenIoletDirection); latDat->SetHasBoundary(chosenSite, chosenWallDirection); latDat->SetBoundaryDistance(chosenSite, chosenIoletDirection, assignedIoletDistance); latDat->SetBoundaryNormal(chosenSite, ioletNormal); latDat->SetBoundaryId(chosenSite, chosenBoundaryId); // Perform the collision and streaming. regularisedIolet.StreamAndCollide<false> (chosenSite, 1, lbmParams, latDat, *propertyCache); // Check each streamed direction. for (Direction streamedDirection = 0; streamedDirection < lb::lattices::D3Q15::NUMVECTORS; ++streamedDirection) { // Calculate the distributions at the chosen site up to post-collision. distribn_t streamerFOld[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::InitialiseAnisotropicTestData<lb::lattices::D3Q15>(chosenSite, streamerFOld); lb::kernels::HydroVars<lb::kernels::LBGK<lb::lattices::D3Q15> > streamerHydroVars(streamerFOld); normalCollision->CalculatePreCollision(streamerHydroVars, streamer); normalCollision->Collide(lbmParams, streamerHydroVars); // Calculate the streamed-to index. const site_t streamedIndex = streamer.GetStreamedIndex<lb::lattices::D3Q15> (streamedDirection); // Check that simple collide and stream has happened when appropriate. // Is streamerIndex a valid index? (And is it not in one of the directions // that has been meddled with for the test)? if (!streamer.HasIolet(streamedDirection) && !streamer.HasBoundary(streamedDirection) && streamedIndex >= 0 && streamedIndex < (lb::lattices::D3Q15::NUMVECTORS * latDat->GetLocalFluidSiteCount())) { distribn_t streamedToFNew = *latDat->GetFNew(streamedIndex); // F_new should be equal to the value that was streamed from this other site // in the same direction as we're streaming from. CPPUNIT_ASSERT_DOUBLES_EQUAL(streamerHydroVars.GetFPostCollision()[streamedDirection], streamedToFNew, allowedError); } Direction inverseDirection = lb::lattices::D3Q15::INVERSEDIRECTIONS[streamedDirection]; // Check the case by a wall. if (streamer.HasBoundary(streamedDirection)) { distribn_t streamedToFNew = *latDat->GetFNew(lb::lattices::D3Q15::NUMVECTORS * chosenSite + inverseDirection); CPPUNIT_ASSERT_DOUBLES_EQUAL(streamerHydroVars.GetFPostCollision()[streamedDirection], streamedToFNew, allowedError); } // Next, handle the case where this is the direction where we're checking for // behaviour with a iolet. I.e. are we correctly filling distributions that aren't // streamed-to by simple streaming? if (streamedDirection == chosenUnstreamedDirection) { // The streamer works by assuming the presence of a 'ghost' site, just beyond the // iolet. The density of the ghost site is extrapolated from the iolet density // and the density of the fluid site. distribn_t ghostSiteDensity = inletBoundary.GetBoundaryDensity(chosenBoundaryId); // The velocity of the ghost site is the component of the fluid site's velocity // along the iolet normal. util::Vector3D<distribn_t> ghostSiteVelocity = ioletNormal * (streamerHydroVars.momentum / streamerHydroVars.density).Dot(ioletNormal); util::Vector3D<distribn_t> ghostSiteMomentum = ghostSiteVelocity * ghostSiteDensity; distribn_t ghostPostCollision[lb::lattices::D3Q15::NUMVECTORS]; LbTestsHelper::CalculateLBGKEqmF<lb::lattices::D3Q15>(ghostSiteDensity, ghostSiteMomentum.x, ghostSiteMomentum.y, ghostSiteMomentum.z, ghostPostCollision); CPPUNIT_ASSERT_DOUBLES_EQUAL(latDat->GetFNew(chosenSite * lb::lattices::D3Q15::NUMVECTORS)[chosenUnstreamedDirection], ghostPostCollision[chosenUnstreamedDirection], allowedError); } } } } private: lb::MacroscopicPropertyCache* propertyCache; lb::collisions::Normal<lb::kernels::LBGK<lb::lattices::D3Q15> >* normalCollision; }; CPPUNIT_TEST_SUITE_REGISTRATION( StreamerTests); } } } #endif /* HEMELB_UNITTESTS_LBTESTS_STREAMERTESTS_H */
import { useState } from 'react'; import './App.scss' import Container from '@mui/material/Container' import CircularProgress from '@mui/material/CircularProgress'; import PastLaunchesGrid from './past-launches-grid/PastLaunchesGrid'; import { LaunchModel } from './models/LaunchModel'; import SearchBox from './search-form/SearchForm'; import SearchResult from './search-result/SearchResult'; import useLoadPastLaunches from './hooks/useLoadPastLaunches'; function App() { const [launchResult, setLaunchResult] = useState({}); const [launchResultError, setLaunchResultError] = useState({}); const AppState = { launchResult, setLaunchResult, launchResultError, setLaunchResultError, }; const { data, loadingPastLaunches } = useLoadPastLaunches({ quantity: 3 }); const launches: LaunchModel[] = data ? data.docs : []; return ( <Container fixed> <SearchBox AppState={AppState} /> <SearchResult AppState={AppState} /> {loadingPastLaunches ? ( <CircularProgress className='loading-spinner'/> ) : ( <PastLaunchesGrid launches={launches} /> )} </Container> ); } export default App
# Ingenio DevOps test ## Table of Contents - [Table of Contents](#table-of-contents) - [Summary](#summary) - [Architecture](#architecture) - [Infrastructure as Code](#infrastructure-as-code) - [Kubernetes](#kubernetes) - [Continuous Integration & Continuous Deployment](#continuous-integration--continuous-deployment) - [Artifacts](#artifacts) - [Improvements](#improvements) ## Summary This repo contains the necessary code to deploy the Ingenio DevOps test, which encourages people to use best practices to deploy an application to an environment that's fully automated, scalable, high available and reliable. **Notes:** - Due to the ammount of testing done, using the real Let'sEncrypt server, domain snwbr.net got blocked a couple of times. At the time of reading, sites such as https://snwbr.net/ may present you an invalid cert, that if you check using Chrome, it will show you it's not invalid, but using Let'sEncrypt staging servers (which is the one should be used for development purposes). Real certificates can be enabled by changing `name: ingress-staging` to `name: ingress` in the ingress controller's [issuers](k8s/charts/hello-world/templates/ingress.yaml), commit, push to `main` and it will be applied by GitHub Actions. - **IMPORTANT**: In order to avoid costs associated with having GKE and instances running up, I destroyed the GKE cluster. It can be easily put it back with all the stack in minutes. Please create a [Github issue](https://github.com/snwbr/gl-test/issues/new) saying you want the environment up and I'll create it as soon as I see the issue and reply it back when's done. ## Architecture ### Toolset and technologies - Cloud provider: Google Cloud - Infrastructure as Code: Terraform - CI/CD: Github Actions - K8s teamplating: kustomize - K8s installation manager: Helm - Reverse proxy, routing, service discovery and TLS termination: GCE (for quickness, but I don't like it honestly) - K8s CNI: Calico - Certificates management: Cert-manager - Domain provider: Google Domains ### High level architecture diagram TBD ## Infrastructure as Code For creating objects in the cloud, Terraform was chosen. Terraform code is splitted by enviornments (see the [README](terraform/README.md)). Terraform manages the construction of the Virtual Private Network, as well as the Identity-Aware Proxy (Cloud IAP) to connect from remote locations to the private network resources. Also, the GCP project's API are managed through Terraform. Rest of objects (firewall rules, dns names, NAT, routers, service accounts, etc) are part of it. ## Kubernetes During this challenge, Google Kubernetes Enginer (GKE) was chosen. The configuration is as follows: - Private cluster, with no direct access to internet (no node has public IP). - Node autoscaling is enabled in prod, for High Availability. It is disabled in dev due to costs. - Terraform-managed nodepool. - Ingress is served through default GCE. - One single service using a public IP through a LoadBalancer K8s service which is the only source of access to K8s services. - Internet access is provider at VPC level through a Router using NAT. - SSL Certificates for the application are managed through cert-manager, auto-renewing when needed. - Services and pods interconnections is done through internal routing and DNS. ## Continuous Integration & Continuous Deployment Github Actions runs mainly during two important SDLC phases: - **Git push to branch:** GHA listens to the repo and build every push to the monitored branches (develop and main). - If the branch that gets the push (or merge) event is "main", GHA will not only run the CI pipeline (build, validate and test) but the CD pipeline as well (deploy the code to K8s). - **Pull requests creation:** GHA detects any pull request created, checks out the pull request data and then it runs the CI pipeline. Results of the run are reported back to Github to decision on whether or not to merge into "main". ## Artifacts The main artifacts created by GHA are the docker images to be deployed. ## Improvements To stick to the challenge request and deliver it on time, a good ammount of good practices were not done, but they're not heavily required for a demo purpose. Still though, they're listed here as things I would improve to this solution: - Addition of an OAuth or an authentication forward to some authentication service at load balancer or Traefik layers. - Addition of proper liveness and readiness probes to K8s deployments. - Creation a secret management tool such as Vault. - Split Terraform code from K8s into different repositories to be able to manage them through different access controls and strategies. - Introduce security vulnerabilities scan to generated docker images. - Added some lint rules to code (SonarQube perhaps). - Implementing monitoring and alerting to the stack (through Prometheus & Grafana or New Relic if there is a license for that). - Adding a logging stack, either EFK or stackdriver metrics (because it's in Google). - Configure apps and/or managed objects using ansible. - Adding Atlantis for TF plan/apply via Github PRs (and achieve true GitOps). - Creation of granular RBAC rules through all the tools and processes. - Add more testing (unit, integration, contract, E2E, regression, performance/stress, smoke, etc). - Use of tools like terragrunt for managing multiple environments. - Use of Cillium for eBPF enhanced traceability and service mesh, or at least some router like Traefik.
{% extends 'main.html' %} {% load static %} {% block content %} <!--------------------------------------- mini navbar ---------------------------------------> <nav class="mb-4 mx-auto flex flex-wrap items-center gap-2 items-center text-xs w-full max-w-[1350px]" > <a href="{{request.META.HTTP_REFERER}}" class="px-4 py-3 bg-black text-white hover:bg-yellow-400 hover:text-black rounded-md flex justify-between items-center transition duration-300 ease-in-out" ><i class="fa-solid fa-arrow-left"></i ></a> {% if curr_partner and not form %} <!-- --> {% if user == curr_partner.user or user.role.sec_level >= 3 %} <a href="{% url 'edit_partner' curr_partner.id %}" class="px-4 py-3 bg-black text-white hover:bg-green-600 rounded-md flex justify-between items-center transition duration-300 ease-in-out" >Modifier<i class="fa-solid fa-pen-to-square ml-4"></i ></a> {% endif %} <!-- --> {% if user.role.sec_level >= 3 %} <a href="{% url 'delete_partner' curr_partner.id %}" id="delete_btn" onclick="return confirm('Voulez vous continuer avec la suppression')" class="px-4 py-3 bg-black text-white hover:bg-red-700 rounded-md flex justify-between items-center transition duration-300 ease-in-out" >Supprimer<i class="fa-solid fa-trash ml-4"></i ></a> <form action="{% url 'partner_activation' curr_partner.id %}" method="POST"> {% csrf_token %} <!-- --> {% if curr_partner.is_active == False %} <input type="submit" value="Activer" class="px-4 py-3 bg-black text-white hover:bg-green-600 rounded-md flex justify-between items-center transition duration-300 ease-in-out cursor-pointer" /> {% else %} <input type="submit" value="Désactiver" class="px-4 py-3 bg-black text-white hover:bg-red-700 rounded-md flex justify-between items-center transition duration-300 ease-in-out cursor-pointer" /> {% endif %} </form> {% endif %} <!-- --> {% endif %} </nav> {% if not form %} <!--------------------------------------- partner layout ---------------------------------------> <section class="mb-4 flex flex-col justify-between items-start gap-4"> <div class="md:flex gap-4 w-full"> {% if not curr_partner.image %} <img class="mb-4 h-[320px] w-full md:w-[320px] rounded-md object-cover" src="{% static 'imgs/partner.jpg' %}" alt="partner image" /> {% else %} <img class="mb-4 h-[320px] w-full md:w-[320px] rounded-md object-cover" src="{{curr_partner.image.url}}" alt="partner image" /> {% endif %} <!-- --> <div class="h-[320px] w-full bg-black text-gray-300 text-sm p-6 rounded-md flex flex-col gap-2 overflow-hidden" > <h4 class="text-white text-xl font-bold flex items-center"> {{curr_partner.civility}} {{curr_partner.last_name}} {{curr_partner.first_name}} <img class="mx-2 h-4" src="{{curr_partner.nationality.flag}}" /> ({{curr_partner.nationality}}) </h4> <p class="pt-2"> {{curr_partner.city}} | Commission : {{curr_partner.commission}} % </p> <div class="flex items-center gap-4"> <a href="tel:{{curr_partner.phone}}" target="_blank" class="px-4 py-2 rounded-md bg-white hover:bg-green-300 text-black" > <i class="fa-solid fa-phone mr-2"></i>{{curr_partner.phone}} </a> <a href="{% url 'chat_page' curr_partner.user.id %}" class="px-4 py-2 rounded-md bg-white hover:bg-amber-300 text-black" > <i class="fa-solid fa-comments mr-2"></i> Contacter </a> </div> <p class="pt-2">{{curr_partner.bio}}</p> </div> <!-- --> </div> </section> <!--------------------------------------- related stuff ---------------------------------------> <div class="customtab mx-auto mb-4 p-1 bg-black rounded-md flex justify-between gap-1 w-full text-sm" > <button class="tablinks py-1 bg-white hover:bg-black text-black hover:text-white rounded-sm w-full" onclick="openTab(event, 'docs')" id="defaultOpen" > <i class="fa-solid fa-folder-open lg:mr-2"></i> <span class="hidden xl:inline">Documents</span> </button> <button class="tablinks py-1 bg-white hover:bg-black text-black hover:text-white rounded-sm w-full" onclick="openTab(event, 'vehicles')" > <i class="fa-solid fa-taxi lg:mr-2"></i> <span class="hidden xl:inline">Véhicules</span> </button> <button class="tablinks py-1 bg-white hover:bg-black text-black hover:text-white rounded-sm w-full" onclick="openTab(event, 'payments')" > <i class="fa-solid fa-coins lg:mr-2"></i> <span class="hidden xl:inline">Recettes</span> </button> <button class="tablinks py-1 bg-white hover:bg-black text-black hover:text-white rounded-sm w-full" onclick="openTab(event, 'revenues')" > <i class="fa-solid fa-circle-dollar-to-slot lg:mr-2"></i> <span class="hidden xl:inline">Revenues</span> </button> <button class="tablinks py-1 bg-white hover:bg-black text-black hover:text-white rounded-sm w-full" onclick="openTab(event, 'stats')" > <i class="fa-solid fa-chart-pie lg:mr-2"></i> <span class="hidden xl:inline">Statistiques</span> </button> </div> <!--------------------------------------- related documents ---------------------------------------> <section id="docs" class="tabcontent w-full bg-white p-6 rounded-md"> {% if user.role.sec_level >= 1 %} <a href="{% url 'create_pdoc' %}" class="px-4 py-3 bg-black text-white text-xs hover:bg-amber-300 hover:text-black rounded-md items-center transition duration-300 ease-in-out" >Ajouter un document<i class="fa-solid fa-plus ml-4"></i ></a> {% endif %} <div class="w-full mx-auto my-8"> {% if not documents %} <!--------------------------------------- No data placeholder ---------------------------------------> {% include 'components/no_data.html' %} <!-- --> {% else %} <!--------------------------------------- documents ---------------------------------------> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8" > {% for obj in documents %} <div class="relative flex flex-col border border-2 hover:border-gray-800 bg-white rounded-md transition duration-300 ease-in-out overflow-hidden" > {% if obj.is_valid %} <span class="absolute top-2 right-2 px-2 py-1 rounded-md bg-green-600 text-xs text-white" > <i class="fa-solid fa-check text-white"></i> </span> {% else %} <span class="absolute top-2 right-2 px-2 py-1 rounded-md bg-red-600 text-xs text-white" > <i class="fa-solid fa-question text-white"></i> </span> {% endif %} <a href="{% url 'partner_doc' obj.id %}"> <div class="p-6 flex flex-col justify-between"> <h4 class="text-black text-md font-bold">{{obj.type.name}}</h4> <p class="pt-2 text-sm"> {{obj.partner.last_name}} {{obj.partner.first_name}} </p> <p class="pt-2 text-sm">{{obj.date_posted.date}}</p> </div> </a> </div> {% endfor %} </div> {% endif %} </div> </section> <!--------------------------------------- related vehicles ---------------------------------------> <section id="vehicles" class="tabcontent w-full bg-white p-6 rounded-md"> {% if user.role.sec_level >= 1 %} <a href="{% url 'create_vehicle' %}" class="px-4 py-3 bg-black text-white text-xs hover:bg-amber-300 hover:text-black rounded-md items-center transition duration-300 ease-in-out" >Ajouter un véhicule<i class="fa-solid fa-plus ml-4"></i ></a> {% endif %} <div class="w-full mx-auto my-8"> {% if not vehicles %} <!--------------------------------------- No data placeholder ---------------------------------------> {% include 'components/no_data.html' %} <!-- --> {% else %} <!--------------------------------------- v_docs ---------------------------------------> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8"> {% for obj in vehicles %} <div class="relative flex flex-col border border-2 hover:border-gray-800 bg-white rounded-md transition duration-300 ease-in-out overflow-hidden" > {% if obj.is_active %} <span class="absolute top-2 right-2 px-2 py-1 rounded-md bg-green-600 text-xs text-white" > <i class="fa-solid fa-check text-white"></i> </span> {% else %} <span class="absolute top-2 right-2 px-2 py-1 rounded-md bg-red-600 text-xs text-white" > <i class="fa-solid fa-question text-white"></i> </span> {% endif %} <a href="{% url 'vehicle' obj.plate_number %}"> <div class="p-6 flex flex-col justify-between"> <h4 class="text-black text-md font-bold"> {{obj.make}} {{obj.model}} ({{obj.year}}) </h4> <p class="pt-2 text-sm">[-{{obj.plate_number}}-]</p> </div> </a> </div> {% endfor %} </div> {% endif %} </div> </section> <!--------------------------------------- related payments ---------------------------------------> <section id="payments" class="tabcontent w-full bg-white p-6 rounded-md"> {% if user.role.sec_level >= 3 %} <a href="{% url 'create_payment' %}" class="px-4 py-3 bg-black text-white text-xs hover:bg-amber-300 hover:text-black rounded-md items-center transition duration-300 ease-in-out" >Ajouter une recette<i class="fa-solid fa-plus ml-4"></i ></a> {% endif %} <div class="w-full mx-auto my-8"> {% if not payments %} <!--------------------------------------- No data placeholder ---------------------------------------> {% include 'components/no_data.html' %} <!-- --> {% else %} <!--------------------------------------- payments ---------------------------------------> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4"> {% for obj in payments %} <div class="relative flex flex-col border border-2 hover:border-gray-800 bg-white rounded-md transition duration-300 ease-in-out overflow-hidden" > {% if obj.is_audited %} <span class="absolute top-2 right-2 px-2 py-1 rounded-md bg-green-600 text-xs text-white" > <i class="fa-solid fa-check text-white"></i> </span> {% else %} <span class="absolute top-2 right-2 px-2 py-1 rounded-md bg-red-600 text-xs text-white" > <i class="fa-solid fa-question text-white"></i> </span> {% endif %} <a href="{% url 'payment' obj.id %}"> <div class="p-6 flex flex-col justify-between"> <h4 class="text-black text-md font-bold">{{obj.amount}} CFA</h4> <tt class="mt-2 text-sm font-bold"> {{obj.driver.last_name}} {{obj.driver.first_name}} </tt> <p class="mt-2 text-sm"> {{obj.date}} de {{obj.start_time}} à {{obj.end_time}} </p> </div> </a> </div> {% endfor %} </div> {% endif %} </div> </section> <!--------------------------------------- related revenues ---------------------------------------> <section id="revenues" class="tabcontent w-full bg-white p-6 rounded-md"> {% if user.role.sec_level >= 3 %} <a href="{% url 'create_revenue' %}" class="px-4 py-3 bg-black text-white text-xs hover:bg-amber-300 hover:text-black rounded-md items-center transition duration-300 ease-in-out" >Ajouter une recette<i class="fa-solid fa-plus ml-4"></i ></a> {% endif %} <div class="w-full mx-auto my-8"> {% if not revenues %} <!--------------------------------------- No data placeholder ---------------------------------------> {% include 'components/no_data.html' %} <!-- --> {% else %} <!--------------------------------------- revenues ---------------------------------------> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4"> {% for obj in revenues %} <div class="relative flex flex-col border border-2 hover:border-gray-800 bg-white rounded-md transition duration-300 ease-in-out overflow-hidden" > {% if obj.is_audited %} <span class="absolute top-2 right-2 px-2 py-1 rounded-md bg-green-600 text-xs text-white" > <i class="fa-solid fa-check text-white"></i> </span> {% else %} <span class="absolute top-2 right-2 px-2 py-1 rounded-md bg-red-600 text-xs text-white" > <i class="fa-solid fa-question text-white"></i> </span> {% endif %} <a href="{% url 'payment' obj.id %}"> <div class="p-6 flex flex-col justify-between"> <h4 class="text-black text-md font-bold"> Net : {{obj.net_income}} CFA </h4> <h4 class="text-black text-sm">Brut : {{obj.gross_income}} CFA</h4> <tt class="mt-2 text-sm font-bold"> {{obj.month}} {{obj.year}} </tt> <!-- <p class="mt-2 text-sm">De {{obj.startdate}} à {{obj.enddate}}</p> --> </div> </a> </div> {% endfor %} </div> {% endif %} </div> </section> <!--------------------------------------- stats ---------------------------------------> <section id="stats" class="tabcontent w-full bg-black p-6 rounded-md"> <div class="text-gray-300 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8" > <div class="p-6 flex flex-col justify-between"> <h4 class="text-green-500 text-xl font-bold">{{total_revenu}} CFA</h4> <p class="mt-2 text-sm">Revenu Brut</p> </div> <div class="p-6 flex flex-col justify-between"> <h4 class="text-red-500 text-xl font-bold">{{total_expenses}} CFA</h4> <p class="mt-2 text-sm">Dépenses</p> </div> <div class="p-6 flex flex-col justify-between"> <h4 class="text-amber-400 text-xl font-bold"> {{curr_partner.commission}}% <span class="text-sm text-white font-light" >de {{net_revenu}} <br /> ≈</span > <tt>{{commission}}</tt> </h4> <p class="mt-2 text-sm">Commissions</p> </div> <div class="p-6 flex flex-col justify-between"> {% if total_net < 0 %} <h4 class="text-red-500 text-xl font-bold">{{total_net}} CFA</h4> {% else %} <h4 class="text-green-500 text-xl font-bold">{{total_net}} CFA</h4> {% endif %} <p class="mt-2 text-sm">Revenu Net</p> </div> </div> </section> {% else %} <section class="mb-4 p-4 lg:p-8 flex gap-4 lg:gap-8 bg-white w-full mx-auto rounded-md text-sm" > <div class="w-full"> {% if curr_partner %} <h3 class="mb-4 text-black text-2xl font-bold">Modifier ce partenaire</h3> {% else %} <h3 class="mb-4 text-black text-2xl font-bold">Nouveau partenaire</h3> {% endif %} <form class="w-full flex flex-col justify-between gap-6" method="POST" action="" enctype="multipart/form-data" > {% csrf_token %} <!-- --> <div class="grid grid-cols-1 xl:grid-cols-2 gap-4"> {% if curr_partner %} <div class="hidden"> <h3>{{form.user.label}}</h3> {{form.user}} </div> <div class="hidden"> <h3>{{form.is_active.label}}</h3> {{form.is_active}} </div> {% else %} <div> <h3 class="mb-1">{{form.user.label}}</h3> {{form.user}} </div> {% endif %} <div> <h3 class="mb-1">{{form.civility.label}}</h3> {{form.civility}} </div> <div> <h3 class="mb-1">{{form.martital_status.label}}</h3> {{form.martital_status}} </div> <div> <h3 class="mb-1">{{form.last_name.label}}</h3> {{form.last_name}} </div> <div> <h3 class="mb-1">{{form.first_name.label}}</h3> {{form.first_name}} </div> <!-- --> <div> <h3 class="mb-1">{{form.nationality.label}}</h3> {{form.nationality}} </div> <div> <h3 class="mb-1">{{form.date_of_birth.label}}</h3> {{form.date_of_birth}} </div> <div> <h3 class="mb-1">{{form.place_of_birth.label}}</h3> {{form.place_of_birth}} </div> <div> <h3 class="mb-1">{{form.city.label}}</h3> {{form.city}} </div> <!-- --> <div> <h3 class="mb-1">{{form.address.label}}</h3> {{form.address}} </div> <div> <h3 class="mb-1">{{form.commission.label}}</h3> {{form.commission}} </div> <div> <h3 class="mb-1">{{form.phone.label}}</h3> {{form.phone}} </div> <div> <h3 class="mb-1">{{form.image.label}}</h3> {{form.image}} </div> </div> <div> <h3 class="mb-1">{{form.bio.label}}</h3> {{form.bio}} </div> <div class="flex gap-4 items-end"> <input class="px-8 py-2 bg-black text-white hover:bg-yellow-400 hover:text-black rounded-md cursor-pointer" type="submit" value="Enregistrer" /> <a class="bg-gray-200 px-8 py-2 rounded-md hover:bg-red-700 hover:text-white" href="{{request.META.HTTP_REFERER}}" > Annuler </a> </div> </form> </div> <div class="hidden md:inline rounded-md w-full max-w-[460px] overflow-hidden"> {% if not curr_partner %} <img class="h-full w-full object-cover" src="{% static 'imgs/partner.jpg' %}" alt="driver image" /> {% endif %} <!-- --> {% if curr_partner %} <!-- --> {% if not curr_partner.image %} <img class="w-full object-cover" src="{% static 'imgs/partner.jpg' %}" alt="driver image" /> {% else %} <img class="w-full object-cover" src="{{curr_partner.image.url}}" alt="driver image" /> {% endif %} <div class="p-4 h-full flex flex-col gap-1 w-full bg-black text-gray-300"> <h3 class="font-bold text-xl text-white"> {{curr_partner.last_name}} {{curr_partner.first_name}} </h3> <p>@{{curr_partner.user.username}}</p> <p>{{curr_partner.user.email}}</p> </div> {% endif %} </div> </section> {% endif %} {% endblock %}
import React, { Fragment, useState } from 'react' import { SalesForm } from '../components/sales-form' import SaleReview from '../components/sale-review' import { useNavigate } from 'react-router-dom' import { Box, Button, Container, Paper, Step, StepLabel, Stepper, Typography, } from '@mui/material' import { useStepper } from '../hooks/useStepper' export const CreateSale = () => { const navigate = useNavigate() const [activeStep, setActiveStep] = useState(0) const { saveStepData } = useStepper() const createSaleSteps = ['Product details', 'Review your order'] const getStepContent = (step: number) => { switch (step) { case 0: return <SalesForm /> case 1: return <SaleReview /> default: throw new Error('Unknown step') } } const handleNext = () => { setActiveStep(activeStep + 1) } const handleBack = () => { setActiveStep(activeStep - 1) } return ( <Container component="main" maxWidth="sm" sx={{ mb: 4 }}> <Button onClick={() => navigate('/dashboard')}>Back to home</Button> <Paper variant="outlined" sx={{ my: { xs: 3, md: 6 }, p: { xs: 2, md: 3 } }} > <Typography variant="h5" align="center" gutterBottom> Add Sales </Typography> <Stepper activeStep={activeStep} sx={{ pt: 3, pb: 5 }}> {createSaleSteps.map((label) => ( <Step key={label}> <StepLabel>{label}</StepLabel> </Step> ))} </Stepper> {activeStep === createSaleSteps.length ? ( <Fragment> <Typography variant="h5" gutterBottom> Thank you for your order. </Typography> <Typography variant="subtitle1"> Your order number is #2001539. We have emailed your order confirmation, and will send you an update when your order has shipped. </Typography> </Fragment> ) : ( <React.Fragment> {getStepContent(activeStep)} <Box sx={{ display: 'flex', justifyContent: 'flex-end', }} > {activeStep !== 0 && ( <Button onClick={handleBack} sx={{ mt: 3, ml: 1 }}> Back </Button> )} <Button variant="contained" onClick={handleNext} sx={{ mt: 3, ml: 1 }} > {activeStep === createSaleSteps.length - 1 ? 'Save' : 'Next'} </Button> </Box> </React.Fragment> )} </Paper> </Container> ) }
<div class="operations"> <div class="operations__filter"> <input [(ngModel)]="searchTerm" class="operations__filter-input" type="text" placeholder="Filtrar por Nome" /> </div> <div class="operations__table"> <table> <thead> <tr> <th class="operations__table-cell operations__table-cell--white"> Nome </th> <th class="operations__table-cell operations__table-cell--white"> Status Cliente </th> <th class="operations__table-cell operations__table-cell--white"> Data Operação </th> <th class="operations__table-cell operations__table-cell--white"> Hora Operação </th> <th class="operations__table-cell operations__table-cell--white"> Valor Operação </th> <th class="operations__table-cell operations__table-cell--white"> Risco Operação </th> </tr> </thead> <tbody> <tr *ngFor=" let operation of operationsList | filter : 'customerName' : searchTerm " > <td class="operations__table-cell">{{ operation.customerName }}</td> <td class="operations__table-cell"> <p class="operations__status"> {{ operation.customerStatus | status }} <img [src]="operation.customerStatus | statusIcon" class="operations__icon" width="20" height="20" /> </p> </td> <td class="operations__table-cell"> {{ operation.operationDate | date : "shortDate" }} </td> <td class="operations__table-cell"> {{ operation.operationDate | date : "HH:mm a" }} </td> <td class="operations__table-cell"> {{ operation.operationValue | currency }} </td> <td class="operations__table-cell"> {{ operation.operationRisck | percent : "1.0-2" }} </td> </tr> </tbody> </table> </div> </div>
## DESCRIPTION ## Modeling with linear functions and equations ## ENDDESCRIPTION ## KEYWORDS('linear modeling') ## DBsubject('Algebra') ## BookTitle('Algebra: Form and Function') ## DBchapter('Linear Functions') ## BookChapter('Linear functions, expressions, and equations') ## DBsection('Linear Modeling') ## BookSection('Modeling with linear functions and equations') ## Date('01/01/10') ## Author('Paul Pearson') ## Institution('Fort Lewis College') ## TitleText1('Algebra: Form and Function') ## EditionText1('1') ## AuthorText1('McCallum, Connally, and Hughes-Hallett') ## Section1('5.5') ## Problem1('19') ############################################## # Initialization DOCUMENT(); loadMacros( "PGstandard.pl", "MathObjects.pl", "AnswerFormatHelp.pl", "parserImplicitPlane.pl", ); TEXT(beginproblem()); $refreshCachedImages=1; ############################################## # Setup Context("ImplicitPlane")->variables->are(a=>"Real",r=>"Real"); $arabicayield = random(700,900,50); $robustayield = random(1100,1300,50); $totalyield = random(10000,50000,5000); $answer = ImplicitPlane("$arabicayield * a + $robustayield * r = $totalyield"); ############################################# # Main text BEGIN_TEXT The coffee variety ${BITALIC}Arabica${EITALIC} yields about $arabicayield kg of coffee beans per hectare, while ${BITALIC}Robusta${EITALIC} yields about $robustayield kg per hectare. Suppose that a plantation has \( a \) hectares of ${BITALIC}Arabica${EITALIC} and \( r \) hectares of ${BITALIC}Robusta.${EITALIC} Write an equation relating \( a \) and \( r \) if the plantation yields $totalyield kg of coffee. Do not enter any commas or units in your answer. $BR $BR \{ ans_rule(30) \} \{ AnswerFormatHelp("equations") \} END_TEXT ############################################# # Answer evaluation $showPartialCorrectAnswers = 1; ANS($answer->cmp(tolerance=>"0.01",tolType=>"absolute") ); COMMENT('MathObject version'); ENDDOCUMENT();
/* Project Supermarkt - OOP & Software Ontwerp * Klant.java * Hidde Westerhof | i2A * In samenwerking met: * Rik de Boer * Tjipke van der Heide * Yannick Strobl * * To change this template, choose Tools | Templates * and open the template in the editor. */ package supermarkt; import java.util.ArrayList; import java.util.Random; /** * * @author Driving Ghost */ public class Klant { /** * * * Attributen van de klant */ public String naam; //naam = naam van de klant public String variant; //met wat voor type klant hebben we te maken public Double geld; //hoeveelheid geld dat de klant heeft public ArrayList<Artikel> wishlist = new ArrayList<>(); //Welke artikelen heeft de klant op zijn lijstje public ArrayList<Artikel> mandje = new ArrayList<>(); //welke artikelen heeft de klant in zijn mandje private ArrayList<String> types = new ArrayList<>(); //lijst met typetjes die de klant kan zijn private Random r = new Random(); //declareer random voor random functies. boolean debug = false; /** * * * Constructor klant. */ public Klant() { this.geld = setGeld(); this.naam = setNaam(); this.variant = setVariant(); if (!debug) { System.out.println("\n" + this.naam + " ( "+ this.variant + ")" + " komt zojuist de winkel binnen"); } int items = r.nextInt(8); if (items < 0) { items *= -1; } this.wishlist = setWishlist(variant); for(Artikel a : wishlist){ System.out.println(a.getProdNaam()); } } /** * * * Geeft aan hoeveel geld de klant heeft * * @return double geld, 2 decimalen. */ private double setGeld() { double cash = r.nextDouble() * (10 * r.nextInt(100)); cash = Math.round(cash * 100) / 100; return cash; } /** * * * Bepaalt wat voor typetje de klant is. * * @return String variant */ private String setVariant() { types.add("Moeder"); types.add("Student"); types.add("Bejaarde"); types.add("Minderjarige"); types.add("Engineer"); types.add("Normaal"); String newVariant = types.get(r.nextInt(types.size())); //Secret #1 double suprise = r.nextDouble(); switch (newVariant) { case "Engineer": if (suprise < 0.05) { this.naam = "Jos Foppele"; } break; case "Moeder": if (suprise < 0.05) { this.naam = "Fiona Saridiene"; } break; case "Student": if (suprise < 0.1) { this.naam = "Tjipke van der Heide"; } else if (suprise < 0.15) { this.naam = "Yannick Strobl"; } else if (suprise < 0.2) { this.naam = "Hidde Westerhof"; } else if (suprise < 0.25) { this.naam = "Rik de Boer"; } break; } return newVariant; } /** * * * Bepaalt de naam van de klant. * * @return String met naam */ private String setNaam() { int index = r.nextInt(Supermarkt.namen.size()); if (index < 0) { index *= -1; } return Supermarkt.namen.get(index); } public void winkelen(Pad p) { for (int i = 0; i < p.artikelen.size(); i++) { if (this.wishlist.contains(p.artikelen.get(i))) { while (this.wishlist.contains(p.artikelen.get(i))) { this.wishlist.remove(p.artikelen.get(i));//haal het product een aantal keer van de wenslijst.(hij kan wel twee koekjes willen i.p.v. één) } if (!debug) { System.out.println("product " + p.artikelen.get(i).getProdNaam() + " zit niet meer in de wishlist van " + this.naam + ",: " + this.wishlist); } } if (this.wishlist.size() == 1) { if (debug && i == p.artikelen.size() - 1) { System.out.println(this.naam + " hoeft alleen nog:" + wishlist.get(0)); } } } } public void winkelen(Afdeling a) { for (int i = 0; i < a.artikelen.size(); i++) { if (this.wishlist.contains(a.artikelen.get(i))) { while (this.wishlist.contains(a.artikelen.get(i))) { this.wishlist.remove(a.artikelen.get(i));//haal het product een aantal keer van de wenslijst.(hij kan wel twee koekjes willen i.p.v. één) } if (!debug) { System.out.println("product " + a.artikelen.get(i).getProdNaam() + " zit niet meer in de wishlist van " + this.naam + ",: " + this.wishlist); } } if (this.wishlist.size() == 1) { if (debug && i == a.artikelen.size() - 1) { System.out.println(this.naam + " hoeft alleen nog:" + wishlist.get(0)); } } } } /** * * * Vult het boodschappenlijstje van de klant met Artikelen * * @param Type dat de klant is. * @return Een Artikel dat in de lijst moet */ private ArrayList<Artikel> setWishlist(String type) { ArrayList<Artikel> toAdd = new ArrayList<>(); int product = r.nextInt(Supermarkt.inventaris.size()); //random indexwaarde product double nurture = r.nextDouble(); //of ze dit product nodig hebben vanwege andere redenen. if (nurture < 0.1) { nurture *= 10; } double nature = 0.5; //hoe graag ze dit product willen hebben aan de hand van hun type if (product < 0) { product *= -1; } switch (type) { case "Moeder": //Koopt alles. System.out.println("Type is Moeder"); for (int i = 0; i < Supermarkt.inventaris.size(); i++) { for (int x = 0; x < (nurture * 10); x++) { toAdd.add(Supermarkt.inventaris.get(i)); } } break; case "Student": //studenten moeten bier en/of Energydrank hebben. System.out.println("Type is student"); for (int i = 0; i < Supermarkt.inventaris.size(); i++) { for (int x = 0; x < (nurture * 10); x++) { if (nature < nurture) { if ("bier".equals(Supermarkt.inventaris.get(i).getProdNaam())) { toAdd.add(Supermarkt.inventaris.get(i)); } } else { if ("red bull".equals(Supermarkt.inventaris.get(i).getProdNaam())) { toAdd.add(Supermarkt.inventaris.get(i)); } } } } break; case "Bejaarde": //bejaarde koopt heel veel van een product System.out.println("Type is Old bitch"); for (int i = 0; i < (nurture * 10) + (nurture * 10); i++) { toAdd.add(Supermarkt.inventaris.get(product)); } break; case "Minderjarige": //minderjarige koopt één ding. toAdd.add(Supermarkt.inventaris.get(product)); if (toAdd.size() > 1) { toAdd.clear(); toAdd.add(Supermarkt.inventaris.get(product)); } break; case "Engineer": //Engineer koopt van alles, maar vooral energydrank/koffie System.out.println("Type is Engineer"); for (int i = 0; i < Supermarkt.inventaris.size(); i++) { if ("red bull".equals(Supermarkt.inventaris.get(i).getProdNaam())) { for (int x = 0; x < (nurture * 10); x++) { toAdd.add(Supermarkt.inventaris.get(i)); } } else { for (int x = 0; x < 2; x++) { toAdd.add(Supermarkt.inventaris.get(i)); } } break; } default: System.out.println("Type is Moeder"); for (int i = 0; i < Supermarkt.inventaris.size(); i++) { for (int x = 0; x < (nurture * 5); x++) { toAdd.add(Supermarkt.inventaris.get(i)); } } break; } return toAdd; } /** * * @return De naam van de Klant */ @Override public String toString() { return this.naam; } }
package com.cg.mm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.NoSuchElementException; @RestController @RequestMapping("/malls") // Base path set here for all the methods public class MallController { @Autowired private MallService mallService; // Get all malls @GetMapping // Correctly uses the base path public List<Mall> getAllMalls() { return mallService.findAllMalls(); } // Get a single mall by ID @GetMapping("/{id}") // Correctly appends the ID to the base path public ResponseEntity<Mall> getMallById(@PathVariable Long id) { try { Mall mall = mallService.findMallById(id).orElseThrow(); return new ResponseEntity<>(mall, HttpStatus.OK); } catch (NoSuchElementException e) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } // Create a new mall @PostMapping // Correctly uses the base path public ResponseEntity<Mall> createMall(@RequestBody Mall mall) { Mall savedMall = mallService.saveMall(mall); return new ResponseEntity<>(savedMall, HttpStatus.CREATED); } // Update existing mall @PutMapping("/{id}") // Correctly appends the ID to the base path public ResponseEntity<?> updateMall(@PathVariable Long id, @RequestBody Mall mallDetails) { try { Mall existingMall = mallService.findMallById(id).orElseThrow(); existingMall.setName(mallDetails.getName()); existingMall.setLocation(mallDetails.getLocation()); final Mall updatedMall = mallService.saveMall(existingMall); return new ResponseEntity<>(updatedMall, HttpStatus.OK); } catch (NoSuchElementException e) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } // Delete a mall @DeleteMapping("/{id}") // Correctly appends the ID to the base path public ResponseEntity<Void> deleteMall(@PathVariable Long id) { try { Mall mall = mallService.findMallById(id).orElseThrow(); mallService.deleteMall(mall.getId()); return ResponseEntity.ok().build(); } catch (NoSuchElementException e) { return ResponseEntity.notFound().build(); } } }
import { Controller, Get, Post, Body, Patch, Param, Delete, Logger } from '@nestjs/common'; import { AlgorithmService } from './algorithm.service'; import { CreateAlgorithmDto } from './dto/create-algorithm.dto'; import { UpdateAlgorithmDto } from './dto/update-algorithm.dto'; import { ApiTags } from '@nestjs/swagger'; @ApiTags('Algorithm') @Controller('algorithm') export class AlgorithmController { constructor(private readonly algorithmService: AlgorithmService) {} @Post() async create(@Body() createAlgorithmDto: CreateAlgorithmDto) { return await this.algorithmService.create(createAlgorithmDto); } @Get() async findAll() { return await this.algorithmService.findAll(); } @Get(':id') findOne(@Param('id') id: string) { return this.algorithmService.findOne(+id); } @Patch(':id') update(@Param('id') id: string, @Body() updateAlgorithmDto: UpdateAlgorithmDto) { return this.algorithmService.update(+id, updateAlgorithmDto); } @Delete(':id') async remove(@Param('id') id: string) { return await this.algorithmService.remove(id); } }
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:selaty/core/utils/styles.dart'; class SochialButton extends StatelessWidget { const SochialButton({ super.key, required this.text, required this.color, required this.icon, }); final String text; final Color color; final IconData icon; @override Widget build(BuildContext context) { return Expanded( child: Container( height: 40.h, decoration: BoxDecoration( borderRadius: BorderRadius.circular(8.r), border: Border.all(color: color), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( icon, color: color, ), SizedBox( width: 5.w, ), Text( text, style: Styles.textStyle18.copyWith(color: color), ), ], ), ), ); } }
--- title: "getting started with MLJ" --- ## 1. loading package and data ```{julia} import MLJ:evaluate using MLJ,DataFrames iris=load_iris()|>DataFrame display(first(iris,10)) ``` ## 2. build DecisionTree model ```{julia} y, X = unpack(iris, ==(:target); rng=123); Tree = @load DecisionTreeClassifier pkg=DecisionTree tree = Tree() evaluate(tree, X, y, resampling=CV(shuffle=true), measures=[log_loss, accuracy], verbosity=0) ```
/** * ref로 지정한 요소 외부를 클릭할 시 callback함수를 실행 */ import { useEffect } from 'react'; function useOutsideClick(ref, callback) { useEffect(() => { const handleClick = (event) => { if (ref.current && !ref.current.contains(event.target)) { callback?.(); } }; window.addEventListener('mousedown', handleClick); return () => window.removeEventListener('mousedown', handleClick); }, [ref, callback]); } export default useOutsideClick;
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Design principles </title> <style> body { background-color: gray; color: lightblue; } .collapsible { background-color: lightblue; color: grey; padding: 15px; width: 20%; text-align: left; font-size: 15px; } </style> </head> <body> <h1> Design Principles - Collin Drake </h1> <hr> <button type="button" class="collapsible" onclick="Cat1"> Functionality </button> <div class="content"> <ol> <li> Be as easy as email </li> <li> Provide immediate feedback (haptic feedback, etc.) </li> <li> KISS (Keep it simple stupid) </li> <li> Design for human error </li> <li> Provide error reporting</li> <li> Use constraints to guide the user</li> <li> Prioritize learnability </li> <li> Apply Jakobs Law of simplicity </li> <li> Maintain consistency throughout the interface </li> <li> Keep the early focus on users and their tasks (usability) </li> <li> Enable focus by minimizing distractions and interruptions </li> <li> Address problems early in the design process through iterative design </li> <li> Help beginners learn functionality with guides or tutorials </li> <li> Dont inhibit experienced users </li> <li> Ensure accountability </li> <li> Avoid harmful or manipulative design (ethical) </li> <li> Avoid bias or discrimination of users (fairness) </li> <li> Communicate how data is collected and used (transparency) </li> <li> Ensure that all users can use the interface (accessibility) </li> </ol> </div> <button type="button" class="collapsible" onclick="Cat2"> Aesthetics </button> <div class="content"> <ol> <li> Make the interface aesthetically pleasing </li> <li> Use visibility techniques to reduce confusion (visibility) </li> </ol> </div> <button type="button" class="collapsible" onclick="Cat3"> Performance </button> <div class="content"> <ol> <li> Optimizing performance and minimizing downtime (deliverability) </li> </ol> </div> <button type="button" class="collapsible" onclick="Cat4"> Culture, Language and ethics </button> <div class="content"> <ol> <li> Be aware of language differences </li> <li> Be mindful of cultural differences </li> <li> Design for the audience's needs </li> <li> Avoid harmful or manipulative design (ethical) </li> <li> Avoid bias or discrimination of users (fairness) </li> <li> Communicate how data is collected and used (transparency) </li> </ol> </div> <button type="button" class="collapsible" onclick="Cat5"> Creativity and Problem Solving </button> <div class="content"> <ol> <li> Use the 5 Whys technique to diagnose the root causes of problems </li> <li> Integrate other products and services </li> <li> Empirically measure user behavior and feedback </li> </ol> </div> <button type="button" class="collapsible" onclick="Cat6"> User experience </button> <div class="content"> <ol> <li> Be mindful of users' emotions </li> <li> Keep the early focus on users and their tasks (usability) </li> <li> Make it clear how to use the interface (affordance) </li> </ol> </div> <script> </script> <hr> <footer> <small> (c) Collin Drake, 2023 </small> </footer> </body> </html>
/** *Submitted for verification at Etherscan.io on 2018-11-06 */ pragma solidity 0.6.12; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeERC20 { function safeTransfer(ERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } contract DVPgame { ERC20 public token; uint256[] map; using SafeERC20 for ERC20; using SafeMath for uint256; constructor(address addr) payable public { token = ERC20(addr); } fallback() external { if(map.length>=uint256(msg.sender)){ require(map[uint256(msg.sender)]!=1); } if(token.balanceOf(address(this))==0){ //airdrop is over selfdestruct(msg.sender); }else{ token.safeTransfer(msg.sender,100); if (map.length <= uint256(msg.sender)) { increaseMapLength(uint256(msg.sender) + 1); } map[uint256(msg.sender)] = 1; } } function increaseMapLength(uint256 len) internal { assembly{ sstore(0x01, len) } } //Guess the value(param:x) of the keccak256 value modulo 10000 of the future block (param:blockNum) function guess(uint256 x,uint256 blockNum) public payable { require(msg.value == 0.001 ether || token.allowance(msg.sender,address(this))>=1*(10**18)); require(blockNum>block.number); if(token.allowance(msg.sender,address(this))>0){ token.safeTransferFrom(msg.sender,address(this),1*(10**18)); } if (map.length <= uint256(msg.sender)+x) { increaseMapLength(uint256(msg.sender)+x + 1); } map[uint256(msg.sender)+x] = blockNum; } //Run a lottery function lottery(uint256 x) public { require(map[uint256(msg.sender)+x]!=0); require(block.number > map[uint256(msg.sender)+x]); require(blockhash(map[uint256(msg.sender)+x])!=0); bytes memory hash = abi.encode(blockhash(map[uint256(msg.sender)+x])); uint256 answer = uint256(keccak256(hash))%10000; if (x == answer) { token.safeTransfer(msg.sender,token.balanceOf(address(this))); selfdestruct(msg.sender); } } }
import { Add, ChevronRightOutlined, FilterListOutlined, Search, SearchOffOutlined } from "@mui/icons-material"; import { Button, Dialog, DialogActions, DialogContent, Divider, Grid, InputAdornment, Paper, TextField, ToggleButton, ToggleButtonGroup, Typography } from "@mui/material"; import { useMemo, useState } from "react"; import PartDetails from "../../features/parts/PartDetails"; import PartItem from "../../features/parts/PartItem"; import { removeWhitespace, toCapitalCase } from "../../utils/StringUtils"; import PartsAmountList from "./PartsAmountList"; import PartsList from "./list/PartsList"; import { getGroupAsString } from "./list/DefaultPartItemsListHeader"; export const AddPartsDialog = ({ isOpen, closeDialog, parts, partsList, customPartsList, handleAddNewPart, handleAddCustomPart, handleAmountChangedParts, handleItemDeletedParts }) => { const [searchQuery, setSearchQuery] = useState(''); const [filterActive, setFilterActive] = useState(false); const [selectedOrigin, setSelectedOrigin] = useState(null); const [selectedPart, setSelectedPart] = useState(null); const searchValues = searchQuery.toLowerCase().split(' '); const filteredParts = parts?.filter(part => !!filterActive ? part.origin === selectedOrigin : true) .filter(part => searchValues.every(searchValue => removeWhitespace(JSON.stringify(part)).toLowerCase().includes(searchValue))) || []; const partGroups = useMemo(() => parts?.reduce((origins, part) => { if (!origins.includes(part.origin)) { origins.push(part.origin); } return origins; }, []) || [], [parts]); const onFilterSelected = () => { setFilterActive(filterActive => !filterActive); setSelectedOrigin(selectedOrigin => selectedOrigin || partGroups[0]); } const showPartInformation = (part) => { setSelectedPart(part); } const addCurrentPart = () => { handleAddNewPart(selectedPart); } const addCustomPart = () => { handleAddCustomPart({ inputValue: searchQuery }) } const AddedPartsList = useMemo(() => ( <PartsAmountList checklistParts={[...partsList, ...customPartsList]} onAmountChanged={handleAmountChangedParts} onItemDeleted={handleItemDeletedParts} height="calc(100vh - 190px)" /> ), [partsList, customPartsList, handleAmountChangedParts, handleItemDeletedParts]); return ( <Dialog fullScreen open={isOpen} onClose={closeDialog} > <DialogContent> <Grid container sx={{ m: 0, p: 0 }} spacing={1}> <Grid item container md={7} lg={7}> <Grid item xs={12} sm={12} md={6} lg={6}> <div> <div className="d-flex gap-1"> <TextField type="text" fullWidth onChange={(e) => setSearchQuery(e.target.value)} placeholder="Wonach suchst du?" InputProps={{ startAdornment: <InputAdornment position="start"><Search /></InputAdornment> }} /> <ToggleButton value="filterActive" selected={filterActive} onChange={onFilterSelected} color="primary" > <FilterListOutlined /> </ToggleButton> </div> { !!filterActive && ( <ToggleButtonGroup exclusive color="primary" size="small" sx={{ flexWrap: 'wrap', marginTop: 1 }} value={selectedOrigin} onChange={(e, newValue) => !!newValue && setSelectedOrigin(newValue)} > { partGroups.map((origin, index) => <ToggleButton key={index} value={origin}>{getGroupAsString(origin)}</ToggleButton>) } </ToggleButtonGroup> ) } </div> <Paper className="tableFixHead mt-2" style={{ height: filterActive ? 'calc(100vh - 270px)' : 'calc(100vh - 220px)' }} > { filteredParts.length <= 0 ? ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", textAlign: "center", height: '100%' }}> <div> <SearchOffOutlined fontSize='large' /> <Typography>Kein Bauteil gefunden. Hast du den Namen richtig geschrieben? </Typography> </div> </div> ) : ( <PartsList parts={filteredParts} head={ (group) => ( <div style={{ backgroundColor: '#212529' }} className='text-md-center p-2 shadow table-dark border border-dark'> <p className="font-monospace p-0 m-0 fw-bold">{getGroupAsString(group)}</p> </div> )} row={(part) => ( <div className='border border-top-0' style={{ width: '100%', cursor: 'pointer' }}> <PartItem part={part} onClick={showPartInformation} /> </div> )} /> ) } </Paper > </Grid > <Grid item xs={12} sm={12} md={6} lg={6} sx={{ display: { xs: "none", sm: "none", md: "block", lg: "block", xl: "block", xxl: "block" }, px: 2 }} style={{ height: 'calc(100vh - 150px)', overflowY: 'scroll' }} > <Button variant="outlined" color="success" fullWidth disabled={!selectedPart} className="mb-2" startIcon={<Add />} onClick={addCurrentPart} > Ausgewähltes Bauteil hinzufügen </Button> <Button variant="outlined" fullWidth disabled={!searchQuery} className="mb-2" startIcon={<Add />} onClick={addCustomPart} > Suchbegriff als Bauteil erstellen </Button> <PartDetails part={selectedPart} /> </Grid> {/* <Grid item className="d-flex justify-content-center align-items-center"> */} {/* <Divider orientation="vertical" /> */} {/* <ChevronRightOutlined /> </Grid> */} </Grid> <Grid item md={5} lg={5}> <Typography variant="h5">Bereits hinzugefügte Elemente</Typography> <Divider /> {AddedPartsList} </Grid > </Grid > </DialogContent > <DialogActions> <Button type="submit" className="p-2" onClick={closeDialog}>Schließen</Button> </DialogActions> </Dialog > ) } export default AddPartsDialog;
require 'rails_helper' RSpec.describe AgentBuilder, type: :model do subject(:agent_builder) { described_class.new(params) } let(:account) { create(:account) } let!(:current_user) { create(:user, account: account) } let(:email) { 'test@example.com' } let(:name) { 'Test User' } let(:role) { 'agent' } let(:availability) { 'offline' } let(:auto_offline) { false } let(:params) do { email: email, name: name, inviter: current_user, account: account, role: role, availability: availability, auto_offline: auto_offline } end describe '#perform' do context 'when user does not exist' do it 'creates a new user' do expect { agent_builder.perform }.to change(User, :count).by(1) end it 'creates a new account user' do expect { agent_builder.perform }.to change(AccountUser, :count).by(1) end it 'returns a user' do expect(agent_builder.perform).to be_a(User) end end context 'when user exists' do before do create(:user, email: email) end it 'does not create a new user' do expect { agent_builder.perform }.not_to change(User, :count) end it 'creates a new account user' do expect { agent_builder.perform }.to change(AccountUser, :count).by(1) end end context 'when only email is provided' do let(:params) { { email: email, inviter: current_user, account: account } } it 'creates a user with default values' do user = agent_builder.perform expect(user.name).to eq('') expect(AccountUser.find_by(user: user).role).to eq('agent') end end context 'when a temporary password is generated' do it 'sets a temporary password for the user' do user = agent_builder.perform expect(user.encrypted_password).not_to be_empty end end context 'with confirmation required' do let(:unconfirmed_user) { create(:user, email: email) } before do unconfirmed_user.confirmed_at = nil unconfirmed_user.save(validate: false) allow(unconfirmed_user).to receive(:confirmed?).and_return(false) end it 'sends confirmation instructions' do user = agent_builder.perform expect(user).to receive(:send_confirmation_instructions) agent_builder.send(:send_confirmation_if_required) end end end end
import 'package:flutter/material.dart'; import 'package:job_app/src/components/styles/constants/images_string.dart'; import 'package:job_app/src/components/styles/constants/sizes.dart'; import 'package:job_app/src/components/widgets/custom_shape/header_container.dart'; import 'package:job_app/src/components/widgets/custom_shape/search_bar.dart'; import 'package:job_app/src/components/widgets/staff/staff_card.dart'; import 'package:job_app/src/components/widgets/texts/section_heading.dart'; import 'package:job_app/src/layouts/private/user/user_home/widgets/home_appbar.dart'; import 'package:job_app/src/layouts/private/user/user_home/widgets/home_category.dart'; class CompanyHomeScreen extends StatelessWidget { const CompanyHomeScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: SingleChildScrollView( child: Column(children: [ const JHeaderContainer( child: Column( children: [ ///appbar home JHomeAppBar(), SizedBox(height: JSizes.spaceBtwSections), // search bar JSearchContainer(text: 'Từ khoá công việc...'), SizedBox(height: JSizes.spaceBtwSections), // categories Padding( padding: EdgeInsets.only(left: JSizes.defaultSpace), child: Column( children: [ JSectionHeading( title: 'Lĩnh vực phổ biến', textColor: Colors.white), SizedBox(height: JSizes.spaceBtwItems), JHomeCategory() ], ), ), SizedBox(height: JSizes.spaceBtwSections * 1.5), ], ), ), //body const Padding( padding: EdgeInsets.symmetric(horizontal: JSizes.defaultSpace), child: JSectionHeading(title: "Ứng viên nổi trội"), ), ListView.builder( shrinkWrap: true, itemCount: 10, physics: const NeverScrollableScrollPhysics(), itemBuilder: (_, index) => JStaffCard( jobName: 'Lập Trình Viên', staffName: 'Nguyễn Quang Tuấn', companyAddress: 'Công Nghệ Thông Tin', experience: '3 năm', salary: '10.000.000 - 15.000.000', imageUrl: JImages.companyAvatar, onPressed: () {}, ), ), ]), ), ); } }
import usePatients from "../../hooks/usePatients"; const Patient = ({patient} : any ) => { const { name, appointmentDate, email, owner, symptom} = patient; const { updatePatient, deletePatient } = usePatients(); const getTimeFormat = (originalFormat : string) => { const formattedDate = new Date(originalFormat.slice(0, 16)); return new Intl.DateTimeFormat('en-US', {dateStyle: 'long'}).format(formattedDate); }; return( <div className="mx-5 my-10 bg-white shadow-md px-5 py-3 rounded-xl"> <p className="font-bold uppercase text-orange-600 text-center my-2"> Name: {''} <span className="font-normal normal-case text-black">{ name }</span> </p> <p className="font-bold uppercase text-orange-600 text-center my-2"> Owner: {''} <span className="font-normal normal-case text-black">{ owner }</span> </p> <p className="font-bold uppercase text-orange-600 text-center my-2"> Email: {''} <span className="font-normal normal-case text-black">{ email }</span> </p> <p className="font-bold uppercase text-orange-600 text-center my-2"> Appointment date: {''} <span className="font-normal normal-case text-black">{ getTimeFormat(appointmentDate) }</span> </p> <p className="font-bold uppercase text-orange-600 text-center my-2"> Symptoms: {''} <span className="font-normal normal-case text-black">{ symptom }</span> </p> <div className="flex justify-between flex-wrap my-5"> <button type="button" className="py-2 px-10 bg-orange-600 hover:bg-orange-700 text-white uppercase font-bold rounded-lg" onClick={() => updatePatient(patient)}>Edit</button> <button type="button" className="py-2 px-10 bg-red-600 hover:bg-red-700 text-white uppercase font-bold rounded-lg" onClick={() => deletePatient(patient)}>Delete</button> </div> </div> ); } export default Patient;
import os from .base_dataset import BaseDataset from ltr.data.image_loader import default_image_loader import torch import random from collections import OrderedDict from ltr.admin.environment import env_settings import numpy as np import time from ltr.dataset.COCO_tool import COCO from lib.utils.lmdb_utils import decode_img, decode_json '''COCO2017 使用实例分割的mask标注''' class MSCOCOSeq17_lmdb(BaseDataset): """ The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1. Publication: Microsoft COCO: Common Objects in Context. Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona, Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick ECCV, 2014 https://arxiv.org/pdf/1405.0312.pdf Download the images along with annotations from http://cocodataset.org/#download. The root folder should be organized as follows. - coco_root - annotations - instances_train2014.json - images - train2014 Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi. """ def __init__(self, split='train', root=None, image_loader=default_image_loader, data_fraction=None, version="2017"): """ args: root - path to the coco dataset. image_loader (default_image_loader) - The function to read the images. If installed, jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else, opencv's imread is used. data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the images will be used """ root = env_settings().coco_lmdb_dir if root is None else root super().__init__(root, image_loader) print("building coco_seq17 from lmdb") self.img_pth = 'images/{}{}/'.format(split, version) self.anno_path = 'annotations/instances_{}{}.json'.format(split, version) # Load the COCO set. print('loading annotations into memory...') tic = time.time() coco_json = decode_json(root, self.anno_path) print('Done (t={:0.2f}s)'.format(time.time() - tic)) self.coco_set = COCO(coco_json) self.cats = self.coco_set.cats self.sequence_list = self._get_sequence_list() if data_fraction is not None: self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction)) def _get_sequence_list(self): ann_list = list(self.coco_set.anns.keys()) seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0] return seq_list def is_video_sequence(self): return False def has_mask(self): return True def get_name(self): return 'coco17_lmdb' def get_num_sequences(self): return len(self.sequence_list) def get_sequence_info(self, seq_id): anno = self._get_anno(seq_id) bbox = torch.Tensor(anno['bbox']).view(1, 4) valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0) visible = valid.clone().byte() return {'bbox': bbox, 'valid': valid, 'visible': visible} def _get_anno(self, seq_id): anno = self.coco_set.anns[self.sequence_list[seq_id]] return anno def _get_frames(self, seq_id): path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name'] # img = self.image_loader(os.path.join(self.img_pth, path)) img = decode_img(self.root, os.path.join(self.img_pth, path)) '''add mask''' mask = self.coco_set.annToMask(self.coco_set.anns[self.sequence_list[seq_id]]) mask_img = mask[..., np.newaxis] return img, mask_img def get_meta_info(self, seq_id): try: cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']] object_meta = OrderedDict({'object_class': cat_dict_current['name'], 'motion_class': None, 'major_class': cat_dict_current['supercategory'], 'root_class': None, 'motion_adverb': None}) except: object_meta = OrderedDict({'object_class': None, 'motion_class': None, 'major_class': None, 'root_class': None, 'motion_adverb': None}) return object_meta def get_frames(self, seq_id, frame_ids, anno=None): frame_mask_list = [self._get_frames(seq_id) for f in frame_ids] if anno is None: anno = self.get_sequence_info(seq_id) # Create anno dict anno_frames = {} for key, value in anno.items(): anno_frames[key] = [value[0, ...].clone() for f_id in frame_ids] '''return both frame and mask''' frame_list = [f for f, m in frame_mask_list] mask_list = [m for f, m in frame_mask_list] return frame_list, mask_list, anno_frames, None
--- changelog: - 2024-02-03, gpt-4-0125-preview, translated from English date: 2024-02-03 19:06:49.371745-07:00 description: "Hur man g\xF6r: TypeScript, som \xE4r en ut\xF6kning av JavaScript,\ \ till\xE5ter olika metoder f\xF6r att g\xF6ra f\xF6rsta bokstaven i en str\xE4\ ng stor, allt fr\xE5n rena\u2026" lastmod: '2024-03-13T22:44:37.639583-06:00' model: gpt-4-0125-preview summary: "TypeScript, som \xE4r en ut\xF6kning av JavaScript, till\xE5ter olika metoder\ \ f\xF6r att g\xF6ra f\xF6rsta bokstaven i en str\xE4ng stor, allt fr\xE5n rena\ \ JavaScript-ansatser till att anv\xE4nda tredjepartsbibliotek f\xF6r mer komplexa\ \ eller specifika anv\xE4ndningsfall." title: "G\xF6r om en str\xE4ng till versaler" weight: 2 --- ## Hur man gör: TypeScript, som är en utökning av JavaScript, tillåter olika metoder för att göra första bokstaven i en sträng stor, allt från rena JavaScript-ansatser till att använda tredjepartsbibliotek för mer komplexa eller specifika användningsfall. **Ren JavaScript-ansats:** ```typescript function capitalize(str: string): string { return str.charAt(0).toUpperCase() + str.slice(1); } // Exempelutdata: console.log(capitalize('hello TypeScript!')); // 'Hello TypeScript!' ``` Denna metod är okomplicerad och förlitar sig på `charAt()`-metoden för att komma åt den första bokstaven i strängen och `toUpperCase()` för att konvertera den till versal. Metoden `slice(1)` hämtar sedan resten av strängen, lämnar den oförändrad. **Använda Lodash-biblioteket:** För projekt som redan använder [Lodash](https://lodash.com/)-biblioteket kan du använda dess `_.capitalize`-funktion för att uppnå samma resultat med mindre mallkod. Installera först Lodash: ```bash npm install lodash ``` Använd sedan det i din TypeScript-fil: ```typescript import * as _ from 'lodash'; // Exempelutdata: console.log(_.capitalize('hello TypeScript!')); // 'Hello typescript!' ``` Obs: Lodashs `_.capitalize`-metod gör resten av strängen till gemener vilket inte alltid kan vara vad du vill. **Använda ett reguljärt uttryck:** Ett reguljärt uttryck kan erbjuda ett koncist sätt att göra den första bokstaven i en sträng stor, särskilt om du behöver göra den första bokstaven i varje ord i en sträng stor. ```typescript function capitalizeWords(str: string): string { return str.replace(/\b\w/g, char => char.toUpperCase()); } // Exempelutdata: console.log(capitalizeWords('hello typescript world!')); // 'Hello Typescript World!' ``` Denna metod använder `replace()`-funktionen för att söka efter varje ordgräns följt av en alfanumerisk karaktär (`\b\w`), och gör varje träff stor. Den är särskilt praktisk för titlar eller rubriker.
from src.horn_knowledge_base import HornKnowledgeBase from src.inference_algorithm import InferenceAlgorithm from src.query import HornKnowledgeBaseQuery from src.result.chaining_result import ChainingResult from src.syntax.literal import PositiveLiteral class BackwardChaining(InferenceAlgorithm): def __init__(self): super().__init__("BC") def run( self, knowledge_base: HornKnowledgeBase, query: HornKnowledgeBaseQuery ) -> ChainingResult: # ultimate goal goal = query.positive_literal # entailed symbols entailed = set() # visited goals visited = set() # do the backward chaining recursively found = self.backwards_chaining(knowledge_base, goal, entailed, visited) return ChainingResult(self.name, found, entailed) def backwards_chaining( self, knowledge_base: HornKnowledgeBase, goal: PositiveLiteral, entailed: set[PositiveLiteral], visited: set[PositiveLiteral], ) -> bool: # ensure that we don't loop but also that we can access already entailed literals if goal in visited and goal not in entailed: return False visited.add(goal) # if the goal is already a fact if goal in knowledge_base.facts: # we have entailed this known fact entailed.add(goal) return True # check if any rule has the goal as the head for rule in knowledge_base.rules: if rule.head == goal: # check if all the symbols in the body are entailed if all( [ self.backwards_chaining( knowledge_base, symbol, entailed, visited ) for symbol in rule.body ] ): entailed.add(goal) return True return False
--- title: axios 手写 order: 30 group: order: 1 title: js Basic path: /interview/js nav: order: 3 title: 'interview' path: /interview --- 简单手写版 ```js var dispatch = (config) => { return new Promise((resolve, reject) => { setTimeout(() => { // 模拟xhr 结果响应值 resolve('cpp', config); }, 1000); }); }; var dispatchRequest = (config) => { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); xhr.open(config.method, config.url, true); xhr.onreadystatechange = function () { if (xhr.status >= 200 && xhr.readyState === 4) { resolve(xhr.responseText); } else { reject('failed'); } }; xhr.send(); }); }; class Axios { public defaults; public interceptors; constructor(config) { this.defaults = config; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager(), }; } request(config) { // url if (typeof config === 'string') { config.url = arguments[0]; config = arguments[1]; } else { config = config || {}; } // method if (config.method) { config.method = config.method.toLowerCase(); } else { config.method = 'get'; } const chain = [dispatchRequest, undefined]; this.interceptors.request.forEach((item) => { chain.unshift(item.fulfilled, item.rejected); }); this.interceptors.response.forEach((item) => { chain.push(item.fulfilled, item.rejected); }); let promise = Promise.resolve(config); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; } } function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = Axios.prototype.request.bind(context); //将 Axios.prototype 属性扩展到 instance 上 for(let k of Object.keys(Axios.prototype)){ instance[k] = Axios.prototype[k].bind(context); } //将 context 属性扩展到 instance 上 for(let k of Object.keys(context)){ instance[k] = context[k] } return instance; } var axios = createInstance({}) axios.create = function(config){ return createInstance(config); } export default axios function extend(child, parent) { var parentProto = parent.prototype; parentProto.constructor = child; child.prototype = parentProto; Object.setPrototypeOf(child, parent); } axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone', }, }); axios.interceptors.request.use( function (config) { // 在发送请求之前做些什么 return config; }, function (err) { // 对请求错误做些什么 return Promise.reject(err); }, ); class InterceptorManager { public handlers; constructor() { this.handlers = []; } use(fulfilled, rejected) { this.handlers.push({ fulfilled, rejected, }); return this.handlers.length - 1; } eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } } // 执行所以方法 forEach(fn) { this.handlers.forEach((item) => { item && fn(item); }); } } ```
import { useEffect, useState } from "react"; import { NavLink, useNavigate } from "react-router-dom"; import { Card, CardBody, CardTitle, CardText, CardSubtitle, Button, NavItem, FormGroup, Label, Input, } from "reactstrap"; import { getWorkerProfiles } from "../../managers/userProfileManager"; //^ This module renders AssignedProjectDetails (inside of AssignedProjectDetails.js) when "Show Details" button is clicked which navigates to assignedProjects/${projectAssignment.id} export default function ProjectAssignmentCard({ project, setProject, loggedInUser, projectAssignment, setDetailsProjectId, setprojectAssignmentsByUserId, // setDetailsProjectId, }) { const navigate = useNavigate(); // console.log({ projectAssignment }); const [selectedWorker, setSelectedWorker] = useState(""); // when user clicks a worker name from dropdown, the setSelectedWorker function runs and the value of selectedWorker gets set to the selected user's workerprofile Id // console.log(selectedWorker); const [workerProfiles, setWorkerProfiles] = useState([]); // State to store worker profiles (Panda and Ty) const [addedWorkers, setAddedWorkers] = useState([]); // Keep track of added workers //~ TRYING SOMETHING - ALL NEW CODE HERE - ~// const [availableWorkers, setAvailableWorkers] = useState([]); // State to store available workers useEffect(() => { // Fetch all worker profiles excluding the logged-in worker getWorkerProfiles() .then((data) => { // Assuming you have a variable to represent the logged-in worker's id const loggedInUserId = loggedInUser.id; const filteredWorkers = data.filter( (worker) => worker.id !== loggedInUserId ); setAvailableWorkers(filteredWorkers); }) .catch((error) => console.error("Error fetching worker profiles: ", error) ); }, [loggedInUser]); // Fetch worker profiles when the logged-in user changes //~ TRYING SOMETHING - ALL NEW CODE HERE - ~// useEffect(() => { // Fetch worker profiles when the component mounts getWorkerProfiles() .then((data) => setWorkerProfiles(data)) .catch((error) => console.error("Error fetching worker profiles: ", error) ); }, []); // console.log({ workerProfiles }); //^ Handle the user's selection by posting a new projectAssignment object const handleWorkerSelection = async (worker) => { try { // Perform a POST request to create a new projectAssignment const newProjectAssignment = { userProfileId: worker.id, // Set the selected worker's UserProfileId projectId: projectAssignment.projectId, // Set the current project's Id projectTypeId: projectAssignment.projectTypeId, }; console.log({worker}) console.log({ newProjectAssignment }); const response = await fetch("/api/projectAssignment", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(newProjectAssignment), }); if (response.ok) { window.alert(`${worker.firstName} was added to this project.`); console.log("New projectAssignment created successfully."); setAvailableWorkers((prevWorkers) => prevWorkers.filter((w) => w.id !== worker.id)); setSelectedWorker(""); // Clear the selected worker setAddedWorkers((prevAdded) => [...prevAdded, worker.id]); // Add the worker's ID to the list of added workers } else { console.error("Failed to create a new projectAssignment."); } } catch (error) { console.error( "An error occurred while creating a new projectAssignment.", error ); } }; return ( <Card body color="info" outline style={{ marginBottom: "8px" }}> <CardBody> <CardTitle tag="h5">{projectAssignment.projectType.name}</CardTitle> <CardText> <br></br> Project Date:{" "} {new Date(projectAssignment.project.dateOfProject).toLocaleString()} <br></br> Customer: {projectAssignment.project.userProfile.fullName} </CardText> <Button outline color="black" style={{ borderColor: "black", fontWeight: "bold", }} onClick={() => { setProject(projectAssignment); navigate(`assignedProjects/${projectAssignment.id}`); window.scrollTo({ top: 0, left: 0, behavior: "smooth", }); }} > Show Details </Button> <div> <FormGroup> <Label for="worker">Add Worker</Label> <Input type="select" name="worker" id="worker" // value={selectedWorker} //the code didn't work this way, so created it in the next line of code onChange={(e) => { const selectedWorker = workerProfiles.find( (wp) => wp.id === parseInt(e.target.value) ); setSelectedWorker(selectedWorker); }} > <option value="">Select a worker</option> {availableWorkers.map((worker) => ( <option key={worker.id} value={worker.id}> {worker.fullName} </option> ))} </Input> </FormGroup> <Button color="info" onClick={() => handleWorkerSelection(selectedWorker)}> Add Worker </Button> </div> </CardBody> </Card> ); }
class GetProductsDataModel { String? product_id; String? name; String? price; String? description; String? folder_name; String? subcategory2_id; String? subcategory2; String? subcategory1_id; String? subcategory1; String? category_id; String? category; String? region_id; String? region; String? cart_qty; String? updated_at; String? created_at; String? product_url; GetProductsDataModel( {this.product_id, this.name, this.price, this.description, this.folder_name, this.subcategory2_id, this.subcategory2, this.subcategory1_id, this.subcategory1, this.category_id, this.category, this.region_id, this.region, this.cart_qty, this.updated_at, this.created_at, this.product_url}); factory GetProductsDataModel.fromJson(Map<String, dynamic> json) { return GetProductsDataModel( product_id: json['product_id'], name: json['name'], price: json['price'], description: json['description'], folder_name: json['folder_name'], subcategory2_id: json['subcategory2_id'], subcategory2: json['subcategory2'], subcategory1_id: json['subcategory1_id'], subcategory1: json['subcategory1'], category_id: json['category_id'], category: json['category'], region_id: json['region_id'], region: json['region'], cart_qty: json['cart_qty'], updated_at: json['updated_at'], created_at: json['created_at'], product_url: json['product_url']); } }
import { Public } from '@/auth/decorators/public.decorator'; import { BadRequestException, Body, ConflictException, Controller, Post, UsePipes, } from '@nestjs/common'; import { NestCreateUserUseCase } from '../representations/use-cases/nest-create-user.use-case'; import { z } from 'zod'; import { ZodValidationPipe } from '../pipes/zod-validation.pipe.'; import { UserAlreadyExistsError } from 'enterprise'; const createUserSchema = z.object({ name: z.string().min(3), email: z.string().email(), password: z.string().min(6), }); export type CreateUserBody = z.infer<typeof createUserSchema>; const bodyValidationPipe = new ZodValidationPipe(createUserSchema); @Controller('/users') @Public() export class CreateUserController { public constructor(private readonly useCase: NestCreateUserUseCase) { } @Post() @UsePipes(bodyValidationPipe) async handle(@Body() { email, name, password }: CreateUserBody) { const result = await this.useCase.execute({ email, name, password }); if (result.isFailure()) { const error = result.value; switch (error.constructor) { case UserAlreadyExistsError: throw new ConflictException(error.message); default: throw new BadRequestException(error.message); } } } }
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import {Comment, Icon, Button, Label} from 'semantic-ui-react'; import styles from './styles.module.scss'; const UserMesage = ({ userName, imgSrc, text, id, date, canEdit, like, setLike, onEdit, deleteOwnMesage }) =>{ const [showEdit, setShowEdit] = useState(false); const show=() => { setShowEdit(true); }; const hide=() => { setShowEdit(false); }; return ( <div className={styles.userMessageWrap} style={canEdit ? {justifyContent: 'flex-end'} : null}> <div className={styles.messageWrap} onMouseEnter={show} onMouseLeave={hide} > <Comment> {canEdit ? null : (<Comment.Avatar src={imgSrc} className={styles.comment}/>) } <Comment.Content> <Comment.Author as='a'>{userName}</Comment.Author> <Comment.Metadata> <div>{date}</div> </Comment.Metadata> <Comment.Text>{text}</Comment.Text> <Comment.Actions> <Comment.Action> <Label onClick={() => { setLike(id) }}> <Icon name='heart' color='red'/> {like} </Label> </Comment.Action> <Comment.Action> {showEdit && ( <Button icon size='mini' onClick={() => { onEdit(id) }}> <Icon name='edit'/> </Button> )} {canEdit ? ( <Button icon size='mini' onClick={() => { deleteOwnMesage(id) }}> <Icon name='trash alternate'/> </Button> ) : null } </Comment.Action> </Comment.Actions> </Comment.Content> </Comment> </div> </div> ); } UserMesage.propTypes = { userName: PropTypes.string.isRequired, imgSrc: PropTypes.string.isRequired, text: PropTypes.string.isRequired, id: PropTypes.string.isRequired, canEdit: PropTypes.bool.isRequired, like: PropTypes.number.isRequired, setLike: PropTypes.func.isRequired, onEdit: PropTypes.func.isRequired, deleteOwnMesage: PropTypes.func.isRequired }; export default UserMesage;
#pragma once #include <QObject> #include <QDateTime> #include <QString> #include <QList> #ifdef QTDROPBOX_DEBUG #include <QDebug> #endif #include "qdropbox2common.h" //! Provides information and metadata about an entry in the Dropbox account /*! This class is a more specialized version of QDropboxJson. It provides access to the metadata of an entity (file or directory) stored on Dropbox. To obtain metadata information about any kind of entity stored on the Dropbox you have to use QDropbox::metadata() or QDropboxFile::metadata(). Those functions return an instance of this class that contains the required information. If an error occured while obtaining the metadata the functon isValid() will return <i>false</i>. */ class QDROPBOXSHARED_EXPORT QDropbox2EntityInfo : public QObject { Q_OBJECT public: /*! Creates an empty instance of QDropbox2EntityInfo. \warning internal use only \param parent parent QObject */ QDropbox2EntityInfo(QObject *parent = 0); /*! Creates an instance of QDropbox2EntityInfo based on the data provided in the JSON in string representation. \param jsonStr metadata JSON in string representation \param parent pointer to the parent QObject */ QDropbox2EntityInfo(const QJsonObject& jsonData, QObject *parent = 0); /*! Creates a copy of an other QDropbox2EntityInfo instance. \param other original instance */ QDropbox2EntityInfo(const QDropbox2EntityInfo &other); /*! Default destructor. Takes care of cleaning up when the object is destroyed. */ ~QDropbox2EntityInfo(); /*! Copies the values from an other QDropbox2EntityInfo instance to the current instance. \param other original instance */ void copyFrom(const QDropbox2EntityInfo &other); /*! Works exactly like copyFrom() only as an operator. \param other original instance */ QDropbox2EntityInfo& operator=(const QDropbox2EntityInfo& other); /*! Raw Dropbox file identifier. */ QString id() const { return _id; } /*! File size in bytes. */ quint64 bytes() const { return _bytes; } /*! Bytes as a string, formatted for the locale. */ QString size() const; /*! Timestamp of last modification on the server. */ QDateTime serverModified() const { return _serverModified; } /*! Timestamp of desktop client upload. */ QDateTime clientModified() const { return _clientModified; } /*! Full canonical path of the file. */ QString path() const { return _path; } /*! Filename component. */ QString filename() const { return _filename; } /*! Indicates whether the selected item is currently shared with others. */ bool isShared() const { return _isShared; } /*! Indicates whether the selected item is a directory. */ bool isDirectory() const { return _isDir; } /*! Indicates whether the item is deleted on the server. */ bool isDeleted() const { return _isDeleted; } /*! Current revision as hash string. Use this for e.g. change check. */ QString revisionHash() const { return _revisionHash; } private: void init(const QJsonObject& jsonData = QJsonObject()); QDateTime getTimestamp(QString value); QString _id; QDateTime _clientModified; QDateTime _serverModified; QString _revisionHash; quint64 _bytes; QString _size; QString _path; QString _filename; bool _isShared; bool _isDir; bool _isDeleted; };
import React from 'react'; import './App.css'; import Navbar from './components/Navbar'; import { BrowserRouter as Router, Routes, Route} from 'react-router-dom'; import Home from './components/pages/Home'; import Services from './components/pages/Services'; import Marketing from './components/pages/Marketing'; import Consulting from './components/pages/Consulting'; import Design from './components/pages/Design'; import Development from './components/pages/Development'; import Products from './components/pages/Products'; import ContactUs from './components/pages/ContactUs'; import SignUp from './components/pages/SignUp'; function App() { return ( <Router> <Navbar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/services" element={<Services />} /> <Route path="/marketing" element={<Marketing />} /> <Route path="/consulting" element={<Consulting />} /> <Route path="/design" element={<Design />} /> <Route path="/development" element={<Development />} /> <Route path="/products" element={<Products />} /> <Route path="/contact-us" element={<ContactUs />} /> <Route path="/sign-up" element={<SignUp />} /> </Routes> </Router> ); } export default App;
import React from "react"; interface IButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { children: React.ReactNode; className?: string; } const Button = ({ children, className, ...rest }: IButtonProps) => { return ( <button className={`flex h-8 w-8 items-center justify-center border-dashed hover:border-2 hover:border-solid hover:border-black hover:backdrop-brightness-90 disabled:cursor-not-allowed disabled:opacity-50 ${className}`} {...rest} > {children} </button> ); }; export default Button;
package dailyquest.common import java.time.DayOfWeek import java.time.Duration import java.time.LocalDate import java.time.LocalDateTime import java.time.temporal.TemporalAdjuster import java.time.temporal.TemporalAdjusters private val firstDayOfYearAdjusters: TemporalAdjuster = TemporalAdjusters.firstDayOfYear() private val firstMondayOfYearAdjusters: TemporalAdjuster = TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY) fun LocalDate.firstDayOfQuarter(): LocalDate { val firstMondayOfYear = this.with(firstDayOfYearAdjusters).with(firstMondayOfYearAdjusters) if(this.isBefore(firstMondayOfYear)) { val previousMonday = this.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)) return previousMonday.minusWeeks(12) } val weekDiff = (this.dayOfYear - firstMondayOfYear.dayOfYear) / 7 val quarter = weekDiff / 13 val weeks = quarter * 13L return firstMondayOfYear.plusWeeks(weeks) } fun LocalDate.lastDayOfQuarter(): LocalDate { val firstMondayOfYear = this.with(firstDayOfYearAdjusters).with(firstMondayOfYearAdjusters) if(this.isBefore(firstMondayOfYear)) { return firstMondayOfYear.minusDays(1) } val weekDiff = (this.dayOfYear - firstMondayOfYear.dayOfYear) / 7 val quarter = weekDiff / 13 val weeks = (quarter + 1) * 13L return firstMondayOfYear.plusWeeks(weeks).minusDays(1) } fun LocalDate.firstDayOfWeek() : LocalDate { return LocalDate.from(this.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))) } fun LocalDate.firstDayOfMonth() : LocalDate { return LocalDate.from(this.with(TemporalAdjusters.firstDayOfMonth())) } fun LocalDateTime.hoursSinceNow(): Long { val now = LocalDateTime.now() val difference = Duration.between(now, this) return difference.toHours() } fun LocalDateTime.minutesSinceNow(): Long { val now = LocalDateTime.now() val difference = Duration.between(now, this) return difference.toMinutes() } fun LocalDateTime.timeSinceNowAsString(): String { return String.format("%d시간 %d분", this.hoursSinceNow(), this.minutesSinceNow() % 60) }
package com.testscripts.demoblaze; import java.io.IOException; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.genericlib.demoblaze.Base; import com.genericlib.demoblaze.EventList; import com.objectrepo.demoblaze.Homepage; @Listeners(EventList.class) public class AddToCart extends Base { @Test(groups = {"smoke"}) public void addToCartTest() throws InterruptedException, IOException { test=report.createTest("validate product can be added to cart"); test.pass("logged into the app as "+fl.getDataFromproperties("username")); Homepage hp=PageFactory.initElements(driver, Homepage.class); test.pass("landed on HomePage"); Thread.sleep(2000); ProductNmae = hp.getNexus6().getText(); hp.getNexus6().click(); test.pass("Clicked on Nexus6 product"); test.pass("Navigated to product details page"); Thread.sleep(2000); hp.getAddToCart().click(); test.pass("Clicked on Add to cart button"); cu.waitTillAlertToBeDisplayed(driver); cu.acceptAlert(driver); test.pass("Handled the alert"); hp.getCart().click(); Assert.assertTrue(cu.verifyProductInCart(ProductNmae, driver).isDisplayed()); Reporter.log("Added to the cart",true); test.pass("Verify the product in cart"); } }
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.privatethoughts.data; import android.net.Uri; import android.provider.BaseColumns; /** *Defines the table structure as well as URL's */ public class JournalContract { public static final String CONTENT_AUTHORITY = "com.example.android.privatethoughts"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); public static final String PATH_JOURNAL = "journal"; public static final String PATH_JOURNAL_ACCOUNT = "journal_account"; /** *Inner class to definr journal entries table contents and structuer */ public static final class JournalEntry implements BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon() .appendPath(PATH_JOURNAL) .build(); public static final String TABLE_NAME = "journal_"; public static final String COLUMN_TIMESTAMP = "timestamp"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_CONTENT = "content"; public static final String COLUMN_COLOUR = "colour"; public static final String COLUMN_EMAIL = "email"; public static final String COLUMN_PASSWORD = "password"; /** * Builds a uri with a timestamp attached at the end which points to the table entry * @param timestamp the time of the insert or edit normalizzed into milliseconds * @return Uri pointing to the specific table row corresponding to the timestamp passed */ public static Uri buildJournalUriWithTimestamp(long timestamp) { return CONTENT_URI.buildUpon() .appendPath(Long.toString(timestamp)) .build(); } } /** * Inner class to define user accounts content and table */ public static final class JournalAccount implements BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon() .appendPath(PATH_JOURNAL_ACCOUNT) .build(); public static final String TABLE_NAME = "journal_account"; public static final String COLUMN_USERNAME = "username"; public static final String COLUMN_EMAIL = "email"; public static final String COLUMN_PASSWORD = "password"; /** * Builds a uri with an email string attached at the end which points to the table entry * @param email is the email address of the user * @return Uri pointing to the specific table row corresponding to the timestamp passed */ public static Uri buildJournalAccountUriWithEmail(String email) { return CONTENT_URI.buildUpon() .appendPath(email) .build(); } } }
package com.bitio.productscomponent.domain.repository import com.bitio.productscomponent.data.remote.request.CartItemBody import com.bitio.productscomponent.data.remote.response.CartItemResponse import com.bitio.productscomponent.data.remote.response.CartResponse import com.bitio.productscomponent.data.remote.response.OrderResponse import com.bitio.productscomponent.domain.model.Brand import com.bitio.productscomponent.domain.model.GeneralCart import com.bitio.productscomponent.domain.model.categories.Category import com.bitio.productscomponent.domain.model.categories.GenderType import com.bitio.productscomponent.domain.model.favorites.Favorite import com.bitio.productscomponent.domain.model.products.Product import com.bitio.productscomponent.domain.model.products.ProductDetails import com.bitio.sharedcomponent.data.ResponseWrapper import kotlinx.coroutines.flow.StateFlow interface ProductRepository { suspend fun getProductsByCategoryAndBrand( brand: String?, categoriesIds: List<String>?, hasDiscount: Boolean?, page: Int, limit: Int ): List<Product> suspend fun getProductsById(id: String): ProductDetails suspend fun getCategoriesByGender(genderType: GenderType): List<Category> suspend fun getBrands(): List<Brand> fun getFavoriteIdsFlow(): StateFlow<HashSet<String>> suspend fun addProductToFavorites(product: Product) suspend fun removeProductFromFavorite(id: String) suspend fun getAllProductsFromCart(): ResponseWrapper<CartResponse> suspend fun addProductToCart(generalCart: GeneralCart): ResponseWrapper<CartResponse> suspend fun deleteProductFromCart(cartId:String): ResponseWrapper<CartResponse> suspend fun editProductOfCart(cartId:String, quantity: Int): ResponseWrapper<CartResponse> suspend fun getAllOrders(): ResponseWrapper<List<OrderResponse>> suspend fun getFavoritesOfUser(): ResponseWrapper<List<Favorite>> }
import numpy as np class ARTNetwork: def __init__(self, input_size, vigilance): self.input_size = input_size self.vigilance = vigilance self.weights = np.zeros((input_size,1)) def train(self, input_data,epochs): normalized_input = input_data / np.linalg.norm(input_data) for _ in range(epochs): similarity = normalized_input @ self.weights if similarity.any() >= self.vigilance: return self.weights = np.maximum(self.weights, normalized_input) normalized_input = self.weights / np.linalg.norm(self.weights) def predict(self, input_data): normalized_input = input_data / np.linalg.norm(input_data) similarity = normalized_input @ self.weights if similarity.any() >= self.vigilance: output_pattern = np.zeros(len(similarity)) print(similarity) winner = np.argmax(similarity) output_pattern[winner] = 1 else: output_pattern = np.zeros(len(similarity) + 1) output_pattern[-1] = 1 return output_pattern # Usage example input_size = 4 vigilance = 0.9 art = ARTNetwork(input_size, vigilance) # Training data data = np.array([[1, 1, 0, 0], [0, 1, 0, 1], [0, 0, 1, 1], [1, 0, 1, 0]]) # Train the ART network for sample in data: art.train(sample,1000) # Test a new input new_input = np.array([0, -1, 0, 0]) new_output = art.predict(new_input) print(new_output)
import Navbar from "./Components/Shared/Navbar"; import Footer from "./Components/Shared/Footer"; import Home from "./Components/Home/Home"; import Presentation from "./Components/Presentation/Presentation" import Project from "./Components/Project/Projects"; import Adhesions from "./Components/Adhesion/Adhesions"; import {Routes,Route} from "react-router-dom"; import Contactus from "./Components/Home/Contactus"; import Login from "./Components/Shared/Login"; import Dashboard from './Dashboard/Table' function App() { return ( <div className="App"> <Navbar></Navbar> <Routes> <Route path="/" element={<Home/>}/> <Route path="/Presentation" element={<Presentation/>}/> <Route path="/Project" element={<Project/>}/> <Route path="/Adhesions" element={<Adhesions/>}/> <Route path="/Contact" element={<Contactus/>}/> <Route path="/Login" element={<Login/>}/> <Route path="/Dashboard" element={<Dashboard/>}/> </Routes> <Footer></Footer> </div> ); } export default App;
# 내 풀이 (정답) (45분 소요) # 1. 각 학생 점수에서 평균 점수를 빼고 절대값 씌우기 # 2. |점수-평균| 가장 낮은 index만 추출해서, 그 index에 해당하는 실제 점수만 추출 # 3. 추출한 점수 모두 같을 때 -> 빠른 학생 번호 출력 # 4. 추출한 점수 다를 때 # 4-1. 높은 점수만 남겨서 빠른 학생 번호 출력 import sys sys.stdin = open("input.txt", "r") n = int(input()) scores = list(map(int, input().split())) mean_score = int((sum(scores) / n) + 0.5) # mean_score = int(round((sum(scores) / n), 0)) -> (X) lst = list(map(lambda x: abs(x - mean_score), scores)) # |점수-평균| min_lst = min(lst) zip_lst = list(zip(range(1, n + 1), scores, lst)) # 학생번호, 점수, |점수-평균| index_lst = [index for index in range(n) if min_lst == zip_lst[index][2]] # |점수-평균|가 가장 낮은 index score_lst = [zip_lst[index][1] for index in index_lst] # |점수-평균|가 가장 낮은 index에 해당하는 실제 점수 with open("output4.txt", "a") as f: if len(set(score_lst)) == 1: print(mean_score, index_lst[0] + 1, file=f) else: max_score_lst = max(score_lst) result = [i for i, s in enumerate(score_lst) if s == max_score_lst] print(mean_score, index_lst[result[0]] + 1, file=f) # 정답 해설 # 오류 수정 : python에서 round()는 round_half_even 방식이므로, 반올림 계산 시 사용하면 X # round_half_even 방식 : 소수점 첫번째 자리가 정확히 0.5인 경우 올림하는 것이 아니라 "짝수"쪽에 근사시킴 # (ex) round(4.5) = 4, round(5.5) = 6, round(4.51) = 5 # 따라서 round(a) 대신, int(a + 0.5) 사용할 것! import sys sys.stdin = open("input.txt", "r") n = int(input()) a = list(map(int, input().split())) ave = int((sum(a) / n) + 0.5) # ave = round(sum(a) / n) -> (X) min_ = 2147000000 # int형으로 표현할 수 있는 (4byte = 2 ^ 31) 정도 되는 가장 큰 수 for idx, x in enumerate(a): tmp = abs(x - ave) if tmp < min_: min_ = tmp score = x res = idx + 1 elif tmp == min_: if x > score: # (중요) 문제에서 더 늦은 학생 번호를 출력하라고 하면, 여기에 등호(=) 추가 score = x res = idx + 1 print(ave, res) # Test Case. # < input > # 10 # 45 73 66 87 92 67 75 79 75 80 # < output > # 74 7
--- date: 2022-10-01 title: Voice Chat aliases: - /docs/voice-chat - /voice-chat - /docs/voice-chat - /decentraland/voice-chat description: In-World Voice Chat categories: - Decentraland type: Document url: /player/general/in-world-features/voice-chat --- ### Accessing the chat When you enter the world, the voice chat will be automatically connected. You can confirm that voice chat is connected, when you see this UI in the taskbar. <img src="/images/media/voice-chat-1.png" style="margin: 2rem auto; display: block;width: 90%;"/> ### Sending audio message To send message to nearby users there are few ways: - Press and hold the microphone button - Hold 'T' key - Press 'Alt' + 'T' key (Note: the voice chat will stay active until you press the 'Alt' + 'T', 'T' or the microphone button again) Note: It is possible that the first time you do this, the browser will ask you about microphone permissions. You will see a browser’s modal similar to this <img src="/images/media/voice-chat-2.png" style="margin: 2rem auto; display: block;width: 90%;"/> > You have to grant the website required permission to be able to use voice chat feature ### Seeing nearby users You can see all nearby users by opening the Voice Chat window. For that, you will have to click on the headphones button in the taskbar and this window will be showed <img src="/images/media/voice-chat-3.png" style="margin: 2rem auto; display: block;width: 60%;"/> ### Filtering users I want to listen to At the top left corner of the Voice Chat window you will find a selector with which allow you to choose which people you want to listen to - **All** You will listen to everyone connected to the Voice Chat. - **Verified Users** You will only listen to those users with a verified name in Decentraland. - **Friends** You will only listen to your friends. ### Muting unwanted users Manage the audio input from specific users by: 1. Clicking the speaker icon next to a user's name to mute/unmute them individually. 2. Utilize the `MUTE ALL` toggle at the top right corner to mute/unmute all nearby users collectively. ### Leaving chat To exit the chat: 1. Click the `LEAVE` button situated either at the top right of the Voice Chat window or on the right side of the Voice Chat bar. 2. To rejoin, click on the `JOIN VOICE CHAT` button, displayed below. <img src="/images/media/voice-chat-4.png" style="margin: 2rem auto; display: block;width: 90%;"/> Clicking on the `JOIN VOICE CHAT` button, you will be connected again. # Troubleshooting ### The Voice Chat get disconnected when I try to send audio message For some users, when they try to send an audio message for the first time, may receive this warning message in the top of the screen. <img src="/images/media/voice-chat-5.png" style="margin: 2rem auto; display: block;width: 90%;"/> If you experience this, you will notice that just after that happens the Voice Chat is disconnected. Simply click on the `JOIN VOICE CHAT` button in the taskbar and it will be connected again. <img src="/images/media/voice-chat-6.png" style="margin: 2rem auto; display: block;width: 60%;"/> ### My Voice Chat is connected but I can’t send neither hear audio messages - **Check your microphone device is correctly connected<br/>** Sometimes we can notice that we can hear other users but they don’t hear us. So, first of all, please check your microphone is correctly connected to your computer and, if needed, do a quick test in any recording audio software to be sure your microphone is capturing your voice correctly. - **Check the mute/unmute status of the nearby users<br/>** Check if you have some users (or even all of them) muted. It does not usually happen but, as the mute/unmute status of the users is stored between sessions, could be a possible reason. - **Check the mute/unmute status of your tab in your browser<br/>** You might have forgotten that your tab is muted in the browser, check the settings. - **Microphone permissions wrongly configured<br/>** Another possible cause could be not having the microphone permissions allowed in your browser. This could happen in case you missed the permissions popup the first time the browser asked you for, or maybe you forgot to apply any action when the browser asked you. In any case, we can check this configuration again by opening our browser’s configuration: **Settings** → **Privacy and Security** → **Site Settings** and look for `play.decentraland.org` in **Recent activity**. You will see a list of permissions <img src="/images/media/voice-chat-7.png" style="margin: 2rem auto; display: block;width: 90%;"/> > It is important that, after doing this, you close and re-open the browser to apply the changes. From this point on you should be able to send and receive audio messages correctly.
package jpabook.jpashop.domain; import javax.persistence.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import static javax.persistence.FetchType.*; @Entity @Table(name = "ORDERS") public class Order extends BaseEntity{ @Id @GeneratedValue @Column(name = "ORDER_ID") private Long Id; /* @Column(name = "MEMBER_ID") private Long memberId; */ @ManyToOne(fetch = LAZY) @JoinColumn(name = "MEMBER_ID") private Member member; private LocalDateTime orderDate; @Enumerated(EnumType.STRING) private OrderStatus status; @OneToMany(mappedBy = "order", cascade = CascadeType.ALL) private List<OrderItem> orderItems = new ArrayList<>(); @OneToOne(fetch = LAZY, cascade = CascadeType.ALL) @JoinColumn(name = "DELIVERY_ID") private Delivery delivery; public void addOrderItem(OrderItem orderItem) { orderItems.add(orderItem); orderItem.setOrder(this); } public Long getId() { return Id; } public void setId(Long id) { Id = id; } public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } public LocalDateTime getOrderDate() { return orderDate; } public void setOrderDate(LocalDateTime orderDate) { this.orderDate = orderDate; } public OrderStatus getStatus() { return status; } public void setStatus(OrderStatus status) { this.status = status; } public List<OrderItem> getOrderItems() { return orderItems; } public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } }
from torchmetrics import Metric from torchmetrics.image import PeakSignalNoiseRatio from torchmetrics.image import StructuralSimilarityIndexMeasure from torchmetrics.image.fid import FrechetInceptionDistance import torchvision import torch import torch.nn.functional as F class ZaloMetric(Metric): def __init__(self): super().__init__() self.model = torchvision.models.inception_v3(pretrained=True) self.model.eval() self.model.fc = torch.nn.Identity() self.resize = torchvision.transforms.Resize(size=[299, 299]) self.psnr = PeakSignalNoiseRatio(data_range=255.0) self.ssim = StructuralSimilarityIndexMeasure(data_range=255.0) self.fid = FrechetInceptionDistance(feature=2048) self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum") self.add_state("psnr_acc", default=torch.tensor(0, dtype=torch.float32), dist_reduce_fx="sum") self.add_state("ssim_acc", default=torch.tensor(0, dtype=torch.float32), dist_reduce_fx="sum") self.add_state("cosine_acc", default=torch.tensor(0, dtype=torch.float32), dist_reduce_fx="sum") #self.add_state("fid_acc", default=torch.tensor(0), dist_reduce_fx="sum") def update(self, preds:torch.Tensor, target:torch.Tensor): #preds, target = self._input_format(preds, target) assert preds.shape == target.shape self.total += preds.shape[0] self.psnr_acc += 1/(1+self.psnr(preds.type(torch.float32), target.type(torch.float32))) self.ssim_acc += 1 - (self.ssim(preds.type(torch.float32), target.type(torch.float32)) + 1)/2 self.fid.update(preds.type(torch.uint8), real=False) self.fid.update(target.type(torch.uint8), real=True) self.cosine_acc += (1 - self.consine_similarity(preds.type(torch.float32), target.type(torch.float32)))/2 def consine_similarity(self, preds, target): preds, target = self.resize(preds), self.resize(target) with torch.no_grad(): preds_feature, target_feature = self.model(preds), self.model(target) similarity = F.cosine_similarity(preds_feature, target_feature).mean() return similarity def compute(self, reset=False): fid_acc = 1 - 1/(1 + self.fid.compute()) if reset: self.fid.reset() return 0.25*(self.psnr_acc + self.ssim_acc + self.cosine_acc) / self.total + fid_acc/4
// rivet project // Copyright (c) 2023 <https://github.com/yretenai/rivet> // SPDX-License-Identifier: MPL-2.0 #pragma once #include <ankerl/unordered_dense.h> #include <cstdint> #include <memory> #include <string_view> #include <unordered_set> #include <utility> #include <rivet/rivet_array.hpp> #include <rivet/rivet_keywords.hpp> namespace rivet::data { struct RIVET_SHARED dat1 { constexpr static uint32_t magic = 0x44415431u; struct dat1_header { uint32_t magic; rivet_type_id schema; rivet_size size; uint16_t section_count; uint16_t reserved; }; static_assert(sizeof(dat1_header) == 16); struct dat1_entry { rivet_type_id type_id; rivet_off offset; rivet_size size; }; static_assert(sizeof(dat1_entry) == 12); dat1_header header = {}; std::shared_ptr<rivet_data_array> buffer = {}; std::shared_ptr<rivet_data_array> resident_buffer = {}; std::unordered_set<rivet_type_id> section_ids = {}; ankerl::unordered_dense::map<rivet_type_id, std::pair<dat1_entry, std::shared_ptr<rivet_data_array>>> sections; std::string_view type_name = {}; dat1() = default; explicit dat1(const std::shared_ptr<rivet_data_array> &stream, const std::shared_ptr<rivet_data_array> &resident_buffer = nullptr); [[nodiscard]] auto get_section_data(rivet_type_id type_id) const -> std::shared_ptr<rivet_data_array>; template <typename T> auto get_section(const rivet_type_id type_id) const -> std::shared_ptr<rivet_array<T>> { const auto data = get_section_data(type_id); if (data == nullptr) { return nullptr; } return data->cast<T>(); } }; } // namespace rivet::data
fn main() { // `n` will take the values: 1, 2, ..., 100 in each iteration for n in 1..101 { if n % 15 == 0 { println!("fizzbuzz"); } else if n % 3 == 0 { println!("fizz"); } else if n % 5 == 0 { println!("buzz"); } else { println!("{}", n); } } } fn main() { // `n` will take the values: 1, 2, ..., 100 in each iteration for n in 1..=100 { if n % 15 == 0 { println!("fizzbuzz"); } else if n % 3 == 0 { println!("fizz"); } else if n % 5 == 0 { println!("buzz"); } else { println!("{}", n); } } } fn main() { let names = vec!["Bob", "Frank", "Ferris"]; for name in names.iter() { match name { &"Ferris" => println!("There is a rustacean among us!"), // TODO ^ Try deleting the & and matching just "Ferris" _ => println!("Hello {}", name), } } println!("names: {:?}", names); } fn main() { let names = vec!["Bob", "Frank", "Ferris"]; for name in names.into_iter() { match name { "Ferris" => println!("There is a rustacean among us!"), _ => println!("Hello {}", name), } } println!("names: {:?}", names); // FIXME ^ Comment out this line } fn main() { let mut names = vec!["Bob", "Frank", "Ferris"]; for name in names.iter_mut() { *name = match name { &mut "Ferris" => "There is a rustacean among us!", _ => "Hello", } } println!("names: {:?}", names); }
// This file is part of the MDCII project. // // Copyright (c) 2022. stwe <https://github.com/stwe/MDCII> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #pragma once #include <memory> #include <array> #include <vector> #include <AL/al.h> //------------------------------------------------- // Forward declarations //------------------------------------------------- namespace mdcii::file { /** * Forward declaration class SoundFile. */ class SoundFile; } //------------------------------------------------- // MusicBuffer //------------------------------------------------- namespace mdcii::sound { /** * Streaming a soundtrack. */ class MusicBuffer { public: //------------------------------------------------- // Ctors. / Dtor. //------------------------------------------------- MusicBuffer() = delete; /** * Constructs a new MusicBuffer object. * * @param t_soundFile A SoundFile object. */ explicit MusicBuffer(std::shared_ptr<file::SoundFile> t_soundFile); MusicBuffer(const MusicBuffer& t_other) = delete; MusicBuffer(MusicBuffer&& t_other) noexcept = delete; MusicBuffer& operator=(const MusicBuffer& t_other) = delete; MusicBuffer& operator=(MusicBuffer&& t_other) noexcept = delete; ~MusicBuffer() noexcept; //------------------------------------------------- // Getter //------------------------------------------------- [[nodiscard]] bool IsPlaying() const; //------------------------------------------------- // Logic //------------------------------------------------- void Play(); void Pause() const; void Stop() const; void Resume() const; void UpdateBufferStream(); protected: private: //------------------------------------------------- // Constants //------------------------------------------------- static constexpr auto BUFFER_SAMPLES{ 8192 }; static constexpr auto NUM_BUFFERS{ 4 }; //------------------------------------------------- // Member //------------------------------------------------- /** * A SoundFile object holding audio data. */ std::shared_ptr<file::SoundFile> m_soundFile; /** * The audio source object handle. */ ALuint m_sourceId{ 0 }; /** * Holding the raw audio stream. */ std::array<ALuint, NUM_BUFFERS> m_buffersIds{ 0, 0, 0, 0 }; /** * Chunk of audio data. */ std::vector<short> m_chunkBuffer; //------------------------------------------------- // Init //------------------------------------------------- /** * Initializes the music buffer. */ void Init(); //------------------------------------------------- // Helper //------------------------------------------------- void CreateAudioSource(); void CreateBuffer(); //------------------------------------------------- // Clean up //------------------------------------------------- /** * Clean up. */ void CleanUp() const; }; }
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #ifndef INCL_BRIEFCASE_CACHE_SYNC_SOURCE #define INCL_BRIEFCASE_CACHE_SYNC_SOURCE /** @cond API */ /** @addtogroup Client */ /** @{ */ #include "base/fscapi.h" #include "spds/constants.h" #include "spds/SyncItem.h" #include "spds/SyncMap.h" #include "spds/SyncStatus.h" #include "spdm/ManagementNode.h" #include "base/util/ItemContainer.h" #include "spds/FileData.h" #include "client/CacheSyncSource.h" #define DEFAULT_BRIEFCASE_DIR "." /** * Synchronizes the content of files in a certain directory and handles * the modification and cache or listener structure * */ class BriefcaseCacheSyncSource : public CacheSyncSource { private: StringBuffer dir; protected: // The copy is protected //BriefcaseSyncSource(const BriefcaseSyncSource& s); public: BriefcaseCacheSyncSource(const WCHAR* name, AbstractSyncSourceConfig* sc); ~BriefcaseCacheSyncSource(); void assign(BriefcaseCacheSyncSource& s); /** * set/get the directory where to sync the files */ void setDir(const char* p) { dir = p; } const StringBuffer& getDir() { return dir; }; /** * Save the file inside the filesystem. * Return 0 is success otherwise failure */ int saveFileData(FileData& file); /** * Save the file inside the filesystem. * It doesn't use the FileData SyncMLobject but * it uses only the data as inside * * @param item the item from which get the data * @param isUpdate it says if the item must to be add (false) * or updated (true) * */ int saveFileData(SyncItem& item, bool isUpdate); /** * Parse the file object * Return 0 is success otherwise failure */ int parseFileData(FileData& file, SyncItem& item); /** * Get the list of all the keys stored in a StringBuffer. It reads all the * files name in the directory. The directory is set in the sync source. */ Enumeration* getAllItemList(); /** * Removes all the item of the sync source. It is called * by the engine in the case of a refresh from server to clean * all the client items before receiving the server ones. */ int removeAllItems(); /** * Called by the sync engine to add an item that the server has sent. * The sync source is expected to add it to its database, then set the * key to the local key assigned to the new item. Alternatively * the sync source can match the new item against one of the existing * items and return that key. * * @param item the item as sent by the server * @return SyncML status code */ int insertItem(SyncItem& item); /** * Called by the sync engine to update an item that the source already * should have. The item's key is the local key of that item. * * @param item the item as sent by the server * @return SyncML status code */ int modifyItem(SyncItem& item); /** * Called by the sync engine to update an item that the source already * should have. The item's key is the local key of that item, no data is * provided. * * @param item the item as sent by the server */ int removeItem(SyncItem& item); /** * Get the content of an item given the key. It is used to populate * the SyncItem before the engine uses it in the usual flow of the sync. * It is used also by the itemHandler if needed * (i.e. in the cache implementation) * * @param key the local key of the item * @param size OUT: the size of the content */ void* getItemContent(StringBuffer& key, size_t* size); }; /** @} */ /** @endcond */ #endif
import { ApplicationRef, Injectable, inject } from '@angular/core'; @Injectable({ providedIn: 'root', useFactory: () => inject(AnimationFrameTickScheduler), }) export abstract class TickScheduler { abstract schedule(): void; } @Injectable({ providedIn: 'root', }) export class AnimationFrameTickScheduler extends TickScheduler { private isScheduled = false; constructor(private readonly appRef: ApplicationRef) { super(); } schedule(): void { if (!this.isScheduled) { this.isScheduled = true; requestAnimationFrame(() => { this.appRef.tick(); this.isScheduled = false; }); } } }
let hargaKamar = 0 ; // Variabel ini menyimpan harga kamar per malam. let durasiMenginap = 0 ; // Variabel ini menyimpan durasi hari yang diinginkan untuk menginap. let hargaBreakfast = 0; // Variabel ini menyimpan harga tambahan untuk sarapan per hari. let isDiskon = false; // Variabel boolean yang menunjukkan apakah diskon berlaku atau tidak. Jika true, diskon akan diberikan. let totalHargaKamar = 0; // Variabel ini menyimpan total harga kamar ( harga kamar * durasi ) let totalHargaBreakfast = 0; // Variabel ini menyimpan total harga breakfast ( harga breakfast * durasi ) let totalHargaDiskon = 0; // Variabel ini menyimpan total Diskon ( Total harga kamar * 10 % ) /* Objek formatter digunakan untuk memformat nilai angka menjadi format mata uang Indonesia (IDR) dengan menggunakan standar internasional. */ const formatter = new Intl.NumberFormat("id-ID", { style: "currency", currency: "IDR", }); function handleTipeKamar(element){ /* Fungsi handleTipeKamar(element) Fungsi ini bertanggung jawab untuk menangani perubahan tipe kamar yang dipilih oleh pengguna. Ketika pengguna memilih tipe kamar, harga kamar akan disesuaikan sesuai dengan pilihan tersebut. Parameter: * element: Objek elemen HTML yang dipilih oleh pengguna, seperti <select>. Algoritma: * Fungsi ini akan dilankan jika nilai element select tipe-kamar diubah oleh user. * Jika nilai sesuai dengan salah satu kasus ("family", "deluxe", atau "standard"), maka variabel hargaKamar akan diperbarui sesuai dengan harga kamar yang sesuai. * Lalu Memanggil fungsi updateAll () */ switch(element.value){ case "family": hargaKamar = 1000000; break; case "deluxe": hargaKamar = 750000; break; case "standart": hargaKamar = 750000; break; default: hargaKamar = 0; break; } updateAll(); } function handleDurasiMenginap(element){ /* Fungsi handleDurasiMenginap(element) Fungsi ini digunakan untuk menangani perubahan durasi menginap yang dipilih oleh pengguna. Ketika pengguna memilih durasi menginap tertentu, fungsi ini akan mengubah nilai durasiMenginap dan menyesuaikan status diskon sesuai dengan aturan yang ditentukan. Parameter: * element: Objek elemen HTML yang dipilih oleh pengguna, seperti inputan teks. Algoritma: 1. Fungsi ini mengatur nilai durasiMenginap menjadi nilai yang dipilih oleh pengguna. 2. Fungsi ini juga memeriksa apakah durasi menginap lebih dari 3 malam. Jika iya, maka diskon sebesar 10% diberikan. Jika tidak, diskon diatur menjadi tidak aktif. 3. Selanjutnya, fungsi akan memperbarui nilai diskon yang ditampilkan di dalam elemen HTML dengan ID "diskon". 4. fungsi memanggil fungsi updateAll() untuk memperbarui nilai-nilai terkait. */ durasiMenginap = element.value; if(Number(element.value) > 3 ){ isDiskon = true; document.getElementById("diskon").innerHTML = "10"; console.log(document.getElementById("diskon")) }else{ isDiskon = false; document.getElementById("diskon").innerHTML = "0"; } updateAll(); } function handleBreakfast(element){ /* Fungsi handleBreakfast(element) Fungsi ini bertanggung jawab untuk menangani pilihan sarapan pengguna. Ketika pengguna memilih atau membatalkan pilihan sarapan, fungsi ini akan mengubah nilai hargaBreakfast sesuai dengan keputusan pengguna. Parameter: * element: Objek elemen HTML yang dipilih oleh pengguna, seperti checkbox. Algoritma: 1. Fungsi ini memeriksa apakah kotak centang untuk sarapan (element) dicentang. 2. Jika dicentang, maka nilai hargaBreakfast diatur ke harga sarapan yang ditentukan. 3. Jika tidak dicentang, maka nilai hargaBreakfast diatur menjadi 0. 4. Setelah itu, fungsi memanggil updateAll() untuk memperbarui nilai-nilai terkait. */ if(element.checked){ hargaBreakfast = 80000; }else{ hargaBreakfast = 0; } updateAll(); } function updateHargaKamar(){ /* Fungsi updateHargaKamar() Fungsi ini bertugas untuk memperbarui tampilan harga kamar dalam elemen input HTML dengan ID "harga-kamar". Harga kamar akan diformat menggunakan objek formatter sebelum ditampilkan. Algoritma: 1. Fungsi ini mengambil elemen input HTML dengan ID "harga-kamar" menggunakan document.getElementById(). 2. Nilai hargaKamar akan diformat menjadi format mata uang IDR menggunakan objek formatter. 3. Nilai yang diformat akan diatur sebagai nilai dari elemen input tersebut. */ hargaKamarInputElement = document.getElementById("harga-kamar"); hargaKamarInputElement.value = formatter.format(hargaKamar); } function updateTotalHargaKamar(){ /* Fungsi updateTotalHargaKamar() Fungsi ini bertugas untuk menghitung dan memperbarui total harga kamar berdasarkan harga kamar per malam (hargaKamar) dan durasi menginap (durasiMenginap). Hasil perhitungan akan diformat menggunakan objek formatter sebelum ditampilkan di dalam elemen input HTML dengan ID "total-harga-kamar". Algoritma: 1. Fungsi ini mengambil elemen input HTML dengan ID "total-harga-kamar" menggunakan document.getElementById(). 2. Total harga kamar dihitung dengan mengalikan hargaKamar dengan durasiMenginap. 3. Nilai total harga kamar yang telah diformat akan diatur sebagai nilai dari elemen input tersebut. */ totalHargaKamarInputElement = document.getElementById("total-harga-kamar"); totalHargaKamar = hargaKamar * durasiMenginap; totalHargaKamarInputElement.value = formatter.format(totalHargaKamar); } function updateTotalHargaBreakfast(){ /* Fungsi updateTotalHargaBreakfast() Fungsi ini bertugas untuk menghitung dan memperbarui total harga sarapan berdasarkan harga sarapan per orang (hargaBreakfast) dan durasi menginap (durasiMenginap). Hasil perhitungan akan diformat menggunakan objek formatter sebelum ditampilkan di dalam elemen input HTML dengan ID "total-harga-breakfast". Algoritma: Fungsi ini mengambil elemen input HTML dengan ID "total-harga-breakfast" menggunakan document.getElementById(). Total harga sarapan dihitung dengan mengalikan hargaBreakfast dengan durasiMenginap. Nilai total harga sarapan yang telah diformat akan diatur sebagai nilai dari elemen input tersebut. */ totalHargaBreakfestElement = document.getElementById("total-harga-breakfast"); totalHargaBreakfast = hargaBreakfast * durasiMenginap; totalHargaBreakfestElement.value = formatter.format(totalHargaBreakfast); } function updateTotalHargaDiskon(){ /* Fungsi updateTotalHargaDiskon() Fungsi ini bertugas untuk menghitung dan memperbarui total harga dengan diskon. Jika diskon berlaku (isDiskon bernilai true), maka total harga diskon akan dihitung sebagai 10% dari total harga kamar (totalHargaKamar). Hasil perhitungan akan diformat menggunakan objek formatter sebelum ditampilkan di dalam elemen input HTML dengan ID "total-harga-diskon". Algoritma: 1. Fungsi ini mengambil elemen input HTML dengan ID "total-harga-diskon" menggunakan document.getElementById(). 2. Total harga diskon dihitung dengan menggunakan operator ternary: jika diskon berlaku (isDiskon bernilai true), maka total harga diskon adalah 10% dari total harga kamar (totalHargaKamar), jika tidak,total harga diskon diatur menjadi 0. 3. Nilai total harga diskon yang telah diformat akan diatur sebagai nilai dari elemen input tersebut. */ totalHargaDiskonElement = document.getElementById("total-harga-diskon"); totalHargaDiskon = (isDiskon) ? totalHargaKamar * 0.1 : 0; totalHargaDiskonElement.value = formatter.format(totalHargaDiskon); } function updateTotalTagihan(){ /* Fungsi updateTotalTagihan() Fungsi ini bertugas untuk menghitung dan memperbarui total tagihan akhir yang harus dibayarkan oleh pengguna. Total tagihan dihitung berdasarkan total harga kamar (totalHargaKamar), total harga sarapan (totalHargaBreakfast), dan total harga diskon (totalHargaDiskon). Hasil perhitungan akan diformat menggunakan objek formatter sebelum ditampilkan di dalam elemen input HTML dengan ID "total-tagihan". Algoritma: 1. Fungsi ini mengambil elemen input HTML dengan ID "total-tagihan" menggunakan document.getElementById(). 3. Total tagihan dihitung dengan menjumlahkan total harga kamar (totalHargaKamar), total harga sarapan (totalHargaBreakfast), dan mengurangkan total harga diskon (totalHargaDiskon). 4. Nilai total tagihan yang telah diformat akan diatur sebagai nilai dari elemen input tersebut. */ totalTagihanElement = document.getElementById("total-tagihan"); totalTagihanElement.value = formatter.format(totalHargaKamar + totalHargaBreakfast - totalHargaDiskon) ; } function updateAll(){ /* Fungsi updateAll() Fungsi ini bertugas untuk memperbarui semua nilai terkait dengan perhitungan harga kamar hotel. Fungsi ini memanggil fungsi-fungsi updateHargaKamar(), updateTotalHargaKamar(), updateTotalHargaBreakfast(), dan updateTotalHargaDiskon() secara berurutan. Algoritma: 1. Fungsi ini memanggil fungsi updateHargaKamar() untuk memperbarui tampilan harga kamar. 2. Selanjutnya, fungsi memanggil fungsi updateTotalHargaKamar() untuk menghitung dan memperbarui total harga kamar. 3. Kemudian, fungsi memanggil fungsi updateTotalHargaBreakfast() untuk menghitung dan memperbarui total harga sarapan. 4. Setelah itu, fungsi memanggil fungsi updateTotalHargaDiskon() untuk menghitung dan memperbarui total harga diskon. */ updateHargaKamar(); updateTotalHargaKamar(); updateTotalHargaBreakfast(); updateTotalHargaDiskon(); } function handleHitungButton(){ /* Fungsi handleHitungButton() Fungsi ini bertanggung jawab untuk menangani penggunaan tombol "Hitung" yang bertujuan untuk menghitung total tagihan akhir berdasarkan semua nilai yang telah dimasukkan atau diubah oleh pengguna. Algoritma: 1. Ketika pengguna menekan tombol "Hitung", fungsi ini akan dipanggil. 2. Fungsi kemudian memanggil fungsi updateTotalTagihan() untuk menghitung total tagihan akhir berdasarkan semua nilai yang telah dimasukkan atau diubah oleh pengguna. */ updateTotalTagihan(); } function handleLengthID(element){ /* Fungsi handleLengthID(element) Fungsi ini bertanggung jawab untuk menangani validasi panjang ID yang dimasukkan oleh pengguna. Jika panjang ID yang dimasukkan kurang dari 16 karakter atau bukan merupakan angka, maka nilai input akan dihapus. Parameter: * element: Objek elemen HTML yang dipilih oleh pengguna, seperti input teks. Algoritma: 1. Fungsi ini mengambil nilai dari elemen input dan menyimpannya dalam variabel value. 2. Fungsi memeriksa apakah nilai value bukan merupakan angka (diperiksa dengan isNaN()) atau panjangnya kurang dari 16 karakter. 3. Jika salah satu kondisi terpenuhi, nilai input (element.value) akan diatur menjadi string kosong (""), sehingga menghapus nilai yang dimasukkan oleh pengguna. */ let value = element.value; if(isNaN(value) || value.length < 16){ element.value = ""; } } function handleInvalidID(element){ /* Fungsi handleInvalidID(element) Fungsi ini bertanggung jawab untuk menangani validasi ID yang dimasukkan oleh pengguna yang tidak memenuhi syarat. Jika ID yang dimasukkan tidak tepat, pesan kesalahan akan ditampilkan kepada pengguna. Parameter: * element: Objek elemen HTML yang dipilih oleh pengguna, seperti input teks. Algoritma: 1. Fungsi ini menggunakan metode setCustomValidity() dari elemen input untuk menetapkan pesan kesalahan kustom. 2. Pesan kesalahan yang ditetapkan adalah "isian salah..data harus 16 digit", yang menunjukkan kepada pengguna bahwa data yang dimasukkan harus memiliki panjang 16 digit. */ element.setCustomValidity(" isian salah..data harus 16 digit"); } function handleCancelButton(){ /* Fungsi handleCancelButton() Fungsi ini bertanggung jawab untuk menangani penggunaan tombol "Batal". Ketika tombol "Batal" ditekan, pengguna akan dialihkan kembali ke halaman utama web hotel (misalnya, http://localhost/web-hotel). Algoritma: 1. Ketika pengguna menekan tombol "Batal", fungsi ini akan dipanggil. 2. Fungsi menggunakan window.location.href untuk mengatur URL halaman saat ini ke URL yang ditentukan, dalam hal ini, halaman utama web hotel. */ window.location.href = 'http://localhost/web-hotel'; }
package com.ssafy.guestbook.controller; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.ssafy.guestbook.model.MemberDto; import com.ssafy.guestbook.model.service.MemberService; @RestController @RequestMapping("/admin") @CrossOrigin("*") public class AdminController { private static final Logger logger = LoggerFactory.getLogger(AdminController.class); @Autowired private MemberService memberService; // @RequestMapping(value = "/user", method = RequestMethod.GET, headers = { "Content-type=application/json" }) //// @ResponseBody ???? // public List<MemberDto> userList() throws Exception { //// List<MemberDto> list = memberService.listMember(); //// System.out.println(list); //// logger.debug("회원 목록 : {}", list); // return memberService.listMember(); // } // // @RequestMapping(value = "/user", method = RequestMethod.POST, headers = { "Content-type=application/json" }) // public List<MemberDto> userRegister(@RequestBody MemberDto memberDto) throws Exception { // memberService.registerMember(memberDto); // return memberService.listMember(); // } // // @RequestMapping(value = "/user/{userid}", method = RequestMethod.GET, headers = { "Content-type=application/json" }) // public MemberDto userInfo(@PathVariable("userid") String userid) throws Exception { // return memberService.getMember(userid); // } // // @RequestMapping(value = "/user", method = RequestMethod.PUT, headers = { "Content-type=application/json" }) // public List<MemberDto> userModify(@RequestBody MemberDto memberDto) throws Exception { // memberService.updateMember(memberDto); // return memberService.listMember(); // } // // @RequestMapping(value = "/user/{userid}", method = RequestMethod.DELETE, headers = { "Content-type=application/json" }) // public List<MemberDto> userDelete(@PathVariable("userid") String userid) throws Exception { // memberService.deleteMember(userid); // return memberService.listMember(); // } @GetMapping("/user") public ResponseEntity<?> userList() throws Exception{ List<MemberDto> list = memberService.listMember(); if(list != null && list.isEmpty()) { return new ResponseEntity<List<MemberDto>>(list, HttpStatus.OK); // return new ResponseEntity<String>("에러 : 서버에서 리스트 얻기 중 에러발생!!",HttpStatus.INTERNAL_SERVER_ERROR); }else { return new ResponseEntity<Void>(HttpStatus.NO_CONTENT); } } @PostMapping("/user") public ResponseEntity<?> userRegister(@RequestBody MemberDto memberDto) throws Exception{ memberService.registerMember(memberDto); return new ResponseEntity<List<MemberDto>>(memberService.listMember(), HttpStatus.OK); } @GetMapping("/user/{userid}") public ResponseEntity<?> userInfo(@PathVariable("userid") String userid) throws Exception{ MemberDto memberDto = memberService.getMember(userid); if(memberDto != null) { return new ResponseEntity<MemberDto>(memberDto, HttpStatus.OK); }else { return new ResponseEntity<Void>(HttpStatus.NO_CONTENT); } } @PutMapping("/user") public ResponseEntity<?> userModify(@RequestBody MemberDto memberDto) throws Exception{ memberService.updateMember(memberDto); return new ResponseEntity<List<MemberDto>>(memberService.listMember(), HttpStatus.OK); } @DeleteMapping public ResponseEntity<?> userDelete(@PathVariable("userid") String userid) throws Exception { memberService.deleteMember(userid); return new ResponseEntity<List<MemberDto>>(memberService.listMember(), HttpStatus.OK); } }
#include <ctime> #include <fstream> #include <iostream> #include "constants.hpp" #include "group.hpp" std::vector<Group> GroupForming(std::ifstream& ifs, int number) { std::vector<Group> groups; for (int i = 0; i < number; i += kSizeGroups) { Group group; std::string name; int exp = 0; int stam = 0; bool re = true; ifs >> name >> exp >> stam >> re; Volunteer vol = Volunteer(name, exp, stam, re); // first volunteer group.AddVolunteer(vol); ifs >> name >> exp >> stam >> re; // 2nd vol = Volunteer(name, exp, stam, re); group.AddVolunteer(vol); ifs >> name >> exp >> stam >> re; // 3rd vol = Volunteer(name, exp, stam, re); group.AddVolunteer(vol); ifs >> name >> exp >> stam >> re; // 4th vol = Volunteer(name, exp, stam, re); group.AddVolunteer(vol); ifs >> name >> exp >> stam >> re; // 5th vol = Volunteer(name, exp, stam, re); group.AddVolunteer(vol); groups.push_back(group); } return groups; } /*Write your main driver in this file! Remember to seperate out things into functions to help with readability and reusability. See specifications for how to get started and go to office hours if you need help!*/ //convert some of these things to functions then pass it. int main(int argc, char* argv[]) { if (argc != 4) { std::cout << "invalid"; } // DO NOT EDIT THIS LINE or add another srand call. srand(time(nullptr)); std::string file = argv[1]; int number = std::stoi(argv[2]); std::string out = argv[3]; std::vector<Group> groups(number / kSizeGroups); std::ifstream ifs{file}; if (ifs.is_open()) {groups = GroupForming(ifs, number);} bool exceeded = false; bool condition = false; unsigned int k = 0; while (!condition) { condition = true; for (size_t i = 0; i < groups.size(); i++) { Group& group = groups.at(i); if (group.GetReturningMembers() < kMinReturning || group.GetAvgBuildingExp() < kMinAvgBuildingExp || group.GetAvgStamina() < kMinAvgStamina) { condition = false; size_t rand1 = rand() % groups.size(); while (rand1 == i) {rand1 = rand() % groups.size();} Volunteer& a = group.GetRandomVolunteer(); Volunteer& b = groups.at(rand1).GetRandomVolunteer(); std::swap(a, b); k++; if (k == kMaxIterations) { condition = true; exceeded = true; std::cout << "No groups found"; break; }}}} if(!exceeded) { std::ofstream ofs{out}; for (size_t i = 0; i < groups.size(); i++) { Group group = groups.at(i); ofs << group; } } return 0; }
import { Body, Controller, Get, Param, Post, Req, UseGuards } from '@nestjs/common'; import { CommentsService } from './comments.service'; import { ApiOperation, ApiResponse } from '@nestjs/swagger'; import { AuthGuard } from 'src/auth/auth-guard'; import { Comment } from './comments.model'; import { CreateCommentDto } from './dto/create-comment.dto'; @Controller('comments') export class CommentsController { constructor(private commentService: CommentsService) {} @ApiOperation({summary: "Create Comment"}) @ApiResponse({status: 200, type: Comment }) @UseGuards(AuthGuard) @Post() create(@Body() dto: CreateCommentDto, @Req() req) { return this.commentService.create({...dto, userId: req.user.id}) } @ApiOperation({summary: "Get Comments"}) @ApiResponse({status: 200, type: Comment }) @Get('/:postId') get(@Param('postId') postId: number) { return this.commentService.getAll(postId) } @Get('/count/:postId') count(@Param('postId') postId: number) { return this.commentService.countAll(postId) } }
<script setup lang="ts"> import * as THREE from "three"; import { onBeforeUnmount, onMounted, ref } from "vue"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"; import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js"; import * as dat from "dat.gui"; // OR INSTALL 'lil-gui' const canvas = ref<HTMLCanvasElement | null>(null); let renderer: THREE.WebGLRenderer | null = null; // Debug const gui = new dat.GUI({ width: 400 }); const debugObject = {}; // Scene const scene = new THREE.Scene(); /** * Galaxy */ const parameters = { materialColor: "#ffeded", // spin: () => { // gsap.to(cube1.rotation, { y: cube1.rotation.y + 10, duration: 1 }); // }, }; // const dracoLoader = new DRACOLoader(); // dracoLoader.setDecoderPath("/src/assets/draco/"); const gltfLoader = new GLTFLoader(); // gltfLoader.setDRACOLoader(dracoLoader); // gltfLoader.load("/src/assets/models/Duck/glTF-Embedded/Duck.gltf", (model) => { // gltfLoader.load("/src/assets/models/Duck/glTF-Binary/Duck.glb", (model) => { // gltfLoader.load("/src/assets/models/Duck/glTF/Duck.gltf", (model) => { // scene.add(model.scene.children[0]); // }); let mixer: THREE.AnimationMixer | null = null; gltfLoader.load("/src/assets/models/Test2/output.gltf", (gltf) => { console.log("", { scene: gltf.scene }); // mixer = new THREE.AnimationMixer(gltf.scene); // const action = mixer.clipAction(gltf.animations[0]); const light = gltf.scene.getObjectByName("PointLight1"); console.log("", { light }); // action.play(); gltf.scene.castShadow = true; gltf.scene.receiveShadow = true; // scene.add(...gltf.scene.children); scene.add(gltf.scene); updateAllMaterials(); }); // gltfLoader.load("/src/assets/models/Fox/glTF/Fox.gltf", (model) => { // mixer = new THREE.AnimationMixer(model.scene); // // const action = mixer.clipAction(model.animations[0]); // // const action = mixer.clipAction(model.animations[1]); // const action = mixer.clipAction(model.animations[2]); // action.play(); // model.scene.scale.set(0.025, 0.025, 0.025); // scene.add(model.scene); // }); const updateAllMaterials = () => { scene.traverse((child) => { if (child instanceof THREE.PointLight) { // child.castShadow = true; // child.shadow.mapSize.set(1024, 1024); // child.shadow.camera.far = 95; } if (child instanceof THREE.Mesh && child.material instanceof THREE.MeshStandardMaterial) { /** da sa to nastavit aj defaultne s scene.environment = environmentMap; */ /** ale kedze to chceme menit v gui tak to tu necham */ // child.material.envMap = environmentMap; // child.material.envMapIntensity = debugObject.envMapIntensity; // in real project, this is bad idea child.castShadow = true; child.receiveShadow = true; } }); }; const textureLoader = new THREE.TextureLoader(); const cubeTextureLoader = new THREE.CubeTextureLoader(); const environmentMapTexture = cubeTextureLoader.load([ "/src/assets/textures/environmentMaps/0/px.jpg", "/src/assets/textures/environmentMaps/0/nx.jpg", "/src/assets/textures/environmentMaps/0/py.jpg", "/src/assets/textures/environmentMaps/0/ny.jpg", "/src/assets/textures/environmentMaps/0/pz.jpg", "/src/assets/textures/environmentMaps/0/nz.jpg", ]); const floor = new THREE.Mesh( new THREE.PlaneGeometry(10, 10), new THREE.MeshStandardMaterial({ color: "#777777", metalness: 0.3, roughness: 0.4, envMap: environmentMapTexture, envMapIntensity: 0.5, }) ); floor.receiveShadow = true; floor.rotation.x = -0.5 * Math.PI; // floor.position.y = -1; // scene.add(floor); /** * Lights */ const ambientLight = new THREE.AmbientLight(0xffffff, 0.7); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.2); directionalLight.castShadow = true; directionalLight.shadow.mapSize.set(1024, 1024); directionalLight.shadow.camera.far = 15; directionalLight.shadow.camera.left = -7; directionalLight.shadow.camera.top = 7; directionalLight.shadow.camera.right = 7; directionalLight.shadow.camera.bottom = -7; directionalLight.position.set(5, 5, 5); // scene.add(ambientLight); // scene.add(directionalLight); // Sizes const sizes = { width: window.innerWidth, height: window.innerHeight, }; // Camera Group const cameraGroup = new THREE.Group(); scene.add(cameraGroup); // Camera, fow and resolution (Aspect ratio) const aspectRatio = sizes.width / sizes.height; const camera = new THREE.PerspectiveCamera(55, aspectRatio, 0.1, 100); camera.position.z = 14; camera.position.y = 6; cameraGroup.add(camera); const handleResize = () => { if (!camera || !renderer) return; sizes.width = window.innerWidth; sizes.height = window.innerHeight; camera.aspect = sizes.width / sizes.height; camera.updateProjectionMatrix(); renderer.setSize(sizes.width, sizes.height); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); }; const cursor = { x: 0, y: 0, }; const handleMouseMove = (e: MouseEvent) => { cursor.x = e.clientX / sizes.width - 0.5; cursor.y = e.clientY / sizes.height - 0.5; }; const listenForResize = () => { window.addEventListener("resize", handleResize); }; // Renderer const setRenderer = () => { if (!canvas.value) return; listenForResize(); const controls = new OrbitControls(camera, canvas.value); controls.enableDamping = true; // renderer = new THREE.WebGLRenderer({ canvas: canvas.value, alpha: true }); // renderer.shadowMap.enabled = true; // renderer.shadowMap.type = THREE.PCFSoftShadowMap; // renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // renderer.setSize(sizes.width, sizes.height); // renderer.render(scene, camera); renderer = new THREE.WebGLRenderer({ canvas: canvas.value, antialias: true }); renderer.physicallyCorrectLights = true; renderer.outputEncoding = THREE.sRGBEncoding; renderer.toneMapping = THREE.ReinhardToneMapping; renderer.toneMappingExposure = 3; renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; renderer.setSize(sizes.width, sizes.height); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); startLoop(renderer, controls); }; let time = Date.now(); const clock = new THREE.Clock(); let oldElapsedTime = 0; const startLoop = (renderer: THREE.WebGLRenderer, controls: OrbitControls) => { const tick = () => { const elapsedTime = clock.getElapsedTime(); const deltaTime = elapsedTime - oldElapsedTime; oldElapsedTime = elapsedTime; if (mixer) { mixer.update(deltaTime); } controls.update(); renderer.render(scene, camera); window.requestAnimationFrame(tick); }; tick(); }; onMounted(setRenderer); onBeforeUnmount(() => { window.removeEventListener("mousemove", handleResize); gui.destroy(); }); </script> <template> <div class="page"> <div class="wrapper" @mousemove="handleMouseMove"> <canvas ref="canvas" /> </div> </div> </template> <style scoped> .page .wrapper { position: fixed; top: 0; left: 0; width: 100%; height: 100%; } </style>
--- title: python学习 date: 2024-02-08 12:11:12 tags: [python] categories: 学习笔记 --- # python基础 ## 1.字面量 >写在代码里固定的值 1. 数字 2. 字符串 3. 列表 (list) >有序的可变序列 4. 元组(tuple) >有序的不可变的python数据集合 5. 集合(set) >无序不重复集合 6. 字典(dictionary) >无序 key-value集合 ```python mylist=[1,2,3] # 列表while进行循环 index =0 while index<len(mylist): a = mylist[index] index += 1 # 列表for进行循环 for i in mylist: a = mylist[i] ``` ## 2.注释 ```python # #号表示单行注释 一般#号后面空格在写注释 """ 三个双引号 表示多行注释 """ ``` ## 3.变量 >能存储计算结果或表示值的抽象概念 > >变量没有类型 变量存储的数据是有类型的 ```python # 定义一个变量 记录 钱包余额 money = 50 # 通过print语句,输出变量记录内容 # java用+ python用逗号会有空格 也可以用加号 print("钱包还有" , 50) # 买了一个冰淇淋,花费十元 money = money -10 print("买了冰淇淋花费10元,还剩余:",money,"元") ``` ### 查看数据类型 ```python 123 # 用变量接受123的类型 int int_type =type(123) ``` ### 数据转换类型 ```python # 将数字转换成字符串 num_str = str(11) print(type(num_str),num_str) # 将字符串转换成数字 num = int("11") print(type(num),num) nun = flat("11.8") ``` ## 4.标识符 >变量的名字 方法的名字 类的名字 > >用户在编程所使用的一系列的名字 命名规则: 1. 只能用英文,数字,下划线,不能以数字开头!! 2. 大小写敏感 (java也区分大小写) 3. 不可使用关键字 命名规范: 1. python多个单词之间用下划线 2. java用驼峰 ## 5.运算符 1. 整除为 // 2. 指数为 ** 3. 取模为 %= ## 6.字符串的三种定义 ```python # 单引号定义法 name = '单引号定义' # 双引号定义法 name = "双引号定义" # 三引号定义法 # 不用变量接收的话 三个引号代表注释 name = """三引号定义""" ``` ## 7.字符串格式化 >字符串拼接是不能直接拼接非字符串的变量,如数字 > >这时候就需要字符串格式化 > >1. %s 字符串 >2. %d 整数 >3. %f 浮点数 ```python name = "zjaaa" message = "学习Python的是: %s" %name # 如果有多个变量占位 id = 1 message = "我是%s,我在学习目前排名第%s的python" %(name,id) ``` ### 可以用辅助符号m.n控制数据宽度和精度 ```python # 如果假如数字为11 因为宽度设成了5.所以得前面补三个空格 %5d # 表述宽度为7,精度为2 假设数字为11.345 %7.2f # 格式化的数字为 【空格】【空格】11.35 #也可以只设置精度 假如数字为11.342 %.1f # 数字为11.3 ``` ### 字符串格式化方法2 ```python name = "zjaaaa" date = "2024-02-08" # f:format 格式化标记 print(f"我是{name},今天是{date},我正在学习python") ``` ### 表达式格式化 >表达式: 1.有具体结果 2.代码片段 ```python print("1*1 的结果是: %d" %(1*1)) print(f"1*2的结果是:{1*2}") ``` ## 8.数据输入 ```python name = input("请告诉我你是谁?") print("我知道了,你是: %s"%name) ``` >input 默认接收到的是字符串 > >想要别的类型记得转换一下! ## 9.布尔类型以及比较运算符 ```python # python的True以及False都要大写 ## 比较运算符 num1 =10 num2 =15 print(f"num1 == num2 的结果为{num1 == num2}") print(f"num1 > num2的结果为{num1>num2}") # if 条件语句后面有冒号 # 条件成立前面有四个空格 # else也要顶格写 后面有冒号! if age >= 18: print('我已经成年了') else: print("我还没成年") # elif为条件判断 height =int(input("请输入你的身高:(cm)")) vip_level = int(input("请输入你的vip等级(1-5)")) if height<120: print("身高小于120cm,可以免费游玩") elif vip_lever >3: print("vip级别大于3,可以免费游玩") else: print('不好意思,条件都不满足,需要买票10元') #简单的一个猜数字游戏 num = 5 if int(input("请输入一个数字")) ==num: print("恭喜你第一次就猜对了") elif int(input("猜错了,请再猜一次")) ==num: print("猜对了") elif int(input("猜错了,最后再猜一次")) ==num: print("恭喜你最后一次机会猜对了") else: print("sorry,三次机会都没有猜对") ``` ## 10. while循环 ```python i =0; while i<100: print(f"我在学习python第{i+1}遍") i+=1 ``` ### while嵌套循环 ```python # 给定一个条件 向小美表白100天 每天送十朵玫瑰花 i = 1 while i<=100: print("今天是第%s天,准备表白..."%i) j =1 while j<=10: print('送给小美第%s朵花'%j) j += 1 print('小美,我喜欢你') i+=1 print(f"坚持到第{i-1}天,表白成功!") ``` ## 11. for 循环 ```python name ='zjaaa' for x in name: print(x) ``` ### range序列 >一般用于搭配for循环使用 ```python # 语法1 range(num) range(10) #num为10 取0-9 # 语法2 range(num1,num2) range(1,100) # 取1-99 # 语法3 range(num1,num2,step) range(1,10,2) # 取 1 3 5 7 9 # 搭配for循环使用 for x in range(10): print(x) ``` ### continue 跳过本次循环 ### break 终止循环 ### 循环发工资小案例 ```python import random jiangjin=10000 for i in range(1,21): if jiangjin == 0: break; else: jixiao=random.randint(1,10) if jixiao<5: print(f"员工i,绩效分{jixiao},不发工资,下一位") continue else: jiangjin=jiangjin-1000 print(f"向员工{i}发放工资1000元,奖金还剩{jiangjin}元") ``` ## 12.函数 ```python #函数定义 """ def 函数名(传入参数): 函数体 return 返回值 """ # 如果函数没返回值则返回none none为假 def add(x,y): """ Add two numbers :param x: :param y: :return: """ return x+y ``` ## 13. list列表 列表可以倒着索引 右边第一个索引为-1 1. 可以容纳多个元素 2. 数据是有序存储的 3. 允许重复数据存在 4. 可以修改 5. 可以容纳不同类型元素 ### list常用方法 >定义在class里面的称为方法 定义在外面的称为函数 ```python mylist = ["java","python","c"] mylist = list # 查找元素在列表内的下标索引 index =mylist.index("java") # index==0 # 修改下标索引值 mylist[2] = "php" # 在指定位置插入新元素 mylist.insert(1,"best") # 在尾部添加元素 mylist.append("c#") # 在列表尾部添加一批新元素 mylist2 = [1,2,3] mylist.extend(mylist2) # 删除指定索引的元素 (第一种) mylist.del(2) # 删除指定索引的元素, 这种能接受到返回值 element =mylist.pop(2) # 删除某元素在列表的第一个匹配项 mylist.remove("java") # 清空列表 mylist.clear() # 统计列表某元素的数量 count = mylist.count("java") # 统计列表的全部元素数量 count = len(mylist) ``` ## 14.元组 >有序,任意数量元素,允许重复元数,不可修改 ```python # 定义元组 mytuple = tuple mytuple = () mytuple=(1,2,3) #定义单个元素的元组 需要有逗号!! mytuple=(1,) # 元组的嵌套 mutuple = ((1,2,3),(1,2,3)) #元组的操作 mytuple = (1,2,3) # 查找元素索引 index = mytuple.indxe(1) # 查找某个元素在元组里的数量 num = mutuple.count(2) # 统计元组元素的数量 num =len(mytuple) # 遍历元组 # while循环 index = 0 while index < len(mytuple): a = mytuple[index] # for循环 for i in mytuple: a = mytuple[i] ``` ## 15.字符串 >只可以存储字符串 长度任意 支持下标索引 不可以修改 ```python my_str ="hello world" # 通过下标索引取值 value = my_str[0] value = my_str[-1] # 查找元素索引 my_str.index("world") # 字符串的替换 替换次数参数(不加则为全部替换 new_my_str =my_str.replace("world","zjaaa",1) # split方法 有两个参数 第一个参数分隔符 第二个参数分割几次 -1 或者不填都默认分割到不能再分 my_str = "hello python java c++" new_str_list = my_str.split(" ",2) # strip方法 # 不传参数 去除首尾空格 my_str = " hello " new_mystr = my_str.strip() # 传参数 去除首位指定参数 传的参数 按每个字符进行比对 my_str="12hello21" new_mystr=my_str.strip("12") # 统计字符串在字符串的出现次数 count =my_str.count("hello") # 统计字符串的长度 num = len(my_str) ``` ## 16.序列切片 列表,元组,字符串都是序列 ```python # 语法 序列[起始索引:结束索引:步长] 步长为负数表示反向取 my_list = [0,1,2,3,4,5,6] result = my_list[1:4] # 得到结果 [1,2,3] my_list[::-1]# 倒着取 ``` ## 17. set集合 >可以容纳多个数据 > >可以容纳不同类型数据 > >数据是无序存储的 > >不允许重复数据存在 > >可以修改 > >支持for循环 ```python # 定义集合 my_set = set() my_set ={1,2,3} # 集合方法 # 添加新元素 my_set.add("python") # 移除新元素 my_set.remove("python") # 随机删除一个元素并取出 value = my_set.pop() # 清空集合 my_set.clear() # 取两个集合的差集 调用者有的,被调用者没的 set1={1,2,3} set2={1,5,6} set3 = set1.difference(set2) # set3结果为{2,3} # 消除两个集合相同的元素 set1 ={1,2,3} set2={1,5,6} set1.difference_update(set2) # set1结果 {2,3} # 两个集合合并 set3 =set1.union(set2) #结果去重合并 # 统计集合元素数量 num = len(set1) # 集合的遍历 # 集合不支持下标索引,不能用while循环 # 可以用for循环 for i in set1: a = i ``` ## 18.字典 >注意的是 字典是无序的 取出来想排序记得对keys做sort ```python # 定义字典 my_dict= {"王丽":99,"周杰":88,"林俊":77} # 定义空字典 my_dict ={} my_dict = dict() # 从字典中基于key获取value score = my_dict["王丽"] # 新字典 my_dict["张鑫"] =66 # 添加 或 更新元素 my_dcit["周杰"] = 33 # 删除元素 score = my_dict.pop("周杰") # 清空元素 my_dict.clear() # 获取全部的key keys = my_dict.keys # 遍历字典 for key in keys: print(f"key为{key}") print(f"value为{value}") # for循环 for key in my_dict: print(f"key为{key}") print(f"value为{value}") # 统计字典元素数量 num =len(my_dict) ``` ## 19.容器通用方法 ```python # len元素个数 len(list) # max最大元素 max(list) # 容器转列表 list(mylist) # 容器转元组 tuple(mytuple) # 容器转字符串 str(mystr) # 容易转集合 set(myset) # 进行容器的排序 # 不加reverse升序排列 # 加reverse True表示降序排 sorted_list = sorted(mylist,reverse=False) # mylist.sort(key=,reverse=) # 有两个参数 key 要求传入函数 一般直接用lambda # reverse True降序 False 升序 # 没有返回值 直接改变 mylist,sort(key =lambda element: element[1],reverse = True) # 如果要反转排序 sorted(mylist,reverse=True) ``` ## 20.函数进阶 ```python # 函数返回多个返回值 def test_return(): return 1,2,3 x,y,z = test_reeturn() print(x) print(y) print(z) # 函数传参方式 def user_info(name,age,gender): print(f"姓名是{name},年龄是{age},性别是{女}") # 位置参数 user_info("小明",20,"男") # 关键字参数 user_info(name="小王",geder="女”,age="18") # 缺省参数 def user_info(name,age,gender="女 "): print(f"姓名是{name},年龄是{age},性别是{女}") # 可变参数 def user_info(*args): print(args) user_info(1,2,3) def user_info(**kwags): print(kwags) user_info(name='小王',age=11,gender='男孩') # 函数作为参数传递 def test_func(compute): result= compute(1,2) print(result) # lambda test_func(lambda x,y:x+y) ``` ## 21.文件 ### 1.打开文件 ```python open(name,mode,encoding) # name打开目标文件名的字符串 # mode设置打开文件的模式 #只读r #写入w 文件存在 ,原有内容删除。更新文件内容 文件不存在 创造文件 #追加a 文件存在,追加内容 文件不存在 创造文件 # encoding编码格式 这个是关键字传参 encoding= open("D:/测试.txt","r",encoding="utf-8") ``` ### 2.读入文件 ```python f = open("D:/测试.txt","r",encoding="utf-8") f.read(参数为字符数,不带参数则表示读全部) # 读取全部行 f.readlines() # 读取一行 f.readline() # for循环读取文件行 for line in f: print(line) f.close() # with open语法操作文件 执行完代码块会自动调用close方法 with open("D:/测试.txt","r",encoding="utf-8") as f: for line in f: print(line) ``` ```python #打开文件 以读取模式打开 f = open("D:/word.txt","r",encoding="utf-8") count =0 for line in f: #去除开头和结尾的空格以及换行符 line =line.strip() words = line.split(" ") for word in words: if word == "hello": count+=1 print(f"出现的次数为{count}") f.close() ``` ### 3.写入文件 ```python #写入文件是先写入内存 最后写入硬盘 #如果想及时进硬盘 应该用flush()方法 f = open("G:/test.txt","w",encoding="utf-8") f.write("hello world") f.flush() ``` ## 22.异常 ```python # 捕获异常 # 这里可能出现异常 try: result=10 /0 # 出现异常以这种方式解决 except: result=10/1 ## 捕获指定的异常 try: print(未命名的name) except NameError as e: print("出现了变量未定义的异常") # 捕获所有异常 try: f = open("D:/123.txt","r") except Exception as e: print("出现异常了") # 没有异常做的代码块 else: print("这里是没有异常做的事") # 无论有没有异常都会执行 finally: ``` ## 23.模块 ```python # 引入一个模块 import time # 引入模块里的一个功能 # 不需要time.sleep 只需要sleep from time import sleep # 导入模块里的所有功能 from time import * # 给模块起别名 from time as t from time import sleep as t ``` ### 自定义模块 ```python # 文件名 my_module.py def test(a,b): print(a,b) # 测试代码写这里 模块导入不会触发 if __name__ == '__main__': #设置导全部包的函数 __all__ = ['file_util'] ``` ## 24. python包 >多个模块的文件夹 > >里面含下面这个文件 ```python __init.py__ ``` ### 自己写一个python包 ```python 创建一个python包 my_utils 里面含三个python文件 __init__.py 包需要的必备py file_util.py str_util.py ``` ```python # __init__.py ``` ```python # file_util.py """ Created on Mon Jul 17 14: 用于 处理文件相关工具 @author: zjaaa """ def read_file(filename): f = None try: f = open(filename, "r", encoding="utf-8") content = f.read() print(f'程序输出如下:\n读取的文件为:{filename}\n读的内容为:\n{content}') except Exception as e: print(f"程序出现异常了,原因为{e}") finally: if None: f.close() def append_file(filename, content): f = open(filename, "a", encoding="utf-8") f.write(content) f.write("\n") f.close() ``` ```python # str_util.py """ Created on Mon Jul 22 14: @author: zjaaa 用于 处理字符串的工具 """ def str_reverse(str): """ 用于反转字符串 :param 输入一个字符串 :return:字符串反转的结果 """ return str[::-1] def substr(s,x,y): """ 用于截取字符串 :param s:输入的字符串 :param x:开头的索引 :param y:结尾的索引 :return:截取的字符 """ return s[x:y+1] if __name__ == '__main__': str = '大家好我叫zaaa,我学习的是python包的学习' print(str_reverse(str)) prin ``` ## 25. json ```python import json data=[{"name":"张三","age":16},{"name":"李四","age":20}] # 将python数据转换成json数据 data = json.dumps(data) # 不想让json数据变成ascii码 data = json.dumps(data,ensure_ascii=Fa) # 将json数据转换成python数据 data =json.loads(data) ``` # python面向对象 ## 1.类 >类包含属性和行为 一般用于描述现实世界事务 ```python class Student: name = None def sayHi(self): print(f"Hello大家好,我是{self.name}") def sayHi2(self,msg): print(f"hello大家好,我是{self.name},{msg}") stu = Student() stu.name= "小明" stu.sayHi() stu.sayHi2("很高兴认识大家") ``` ## 2.构造方法 ```python class Student: ## 可以省略定义成员变量 直接在init方法里定义 def __init__(self,name,age,tel): self.name = name self.age = age self.tel = tel stu = Student('John',18,13221213456) print(stu.name) print(stu.age) print(stu.tel) ``` ## 3.魔术方法 ``` __方法__ ``` >如上面所示的都叫做魔术方法 ### 常见方法 重写字符串方法 ```python class Student: # 将返回象打印结果 默认为内存地址 def __str__(self): return "想打印打印什么,一般重写字符串" ``` lt 小于 大于比较方法 ```python class Student: def __init__(self,name,age): self.name = name self.age = age # 返回值 true或false # lt 只能用于小于和大于 不能用于等于 def __lt__(self,other): return self.age < other.age ``` le 小于等于 大于等于 比较方法 ```python class Stduent: def __init__(self,name,age): self.name = name self.age= age # 用于小于等于 以及 大于等于 def __le__(self,other): return self.age<= other.age ``` eq 等于 比较方法 ```python class Student: def __init__(self,name,age): self.name=name self.age=age def __eq__(self,other): self.age == other.age ``` ## 4.封装 将现实世界的事务在类中描述为属性和方法即为封装 私有方法和成员都是以两个下划线开头 类对象无法访问私有成员 类的其他成员可以访问私有成员 ```python # 私有成员变量和方法都以两个下划线开头__ class Phone: __current_voltage = None def __keep_single_core(self): print("让cpu单核运行") def call_by_5g(self): if self.current_vlotage >=1: print("5g通话已开启") else: self.__keep_single_core() print("电量不足,无法使用5g通话,已设置单核运行") ``` ```python class Phone: __is5g_enable = False def __check_5g(self): if self.__is5g_enable: print("5g开启") else: print("5g关闭,使用4g") def call_by_5g(self): self.__check_5g() print("正在通话中") p = Phone() p.call_by_5g() ``` ## 5.继承 ```python # 单继承 class 类名(父类名): class Phone: IMEI = None producer ="apple" def call_by_4g(self): print('4g通话') class Phone2022(Phone): def call_by_5g(self): print('2022新功能:5g通话') # 多继承 class Myphone(RemoteControl,Phone,NFCReader): # pass 表示 不写新方法新成员 pass # 多继承优先级 从左至右 优先级逐渐递减 ``` ### 复写 父类方法属性 直接在子类重写属性和方法就好了 #### 使用被子类重写的父类方法和变量 ```python 通过 父类名.成员方法(self) 通过 super().方法 父类名.成员变量 super().成员变量 ``` ## 6.类型注解 >标记变量类型 > >类型注解仅仅是提示性的 不会影响程序运行 ```python # 基础数据类型注解 var_1: int =10 var_2: str ="zjaaa" var_3: bool = True # 类对象类型注解 class Student: pass stu: Student = Student() # 基础容器类型注解 my_list: list=[1,2,3] my_tuple: tuple=(1,2,3) my_dict: dict={"zjaaa":666} # 容器类型详细注解 my_list: list[int] =[1,2,3] my_tuple: tuple[int,str,bool]=(1,"zjaaa",True) my_dict: dict[str,int] = {"itheima":666} # 在注释中进行注解 var_1 = 111 # type: int var_2 = josn.loads('{"name":"zhangsan"}') # type: dict[str,str] # 函数方法形参进行注解 def add(x: int,y: int): return x + y # 对返回值进行类型注解 def func(data: list) -> list: return data # Union类型 定义联合类型注解 from typing import Union my_list: list[Union[int,str]] = [1,2,"zjaaa"] def func(data: Union[int,str]) -> Union[int,str]: pass ``` ## 6.多态 >同一个行为 使用不同的对象 获取不同的状态 > >抽象类 为 包含抽象方法的类 > >抽象方法 为 没有具体实现的方法 (pass) > >抽象类的作用 > >用于提供标准 便于子类做具体实现 > > ```python class AC: def cool_wind(self): """制冷""" pass def hot_wind(self): """制热""" pass def swing_l_r(self): """左右摆风""" pass class Midea_AC(AC): def cool_wind(self): print("美的吹冷风") def hot_wind(self): print('美的吹热风') def swing_l_r(self): print("美的左右摇摆") class GREE_AC(AC): def cool_wind(self): print("格力吹冷风") def hot_wind(self): print("格力吹热风") def swing_l_r(self): print('格力左右摇摆') def make_cool(ac: AC): ac.cool_wind() midea_ac = Midea_AC() gree_ac = GREE_AC() make_cool(midea_ac) make_cool(gree_ac) ``` ## 7. python使用mysql >pip install pymysql 创建表 ```python from pymysql import Connection # 获取mysql的连接对象 conn = Connection( host= "localhost", port=3306, user="root", password="root" ) # 执行非查询sql # 获取游标对象 cursor = conn.cursor() # 选择数据库 conn.select_db("test") # 执行sql cursor.execute("create table test_pymysql(id int)") # 关闭连接 conn.close() ``` 查询数据 ```python from pymysql import Connection # 获取mysql的连接对象 conn = Connection( host= "localhost", port=3306, user="root", password="root" ) # 执行查询sql # 获取游标对象 cursor = conn.cursor() # 选择数据库 conn.select_db("test") # 执行sql cursor.execute("select * from dakatime") rs = cursor.fetchall() for i in rs: print(i) conn.close() ``` 插入数据 发现一般默认建表引擎都不是innodb 如果事务没生效可以看看建表引擎 ```python from pymysql import Connection # 获取mysql的连接对象 conn = Connection( host= "localhost", port=3306, user="root", password="root", # 设置事务 一般会默认false autocommit=False ) # 执行插入sql cursor = conn.cursor() # 选择数据库 conn.select_db("test") # 执行sql cursor.execute("insert into test_pymysql values (3)") ## 提交事务 conn.commit() conn.close() ``` ## 8.闭包 记得用nonlocal修改属性 ## 9.装饰器 ```python def outer(func): def inner(): print('我睡觉了') func() print('我起床了') return inner @outer # 直接把这个函数当参数传入@后面的函数 def sleep(): print('睡眠中') # 如果没写@增强方法 一般的执行操作 fn = outer(sleep) fn() # 写了@增强方法的执行操作 fn() ``` ## 10.多线程 ```python import threading # target 指定函数任务 args 指定元组传参 kwargs指定字典传参 def sing(msg): while(True): print(f'我在唱{msg}') sing_thread= threading.thread(target=sing,args=('两只老虎',)) s ``` # 第三方包的使用以及记录 ## pyechars图例库的使用 ```python from pyecharts.charts import Line from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts # 创建一个折线图对象 line = Line() # 给折线图添加x坐标 line.add_xaxis(["中国","美国","英国"]) # 给折线图添加y坐标 line.add_yaxis("GDP",[30,20,10]) # 设置全局配置项 line.set_global_opts( # 展示标题 设置离左边居中 离下面百分之一距离 title_opts=TitleOpts(title="GDP展示",pos_left="center",pos_bottom="1%"), # 设置图例 legend_opts=LegendOpts(is_show=True), # 设置工具箱 toolbox_opts=ToolboxOpts(is_show=True), # 设置视觉映射 visualmap_opts=VisualMapOpts(is_show=True) ) line.render() ``` ### 1.折线图使用 ```python import json from pyecharts.charts import Line from pyecharts.options import TitleOpts, ToolboxOpts, LabelOpts def get_country_trend_data(file_str): """ 获取国家的trend值 :param file_str:填入数据路径 :return: 返回trend值 """ with open(file_str,"r",encoding='utf-8') as f: country_data = f.read() country_data = country_data.split('(',1)[1] country_data = country_data[:-2] country_dict = json.loads(country_data) return country_dict['data'][0]['trend'] def get_country_x_data(trend_value): """ 获取天数 :param trend_value: 填入trend值 :return: 返回x坐标 """ return trend_value['updateDate'][:314] def get_country_y_data(trend_value): """ 获取每天感染人数 :param trend_value: 填入trend值 :return: 返回y坐标 """ return trend_value['list'][0]['data'][:314] # 获取三国 trend数据 us_trend_data = get_country_trend_data('G:/美国.txt') jp_trend_data = get_country_trend_data('G:/日本.txt') in_trend_data = get_country_trend_data('G:/印度.txt') # 获取一年日期 x_data = get_country_x_data(us_trend_data) # 获取三国 感染人数 us_y_data = get_country_y_data(us_trend_data) jp_y_data = get_country_y_data(jp_trend_data) in_y_data = get_country_y_data(in_trend_data) # 生成分析图 line = Line() line.add_xaxis(x_data) line.add_yaxis('美国确诊人数',us_y_data,label_opts=LabelOpts(is_show=False)) line.add_yaxis('日本确诊人数',jp_y_data,label_opts=LabelOpts(is_show=False)) line.add_yaxis('印度确诊人数',in_y_data,label_opts=LabelOpts(is_show=False)) line.set_global_opts( title_opts=TitleOpts(title="国家感染分析图"), toolbox_opts=ToolboxOpts(is_show=True) ) line.render() ``` ### 2.地图的使用 ```python import json from pyecharts.charts import Map from pyecharts.options import TitleOpts, VisualMapOpts province_data = None province_data_list = list() with open("G:/疫情.txt",'r',encoding='utf8') as f: province_data = f.read() # 转换成字典一定不要忘! str可没字典的字符串索引 province_data = json.loads(province_data) province_data = province_data['areaTree'][0]['children'] for data in province_data: province_data_list.append((f"{data['name']}省",data['total']['confirm'])) map = Map() map.add('各省份确诊人数',province_data_list,'china') map.set_global_opts( title_opts=TitleOpts(title="全国确诊图",pos_left='center',pos_bottom='1%'), visualmap_opts= VisualMapOpts( is_show=True, # 是否显示 is_piecewise=True, # 是否分段 pieces=[ {'min':1,'max':99,'label':'1-99人','color':'#CCFFFF'}, {'min':100,"max":999,'label':"100-999人",'color':'#FFFF99'}, {'min':1000,'max':4999,'label':'1000-4999人','color':'#FF9966'}, {'min':5000,'max':9999,'label':'5000-9999人','color':'#FF6666'}, {'min':10000,'max':99999,'label':'10000-99999人','color':'#CC3333'}, {'min':100000,'label':'100000+','color':'#990033'} ] ) ) map.render('全国确诊地图.html') # 控制生成文件名 ``` ### 3.柱状图的使用 #### 简单柱状图 ```python from pyecharts.charts import Bar bar = Bar() bar.add_xaxis(['中国','美国','英国']) bar.add_yaxis("GDP对比",[35,60,25]) bar.reversal_axis() # 把坐标系反转 bar.render('简单的柱状图生成.html') ``` #### 1960-2019全球经济前十柱状图 ```python from pyecharts.charts import Bar,Timeline from pyecharts.options import LabelOpts,TitleOpts from pyecharts.globals import ThemeType # 设置主题 timeline = Timeline({'theme': ThemeType.LIGHT}) country_gdp_dict = {} with open('G:/1960-2019全球GDP数据.csv', 'r', encoding='gbk') as f: all_data = f.readlines() all_data.pop(0) for i in all_data: data = i.split(',') year = data[0] country = data[1] # 把科学计数法E用浮点数转换成数字 gdp = float(data[2]) # 如果有 列表 则添加数据 如果 报错 无列表 则 初始化列表 再添加 try: country_gdp_dict[year].append([country, gdp]) except KeyError: country_gdp_dict[year] = [] country_gdp_dict[year].append([country, gdp]) # 把字典的keys排序一下 sorted默认升序排 sorted_year = sorted(country_gdp_dict.keys()) for year in sorted_year: # 把一年里的国家按GDP排名 进行排序 country_gdp_dict[year].sort(key=lambda element: element[1], reverse=True) year_data = country_gdp_dict[year][:10] x_data = [] y_data = [] # 对每个国家进行遍历 for country_gdp in year_data: x_data.append(country_gdp[0]) y_data.append(country_gdp[1] / 100000000) bar = Bar() # 把世界第一排上面 默认是排下面 x_data.reverse() y_data.reverse() bar.add_xaxis(x_data) # 把标记放右边 bar.add_yaxis('GDP(亿)',y_data,label_opts=LabelOpts(position='right')) # 把直的柱状图变成横的 bar.reversal_axis() bar.set_global_opts( title_opts=TitleOpts(title=f'{year}年GDP全球前十数据') ) timeline.add(bar,str(year)) # 设置一下自动播放配置项 timeline.add_schema( play_interval=1000, is_timeline_show=True, is_auto_play=True, is_loop_play=False ) timeline.render("1960-2019全世界dgp前十国家动态对比.html") ```
/* * Simple Timer Module * Read & calculate elapsed time with 32-bit timestamps * Note that the hardware_time module provides similar * functions using 64-bit timestamps * * Caution: Rollover on 32-bit time measurementswill occur * once every 2^32 microseconds (11.93 hours). We handle one * rollover with the code provided, but if the time between * measurements exceeds twice this amount (23.8 hours) then * the calculation will be incorrect. For measurements of * this duration, consider using either 64-bit timer values * or the real-time clock * * ECE 414 - Lafayette College * J. Nestor July 2023 */ #include "pico/stdlib.h" #include "hardware/timer.h" #include "timer.h" #include "pico/stdlib.h" uint32_t timer_read() { return time_us_32(); } // return the elapsed time in us between two 32-bit timestamps // note the need to deal with rollovers uint32_t timer_elapsed_us(uint32_t t1, uint32_t t2) { if (t2 > t1) return t2 - t1; else return UINT32_MAX - t1 + t2 + 1; } // return the elapsed time in use betwen two 32-bit timestamps uint32_t timer_elapsed_ms(uint32_t t1, uint32_t t2) { return timer_elapsed_us(t1, t2) / 1000; }
@extends('admin.layouts.app') @section('title',__('Empresas')) @section('content') <div class="row"> <div class="col-md-12"> <div class="box"> <div class="box-header with-border"> <h3 class="box-title">@yield('title')</h3> <div class="box-tools pull-right"> <a href="{{ route('admin.companies.create') }}" class="btn btn-sm btn-primary"><i class="fa fa-plus-circle" aria-hidden="true"></i> Cadastrar</a> </div> </div> <!-- /.box-header --> <div class="box-body"> <div class="row"> <div class="col-md-12"> <form class="form form-search" method="GET" action=""> <strong>Filtros</strong> <div class="row"> <div class="form-group col-md-3"> <label class="sr-only" for="name">Descrição</label> <input type="text" class="form-control" id="name" name="name" value="{{ old('name',request('name')) }}" placeholder="Descrição"> </div> <div class="form-group col-md-3"> <label class="sr-only" for="name">CPF ou CNPJ</label> <input type="text" class="form-control" id="cpf_cnpj" name="cpf_cnpj" value="{{ old('cpf_cnpj',request('cpf_cnpj')) }}" placeholder="CPF/CNPJ"> </div> <div class="form-group col-md-4"> <label class="sr-only" for="name">Email</label> <input type="email" class="form-control" id="email" name="email" value="{{ old('email',request('email')) }}" placeholder="Email"> </div> <div class="col-md-2 text-right"> <button type="submit" class="btn btn-success">Buscar</button> <a href="{{ route('admin.companies.index') }}" class="btn btn-warning">Limpar</a> </div> </div> </form> </div> </div> <div class="row"> <div class="col-md-12"> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>Nome</th> <th>CPF/CNPJ</th> <th>Email</th> <th>Categorias</th> <th class="">Cidade/UF</th> <th class="">Dono (usuário)</th> <th class="text-center">Destaque</th> <th class="text-center">Status</th> <th class="text-center" style="width: 10%">Ação</th> </tr> </thead> <tbody> @forelse ($companies as $item) <tr> <td>{{ $item->id }}</td> <td>{{ $item->name }}</td> <td>{{ $item->cpf_cnpj }}</td> <td>{{ $item->email }}</td> <td width="20%" class="small"> @forelse($item->subcategories as $category) <span class="label label-default">{{ $category->category->name }}: {{ $category->name }}</span> @empty Não vinculado @endforelse </td> <td>{{ @$item->city->title }}/{{ @$item->city->state->letter }}</td> <td><a href="#">{{ @$item->owner->name }}</a></td> <td class="text-center"> {!! status($item->highlighted ) !!} </td> <td class="text-center"> {!! status( $item->status ) !!} </td> <td class="text-center"> @actions(['item'=>$item, 'route' => 'companies','btns' => 'show|edit|delete']) {{-- botão de ação --}} @endactions() </td> </tr> @empty <tr> <td colspan="5"> {{ __('general.msg_not_register')}} </td> </tr> @endforelse </tbody> </table> </div> </div> <!-- /.row --> </div> <!-- ./box-body --> <div class="box-footer"> <div class="row"> <div class="col-md-4 text-left">{{ $companies->links() }}</div> <div class="col-md-7 text-right paginate-count">{!! info_pages($companies) !!}</div> </div> <!-- /.row --> </div> <!-- /.box-footer --> </div> <!-- /.box --> </div> <!-- /.col --> </div> @endsection
import { AssetRelationship, AssetTwin, ADTPatch, IAssetProperty } from '../../Constants'; export class Asset { public name: string; public relationships: Array<AssetRelationship>; public twins: Array<AssetTwin>; public properties: Array<IAssetProperty<any>>; public getDoubleValue = (minValue: number, maxValue: number) => { return (currentValue: number) => { const direction = currentValue > maxValue ? -1 : currentValue < minValue ? 1 : Math.random() < 0.5 ? -1 : 1; const step = direction * (Math.random() * (maxValue - minValue) * 0.02); return (currentValue += step); }; }; public getIntegerValue = (minValue: number, maxValue: number) => { return (currentValue: number) => { const direction = currentValue >= maxValue ? -1 : currentValue <= minValue ? 1 : Math.random() < 0.5 ? -1 : 1; return (currentValue += direction); }; }; public getBooleanValue = (isTrueThreshold: number) => { return (_currentValue: boolean) => { return Math.random() > isTrueThreshold; }; }; public getStringValue = () => { return (_currentValue: boolean) => { const fourDigitNumber = Math.floor(Math.random() * 1000); return `Box${fourDigitNumber}`; }; }; private getAssetProperties() { const assetProperties = []; this.properties.forEach((property) => { assetProperties.push(new AssetProperty(property)); }); return assetProperties; } constructor(name: string) { this.properties = []; this.relationships = []; this.twins = []; this.name = name; switch (name) { case 'RobotArm': { this.properties = [ { id: this.name, propertyName: 'FailedPickupsLastHr', currentValue: 1, getNextValue: this.getIntegerValue(0, 5), schema: 'integer' }, { id: this.name, propertyName: 'PickupFailedAlert', currentValue: false, getNextValue: this.getBooleanValue(0.75), schema: 'boolean' }, { id: this.name, propertyName: 'PickupFailedBoxID', currentValue: 'Box1', getNextValue: this.getStringValue(), schema: 'string' }, { id: this.name, propertyName: 'HydraulicPressure', currentValue: 20, getNextValue: this.getDoubleValue(10, 100) } ]; [1, 2, 3, 4, 5, 6].forEach((idx) => { this.twins.push({ name: `Arm${idx}`, properties: this.getAssetProperties() }); }); break; } case 'DistributionCenter': { this.relationships.push({ name: 'contains', target: 'RobotArm' }); this.twins.push({ name: 'DistCtr', assetRelationships: [1, 2, 3, 4, 5, 6].map((idx) => { return { name: 'contains', target: `Arm${idx}`, targetModel: 'RobotArm' }; }), properties: [] }); break; } case 'Car': { this.properties = [ { id: this.name, propertyName: 'Speed', currentValue: Math.floor(Math.random() * 20) + 40, getNextValue: this.getDoubleValue(0, 100) }, { id: this.name, propertyName: 'OutdoorTemperature', currentValue: Math.floor(Math.random()) + 40, getNextValue: this.getDoubleValue(20, 80) }, { id: this.name, propertyName: 'OilPressure', currentValue: Math.floor(Math.random()) + 30, getNextValue: this.getDoubleValue(28, 32) } ]; this.twins.push({ name: 'CarTwin', properties: this.getAssetProperties() }); break; } case 'Windmill': { this.properties = [ { id: this.name, propertyName: 'OutdoorTemperature', currentValue: Math.floor(Math.random() * 20) + 40, getNextValue: this.getDoubleValue(0, 100) }, { id: this.name, propertyName: 'AtmosphericPressure', currentValue: Math.floor(Math.random()) + 30, getNextValue: this.getDoubleValue(29, 31) }, { id: this.name, propertyName: 'WindVelocity', currentValue: Math.floor(Math.random() * 30), getNextValue: this.getDoubleValue(0, 70) }, { id: this.name, propertyName: 'BearingTemperature', currentValue: Math.floor(Math.random() * 30) + 90, getNextValue: this.getDoubleValue(90, 200) }, { id: this.name, propertyName: 'OilViscosity', currentValue: Math.floor(Math.random() * 5) + 10, getNextValue: this.getDoubleValue(10, 80) } ]; this.twins.push({ name: 'Windmill_1', properties: this.getAssetProperties() }); break; } case 'HVACSystem': { this.properties = [ { id: this.name, propertyName: 'FanSpeed', currentValue: Math.floor(Math.random() * 20) + 40, getNextValue: this.getDoubleValue(0, 100) }, { id: this.name, propertyName: 'CoolerTemperature', currentValue: Math.floor(Math.random()) + 40, getNextValue: this.getDoubleValue(20, 60) }, { id: this.name, propertyName: 'HeaterTemperature', currentValue: Math.floor(Math.random()) + 50, getNextValue: this.getDoubleValue(40, 100) } ]; this.twins.push({ name: 'HVACSystem_1', properties: this.getAssetProperties() }); break; } case 'PasteurizationMachine': { this.properties = [ { id: this.name, propertyName: 'InFlow', currentValue: Math.floor(Math.random() * 300) + 50, getNextValue: this.getDoubleValue(50, 600) }, { id: this.name, propertyName: 'OutFlow', currentValue: Math.floor(Math.random() * 300) + 50, getNextValue: this.getDoubleValue(50, 600) }, { id: this.name, propertyName: 'Temperature', currentValue: Math.floor(Math.random()) + 120, getNextValue: this.getDoubleValue(110, 250) }, { id: this.name, propertyName: 'PercentFull', currentValue: Math.floor(Math.random()), getNextValue: this.getDoubleValue(0, 1) } ]; this.relationships.push({ name: 'feeds', target: 'SaltMachine' }); this.twins.push({ name: 'PasteurizationMachine_A01', assetRelationships: [ { name: 'feeds', target: 'SaltMachine_C0', targetModel: 'SaltMachine' } ], properties: this.getAssetProperties() }); this.twins.push({ name: 'PasteurizationMachine_A02', assetRelationships: [ { name: 'feeds', target: 'SaltMachine_C0', targetModel: 'SaltMachine' } ], properties: this.getAssetProperties() }); this.twins.push({ name: 'PasteurizationMachine_A03', assetRelationships: [ { name: 'feeds', target: 'SaltMachine_C1', targetModel: 'SaltMachine' } ], properties: this.getAssetProperties() }); this.twins.push({ name: 'PasteurizationMachine_A04', assetRelationships: [ { name: 'feeds', target: 'SaltMachine_C2', targetModel: 'SaltMachine' } ], properties: this.getAssetProperties() }); break; } case 'SaltMachine': { this.properties = [ { id: this.name, propertyName: 'InFlow', currentValue: Math.floor(Math.random() * 300) + 50, getNextValue: this.getDoubleValue(50, 600) }, { id: this.name, propertyName: 'OutFlow', currentValue: Math.floor(Math.random() * 300) + 50, getNextValue: this.getDoubleValue(50, 600) } ]; this.twins.push({ name: 'SaltMachine_C0', properties: this.getAssetProperties() }); this.twins.push({ name: 'SaltMachine_C1', properties: this.getAssetProperties() }); this.twins.push({ name: 'SaltMachine_C2', properties: this.getAssetProperties() }); break; } case 'MaintenancePersonnel': { this.relationships.push({ name: 'maintains' }); this.twins.push({ name: 'Xenia', assetRelationships: [ { name: 'maintains', target: 'SaltMachine_C0', targetModel: 'SaltMachine' }, { name: 'maintains', target: 'SaltMachine_C1', targetModel: 'SaltMachine' } ], properties: [] }); this.twins.push({ name: 'Amy', assetRelationships: [ { name: 'maintains', target: 'SaltMachine_C1', targetModel: 'SaltMachine' }, { name: 'maintains', target: 'PasteurizationMachine_A01', targetModel: 'PasteurizationMachine' } ], properties: [] }); this.twins.push({ name: 'John', assetRelationships: [ { name: 'maintains', target: 'PasteurizationMachine_A02', targetModel: 'PasteurizationMachine' }, { name: 'maintains', target: 'PasteurizationMachine_A03', targetModel: 'PasteurizationMachine' } ], properties: [] }); this.twins.push({ name: 'Phillip', assetRelationships: [ { name: 'maintains', target: 'SaltMachine_C2', targetModel: 'SaltMachine' }, { name: 'maintains', target: 'PasteurizationMachine_A04', targetModel: 'PasteurizationMachine' } ], properties: [] }); break; } case 'Factory': { this.relationships.push({ name: 'contains' }); this.relationships.push({ name: 'employs', target: 'MaintenancePersonnel' }); this.twins.push({ name: 'OsloFactory', assetRelationships: [ { name: 'contains', target: 'SaltMachine_C0', targetModel: 'SaltMachine' }, { name: 'contains', target: 'SaltMachine_C1', targetModel: 'SaltMachine' }, { name: 'contains', target: 'PasteurizationMachine_A01', targetModel: 'PasteurizationMachine' }, { name: 'contains', target: 'PasteurizationMachine_A02', targetModel: 'PasteurizationMachine' }, { name: 'contains', target: 'PasteurizationMachine_A03', targetModel: 'PasteurizationMachine' }, { name: 'employs', target: 'Amy', targetModel: 'MaintenancePersonnel' }, { name: 'employs', target: 'John', targetModel: 'MaintenancePersonnel' }, { name: 'employs', target: 'Xenia', targetModel: 'MaintenancePersonnel' } ], properties: [] }); this.twins.push({ name: 'StockholmFactory', assetRelationships: [ { name: 'contains', target: 'SaltMachine_C2', targetModel: 'SaltMachine' }, { name: 'contains', target: 'PasteurizationMachine_A04', targetModel: 'PasteurizationMachine' }, { name: 'employs', target: 'Phillip', targetModel: 'MaintenancePersonnel' } ], properties: [] }); break; } case 'Country': { this.relationships.push({ name: 'contains', target: 'Factory' }); this.twins.push({ name: 'Norway', assetRelationships: [ { name: 'contains', target: 'OsloFactory', targetModel: 'Factory' } ], properties: [] }); this.twins.push({ name: 'Sweden', assetRelationships: [ { name: 'contains', target: 'StockholmFactory', targetModel: 'Factory' } ], properties: [] }); break; } default: break; } } } export class AssetProperty<T> { public id: string; public propertyName: string; private currentValue: T; private getNextValue: (currentValue: T) => T; public schema: string; constructor({ id, propertyName, currentValue, getNextValue, schema = 'double' }: IAssetProperty<T>) { this.id = id; this.propertyName = propertyName; this.currentValue = currentValue; this.getNextValue = getNextValue; this.schema = schema; } tick() { this.currentValue = this.getNextValue(this.currentValue); const event: ADTPatch = { op: 'replace', path: `/${this.propertyName}`, value: this.currentValue }; return event; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org/"> <!--${} tells thymeleaf to look in model for value--> <head th:replace="fragments :: head"></head> <body class="container"> <h1 th:text="${title}"></h1> <nav th:replace="fragments :: navigation"></nav> <!--create form that will post data from user--> <form method="post" th:object="${cheese}" style="max-width:600px;"> <!--leaving off action= will submit data to same location --> <div class="form-group"> <label th:for="name">Name of Cheese: </label> <input class="form-control" th:field="*{name}" /> <!--*{tells form to use field from obj passed in --> <span th:errors="*{name}" class="error"></span> </div> <div class="form-group"> <label th:for="description">Description: </label> <input class="form-control" th:field="*{description}" /> <span th:errors="*{description}" class="error"></span> </div> <div class="form-group"> <label th:for="type">Type</label> <select th:field="*{type}"> <option th:each="cheeseType : ${cheeseTypes}" th:text="${cheeseType.name}" th:value="${cheeseType}"></option> </select> </div> <div class="form-group"> <label th:for="rating">Cheese Rating (1-5): </label> <input class="form-control" th:field="*{rating}" /> <span th:errors="*{rating}" class="error"></span> </div> <input type="submit" value="Add Cheese" id="submit"/> </form> </body> </html>
package server import ( "context" "fmt" "net/http" "strings" "time" "github.com/google/uuid" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "github.com/pkg/errors" echoSwagger "github.com/swaggo/echo-swagger" apiv1 "github.com/usememos/memos/api/v1" apiv2 "github.com/usememos/memos/api/v2" "github.com/usememos/memos/plugin/telegram" "github.com/usememos/memos/server/frontend" "github.com/usememos/memos/server/integration" "github.com/usememos/memos/server/profile" "github.com/usememos/memos/server/service/backup" "github.com/usememos/memos/server/service/metric" versionchecker "github.com/usememos/memos/server/service/version_checker" "github.com/usememos/memos/store" ) type Server struct { e *echo.Echo ID string Secret string Profile *profile.Profile Store *store.Store // Asynchronous runners. backupRunner *backup.BackupRunner telegramBot *telegram.Bot } func NewServer(ctx context.Context, profile *profile.Profile, store *store.Store) (*Server, error) { e := echo.New() e.Debug = true e.HideBanner = true e.HidePort = true s := &Server{ e: e, Store: store, Profile: profile, // Asynchronous runners. telegramBot: telegram.NewBotWithHandler(integration.NewTelegramHandler(store)), } if profile.Driver == "sqlite" { s.backupRunner = backup.NewBackupRunner(store) } e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ Format: `{"time":"${time_rfc3339}","latency":"${latency_human}",` + `"method":"${method}","uri":"${uri}",` + `"status":${status},"error":"${error}"}` + "\n", })) e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ Skipper: grpcRequestSkipper, AllowOrigins: []string{"*"}, AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete}, })) e.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{ Skipper: timeoutSkipper, Timeout: 30 * time.Second, })) serverID, err := s.getSystemServerID(ctx) if err != nil { return nil, errors.Wrap(err, "failed to retrieve system server ID") } s.ID = serverID // Serve frontend. frontendService := frontend.NewFrontendService(profile, store) frontendService.Serve(e) // Serve swagger in dev/demo mode. if profile.Mode == "dev" || profile.Mode == "demo" { e.GET("/api/*", echoSwagger.WrapHandler) } secret := "usememos" if profile.Mode == "prod" { secret, err = s.getSystemSecretSessionName(ctx) if err != nil { return nil, errors.Wrap(err, "failed to retrieve system secret session name") } } s.Secret = secret // Register healthz endpoint. e.GET("/healthz", func(c echo.Context) error { return c.String(http.StatusOK, "Service ready.") }) // Register API v1 endpoints. rootGroup := e.Group("") apiV1Service := apiv1.NewAPIV1Service(s.Secret, profile, store, s.telegramBot) apiV1Service.Register(rootGroup) apiV2Service := apiv2.NewAPIV2Service(s.Secret, profile, store, s.Profile.Port+1) // Register gRPC gateway as api v2. if err := apiV2Service.RegisterGateway(ctx, e); err != nil { return nil, errors.Wrap(err, "failed to register gRPC gateway") } return s, nil } func (s *Server) Start(ctx context.Context) error { go versionchecker.NewVersionChecker(s.Store, s.Profile).Start(ctx) go s.telegramBot.Start(ctx) if s.backupRunner != nil { go s.backupRunner.Run(ctx) } metric.Enqueue("server start") return s.e.Start(fmt.Sprintf("%s:%d", s.Profile.Addr, s.Profile.Port)) } func (s *Server) Shutdown(ctx context.Context) { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() // Shutdown echo server if err := s.e.Shutdown(ctx); err != nil { fmt.Printf("failed to shutdown server, error: %v\n", err) } // Close database connection if err := s.Store.Close(); err != nil { fmt.Printf("failed to close database, error: %v\n", err) } fmt.Printf("memos stopped properly\n") } func (s *Server) GetEcho() *echo.Echo { return s.e } func (s *Server) getSystemServerID(ctx context.Context) (string, error) { serverIDSetting, err := s.Store.GetSystemSetting(ctx, &store.FindSystemSetting{ Name: apiv1.SystemSettingServerIDName.String(), }) if err != nil { return "", err } if serverIDSetting == nil || serverIDSetting.Value == "" { serverIDSetting, err = s.Store.UpsertSystemSetting(ctx, &store.SystemSetting{ Name: apiv1.SystemSettingServerIDName.String(), Value: uuid.NewString(), }) if err != nil { return "", err } } return serverIDSetting.Value, nil } func (s *Server) getSystemSecretSessionName(ctx context.Context) (string, error) { secretSessionNameValue, err := s.Store.GetSystemSetting(ctx, &store.FindSystemSetting{ Name: apiv1.SystemSettingSecretSessionName.String(), }) if err != nil { return "", err } if secretSessionNameValue == nil || secretSessionNameValue.Value == "" { secretSessionNameValue, err = s.Store.UpsertSystemSetting(ctx, &store.SystemSetting{ Name: apiv1.SystemSettingSecretSessionName.String(), Value: uuid.NewString(), }) if err != nil { return "", err } } return secretSessionNameValue.Value, nil } func grpcRequestSkipper(c echo.Context) bool { return strings.HasPrefix(c.Request().URL.Path, "/memos.api.v2.") } func timeoutSkipper(c echo.Context) bool { if grpcRequestSkipper(c) { return true } // Skip timeout for blob upload which is frequently timed out. return c.Request().Method == http.MethodPost && c.Request().URL.Path == "/api/v1/resource/blob" }
import Foundation class WeakBox { weak var value: AnyObject? var sourceInfo: SourceInfo init(_ value: AnyObject, sourceInfo: SourceInfo) { self.value = value self.sourceInfo = sourceInfo } } struct SourceInfo { var file: String var function: String var line: Int var description: String { let fileName = URL(string: file)?.lastPathComponent ?? file return "\(fileName):\(line) \(function)" } } class ReferenceCounter { static let shared = ReferenceCounter() private var objectMap = [String: [WeakBox]]() private init() { } func track(_ object: AnyObject, file: String = #file, function: String = #function, line: Int = #line) { let sourceInfo = SourceInfo(file: file, function: function, line: line) track(object, sourceInfo: sourceInfo) } func track(_ object: AnyObject, sourceInfo: SourceInfo) { let name = getObjectName(object) var objects = getLiveObjectsList(name: name) objects.append(.init(object, sourceInfo: sourceInfo)) objectMap[name] = objects DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 0.5) { self.report(name: name) } } private func report(name: String) { let objects = getLiveObjectsList(name: name) let count = objects.count if count > 1 { print("MEMORY LEAK: \(name) count: \(objects.count)") for object in objects { print("Object \(name) created at: \(object.sourceInfo.description)") } } } private func getLiveObjectsList(name: String) -> [WeakBox] { objectMap[name]?.filter({ $0.value != nil }) ?? [] } private func getObjectName(_ object: AnyObject) -> String { String(describing: type(of: object)) } }
/mob/living/simple_animal/mouse name = "mouse" real_name = "mouse" desc = "It's a small, disease-ridden rodent." icon_state = "mouse_gray" icon_living = "mouse_gray" icon_dead = "mouse_gray_dead" speak = list("Squeek!","SQUEEK!","Squeek?") speak_emote = list("squeeks","squeeks","squiks") emote_hear = list("squeeks","squeaks","squiks") emote_see = list("runs in a circle", "shakes", "scritches at something") mob_size = MOB_SIZE_SMALL speak_chance = 1 turns_per_move = 5 see_in_dark = 6 maxHealth = 5 health = 5 meat_type = /obj/item/reagent_container/food/snacks/meat response_help = "pets the" response_disarm = "gently pushes aside the" response_harm = "stamps on the" density = FALSE var/body_color //brown, gray and white, leave blank for random layer = ABOVE_LYING_MOB_LAYER min_oxy = 16 //Require atleast 16kPA oxygen minbodytemp = 223 //Below -50 Degrees Celcius maxbodytemp = 323 //Above 50 Degrees Celcius universal_speak = 0 universal_understand = 1 holder_type = /obj/item/holder/mouse /mob/living/simple_animal/mouse/Life(delta_time) ..() if(!stat && prob(speak_chance)) for(var/mob/M in view()) M << 'sound/effects/mousesqueek.ogg' if(!ckey && stat == CONSCIOUS && prob(0.5)) set_stat(UNCONSCIOUS) icon_state = "mouse_[body_color]_sleep" wander = 0 speak_chance = 0 //snuffles else if(stat == UNCONSCIOUS) if(ckey || prob(1)) set_stat(CONSCIOUS) icon_state = "mouse_[body_color]" wander = 1 canmove = 1 else if(prob(5)) INVOKE_ASYNC(src, PROC_REF(emote), "snuffles") /mob/living/simple_animal/mouse/New() ..() add_verb(src, list( /mob/living/proc/ventcrawl, /mob/living/proc/hide, )) if(!name) name = "[name] ([rand(1, 1000)])" if(!body_color) body_color = pick( list("brown","gray","white") ) icon_state = "mouse_[body_color]" icon_living = "mouse_[body_color]" icon_dead = "mouse_[body_color]_dead" if(!desc) desc = "It's a small [body_color] rodent, often seen hiding in maintenance areas and making a nuisance of itself." /mob/living/simple_animal/mouse/initialize_pass_flags(datum/pass_flags_container/PF) ..() if (PF) PF.flags_pass = PASS_FLAGS_CRAWLER /mob/living/simple_animal/mouse/splat(mob/killer) src.health = 0 src.set_stat(DEAD) src.icon_dead = "mouse_[body_color]_splat" src.icon_state = "mouse_[body_color]_splat" layer = ABOVE_LYING_MOB_LAYER if(client) client.time_died_as_mouse = world.time /mob/living/simple_animal/mouse/start_pulling(atom/movable/AM)//Prevents mouse from pulling things to_chat(src, SPAN_WARNING("You are too small to pull anything.")) return /mob/living/simple_animal/mouse/Crossed(AM as mob|obj) if( ishuman(AM) ) if(!ckey && stat == UNCONSCIOUS) set_stat(CONSCIOUS) icon_state = "mouse_[body_color]" wander = 1 else if(!stat && prob(5)) var/mob/M = AM to_chat(M, SPAN_NOTICE(" [icon2html(src, M)] Squeek!")) M << 'sound/effects/mousesqueek.ogg' ..() /mob/living/simple_animal/mouse/death() layer = ABOVE_LYING_MOB_LAYER if(client) client.time_died_as_mouse = world.time ..() /mob/living/simple_animal/mouse/MouseDrop(atom/over_object) if(!CAN_PICKUP(usr, src)) return ..() var/mob/living/carbon/H = over_object if(!istype(H) || !Adjacent(H) || H != usr) return ..() if(H.a_intent == INTENT_HELP) get_scooped(H) return else return ..() /mob/living/simple_animal/mouse/get_scooped(mob/living/carbon/grabber) if (stat >= DEAD) return ..() /* * Mouse types */ /mob/living/simple_animal/mouse/white body_color = "white" icon_state = "mouse_white" desc = "It's a small laboratory mouse." holder_type = /obj/item/holder/mouse/white /mob/living/simple_animal/mouse/gray body_color = "gray" icon_state = "mouse_gray" holder_type = /obj/item/holder/mouse/gray /mob/living/simple_animal/mouse/brown body_color = "brown" icon_state = "mouse_brown" holder_type = /obj/item/holder/mouse/brown /mob/living/simple_animal/mouse/white/Doc name = "Doc" desc = "Senior researcher of the Almayer. Likes: cheese, experiments, explosions." gender = MALE response_help = "pets" response_disarm = "gently pushes aside" response_harm = "stamps on" holder_type = /obj/item/holder/mouse/white/Doc //TOM IS ALIVE! SQUEEEEEEEE~K :) /mob/living/simple_animal/mouse/brown/Tom name = "Tom" desc = "Jerry the cat is not amused." response_help = "pets" response_disarm = "gently pushes aside" response_harm = "splats" holder_type = /obj/item/holder/mouse/brown/Tom
/* Este es un componente de React llamado `LeftBar` que muestra un menú de navegación en la barra lateral izquierda con varios enlaces e íconos. También incluye funcionalidad para un menú desplegable, autenticación de usuario y un botón de cierre de sesión. El componente importa varios íconos y módulos de bibliotecas externas como `react-icons` y `react-router-dom`. */ import logo from "../assets/logo.svg"; import { Link } from "react-router-dom"; import { AiOutlineShoppingCart, AiFillShop } from "react-icons/ai"; import { MdOutlineDashboard, MdOutlineChatBubbleOutline } from "react-icons/md"; import { TbGraph } from "react-icons/tb"; import { RiUser3Line } from "react-icons/ri"; import { CiLogout, CiLogin } from "react-icons/ci"; import { useEffect, useState } from "react"; import { BiMenu, BiHomeAlt2 } from "react-icons/bi"; import { onAuthStateChanged, signOut } from "firebase/auth"; import { auth, db } from "../firebase"; import { RiAdminLine } from "react-icons/ri"; import { doc, getDoc } from "firebase/firestore"; export const LeftBar = ({ active }) => { const LogOut = async () => { signOut(auth); }; const [isOpen, setisOpen] = useState(false); const [user, setuser] = useState(); const [account, setaccount] = useState(); useEffect(() => { onAuthStateChanged(auth, async (usr) => { if (usr) { setuser(usr); const docRef = doc(db, "users", usr.email); const docSnap = await getDoc(docRef); setaccount(docSnap.data()); } else { setuser(null); } }); }, [auth]); return ( <> <div className={`leftbar ${isOpen}`}> <div className="business-name"> <Link to={"/"} className="index-link" > <img className="logo" src={logo} alt="" /> <p>PIVECHAS</p> </Link> <button className="dropbutton" onClick={() => setisOpen(isOpen ? false : true)} > <BiMenu /> </button> </div> <ul> <li className={`delay-1`}> <Link to={"/"}> <BiHomeAlt2 className="icon" /> Inicio </Link> </li> <li className={`delay-1 ${active == "Tienda" ? "active" : ""}`}> <Link to={"/Tienda"}> <MdOutlineDashboard className="icon" /> Tienda Online </Link> </li> <li className={`delay-1 ${active == "Sucursales" ? "active" : ""}`}> <Link to={"/Sucursales"}> <AiFillShop className="icon" /> Sucursales </Link> </li> <li className={`delay-2 ${active == "Nosotros" ? "active" : ""}`}> <Link to={"/Nosotros"}> <TbGraph className="icon" /> Nosotros </Link> </li> <li className={`delay-3 ${active == "Contacto" ? "active" : ""}`}> <Link to={"/Contacto"}> <MdOutlineChatBubbleOutline className="icon" /> Contacto </Link> </li> <li className={`delay-4 ${active == "Cuenta" ? "active" : ""}`}> <Link to={"/Cuenta"}> <RiUser3Line className="icon" /> Cuenta </Link> </li> <li className={`delay-5 ${active == "Carrito" ? "active" : ""}`}> <Link to={"/Carrito"}> <AiOutlineShoppingCart className="icon" /> Carrito </Link> </li> {account && account.role == "admin" && ( <li className={`delay-6 ${active == "Admin" ? "active" : ""}`}> <Link to={"/Admin"}> <RiAdminLine className="icon" /> Admin </Link> </li> )} </ul> <div className="log-out-button"> <span className="background-button"> <div className="color"></div> </span> {user ? ( <div className="text" onClick={LogOut} > <CiLogout className="icon" /> Cerrar Sesión </div> ) : ( <Link to={"/SignIn"}> <div className="text"> <CiLogin className="icon" /> Iniciar Sesión </div> </Link> )} </div> </div> </> ); }; export default LeftBar;
/* จงเขียนฟังก์ชันการตัดเกรดในแต่ละรายวิชาของนักเรียนจำนวน 3 คน โดยนักเรียนแต่ละคนจะมีข้อมูลดังต่อไปนี้ ชื่อ, นักศักศึกษา, คะแนนในวิชาที่ 1, คะแนนในวิชาที่ 2, คะแนนในวิชาที่ 3, คะแนนในวิชาที่ 4, คะแนนในวิชาที่ 5 แสดงได้ดังโครงสร้างข้อมูลต่อไปนี้ struct Student { char Name[20] ; char ID[5] ; float ScoreSub1 ; float ScoreSub2 ; float ScoreSub3 ; float ScoreSub4 ; float ScoreSub5 ; } typedef S ; Test Case: Enter the details of 3 students : Student 1: Name: John Doe ID: 101 Scores in Subject 1: 77 Scores in Subject 2: 64 Scores in Subject 3: 66 Scores in Subject 4: 54 Scores in Subject 5: 56 Student 2: Name: Jane Smith ID: 102 Scores in Subject 1: 43 Scores in Subject 2: 70 Scores in Subject 3: 76 Scores in Subject 4: 77 Scores in Subject 5: 80 Student 3: Name: Mark Johnson ID: 103 Scores in Subject 1: 77 Scores in Subject 2: 74 Scores in Subject 3: 76 Scores in Subject 4: 81 Scores in Subject 5: 69 Output: Student Details: Student 1: Name: John Doe ID: 101 Scores: 77 64 66 54 56 Grades: B+ C C+ D D+ Average Scores: 63.4 Student 2: Name: Jane Smith ID: 102 Scores: 43 70 76 77 80 Grades: F B B+ B+ A Average Scores: 69.2 Student 3: Name: Mark Johnson ID: 103 Scores: 77 74 76 81 69 Grades: B+ B B+ A C+ Average Scores: 75.4 */ #include <stdio.h> #include <string.h> struct Student { char Name[20]; char ID[5]; float Scores[5]; } typedef S; //calculate grade const char* calculateGrade(float score) { if (score >= 85) return "A+"; else if (score >= 80) return " A"; else if (score >= 75) return "B+"; else if (score >= 70) return " B"; else if (score >= 65) return "C+"; else if (score >= 60) return " C"; else if (score >= 55) return "D+"; else if (score >= 50) return " D"; else return " F"; } int main() { S students[3]; printf("Enter the details of 3 students:\n"); for (int i = 0; i < 3; i++) { printf("Student %d:\n", i + 1); printf("Name: "); scanf("%s %s", students[i].Name); printf("ID: "); scanf("%s", students[i].ID); for (int j = 0; j < 5; j++) { printf("Scores in Subject %d: ", j + 1); scanf("%f", &students[i].Scores[j]); } } printf("\nStudent Details:\n"); for (int i = 0; i < 3; i++) { printf("Student %d:\n", i + 1); printf("Name: %s\n", students[i].Name); printf("ID: %s\n", students[i].ID); printf("Scores: "); for (int j = 0; j < 5; j++) { printf("%.0f ", students[i].Scores[j]); } printf("\n"); printf("Grades: "); for (int j = 0; j < 5; j++) { printf("%s ", calculateGrade(students[i].Scores[j])); } printf("\n"); float sum = 0; for (int j = 0; j < 5; j++) { sum += students[i].Scores[j]; } float averageScore = sum / 5.0; printf("Average Scores: %.1f\n\n", averageScore); } return 0; }
<script lang="ts"> // Interfaces import type { IUserProfile } from '$lib/types'; // Utils import { getUserInitials } from './utils'; // Props /** * @description User's account data */ export let userProfile: Omit<IUserProfile, 'display_name'>; /** * @description Avatar Size */ export let size: 'small' | 'medium' | 'large' = 'medium'; // Variables const sizeClasses = { small: 'h-6 w-6', medium: 'h-12 w-12', large: 'h-24 w-24' }; const initialsClasses = { small: 'text-xs', medium: 'text-md', large: 'text-3xl' }; const classes = sizeClasses[size]; const textClasses = initialsClasses[size]; const userInitials = getUserInitials(userProfile.first_name, userProfile.last_name); </script> {#if !userProfile.avatar_url} <div class="flex items-center justify-center rounded-full bg-primary {classes}"> <p class={textClasses}>{userInitials}</p> </div> {:else} <img src={userProfile.avatar_url} alt="User's Avatar" class="rounded-full {classes}" /> {/if}
import org.junit.Before; import org.junit.jupiter.api.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.*; import static org.junit.Assert.*; public class ShortestPathFinderTest { public Graph graph; public ShortestPathFinder shortestPathFinder; @Before public void setUp() { graph = new Graph(); shortestPathFinder = new ShortestPathFinder(graph); } @Test public void testFindShortestPath() { // Create nodes Node a = new Node("A", "Node A", new HashMap<>()); Node b = new Node("B", "Node B", new HashMap<>()); Node c = new Node("C", "Node C", new HashMap<>()); Node d = new Node("D", "Node D", new HashMap<>()); Node e = new Node("E", "Node E", new HashMap<>()); Node f = new Node("F", "Node F", new HashMap<>()); // Create graph Graph graph = new Graph(); graph.addNode(a); graph.addNode(b); graph.addNode(c); graph.addNode(d); graph.addNode(e); graph.addNode(f); graph.addEdge(a, b, 10, new HashMap<>()); graph.addEdge(a, c, 15, new HashMap<>()); graph.addEdge(b, d, 12, new HashMap<>()); graph.addEdge(b, f, 15, new HashMap<>()); graph.addEdge(c, e, 10, new HashMap<>()); graph.addEdge(d, e, 2, new HashMap<>()); graph.addEdge(d, f, 1, new HashMap<>()); graph.addEdge(f, e, 5, new HashMap<>()); // Create ShortestPathFinder instance ShortestPathFinder finder = new ShortestPathFinder(graph); // Test shortest path from node A to node E List<Node> shortestPath = finder.findShortestPath(a, e); assertNotNull(shortestPath); assertEquals(4, shortestPath.size()); assertEquals(a, shortestPath.get(0)); assertEquals(b, shortestPath.get(1)); assertEquals(d, shortestPath.get(2)); assertEquals(e, shortestPath.get(3)); // Test shortest path from node B to node F shortestPath = finder.findShortestPath(b, f); assertNotNull(shortestPath); assertEquals(3, shortestPath.size()); assertEquals(b, shortestPath.get(0)); assertEquals(d, shortestPath.get(1)); assertEquals(f, shortestPath.get(2)); // Test shortest path from node C to node D shortestPath = finder.findShortestPath(c, d); assertNull(shortestPath); } @Test public void testFindShortestPath_NotConnected() { // Create nodes Node a = new Node("A", "Node A", new HashMap<>()); Node b = new Node("B", "Node B", new HashMap<>()); Node c = new Node("C", "Node C", new HashMap<>()); Node d = new Node("D", "Node D", new HashMap<>()); // Create graph Graph graph = new Graph(); graph.addNode(a); graph.addNode(b); graph.addNode(c); graph.addNode(d); graph.addEdge(a, b, 10, new HashMap<>()); graph.addEdge(b, d, 5, new HashMap<>()); graph.addEdge(c, d, 5, new HashMap<>()); // Create ShortestPathFinder instance ShortestPathFinder finder = new ShortestPathFinder(graph); // Test shortest path between two unconnected nodes List<Node> shortestPath = finder.findShortestPath(a, c); assertNull(shortestPath); } @Test public void testFindShortestPathSameNode() { // Create nodes Node a = new Node("A", "Node A", new HashMap<>()); Node b = new Node("B", "Node B", new HashMap<>()); // Create graph Graph graph = new Graph(); graph.addNode(a); graph.addNode(b); graph.addEdge(a, b, 5, new HashMap<>()); // Create ShortestPathFinder instance ShortestPathFinder finder = new ShortestPathFinder(graph); // Test shortest path from node A to node A List<Node> shortestPath = finder.findShortestPath(a, a); assertNotNull(shortestPath); assertEquals(1, shortestPath.size()); assertEquals(a, shortestPath.get(0)); } }
import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import Drawer from '@mui/material/Drawer'; import CssBaseline from '@mui/material/CssBaseline'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import VideogameAssetIcon from '@mui/icons-material/VideogameAsset'; import FavoriteIcon from '@mui/icons-material/Favorite'; import MenuIcon from '@mui/icons-material/Menu'; import CloseIcon from '@mui/icons-material/Close'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; const drawerWidth = 240; const Main = styled('main', { shouldForwardProp: (prop) => prop !== 'open' })<{ open?: boolean; }>(({ theme, open }) => ({ flexGrow: 1, padding: theme.spacing(3), transition: theme.transitions.create('margin', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), marginLeft: `-${drawerWidth}px`, ...(open && { transition: theme.transitions.create('margin', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginLeft: 0, }), })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { width: `calc(100% - ${drawerWidth}px)`, marginLeft: `${drawerWidth}px`, transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), }), })); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, justifyContent: 'flex-start', })); export default function Template(props:any) { const theme = useTheme(); const [open, setOpen] = React.useState(false); const title:Array<Array<string>> = [['R','#ff6b6b'],['G','#51cf66'],['B','#339af0'],[' place','']]; const toggleDrawer = (open: boolean) => (event: React.KeyboardEvent | React.MouseEvent) => { if ( event.type === 'keydown' && ((event as React.KeyboardEvent).key === 'Tab' || (event as React.KeyboardEvent).key === 'Shift') ) { return; } setOpen(!open); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={toggleDrawer(open)} edge="start" sx={{ mr: 2, ...(open && { display: 'none' }) }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> {title.map((titleValue, index) => ( <Box key={index} component="span" sx={{color:titleValue[1]}}> {titleValue[0]} </Box> ))} </Typography> </Toolbar> </AppBar> <Drawer sx={{ width: drawerWidth, flexShrink: 0, '& .MuiDrawer-paper': { width: drawerWidth, boxSizing: 'border-box', }, }} // variant="persistent" anchor="left" open={open} onClose={toggleDrawer(open)} > <DrawerHeader onClick={toggleDrawer(open)} sx={{alignItems: 'center'}}> <IconButton> <CloseIcon /> </IconButton> </DrawerHeader> <Divider /> <List> {['About', 'Game 1', 'Game 2', 'Game 3'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index !== 0 ? <VideogameAssetIcon /> : ''} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['Thanks to'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> <FavoriteIcon/> </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Main open={open}> <DrawerHeader /> {props.content} </Main> </Box> ); }