text
stringlengths
184
4.48M
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:recd/helpers/variable_keys.dart'; import 'package:recd/pages/common/shimmer_effect_widget.dart'; import 'package:shimmer/shimmer.dart'; class ImageWidget extends StatefulWidget { final String imageUrl; final double height; final double width; final int cacheHeight; final int cacheWidth; ImageWidget({ Key key, @required this.imageUrl, this.cacheHeight = 200, this.cacheWidth = 200, this.height = 200, this.width = 200, }) : super(key: key); @override _ImageWidgetState createState() => _ImageWidgetState(); } class _ImageWidgetState extends State<ImageWidget> { @override Widget build(BuildContext context) { return Container( // child: Image.network('${widget.img}', // cacheHeight: widget.cacheHeight, // // cacheWidth: widget.cacheWidth, // fit: BoxFit.cover, // errorBuilder: (context, url, error) => Icon(Icons.error), // loadingBuilder: (BuildContext context, Widget child, // ImageChunkEvent loadingProgress) { // if (loadingProgress == null) return child; // return Center( // child: relatedItemShimmer(), // // child: CircularProgressIndicator( // // value: loadingProgress.expectedTotalBytes != null // // ? loadingProgress.cumulativeBytesLoaded / // // loadingProgress.expectedTotalBytes // // : null, // // ), // ); // }), child: CachedNetworkImage( imageUrl: '${widget.imageUrl}', fit: BoxFit.cover, memCacheWidth: 170, height: widget.height, width: widget.width, errorWidget: (context, url, error) => errorImage(), fadeInDuration: Duration(microseconds: 10), fadeInCurve: Curves.easeIn, placeholder: (context, url) => popularMovieShimmer()), ); } Widget relatedItemShimmer() { return Shimmer.fromColors( child: Container( height: widget.height, width: widget.width, decoration: BoxDecoration(color: Colors.grey), child: Text(" ")), baseColor: Colors.grey[200], highlightColor: Colors.black26); } static errorImage() => Image.asset( ImagePath.RECDLOGO, filterQuality: FilterQuality.low, ); }
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:food_app/config/colors.dart'; import 'package:food_app/controllers/review_cart_provider.dart'; import 'package:provider/provider.dart'; class Count extends StatefulWidget { String? productName; String? productImage; String? productId; int? productPrice; Count({ this.productId, this.productImage, this.productName, this.productPrice, }); @override _CountState createState() => _CountState(); } class _CountState extends State<Count> { bool isTrue = false; int count = 1; getAddQuantity() { FirebaseFirestore.instance .collection("ReviewCart") .doc(FirebaseAuth.instance.currentUser!.uid) .collection("YourReviewCart") .doc(widget.productId) .get() .then((value) => { if (this.mounted) { { if (value.exists) { setState(() { count = value.get("cartQuantity"); isTrue = value.get("isAdd"); }) } } }, }); } @override Widget build(BuildContext context) { getAddQuantity(); // ignore: avoid_print ReviewCartProvider reviewCartProvider = Provider.of(context); return Container( child: Container( height: 30, width: 60, decoration: BoxDecoration( border: Border.all(color: Colors.yellowAccent), borderRadius: BorderRadius.circular(10), ), child: isTrue == true ? Row( mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( onTap: () { if (count > 1) { setState(() { count--; }); reviewCartProvider.updateReviewCartData( cartId: widget.productId, cartImage: widget.productImage, cartName: widget.productName, cartPrice: widget.productPrice, cartQuantity: count, ); } else if (count == 1) { setState(() { isTrue = false; }); reviewCartProvider.reviewCartDataDelete(widget.productId); } }, child: Icon( Icons.remove, size: 15, ), ), Text( "$count", ), InkWell( onTap: () { setState(() { count++; }); reviewCartProvider.updateReviewCartData( cartId: widget.productId, cartImage: widget.productImage, cartName: widget.productName, cartPrice: widget.productPrice, cartQuantity: count, ); }, child: Icon( Icons.add, size: 15, ), ) ], ) : Center( child: InkWell( onTap: () { setState(() { isTrue = true; }); reviewCartProvider.addReviewCartData( cartId: widget.productId, cartImage: widget.productImage, cartName: widget.productName, cartPrice: widget.productPrice, cartQuantity: count, ); }, child: Text( "ADD", style: TextStyle(color: primaryColor), ), ), ), )); } }
import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Course { private String courseCode; private String title; private String description; private int capacity; private String schedule; private int occupiedSlots; public Course(String courseCode, String title, String description, int capacity, String schedule) { this.courseCode = courseCode; this.title = title; this.description = description; this.capacity = capacity; this.schedule = schedule; this.occupiedSlots = 0; } public String getCourseCode() { return courseCode; } public String getTitle() { return title; } public String getDescription() { return description; } public int getCapacity() { return capacity; } public String getSchedule() { return schedule; } public int getOccupiedSlots() { return occupiedSlots; } public void occupySlot() { occupiedSlots++; } public void releaseSlot() { occupiedSlots--; } } class Student { private int studentID; private String name; private List<Course> registeredCourses; public Student(int studentID, String name) { this.studentID = studentID; this.name = name; this.registeredCourses = new ArrayList<>(); } public int getStudentID() { return studentID; } public String getName() { return name; } public List<Course> getRegisteredCourses() { return registeredCourses; } public void registerForCourse(Course course) { registeredCourses.add(course); course.occupySlot(); } public void dropCourse(Course course) { registeredCourses.remove(course); course.releaseSlot(); } } public class CourseRegistrationSystem { public static void main(String[] args) { List<Course> courses = new ArrayList<>(); courses.add(new Course("CSCI101", "Introduction to Computer Science", "Fundamental concepts of programming", 30, "MWF 10:00 AM - 11:30 AM")); courses.add(new Course("MATH201", "Calculus I", "Limits, derivatives, and integrals", 25, "TTH 1:00 PM - 2:30 PM")); // Add more courses as needed List<Student> students = new ArrayList<>(); students.add(new Student(1, "Alice")); students.add(new Student(2, "Bob")); // Add more students as needed Scanner scanner = new Scanner(System.in); while (true) { System.out.println("\nOptions:"); System.out.println("1. Display Course Listing"); System.out.println("2. Display Student Information"); System.out.println("3. Register for a Course"); System.out.println("4. Drop a Course"); System.out.println("5. Exit"); System.out.print("Enter your choice (1-5): "); int choice = scanner.nextInt(); switch (choice) { case 1: displayCourseListing(courses); break; case 2: displayStudentInformation(students); break; case 3: registerForCourse(students, courses, scanner); break; case 4: dropCourse(students, courses, scanner); break; case 5: System.out.println("Exiting. Thank you!"); scanner.close(); System.exit(0); default: System.out.println("Invalid choice. Please enter a number between 1 and 5."); } } } private static void displayCourseListing(List<Course> courses) { System.out.println("\nCourse Listing:"); for (Course course : courses) { System.out.println(course.getCourseCode() + " - " + course.getTitle() + " (Capacity: " + (course.getCapacity() - course.getOccupiedSlots()) + "/" + course.getCapacity() + ")"); } } private static void displayStudentInformation(List<Student> students) { System.out.println("\nStudent Information:"); for (Student student : students) { System.out.println(student.getStudentID() + " - " + student.getName() + " (Registered Courses: " + student.getRegisteredCourses().size() + ")"); } } private static void registerForCourse(List<Student> students, List<Course> courses, Scanner scanner) { displayStudentInformation(students); System.out.print("Enter student ID: "); int studentID = scanner.nextInt(); Student student = findStudent(students, studentID); if (student == null) { System.out.println("Student not found."); return; } displayCourseListing(courses); System.out.print("Enter course code to register: "); String courseCode = scanner.next(); Course course = findCourse(courses, courseCode); if (course == null) { System.out.println("Course not found."); return; } if (course.getOccupiedSlots() < course.getCapacity()) { student.registerForCourse(course); System.out.println("Registration successful."); } else { System.out.println("Course is full. Registration unsuccessful."); } } private static void dropCourse(List<Student> students, List<Course> courses, Scanner scanner) { displayStudentInformation(students); System.out.print("Enter student ID: "); int studentID = scanner.nextInt(); Student student = findStudent(students, studentID); if (student == null) { System.out.println("Student not found."); return; } System.out.println("\nCourses registered by " + student.getName() + ":"); List<Course> registeredCourses = student.getRegisteredCourses(); for (Course registeredCourse : registeredCourses) { System.out.println(registeredCourse.getCourseCode() + " - " + registeredCourse.getTitle()); } System.out.print("Enter course code to drop: "); String courseCode = scanner.next(); Course course = findCourse(registeredCourses, courseCode); if (course == null) { System.out.println("Course not found in registered courses."); return; } student.dropCourse(course); System.out.println("Course dropped successfully."); } private static Student findStudent(List<Student> students, int studentID) { for (Student student : students) { if (student.getStudentID() == studentID) { return student; } } return null; } private static Course findCourse(List<Course> courses, String courseCode) { for (Course course : courses) { if (course.getCourseCode().equalsIgnoreCase(courseCode)) { return course; } } return null; } }
import 'dart:developer'; import 'package:chat_app/features/user/model/user_model.dart'; import 'package:chat_app/services/firestore_services.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/services.dart'; import 'package:get/get.dart'; class HomeController extends GetxController { RxBool isLoading = false.obs; RxBool isSearching = false.obs; final RxList<UserModel> userList = <UserModel>[].obs; final RxList<UserModel> searchList = <UserModel>[].obs; @override void onInit() { fetchData(); FireStoreServices().getSelfInfo(); SystemChannels.lifecycle.setMessageHandler((message) { log('Message: $message'); //for updating user active status according to lifecycle events //resume -- active or online //pause -- inactive or offline if (FireStoreServices.firebaseAuth.currentUser != null) { if (message.toString().contains('resume')) { FireStoreServices().updateActiveStatus(true); } if (message.toString().contains('pause')) { FireStoreServices().updateActiveStatus(false); } } return Future.value(message); }); super.onInit(); } Future<void> fetchData() async { final List<UserModel> result = await FireStoreServices().fetchData(); userList.value = result; } searchUser(String value) { searchList.clear(); for (var e in userList) { if (e.name.toLowerCase().contains(value.toLowerCase()) || e.email.toLowerCase().contains(value.toLowerCase())) { searchList.add(e); } searchList; } } }
import {Level} from "../level"; export type MachineGUIAction = { editorLine?: number, shiftInput?: boolean, addValueToOutput?: number, // I am not sure how this could be done different (like index: value). This worked. memory?: { index: number, value: number | undefined }[] error?: string, finished?: boolean, } /** Contains all results that are available after running the code on the machine. */ export type MachineResult = { machineGUIActions: MachineGUIAction[] finishedWithError: boolean } enum MachineState { RUNNING, FINISHED, FINISHED_WITH_ERROR } /** * Represents the internal state of the level. Methods represent actions that are allowed on the level. * After all actions are executed, results can be gathered. */ export class Machine { input: number[] expectedOut: number[] memorySlots: (undefined | number)[] machineGUIActions: MachineGUIAction[] machineState: MachineState constructor(level: Level) { // Clone arrays to make sure that we don't change the level object. this.input = [...level.input] this.expectedOut = [...level.expectedOut] this.memorySlots = [] for (let i = 0; i < level.nrOfMemorySlots; i++) { this.memorySlots.push(undefined) } this.machineGUIActions = [] this.machineState = MachineState.RUNNING } isRunning(): boolean { return this.machineState == MachineState.RUNNING } createMachineResult(): MachineResult { return { machineGUIActions: this.machineGUIActions, finishedWithError: this.machineState == MachineState.FINISHED_WITH_ERROR } } getValueOfMemorySlot(i: number): number { this.throwErrorIfMachineStopped() const value = this.memorySlots[i] if (value == undefined) { this.error('Trying to read memory slot ' + i + ', but it is empty') return 0 } return value } getValueOfInputElement(): number { this.throwErrorIfMachineStopped() return this.input[0] } moveInputToOutput(editorLine: number) { this.throwErrorIfMachineStopped() if (this.input.length == 0) { this.error('Cannot read from input anymore') return } const expectedOutNumber = this.expectedOut.shift() if (expectedOutNumber != this.input[0]) { this.error('Output is not correct! Expected output was ' + expectedOutNumber + ', but you tried to add ' + this.input[0] + ' to the output.') return } this.handle({ editorLine: editorLine, shiftInput: true, addValueToOutput: this.input.shift() }) if (this.expectedOut.length == 0) { this.finished() } } moveInputToMemorySlot(i: number, editorLine: number) { this.throwErrorIfMachineStopped() if (this.input.length == 0) { this.error('Cannot read from input anymore') return } this.memorySlots[i] = this.input.shift() this.handle({ editorLine: editorLine, shiftInput: true, memory: [{ index: i, value: this.memorySlots[i] }] }) } moveMemorySlotToOutput(i: number, editorLine: number) { this.throwErrorIfMachineStopped() if (this.memorySlots[i] == undefined) { this.error('No value to move to output') return } const expectedOutNumber = this.expectedOut.shift() if (expectedOutNumber != this.memorySlots[i]) { this.error('Output is not correct! Expected output was ' + expectedOutNumber + ', but you tried to add ' + this.memorySlots[i] + ' to the output.') return } // @ts-ignore this.handle({ editorLine: editorLine, addValueToOutput: this.memorySlots[i], memory: [{ index: i, value: undefined }] }) this.memorySlots[i] = undefined if (this.expectedOut.length == 0) { this.finished() } } moveMemorySlotToMemorySlot(from: number, to: number, editorLine: number) { this.throwErrorIfMachineStopped() if (this.memorySlots[from] == undefined) { this.error('No value to move to memory slot ' + to) return } this.memorySlots[to] = this.memorySlots[from] this.memorySlots[from] = undefined this.handle({ editorLine: editorLine, memory: [ { index: to, value: this.memorySlots[to] }, { index: from, value: undefined } ] }) } copyMemorySlotToMemorySlot(from: number, to: number, editorLine: number) { this.throwErrorIfMachineStopped() if (this.memorySlots[from] == undefined) { this.error('No value to move to memory slot ' + to) return } this.memorySlots[to] = this.memorySlots[from] this.handle({ editorLine: editorLine, memory: [{ index: to, value: this.memorySlots[to] }] }) } copyMemorySlotToOutput(from: number, editorLine: number) { this.throwErrorIfMachineStopped() if (this.memorySlots[from] == undefined) { this.error('Memory slot ' + from + ' does not exist') return } const numberToCopyToOutput = this.memorySlots[from] const expectedOutNumber = this.expectedOut.shift() if (expectedOutNumber != numberToCopyToOutput) { this.error('Output is not correct! Expected output was ' + expectedOutNumber + ', but you tried to add ' + numberToCopyToOutput + ' to the output.') return } this.handle({ editorLine: editorLine, addValueToOutput: numberToCopyToOutput }) if (this.expectedOut.length == 0) { this.finished() } } incrementMemorySlot(i: number, editorLine: number) { this.throwErrorIfMachineStopped() if (this.memorySlots[i] == undefined) { this.error('Memory slot ' + i + ' does not exist') return } // @ts-ignore this.memorySlots[i]++ this.handle({ editorLine: editorLine, memory: [{ index: i, value: this.memorySlots[i] }] }) } decrementMemorySlot(i: number, editorLine: number) { this.throwErrorIfMachineStopped() if (this.memorySlots[i] == undefined) { this.error('Memory slot ' + i + ' does not exist') return } // @ts-ignore this.memorySlots[i]-- this.handle({ editorLine: editorLine, memory: [{ index: i, value: this.memorySlots[i] }] }) } checkWinningCondition() { // This method is called after a full run is completed, so we should be able to call this at any point in time // without throwing an error. To prevent adding multiple finish or error clauses, we only execute the content if the // machine is running. if (this.isRunning()) { if (this.expectedOut.length != 0) { this.error('Your program stopped executing, but more output is still expected. Value ' + this.expectedOut[0] + ' is still expected.') } else { this.finished() } } } addMemorySlotToMemorySlot(from: number, to: number, editorLine: number) { this.throwErrorIfMachineStopped() if (this.memorySlots[from] == undefined || this.memorySlots[to] == undefined) { this.error('One of the two memory slots does not exist: ' + from + ", " + to) return } // @ts-ignore this.memorySlots[to] += this.memorySlots[from] this.handle({ editorLine: editorLine, memory: [{ index: to, value: this.memorySlots[to] }] }) } subtractMemorySlotFromMemorySlot(valueToSubtract: number, toBeSubtractedFrom: number, editorLine: number) { this.throwErrorIfMachineStopped() if (this.memorySlots[valueToSubtract] == undefined || this.memorySlots[toBeSubtractedFrom] == undefined) { this.error('One of the two memory slots does not exist: ' + valueToSubtract + ", " + toBeSubtractedFrom) return } // @ts-ignore this.memorySlots[toBeSubtractedFrom] -= this.memorySlots[valueToSubtract] this.handle({ editorLine: editorLine, memory: [{ index: toBeSubtractedFrom, value: this.memorySlots[toBeSubtractedFrom] }] }) } private handle(machineGUIAction: MachineGUIAction) { this.machineGUIActions.push(machineGUIAction) } error(message: string) { this.throwErrorIfMachineStopped() this.machineGUIActions.push({error: message}) this.machineState = MachineState.FINISHED_WITH_ERROR } private finished() { this.throwErrorIfMachineStopped() this.machineGUIActions.push({finished: true}) this.machineState = MachineState.FINISHED } private throwErrorIfMachineStopped() { if (!this.isRunning()) { throw new Error('Cannot execute this command after execution is done') } } }
question link -: https://leetcode.com/problems/design-a-stack-with-increment-operation/description/ solution -: class CustomStack { private List<Integer> stk = new ArrayList<>(); private int sz; public CustomStack(int maxSize) { sz = maxSize; } public void push(int x) { if (stk.size() < sz) { stk.add(x); } } public int pop() { return stk.isEmpty() ? -1 : stk.remove(stk.size() - 1); } public void increment(int k, int val) { for (int i = 0; i < k && i < stk.size(); ++i) { stk.set(i, stk.get(i) + val); } } }
import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; const BrandCard = ({ brand }) => { const { id, brand_name, brand_image, description } = brand; return ( <div className="flex flex-col items-center border-2 border-gray-200 md:max-w-xl"> <img className="object-cover w-full h-96 md:h-56" src={brand_image} alt=""></img> <div className="flex flex-col justify-between p-4 leading-normal flex-grow"> <Link className="hover:text-blue-500 mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white" to={`/products/${id}`}>{brand_name}</Link> <p className="main mb-3 font-normal text-gray-700 dark:text-gray-400">{description}</p> </div> </div> ); }; BrandCard.propTypes = { brand: PropTypes.object } export default BrandCard;
// Create a stack and perform Pop, Push, and Traverse operations on the stack using a Linear Linked list #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; struct Node *top = NULL; void push(int value) { struct Node *new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->data = value; new_node->next = top; top = new_node; } void pop() { if (top == NULL) printf("Stack is empty\n"); else { struct Node *temp = top; top = top->next; free(temp); } } void traverse() { if (top == NULL) printf("Stack is empty\n"); else { struct Node *temp = top; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } } int main() { push(1); push(2); push(3); traverse(); pop(); traverse(); return 0; } /* Stack Algorithm Using Linear Linked List: 1. Create a class Node that contains a value and a pointer to the next node. 2. Create a class Stack that contains a pointer to the top node of the stack. 3. Implement the following operations: • Push: 1. Create a new node and set its value to the value to be pushed. 2. Set the next pointer of the new node to the current top node. 3. Update the top pointer to the new node. • Pop: 1. If the stack is empty, return null. 2. Store the value of the top node in a variable. 3. Update the top pointer to the next node. 4. Return the stored value. • Traverse: 1. Create a current pointer and set it to the top node. 2. Repeat the following until the current pointer is null: a. Print the value of the current node. b. Update the current pointer to the next node. */
package annotation_example; import java.io.Serializable; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.IOException; import java.io.*; import java.util.*; class MySingleton implements Serializable { private static final MySingleton INSTANCE = new MySingleton(); private MySingleton() {} public static MySingleton getInstance() { return INSTANCE; } private Object writeReplace() { return new SerializationProxy(); } private static class SerializationProxy implements Serializable { private static final long serialVersionUID = 1L; private Object readResolve() { return MySingleton.getInstance(); } } } public class SerializationExample { public static void main(String[] args) throws IOException, ClassNotFoundException { MySingleton originalSingleton = MySingleton.getInstance(); // Сериализация в массив байтов byte[] serializedData; try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) { objectOutputStream.writeObject(originalSingleton); serializedData = byteArrayOutputStream.toByteArray(); } // Десериализация из массива байтов try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serializedData); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) { MySingleton deserializedSingleton = (MySingleton) objectInputStream.readObject(); System.out.println("Are they the same instance? " + (originalSingleton == deserializedSingleton)); } } }
from fastapi import Request from fastapi.routing import APIRouter from loopquest import schema from datetime import datetime from .crud import * from shortuuid import ShortUUID ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz" gen_short_uuid = lambda: ShortUUID(alphabet=ALPHABET).random(length=8) api_router = APIRouter( prefix="/exp", tags=["Experiment"], ) @api_router.post("", response_model=schema.Experiment) async def create_experiment(request: Request, experiment: schema.ExperimentCreate): while True: try: short_uuid = gen_short_uuid() env = schema.Experiment( **experiment.model_dump(), id=short_uuid, creation_time=datetime.now(), update_time=datetime.now() ) return await db_create_experiment(request.app.db, env) except HTTPException as e: if e.status_code == 409: continue else: raise e @api_router.get("/all", response_model=list[schema.Experiment]) async def get_all_experiments(request: Request): exps = await db_get_all_experiments(request.app.db) return exps @api_router.get("/{id}", response_model=schema.Experiment) async def read_experiment(request: Request, id: str): env = await db_get_experiment(request.app.db, id) return env @api_router.put("/{id}", response_model=schema.Experiment) async def update_experiment( request: Request, id: str, experiment: schema.ExperimentUpdate ): env = await db_update_experiment(request.app.db, id, experiment) return env @api_router.delete("/{id}") async def delete_experiment(request: Request, id: str): await db_delete_experiment(request.app.db, id) return {"message": "Experiment deleted successfully"} @api_router.get("/user/{user_id}/env/{env_id}", response_model=list[schema.Experiment]) async def get_experiment_by_user_env(request: Request, user_id: str, env_id: str): exps = await db_get_experiment_by_user_env(request.app.db, user_id, env_id) return exps @api_router.get("/user/{user_id}", response_model=list[schema.Experiment]) async def get_experiment_by_user(request: Request, user_id: str): exps = await db_get_experiment_by_user(request.app.db, user_id) return exps
// -*- mode: c++; -*- // DESCRIPTION: Header file for Timer class // // Copyright(C) 1/24/2008 by Walt Mankowski // [email protected] // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // $Id: timer.h 163 2008-02-17 19:51:24Z walt $ #ifndef _TIMER_H #define _TIMER_H #include <sys/time.h> #include <sys/resource.h> // Simple object that functions like a stopwatch to get elapsed // system, user, and wall time. Call the start() method to set the // timer, stop() to stop it. You can then query the values with // utime() stime(), and wtime(). // // This is mainly a wrapper to convert the struct timeval's into // doubles so the caller doesn't have to worry about them. class Timer { private: struct timeval start_utime; struct timeval start_stime; struct timeval start_wtime; struct timeval stop_utime; struct timeval stop_stime; struct timeval stop_wtime; void die(const char *fmt, ...); double delta_tv(const struct timeval *a, const struct timeval *b) const; double tv2double(const struct timeval *tv) const; public: Timer(); ~Timer() {} void start(); void stop(); double utime() const { return delta_tv(&start_utime, &stop_utime); } double stime() const { return delta_tv(&start_stime, &stop_stime); } double wtime() const { return delta_tv(&start_wtime, &stop_wtime); } }; #endif
package controllers.budget; import java.io.IOException; import java.sql.Date; import java.util.List; import javax.persistence.EntityManager; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import models.Budget; import models.Item; import models.validators.BudgetValidator; import utils.DBUtil; /** * Servlet implementation class BudgetUpdateServlet */ @WebServlet("/budget/update") public class BudgetUpdateServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public BudgetUpdateServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String _token = (String)request.getParameter("_token"); if(_token != null && _token.equals(request.getSession().getId())) { EntityManager em = DBUtil.createEntityManager(); Budget b = em.find(Budget.class, (Integer)(request.getSession().getAttribute("budget_id"))); b.setBudget_date(Date.valueOf(request.getParameter("budget_date"))); Item i = em.find(Item.class, Integer.parseInt(request.getParameter("item_id"))); b.setItem(i); List<Item> itemList = em.createNamedQuery("getAllItems", Item.class) .getResultList(); b.setDetail(request.getParameter("detail")); String amountNull_error= new String(); String tooBigAmount_error= new String(); try { if(request.getParameter("amount")==null || request.getParameter("amount").equals("")){ amountNull_error="金額を入力してください。"; } else if(Integer.parseInt(request.getParameter("amount"))>999999){ tooBigAmount_error = "金額は999,999以下で入力してください。"; } else { b.setAmount(Integer.parseInt(request.getParameter("amount"))); } } catch(NumberFormatException e) { tooBigAmount_error = "金額は999,999以下で入力してください。"; } List<String> errors = BudgetValidator.validate(b); if(!amountNull_error.equals("")) { errors.add(amountNull_error); } if(!tooBigAmount_error.equals("")) { errors.add(tooBigAmount_error); } if(errors.size() > 0) { em.close(); request.setAttribute("_token", request.getSession().getId()); request.setAttribute("budget", b); request.setAttribute("errors", errors); request.setAttribute("itemList", itemList); RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/views/budget/edit.jsp"); rd.forward(request, response); } else { em.getTransaction().begin(); em.getTransaction().commit(); em.close(); request.getSession().setAttribute("flush", "更新が完了しました。"); request.setAttribute("_token", request.getSession().getId()); request.getSession().removeAttribute("budget_id"); response.sendRedirect(request.getContextPath() + "/budget/index"); } } } }
// Recursive Mathematical Functions // Notes from video /* My understanding of it There are two types: - permutation: elements can not repeat - Arrangement: elements are allowed to repeat */ // MARK: - Find the factorial of n aka (n)! // resursive verion func fact(_ n: Int) -> Int { // if n == 0 { return 1 } // (0)! = 1 return n * fact(n - 1) // n * (n-1)! } print(10, "Factorial:", fact(10)) // Iterative func fact2(_ n: Int) -> Int { // O(n) var result = 1 for i in 1 ... n { result = result * i } return result } print(10, "Factorial:", fact2(10))
<div class="container mx-auto pb-[200px]"> <h1 class="text-2xl text-center text-white font-bold my-8">Misiones Seguidas</h1> @if ($missions->count() == 0) <p class="text-center text-red-500 font-bold my-8 text-3xl">No sigues ninguna misión</p> @endif @foreach ($missions as $mission) <div class="bg-white shadow-lg rounded-lg overflow-hidden mb-8"> @if ($mission->photo) <img src="{{ asset('/storage/Images/images-Missions/missions/' . $mission->photo) }}" alt="Mission Photo" class="w-full h-56 object-cover object-center"> @endif <div class="p-6"> <h2 class="text-xl font-bold mb-2">{{ $mission->title }}</h2> <p class="text-gray-700 mb-4">{{ $mission->subtitle }}</p> <p class="mb-4">{{ $mission->description }}</p> <div class="flex justify-between items-center mb-4"> <div> <p><strong>Fecha:</strong> {{ $mission->date }}</p> <p><strong>Estado:</strong> {{ $mission->status }}</p> </div> <div> <p><strong>Tipo:</strong> {{ $mission->type }}</p> <p><strong>Prioridad:</strong> {{ $mission->priority }}</p> </div> </div> <div class="flex justify-between items-center mb-4"> <div> <p><strong>Objetivo:</strong> {{ $mission->objective }}</p> <p><strong>Acción:</strong> {{ $mission->action }}</p> </div> <div> <p><strong>Resultado:</strong> {{ $mission->result }}</p> </div> </div> <div class="flex justify-between items-center"> <div> <p><strong>Armada:</strong> {{ $mission->army->name }}</p> <p><strong>Destino:</strong> {{ $mission->destination->name }}</p> <p><strong>Persona a cargo:</strong> {{ $mission->user->name }}</p> </div> <div> <button onclick="showFollowers({{ $mission->id }})" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"> Ver Seguidores </button> <button wire:click="unfollow({{ $mission->id }})" class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"> Dejar de Seguir </button> </div> </div> </div> </div> @endforeach </div>
package com.example.mscustomers.service.impl; import com.example.mscustomers.client.ProductServiceClient; import com.example.mscustomers.dto.enumeration.OrderStatus; import com.example.mscustomers.dto.request.OrderRequestDto; import com.example.mscustomers.dto.response.OrderResponseDto; import com.example.mscustomers.entity.CartEntity; import com.example.mscustomers.entity.CustomerEntity; import com.example.mscustomers.entity.OrderEntity; import com.example.mscustomers.exception.MethodArgumentNotValidException; import com.example.mscustomers.exception.OrderCancellationException; import com.example.mscustomers.exception.ResourceNotFoundException; import com.example.mscustomers.mapper.OrderMapper; import com.example.mscustomers.repository.CartRepository; import com.example.mscustomers.repository.CustomerRepository; import com.example.mscustomers.repository.OrderRepository; import com.example.mscustomers.service.OrderService; import lombok.RequiredArgsConstructor; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.LocalDate; import java.util.List; import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class OrderServiceImpl implements OrderService { private final OrderRepository orderRepository; private final CartRepository cartRepository; private final OrderMapper orderMapper; private final ProductServiceClient productServiceClient; private final CustomerRepository customerRepository; @Override @Transactional public void addOrder(OrderRequestDto orderRequestDto) { List<CartEntity> cartEntityList = cartRepository.getCartEntitiesByCartIdIn(orderRequestDto.getCardId()); List<OrderEntity> orderEntity = orderMapper.fromDtoList(orderRequestDto); orderRepository.saveAll(orderEntity); cartRepository.deleteCartEntitiesByCartIdIn(orderRequestDto.getCardId()); orderEntity.stream().map(n->productServiceClient.updateProductStock(n.getProductId(),n.getQuantity())).collect(Collectors.toList()); } @Override public void cancelOrder(Long id) { OrderEntity orderEntity = orderRepository.getById(id); if(orderEntity.getStatus().getDisplayName() == "Pending" || orderEntity.getStatus().getDisplayName() == "Processing"){ orderEntity.setStatus(OrderStatus.CANCELLED); orderEntity.setCancelDate(LocalDate.now()); orderRepository.save(orderEntity); }else { throw new OrderCancellationException("You can't cancel order in " + orderEntity.getStatus().getDisplayName()); } } @Override public OrderResponseDto getOrderById(Long id) throws ResourceNotFoundException { OrderEntity orderEntity = orderRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Order not found with ID: " + id)); return orderMapper.toDto(orderEntity); } @Override public List<OrderResponseDto> getAllOrders() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserDetails userDetails = (UserDetails) authentication.getPrincipal(); CustomerEntity customerEntity = customerRepository.findCustomerEntityByEmail( userDetails.getUsername()); List<OrderEntity> orderEntities = orderRepository.getOrderEntitiesByCustomerEntity(customerEntity); return orderEntities.stream().map(n->orderMapper.toDto(n)).collect(Collectors.toList()); } @Override public void updateOrder(Long id, OrderStatus orderStatus) throws MethodArgumentNotValidException { OrderEntity orderEntity = orderRepository.getById(id); switch (orderStatus){ case SHIPPED: orderEntity.setShippingDate(LocalDate.now()); orderEntity.setStatus(orderStatus); case DELIVERED: orderEntity.setDeliveredDate(LocalDate.now()); orderEntity.setStatus(orderStatus); case PROCESSING: orderEntity.setStatus(orderStatus); case CANCELLED:throw new MethodArgumentNotValidException("You can't cancel in this controller"); } orderRepository.save(orderEntity); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdn.tiny.cloud/1/ccfwwhqm4w7lrxwp1zz4l7xeej6uq3si24gldj34zyqqtcj4/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script> <title>Admintrator</title> <link rel="icon" href="{{ asset('assets/img/icon-website/it-icon-3.jpg') }}" type="image/png"> @vite(['resources/sass/admin.scss', 'resources/js/admin.js']) </head> <body> <div id="warpper" class="nav-fixed"> @php $module_active = session('module_active'); @endphp <nav class="topnav shadow navbar-light bg-white d-flex"> <div class="navbar-brand"><a href="?">IT Device Administrator</a></div> <div class="nav-right "> <div class="btn-group mr-auto"> <button type="button" class="btn dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="plus-icon fas fa-plus-circle"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="?view=add-post">Thêm bài viết</a> <a class="dropdown-item" href="?view=add-product">Thêm sản phẩm</a> <a class="dropdown-item" href="?view=list-order">Thêm đơn hàng</a> </div> </div> <div class="btn-group"> <button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ Auth::user()->name }} </button> <div class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="#">Tài khoản</a> <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none"> @csrf </form> </div> </div> </div> </nav> <div id="page-body" class="d-flex"> <div id="sidebar" class="bg-white"> <ul id="sidebar-menu"> <li class="nav-link {{ $module_active == 'dashboard' ? 'active' : '' }}"> <a href="{{ route('admin.dashboard') }}"> <div class="nav-link-icon d-inline-flex"> <i class="far fa-folder"></i> </div> Dashboard </a> </li> <li class="nav-link {{ $module_active == 'page' ? 'active' : '' }}"> <a href="{{ route('admin.page.index') }}"> <div class="nav-link-icon d-inline-flex"> <i class="far fa-folder"></i> </div> Trang </a> <i class="arrow fas fa-angle-right"></i> <ul class="sub-menu"> <li><a href="{{ route('admin.page.create') }}">Thêm mới</a></li> <li><a href="{{ route('admin.page.index') }}">Danh sách</a></li> </ul> </li> <li class="nav-link {{ $module_active == 'post' ? 'active' : '' }}"> <a href="{{ route('admin.post.index') }}"> <div class="nav-link-icon d-inline-flex"> <i class="far fa-folder"></i> </div> Bài viết </a> <i class="arrow fas fa-angle-right"></i> <ul class="sub-menu"> <li><a href="{{ route('admin.post.create') }}">Thêm mới</a></li> <li><a href="{{ route('admin.post.index') }}">Danh sách</a></li> </ul> </li> <li class="nav-link {{ $module_active == 'product' ? 'active' : '' }}"> <a href="{{ route('admin.product.index') }}"> <div class="nav-link-icon d-inline-flex"> <i class="far fa-folder"></i> </div> Sản phẩm </a> <i class="arrow fas fa-angle-right"></i> <ul class="sub-menu"> <li><a href="{{ route('admin.product.create') }}">Thêm mới</a></li> <li><a href="{{ route('admin.product.index') }}">Danh sách</a></li> <li><a href="{{ route('admin.product.childCategory') }}">Danh mục con</a></li> <li><a href="{{ route('admin.product.category') }}">Danh mục</a></li> <li><a href="{{ route('admin.product.mainCategory') }}">Danh mục lớn</a></li> </ul> </li> <li class="nav-link {{ $module_active == 'attribute' ? 'active' : '' }}"> <a href="{{ route('admin.attribute.index') }}"> <div class="nav-link-icon d-inline-flex"> <i class="far fa-folder"></i> </div> Thuộc tính sản phẩm </a> <i class="arrow fas fa-angle-right"></i> <ul class="sub-menu"> <li><a href="{{ route('admin.attribute.index') }}">Thêm mới</a></li> </ul> </li> <li class="nav-link {{ $module_active == 'order' ? 'active' : '' }}"> <a href="{{ route('admin.order.index') }}"> <div class="nav-link-icon d-inline-flex"> <i class="far fa-folder"></i> </div> Bán hàng </a> <i class="arrow fas fa-angle-right"></i> <ul class="sub-menu"> <li><a href="{{ route('admin.order.index') }}">Đơn hàng</a></li> </ul> </li> <li class="nav-link {{ $module_active == 'coupon' ? 'active' : '' }}"> <a href="{{ route('admin.coupon.index') }}"> <div class="nav-link-icon d-inline-flex"> <i class="far fa-folder"></i> </div> Coupon </a> <i class="arrow fas fa-angle-right"></i> <ul class="sub-menu"> <li><a href="{{ route('admin.coupon.index') }}">Danh sách</a></li> </ul> <ul class="sub-menu"> <li><a href="{{ route('admin.coupon.create') }}">Thêm mới</a></li> </ul> </li> <li class="nav-link {{ $module_active == 'user' ? 'active' : '' }}"> <a href="{{ route('admin.user.index') }}"> <div class="nav-link-icon d-inline-flex"> <i class="far fa-folder"></i> </div> Users </a> <i class="arrow fas fa-angle-right"></i> <ul class="sub-menu"> <li><a href="{{ route('admin.user.create') }}">Thêm mới</a></li> <li><a href="{{ route('admin.user.index') }}">Danh sách</a></li> </ul> </li> <li class="nav-link {{ $module_active == 'website' ? 'active' : '' }}"> <a href="{{ route('admin.website.info') }}"> <div class="nav-link-icon d-inline-flex"> <i class="far fa-folder"></i> </div> Websites </a> <i class="arrow fas fa-angle-right"></i> <ul class="sub-menu"> <li><a href="{{ route('admin.website.image') }}">Hình ảnh</a></li> <li><a href="{{ route('admin.website.info') }}">Thông tin</a></li> </ul> </li> </ul> </div> </div> <div id="wp-content"> @yield('admin-content') </div> </div> <script> tinymce.init({ selector: 'textarea', plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount', toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table | align lineheight | numlist bullist indent outdent | emoticons charmap | removeformat', }); </script> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> </script> </body> </html>
import { BaseAsset, ApplyAssetContext, ValidateAssetContext } from 'lisk-sdk'; import { RedeemableNFTAccountProps } from '../../../../types/core/account/profile'; import { ReplyCommentClubsProps } from '../../../../types/core/asset/redeemable_nft/reply_comment_clubs_asset'; import { ReplyAsset } from '../../../../types/core/chain/engagement'; import { ACTIVITY } from '../constants/activity'; import { VALIDATION } from '../constants/validation'; import { replyCommentClubsAssetSchema } from '../schemas/asset/reply_comment_clubs_asset'; import { getAccountStats, setAccountStats } from '../utils/account_stats'; import { addActivityEngagement } from '../utils/activity'; import { getCollectionById } from '../utils/collection'; import { addCommentClubsReplyById, getCommentClubsById, setCommentClubsById, } from '../utils/engagement'; import { getNFTById } from '../utils/redeemable_nft'; import { getBlockTimestamp } from '../utils/transaction'; export class ReplyCommentClubsAsset extends BaseAsset { public name = 'replyCommentClubs'; public id = 13; // Define schema for asset public schema = replyCommentClubsAssetSchema; public validate({ asset }: ValidateAssetContext<ReplyCommentClubsProps>): void { if (asset.id.length > VALIDATION.ID_MAXLENGTH) { throw new Error(`asset.id max length is ${VALIDATION.ID_MAXLENGTH}`); } if (asset.cid.length > VALIDATION.IPFS_CID_v1_MAXLENGTH) { throw new Error(`asset.cid max length is ${VALIDATION.IPFS_CID_v1_MAXLENGTH}`); } } // eslint-disable-next-line @typescript-eslint/require-await public async apply({ asset, transaction, stateStore, }: ApplyAssetContext<ReplyCommentClubsProps>): Promise<void> { const timestamp = getBlockTimestamp(stateStore); const comment = await getCommentClubsById(stateStore, asset.id); if (!comment) { throw new Error('Comment doesnt exists'); } if (comment.type === 'nft') { const nft = await getNFTById(stateStore, comment.target.toString('hex')); if (!nft) { throw new Error('NFT not found while checking authorization'); } if ( Buffer.compare(nft.creator, transaction.senderAddress) !== 0 && Buffer.compare(nft.owner, transaction.senderAddress) !== 0 ) { throw new Error('You are not authorized to give reply on this NFT clubs'); } } else if (comment.type === 'collection') { const collection = await getCollectionById(stateStore, comment.target.toString('hex')); if (!collection) { throw new Error('Collection not found while checking authorization'); } if ( Buffer.compare(collection.creator, transaction.senderAddress) !== 0 && collection.stat.owner.findIndex(o => Buffer.compare(o, transaction.senderAddress) === 0) === -1 ) { throw new Error('You are not authorized to give reply on this collection clubs'); } } comment.reply += 1; const reply: ReplyAsset = { id: transaction.id, owner: transaction.senderAddress, data: asset.cid, date: BigInt(timestamp), like: 0, target: comment.id, }; await addCommentClubsReplyById(stateStore, asset.id, reply); await setCommentClubsById(stateStore, asset.id, comment); await addActivityEngagement(stateStore, transaction.senderAddress.toString('hex'), { transaction: transaction.id, name: ACTIVITY.ENGAGEMENT.REPLYCOMMENTCLUBS, date: BigInt(timestamp), target: comment.id, }); const senderAccount = await stateStore.account.get<RedeemableNFTAccountProps>( transaction.senderAddress, ); senderAccount.redeemableNft.commentClubsSent += 1; await stateStore.account.set(transaction.senderAddress, senderAccount); const accountStats = await getAccountStats( stateStore, transaction.senderAddress.toString('hex'), ); accountStats.commentClubsSent.reply.unshift(transaction.id); accountStats.commentClubsSent.total = accountStats.commentClubsSent.comment.length + accountStats.commentClubsSent.reply.length; await setAccountStats(stateStore, transaction.senderAddress.toString('hex'), accountStats); } }
import styled from "styled-components"; import { motion } from "framer-motion"; const FilterBox = ({ tab, setTab, filterList }: FilterBoxProps) => { return ( <AsideContainer> <Ul> {filterList.map((filter) => ( <Li key={filter.id} onClick={() => setTab(filter.id)} active={filter.id === tab} > {filter.id === tab && ( <SideDiv as={motion.div} layoutId="sideDiv" animate={{ transition: { duration: 0.25, }, }} /> )} <p>{filter.label}</p> </Li> ))} </Ul> </AsideContainer> ); }; export default FilterBox; export const AsideContainer = styled.aside` background-color: white; padding-block: 2.5rem; font: 600 1.4rem var(--ff-poppins); box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.05); border-radius: 8px; height: fit-content; min-width: 15rem; `; const Ul = styled.ul` display: grid; gap: 2rem; `; const Li = styled.li<{ active: boolean }>` display: flex; align-items: center; gap: 1rem; cursor: pointer; color: ${(props) => props.active ? "var(--clr-primary)" : "var(--clr-gray)"}; p { padding-left: 2rem; } `; const SideDiv = styled.div` background-color: var(--clr-primary); width: 5px; height: 4rem; border-radius: 0px 8px 8px 0px; position: absolute; `;
--- title: "Cricket Dashboard" runtime: shiny output: flexdashboard::flex_dashboard: orientation: rows --- ```{r} library(dplyr) library(ggplot2) odi <- read.csv(file = "D:/Data Science 2017/Manipal Academy of Data Science/MGADS TERM2/2 Data Visualization/odi-batting.csv") odi$MatchDate = as.Date(odi$MatchDate, format="%m-%d-%Y") odi$year = format(odi$MatchDate, "%Y") uniq_years = sort(unique(as.numeric(odi$year))) uniq_countries = unique(odi$Country) ``` Sidebar {.sidebar} ```{r} selectInput(inputId = "select_country", label = "select a country", choices = uniq_countries) #selectInput(inputId = "select_year", label= "select a year", choices = uniq_years) sliderInput(inputId = "slide_year", label= "select a year", min = min(uniq_years), max = max(uniq_years) , value = max(uniq_years)) ``` Dashboard Row --------------------------------------- ### output ```{r} renderPlot({ odi %>% filter(Country == input$select_country, year == input$slide_year) %>% group_by(Player) %>% summarise(Runs=sum(Runs, na.rm = T)) %>% arrange(-Runs) %>% head(5) %>% ggplot(aes(x=reorder(Player, - Runs) , y = Runs)) + geom_bar(stat = 'identity') }) ``` Row --------------------------------------- ### output9 {.text} ```{r} renderText({input$select_year}) ``` ### output8 {.text} ```{r} renderText({input$select_country}) ```
import { UseMutationResult, useMutation } from '@tanstack/react-query'; import { AxiosResponse } from 'axios'; import { createUserProfilService } from '@/services/auth'; import { queryClient } from '@/App'; function useCreateUser(): UseMutationResult<AxiosResponse<any, any>> { return useMutation({ mutationFn: createUserProfilService, onMutate: async (newTodo) => { console.log('newTodo newTodo newTodo newTodo', newTodo); // Cancel any outgoing refetches // (so they don't overwrite our optimistic update) await queryClient.cancelQueries({ queryKey: ['userList'] }); // Snapshot the previous value const previousTodos = queryClient.getQueryData(['userList']); // Optimistically update to the new value queryClient.setQueryData(['userList'], (old: any) => { console.log('old old old', old); //return [...old, newTodo]; //TODO: add optimistic update return { data: { date: old?.data?.date, success: true, data: { pageInfo: { count: old?.data?.data?.pageInfo?.count, next: old?.data?.data?.pageInfo?.next + 1, page: 1, prev: old?.data?.data?.pageInfo?.prev, }, results: [ ...old?.data?.data?.results, { created_at: new Date().toISOString(), deleted_at: 0, email: newTodo.email, id: 15, last_connected_at: null, modified_at: new Date().toISOString(), password: newTodo.password, reset_password_expires: null, reset_password_token: null, username: null, }, ], }, }, }; }); console.log('previousTodos previousTodos previousTodos', previousTodos); // Return a context object with the snapshotted value return { previousTodos }; }, onError: (err, newTodo, context) => { queryClient.setQueryData(['userList'], context.previousTodos); }, // Always refetch after error or success: onSettled: () => { queryClient.invalidateQueries({ queryKey: ['userList'] }); }, }); } export default useCreateUser;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCategoryTranslationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('category_translations', function (Blueprint $table) { $table->unsignedBigInteger('category_id'); $table->unsignedBigInteger('language_id'); $table->string('name'); $table->primary(['category_id', 'language_id']); $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); $table->foreign('language_id')->references('id')->on('languages')->onDelete('cascade')->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('category_translations'); } }
#ifndef dataset #include<iostream> #include<fstream> #include<vector> #include<string> #include<sstream> #include<valarray> using namespace std; class Dataset { public: vector<vector<vector<float>>> read(string s, bool write=false, string pathToWrite="") { fstream fin; fin.open(s, ios::in); vector<vector<float>> rows; vector<float> single; string row, num; while(!fin.eof()) { single.clear(); getline(fin, row); stringstream ss(row); while(getline(ss, num, ',')) { single.emplace_back((float)atof(num.c_str())); } rows.emplace_back(single); } int size = rows.size(), attr = rows[0].size(); int train = size * 0.8; //cout<<size<<" "<<attr<<" "<<train<<"\n"; vector<vector<float>> xTrain, yTrain, xTest, yTest; for(int i = 0; i < train; i++) { single.resize(attr - 1); copy(rows[i].begin(), rows[i].begin() + attr - 1, single.begin()); xTrain.emplace_back(single); single.clear(); single.emplace_back(rows[i][attr - 1]); yTrain.emplace_back(single); } for(int i = train; i < size - 1; i++) { single.resize(attr - 1); copy(rows[i].begin(), rows[i].begin() + attr - 1, single.begin()); xTest.emplace_back(single); single.clear(); single.emplace_back(rows[i][attr - 1]); yTest.emplace_back(single); } if(write) { writeToDisk(pathToWrite, {xTrain, yTrain, xTest, yTest}); } return {xTrain, yTrain, xTest, yTest}; //return {rows}; } void writeToDisk(string path, vector<vector<vector<float>>> splits) { fstream fout; string paths[4]; if(path.length() != 0) { paths[0] = path + "/xTrain.csv"; paths[1] = path + "/yTrain.csv"; paths[2] = path + "/xTest.csv"; paths[3] = path + "/yTest.csv"; } else { paths[0] = "xTrain.csv"; paths[1] = "yTrain.csv"; paths[2] = "xTest.csv"; paths[3] = "yTest.csv"; } for(int i = 0; i < 4; i++) { fout.open(paths[i], ios::out); vector<vector<float>> cur = splits[i]; for(int j = 0; j < cur.size(); j++) { int k; for(k = 0; k < cur[j].size() - 1; k++) fout<<cur[j][k]<<", "; fout<<cur[j][k]<<"\n"; } fout.close(); } } }; #endif
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:pds_route/dataHandler/appData.dart'; import 'package:pds_route/screens/search_screen.dart'; import 'package:pds_route/screens/stepper_demo.dart'; import 'package:pds_route/screens/welcome_screen.dart'; import 'package:pds_route/screens/login_screen.dart'; import 'package:pds_route/screens/registration_screen.dart'; import 'package:pds_route/screens/maps_screen.dart'; import 'package:provider/provider.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (context) => AppData(), child: MaterialApp( initialRoute: WelcomeScreen.id, routes: { WelcomeScreen.id: (context) => WelcomeScreen(), LoginScreen.id: (context) => LoginScreen(), RegistrationScreen.id: (context) => RegistrationScreen(), MapsScreen.id: (context) => MapsScreen(), SearchScreen.id: (context) => SearchScreen(), StepperDemo.id: (context) => StepperDemo(), }, ), ); } }
#include "lists.h" /** * add_nodeint - function to add node at the beginning * @head: pointer to the first node * @n: value of the new nodes * * Return: address of new element, or NULL on failure */ listint_t *add_nodeint(listint_t **head, const int n) { listint_t *new; new = malloc(sizeof(listint_t)); if (!new) return (NULL); new->n = n; new->next = *head; *head = new; return (new); }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HomeComponent } from './modules/home/home.component'; import { SharedModule } from './shared/shared.module'; import { CoreModule } from './core/core.module'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { CourseComponent } from './modules/course/course.component'; import { MessageService } from 'primeng/api'; @NgModule({ declarations: [AppComponent, HomeComponent, CourseComponent], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, CoreModule, SharedModule, FontAwesomeModule, ], providers: [MessageService], bootstrap: [AppComponent], }) export class AppModule {}
// // ViewController.swift // RatingViewApp // // Created by Silvia Kuzmova on 27.01.22. // import UIKit import Combine class ViewController: UIViewController { private var subscriptions: Set<AnyCancellable> = [] private let movieRatingView: RatingView = { let ratingView = RatingView(allStars: 5, selectedStars: 3) return ratingView }() private let foodRatingView: RatingView = { let ratingView = RatingView() ratingView.selectedStars = 7 return ratingView }() override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() setupBindings() movieRatingView.selectedStars = 2 } } private extension ViewController { func setupViews() { view.backgroundColor = .white view.addSubview(movieRatingView) view.addSubview(foodRatingView) } func setupConstraints() { movieRatingView.translatesAutoresizingMaskIntoConstraints = false movieRatingView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true movieRatingView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true movieRatingView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 200).isActive = true movieRatingView.heightAnchor.constraint(equalToConstant: 100).isActive = true foodRatingView.translatesAutoresizingMaskIntoConstraints = false foodRatingView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true foodRatingView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true foodRatingView.topAnchor.constraint(equalTo: movieRatingView.bottomAnchor, constant: 200).isActive = true foodRatingView.heightAnchor.constraint(equalToConstant: 50).isActive = true } func setupBindings() { movieRatingView.ratingHasChangedPublisher .sink { rank in print("⭐️ ranking has changed to: \(rank)") } .store(in: &subscriptions) } }
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ui:composition xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" > <h:form id="BrkRepForm"> <p:panelGrid id="reportPanel" > <f:facet name="header"> <p:row> <p:column colspan="3"> Breakdown Report </p:column> </p:row> </f:facet> <p:row> <p:column><h:outputText value="Facility: "/> </p:column> <p:column> <p:selectOneMenu value="#{reportView.selectedFacility}" var="p" converter="#{facilityConverter}" filter="true" filterMatchMode="startsWith" > <f:selectItems value="#{reportView.facilities}" var="faci" itemLabel="#{faci.facilityName}" itemValue="#{faci}"/> <p:column> #{p.facilityName} </p:column> <p:column > #{p.description} </p:column> <f:validateBean/> </p:selectOneMenu> </p:column> </p:row> <p:row rendered="true"> <p:column><h:outputLabel for="type" value="Report Type" /></p:column> <p:column> <p:selectOneMenu id="type" value="#{reportView.selectedRepType}"> <f:selectItems value="#{reportView.reports}" /> <p:ajax update="reportPanel" process="reportPanel"/> </p:selectOneMenu> </p:column> </p:row> <p:row rendered="#{reportView.weeklyReport}"> <p:column><h:outputLabel for="week" value="Week" /></p:column> <p:column > <p:selectOneMenu id="week" value="#{reportView.selectedWeek}"> <f:selectItems value="#{reportView.weeks}" /> </p:selectOneMenu> </p:column> </p:row> <p:row rendered="#{reportView.monthlyReport}"> <p:column><h:outputLabel for="month" value="Month" /></p:column> <p:column> <p:selectOneMenu id="month" value="#{reportView.selectedMonth}"> <f:selectItems value="#{reportView.months}" /> </p:selectOneMenu> </p:column> </p:row> <p:row rendered="#{reportView.quarterlyReport}"> <p:column><h:outputLabel for="quarter" value="Quarter" /></p:column> <p:column> <p:selectOneMenu id="quarter" value="#{reportView.selectedQuarter}"> <f:selectItems value="#{reportView.quarters}" /> </p:selectOneMenu> </p:column> </p:row> <p:row rendered="#{!reportView.periodReport}"> <p:column><h:outputLabel for="year" value="Year" /></p:column> <p:column> <p:selectOneMenu id="year" value="#{reportView.selectedYear}"> <f:selectItems value="#{reportView.years}" /> </p:selectOneMenu> </p:column> </p:row> <p:row rendered="#{reportView.periodReport}"> <p:column><h:outputText value="Start Time "/></p:column> <p:column> <p:calendar id="sdate" value="#{reportView.selectedStartDate}" mindate="#{reportView.minDate}" maxdate="#{reportView.maxDate}" yearRange="#{msgs.calYearRange}" showButtonPanel="true" pattern="#{msgs.calDatePattern}" title="Format: #{msgs.calDatePattern}" navigator="true" /> </p:column> </p:row> <p:row rendered="#{reportView.periodReport}"> <p:column><h:outputText value="End Time "/></p:column> <p:column> <p:calendar id="edate" value="#{reportView.selectedEndDate}" mindate="#{reportView.minDate}" maxdate="#{reportView.maxDate}" yearRange="#{msgs.calYearRange}" showButtonPanel="true" pattern="#{msgs.calDatePattern}" title="Format: #{msgs.calDatePattern}" navigator="true" /> </p:column> </p:row> <p:row rendered="false"> <p:column><h:outputText value="Categories"/></p:column> <p:column> <p:selectCheckboxMenu value="#{reportView.selectedCategories}" label="Categories" converter="#{brkCategoryConverter}" filter="true" filterMatchMode="startsWith" disabled="true"> <f:selectItems value="#{reportView.categories}" var="bcat" itemLabel="#{bcat.name}" /> </p:selectCheckboxMenu> </p:column> </p:row> </p:panelGrid> <p:commandButton id="repButton" value="Generate" action="#{reportView.generateReport('breakdown')}" onclick="this.form.target = '_blank'" ajax="false" process="@form" disabled="#{reportView.canNotGenerateReports()}"/> <p:blockUI block=":reportInputs" trigger="repButton" > <p:graphicImage value="/resources/images/ajax-loader.gif" style="background-color: transparent" /> </p:blockUI> </h:form> </ui:composition>
"use client"; import React from "react"; import Link from "next/link"; function Signup() { return ( <div> <body className="font-mono "> <div className="container mx-auto"> <div className="flex justify-center px-6 my-12"> <div className="w-full xl:w-3/4 lg:w-11/12 flex "> <div className="w-full h-auto hidden lg:block lg:w-5/12 bg-cover rounded-l-lg" style={{ backgroundImage: `url('https://images.unsplash.com/photo-1482440308425-276ad0f28b19?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80')`, backgroundSize: "cover", backgroundPosition: "center center", width: "60%", }} ></div> <div className="w-full lg:w-7/12 bg-white p-5 rounded-lg lg:rounded-l-none" style={{ background: "#bebcb7" }} > <h3 className="pt-4 text-2xl text-center"> Create an Account! </h3> <form className="px-8 pt-6 pb-8 mb-4 bg-white rounded" style={{ background: "#bebcb7" }} > <div className="mb-4 md:flex md:justify-between"> <div className="mb-4 md:mr-2 md:mb-0"> <label className="block mb-2 text-sm font-bold text-gray-700" htmlFor="firstName" > First Name </label> <input className="w-full px-3 py-2 text-sm leading-tight text-gray-700 border rounded shadow appearance-none focus:outline-none focus:shadow-outline" id="firstName" type="text" placeholder="First Name" /> </div> <div className="md:ml-2"> <label className="block mb-2 text-sm font-bold text-gray-700" for="lastName" > Last Name </label> <input className="w-full px-3 py-2 text-sm leading-tight text-gray-700 border rounded shadow appearance-none focus:outline-none focus:shadow-outline" id="lastName" type="text" placeholder="Last Name" /> </div> </div> <div className="mb-4"> <label className="block mb-2 text-sm font-bold text-gray-700" for="email" > Email </label> <input className="w-full px-3 py-2 mb-3 text-sm leading-tight text-gray-700 border rounded shadow appearance-none focus:outline-none focus:shadow-outline" id="email" type="email" placeholder="Email" /> </div> <div className="mb-4 md:flex md:justify-between"> <div className="mb-4 md:mr-2 md:mb-0"> <label className="block mb-2 text-sm font-bold text-gray-700" for="password" > Password </label> <input className="w-full px-3 py-2 mb-3 text-sm leading-tight text-gray-700 border border-red-500 rounded shadow appearance-none focus:outline-none focus:shadow-outline" id="password" type="password" placeholder="******************" /> <p className="text-xs italic text-red-500"> Please choose a password. </p> </div> <div className="md:ml-2"> <label className="block mb-2 text-sm font-bold text-gray-700" for="c_password" > Confirm Password </label> <input className="w-full px-3 py-2 mb-3 text-sm leading-tight text-gray-700 border rounded shadow appearance-none focus:outline-none focus:shadow-outline" id="c_password" type="password" placeholder="******************" /> </div> </div> <div className="mb-6 text-center"> <button className="w-full px-4 py-2 font-bold text-white bg-blue-500 rounded-full hover:bg-blue-700 focus:outline-none focus:shadow-outline" type="button" > Register Account </button> </div> <hr className="mb-6 border-t" /> <div className="text-center"> <a className="inline-block text-sm text-blue-500 align-baseline hover:text-blue-800" href="#" > Forgot Password? </a> </div> <div className="text-center"> <Link href="/login"> <p className="inline-block text-sm text-blue-500 align-baseline hover:text-blue-800"> Already have an account? Login! </p> </Link> </div> </form> </div> </div> </div> </div> </body> </div> ); } export default Signup;
using System.Text; using Application; using Application.Interfaces; using Application.Services; using Discord; using Discord.Commands; using Discord.Interactions; using Discord.WebSocket; using Hangfire; using Hangfire.PostgreSql; using Infrastructure.Configuration; using Infrastructure.Data.Contexts; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Serilog; var builder = WebApplication.CreateBuilder(args); // Register appsettings.json builder.Configuration.AddJsonFile("appsettings.json", false, true); builder.Configuration.AddUserSecrets<Program>(); // Configure Serilog var logger = new LoggerConfiguration() .ReadFrom.Configuration(builder.Configuration) .CreateLogger(); builder.Logging.ClearProviders(); builder.Logging.AddSerilog(logger); // Add services to the container. var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext<ApplicationDbContext>(options => { options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")); options.UseSnakeCaseNamingConvention(); }); builder.Services.RegisterRequestHandlers(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); // Authentication var authConfig = builder.Configuration.GetRequiredSection("Authentication").Get<AuthConfiguration>() ?? throw new InvalidOperationException("Authentication configuration is missing"); builder.Services.AddSingleton(authConfig); builder.Services.AddAuthentication(options => { options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie() .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authConfig.Jwt.SigningKey)), ValidateIssuerSigningKey = true, ValidAudience = authConfig.Jwt.Audience, ValidIssuer = authConfig.Jwt.Issuer }; }); // Hangfire builder.Services.AddHangfire(x => x.UsePostgreSqlStorage(options => { options.UseNpgsqlConnection(connectionString); })); builder.Services.AddHangfireServer(); // Configure Discord var discordConfig = builder.Configuration.GetRequiredSection("Discord").Get<DiscordConfiguration>() ?? throw new InvalidOperationException("Discord configuration is missing"); discordConfig.SocketConfig.GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent | GatewayIntents.GuildMembers; builder.Services.AddSingleton(discordConfig); builder.Services.AddSingleton(discordConfig.SocketConfig); builder.Services.AddSingleton<DiscordSocketClient>(); builder.Services.AddSingleton<IDiscordClient>(x => x.GetRequiredService<DiscordSocketClient>()); builder.Services.AddSingleton<CommandService>(); builder.Services.AddSingleton<InteractionService>(); builder.Services.AddSingleton<ILoggingService, LoggingService>(); builder.Services.AddSingleton<IModerationMessageService, ModerationMessageService>(); builder.Services.AddSingleton<ICommandHandlingService, CommandHandlingService>(); builder.Services.AddScoped<IUnbanSchedulingService, UnbanSchedulingService>(); builder.Services.AddSpaStaticFiles(options => { options.RootPath = "wwwroot"; }); var app = builder.Build(); // Migrate the database using (var scope = app.Services.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); await dbContext.Database.MigrateAsync(); } // Start the Discord client var discordClient = app.Services.GetRequiredService<DiscordSocketClient>(); await discordClient.LoginAsync(TokenType.Bot, discordConfig.BotToken); await discordClient.StartAsync(); await discordClient.SetStatusAsync(UserStatus.DoNotDisturb); // Initialize the command handler for each scope var commandHandlingService = app.Services.GetRequiredService<ICommandHandlingService>(); discordClient.Ready += async () => { await commandHandlingService.InitializeAsync(); await discordClient.SetStatusAsync(UserStatus.Online); }; // Make sure the bot logs out instantly when the app stops var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>(); lifetime.ApplicationStopping.Register(() => { // Stop the Discord client discordClient.SetStatusAsync(UserStatus.DoNotDisturb).Wait(); discordClient.LogoutAsync().Wait(); }); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHangfireDashboard(); app.UseHttpsRedirection(); app.UseCors(corsPolicyBuilder => corsPolicyBuilder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() ); app.UseCookiePolicy(new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.Lax }); app.UseRouting(); app.UseAuthorization(); // Using UseEndpoints to map controllers instead of app.MapControllers since // the latter doesn't seem to work with the SPA middleware. #pragma warning disable ASP0014 app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); #pragma warning restore ASP0014 app.UseSpaStaticFiles(); app.UseSpa(spaBuilder => { spaBuilder.Options.SourcePath = "wwwroot"; if (app.Environment.IsDevelopment()) spaBuilder.UseProxyToSpaDevelopmentServer("http://localhost:3000"); }); app.Run();
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>EASA FORM 1</title> <script th:include="fragments/header :: headerScripts" th:remove="tag"></script> <link rel="stylesheet" href="../static/css/style.css" th:href="@{css/style.css}"> </head> <body> <h2></h2> <div class="card container"> <div class="card-body"> <div id="errorMsg" class="alert alert-danger d-none" role="alert" th:object="${error}" th:text="${error}"></div> <div class="row"> <div class="col-6"> <form id="form" action="" method="post" th:object="${form}"> <small><span style="color: red">*</span> All fields are mandatory</small> <div class="row"> <div class="col-6"> <div class="form-group mb-2"> <label for="authority"></label> <input class="form-control form-control-lg" id="authority" th:field="${form.authority}" aria-describedby="emailHelp" placeholder="1. Authority/Country"/> </div> <div class="form-group mb-2"> <label for="trackingNumber"></label> <input id="trackingNumber" class="form-control form-control-lg" th:field="${form.trackingNumber}" placeholder="3. Tracking number"/> </div> <div class="form-group mb-2"> <label for="orgNameAndAddress"></label> <input id="orgNameAndAddress" class="form-control form-control-lg" th:field="${form.orgNameAndAddress}" placeholder="4. Organisation name and address"/> </div> <div class="form-group mb-2"> <label for="workOrder"></label> <input id="workOrder" class="form-control form-control-lg" th:field="${form.workOrder}" placeholder="5. Workorder number"/> </div> <div class="form-group mb-2"> <label for="item"></label> <input id="item" class="form-control form-control-lg" th:field="${form.item}" placeholder="6. Item"/> </div> <div class="form-group mb-2"> <label for="description"></label> <input id="description" class="form-control form-control-lg" th:field="${form.description}" placeholder="7. Description"/> </div> <div class="form-group margin-bottom"> <label for="partNo"></label> <input id="partNo" class="form-control form-control-lg" th:field="${form.partNo}" placeholder="8. Part number"/> </div> <div class="form-group mt-2"> <div class="d-grid gap-2 col-12 mx-auto"> <button id="submit" class="btn btn-lg btn-outline-primary">Submit</button> </div> </div> </div> <div class="col-6"> <div class="form-group mb-2"> <label for="qty"></label> <input id="qty" class="form-control form-control-lg" th:field="${form.qty}" placeholder="9. Qty"/> </div> <div class="form-group mb-2"> <label for="serialNo"></label> <input id="serialNo" class="form-control form-control-lg" th:field="${form.serialNo}" placeholder="10. Serial number"/> </div> <div class="form-group mb-2"> <label for="status"></label> <input id="status" class="form-control form-control-lg" th:field="${form.status}" placeholder="11. Status"/> </div> <div class="form-group mb-2"> <label for="remarks"></label> <input id="remarks" class="form-control form-control-lg" th:field="${form.remarks}" placeholder="12. Remarks"/> </div> <div class="form-group mb-2"> <label for="signature"></label> <input id="signature" class="form-control form-control-lg" th:field="${form.signature}" placeholder="14b. Signature"/> </div> <div class="form-group mb-2"> <label for="approvalRef"></label> <input id="approvalRef" class="form-control form-control-lg" th:field="${form.approvalRef}" placeholder="14c. Approval"/> </div> <div class="form-group mb-2"> <label for="name"></label> <input id="name" class="form-control form-control-lg" th:field="${form.name}" placeholder="14d. Name"/> </div> <div class="form-group mb-2"> <label for="date"></label> <input id="date" class="form-control form-control-lg" th:field="${form.date}" placeholder="14e. Date"/> </div> </div> </div> </form> </div> <div class="col-6 align-self-center" align="center"> <h2 class="card-header"> Please fill out the form: </h2> <img width="600px" th:src="@{img/form.png}" alt="Image" src="../static/img/form.png"> </div> </div> </div> </div> </body> <script src="../static/js/form.js" th:src="@{js/form.js}" type="text/javascript"></script> </html>
import { useState } from "react"; import { Button } from "../Components/Button"; import { ButtonWarming } from "../Components/Buttonwarming"; import { Heading } from "../Components/Heading"; import { Inputbox } from "../Components/Inputbox"; import { Subheading } from "../Components/Subheading"; import axios from "axios"; import { useNavigate } from "react-router-dom"; export function Signup() { const[username,setusername]=useState(); const[firstname,setfirstname]=useState(); const[lastname,setlastname]=useState(); const[password,setpassword]=useState(); const navigate=useNavigate(); return( <div className=" bg-slate-200n h-screen flex justify-center"> <div className="flex flex-col"> <div className=" bg-white rounded-lg w-80 text-center p-2 h-max px-4"> <Heading label={"Signup"}/> <Subheading text={"provide all the below mentioned details to signin"}/> <Inputbox onchange={(e)=>{setusername(e.target.value)}}label={"Username/email"} type={"text"} inplace={"[email protected]"} /> <Inputbox onchange={(e)=>{setfirstname(e.target.value)}} label={"Firstname"} type={"text"} inplace={"Deepak"} /> <Inputbox onchange={(e)=>{setlastname(e.target.value)}}label={"Lastname"} type={"text"} inplace={"Sakthivel"} /> <Inputbox onchange={(e)=>{setpassword(e.target.value)}} label={"Password"} type={"password"} inplace={"123@123"} /> <div className="pt-4"> <Button label={"Signup"} onClick={async function() { const res= await axios.post("http://localhost:3000/api/v1/users/signup",{ username, firstname, lastname, password }); console.log(res.data); navigate("signin"); }}/> </div> <div> <ButtonWarming label={"Already have a account"} to={"/signin"} buttontext={"Signin"}/> </div> </div> </div> </div> ) }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h> typedef struct { char iban[25]; char* titular; char moneda[4]; float sold; } ContBancar; typedef struct { ContBancar cb; struct NodLS* next; } NodLS; typedef struct { char* iban; struct NodLS2* next; } NodLS2; void printare_lista_simplar(NodLS* prim) { NodLS* temp = prim; while (temp != NULL) { printf("IBAN: %s \t Titluar: %s \t Moneda: %s \t Sold: %f\n", temp->cb.iban, temp->cb.titular, temp->cb.moneda, temp->cb.sold); temp = temp->next; } } NodLS* inserare_sfarsit(NodLS* prim, ContBancar cont) { NodLS* nou = (NodLS*)malloc(sizeof(NodLS)); strcpy(nou->cb.iban, cont.iban); nou->cb.titular = (char*)malloc(sizeof(char) * (strlen(cont.titular) + 1)); strcpy(nou->cb.titular, cont.titular); strcpy(nou->cb.moneda, cont.moneda); nou->cb.sold = cont.sold; nou->next = NULL; if (prim == NULL) { prim = nou; } else { NodLS* temp = prim; while (temp->next != NULL) { temp = temp->next; } temp->next = nou; } return prim; } void inserare_inceput(NodLS** prim, ContBancar cont) { NodLS* nou = (NodLS*)malloc(sizeof(NodLS)); strcpy(nou->cb.iban, cont.iban); nou->cb.titular = (char*)malloc(sizeof(char*) * (strlen(cont.titular) + 1)); strcpy(nou->cb.titular, cont.titular); strcpy(nou->cb.moneda, cont.moneda); nou->cb.sold = cont.sold; if (*prim == NULL) { *prim = nou; } else { nou->next = *prim; *prim = nou; } } void salvare_conturi_euro_in_vector(ContBancar* vector, NodLS* prim, int* nrElem) { if (prim == NULL) { return; } else { NodLS* temp = prim; while (temp != NULL) { if (strcmp(temp->cb.moneda, "EUR") == 0) { /*strcpy(vector[*nrElem].iban, temp->cb.iban); vector[*nrElem].titular = (char*)malloc(strlen(temp->cb.titular) + 1); strcpy(vector[*nrElem].titular, temp->cb.titular); strcpy(vector[*nrElem].moneda, temp->cb.moneda); vector[*nrElem].sold = temp->cb.sold;*/ vector[*nrElem] = temp->cb; (*nrElem)++; } temp = temp->next; } } } void salvare_conturi_persoan_in_ls(NodLS* capListaInitiala, NodLS2** capListaSecundara, char* titular) { if (capListaInitiala == NULL) { return; } else { NodLS* temp = capListaInitiala; while (temp != NULL) { if (strcmp(temp->cb.titular, titular) == 0) { NodLS2* nou = (NodLS2*)malloc(sizeof(NodLS2)); nou->iban = (char*)malloc(strlen(temp->cb.iban) + 1); strcpy(nou->iban, temp->cb.iban); nou->next = NULL; if (*capListaSecundara == NULL) { *capListaSecundara = nou; } else { NodLS2* temp2 = *capListaSecundara; while (temp2->next != NULL) { temp2 = temp2->next; } temp2->next = nou; } } temp = temp->next; } } } NodLS* stergere_cont(NodLS* prim, char* titular) { if (prim == NULL) { return prim; } else { if (strcmp(prim->cb.titular, titular) == 0) { NodLS* toBeDeleted = prim; prim = prim->next; free(toBeDeleted->cb.titular); free(toBeDeleted); } NodLS* temp = prim; //ma opresc cand ajung pe ultimul nod while (temp->next != NULL) { if (strcmp(temp->cb.titular, titular) == 0) { NodLS* prev = prim; while (prev->next != temp) { prev = prev->next; } prev->next = temp->next; free(temp->cb.titular); free(temp); temp = prev->next; } temp = temp->next; } //am iesit din while si vreau sa steg ultimul nod if (strcmp(temp->cb.titular, titular) == 0) { NodLS* prev = prim; while (prev->next != temp) { prev = prev->next; } prev->next = temp->next; free(temp->cb.titular); free(temp); } } return prim; } void dezalocareLS(NodLS* prim) { NodLS* temp = prim; while (temp != NULL) { NodLS2* aux = temp->next; free(temp->cb.titular); free(temp); temp = aux; } } void dezalocareLS2(NodLS2* prim) { NodLS2* temp = prim; while (temp != NULL) { NodLS2* aux = temp->next; free(temp->iban); free(temp); temp = aux; } } int main() { NodLS* prim = NULL; FILE* f = fopen("Conturi.txt", "r"); if (f == NULL) { printf("Fisierul nu a fost deschis!"); return -1; } char buffer[250]; ContBancar contB; while (fscanf(f, "%s", contB.iban) == 1) { fscanf(f, " %[^\n]", buffer); contB.titular = (char*)malloc(sizeof(char) * (strlen(buffer) + 1)); strcpy(contB.titular, buffer); fscanf(f, "%s", contB.moneda); fscanf(f, "%f", &contB.sold); prim = inserare_sfarsit(prim, contB); free(contB.titular); } printf("Lista simpla citita din fisier\n"); printare_lista_simplar(prim); ContBancar contBancarInseratLaInceput; strcpy(contBancarInseratLaInceput.iban, "RO04BRDE1234567890556333"); contBancarInseratLaInceput.titular = (char*)malloc(strlen("Serban Timofte") + 1); strcpy(contBancarInseratLaInceput.titular, "Serban Timofte"); strcpy(contBancarInseratLaInceput.moneda, "EUR"); contBancarInseratLaInceput.sold = 10000; inserare_inceput(&prim, contBancarInseratLaInceput); // inserare la inceput printf("\nLista simpla dupa inserarea la inceput\n"); printare_lista_simplar(prim); //salvez conturile in EUR intr-un vector int nrElem = 0; ContBancar* conturiEURO = (ContBancar*)malloc(5 * sizeof(ContBancar)); salvare_conturi_euro_in_vector(conturiEURO, prim, &nrElem); printf("\nVectorul cu conturile bancare in EURO este:\n"); for (int i = 0; i < nrElem; i++) { printf("IBAN: %s \t Titular: %s \t MONEDA: %s \t Sold: %f\n", conturiEURO[i].iban, conturiEURO[i].titular, conturiEURO[i].moneda, conturiEURO[i].sold); } //salvam conturile unei persoane intr-o alta lista simpla NodLS2* primListaPopescuIulian = NULL; salvare_conturi_persoan_in_ls(prim, &primListaPopescuIulian, "Popescu Iulian"); printf("Lista lui Iulian Popescu: \n"); NodLS2* temp = primListaPopescuIulian; while (temp != NULL) { printf("\nIBAN: %s", temp->iban); temp = temp->next; } prim = stergere_cont(prim, "Ionescu Georgica"); printf("\nLista simpla dupa prima stergere:\n"); printare_lista_simplar(prim); prim = stergere_cont(prim, "Popescu Iulian"); printf("\nLista simpla dupa a doua stergere:\n"); printare_lista_simplar(prim); prim = stergere_cont(prim, "Serban Timofte"); printf("\nLista simpla dupa a treia stergere:\n"); printare_lista_simplar(prim); dezalocareLS(prim); dezalocareLS2(primListaPopescuIulian); free(conturiEURO); return 0; }
import graphviz import uuid import datetime import html import os import zipfile from selenium import webdriver from selenium.webdriver.chrome.options import Options from Crawler import Login # 受け取った連想配列から画面遷移図を作成する関数 def create_graph(associative_array, pdfimages, ORIGIN, SCANID, ScreenTitle): # rankdirは遷移図のデザインでLRは左から右に遷移していく、nodesepとranksepはノード間またはエッジ間の間隔を指定する graph = graphviz.Digraph(format='pdf', graph_attr={'rankdir': 'LR', 'nodesep': '3', 'ranksep': '3'}) # ノードとエッジの追加 # penwidthはエッジの太さ、arrowsizeは矢印の大きさ for source_node, target_nodes in associative_array.items(): if isinstance(target_nodes, list): target_nodes = list(dict.fromkeys(target_nodes)) for target_node in target_nodes: graph.edge(source_node, target_node, _attributes={'penwidth': '10', 'arrowsize': '5'}) else: graph.edge(source_node, target_nodes, _attributes={'penwidth': '10', 'arrowsize': '5'}) # 画像の追加 for key in pdfimages.keys(): Title = str(html.escape(ScreenTitle[key])).replace("\\", "") imagepath = str(html.escape(pdfimages[key])).replace("\\", "") if(len(ScreenTitle[key]) <= 0): Title = "No Title" # href属性はエスケープ処理しないとエラーが発生する 参考: https://docs.python.org/3/library/html.html#html.escape graph.node(str(key).replace(ORIGIN, ""), shape="record", label=f"""<<table style="rounded"> <tr><td border="0"><font point-size="100">{Title}</font></td></tr> <hr/> <tr><td border="0"><img src="{imagepath}" /></td></tr> </table>>""") pdffilepath = './Python/PDFFiles/'+str(SCANID)+'_transition_diagram' # 画面遷移図の保存 graph.render(pdffilepath)# badtodoアプリに対しての画面遷移図を生成しようとするとエラーが発生する問題に対処する必要がある。 return pdffilepath+".pdf" def create_transition_img(associative_array, ORIGIN, loginurl, loginpara, SCANID, scanonly, pdfimages, fasturl, ScreenTitle): # 一番最初のURLはクローラ側でスクショを撮影していないので撮影する if(fasturl not in pdfimages): # chromedriverの設定 options = Options() options.add_argument('--headless') options.add_argument("--no-sandbox") options.add_argument('--disable-gpu') options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome('/usr/bin/chromedriver', chrome_options=options) # ウィンドウのサイズを最大化する w = 1500 h = 1000 driver.set_window_size(w, h) start_time = datetime.datetime.now() driver = Login(loginurl, driver, loginpara, start_time, ORIGIN) driver.get(fasturl) filepath = "./Python/TransitionImages/"+str(SCANID)+"/"+str(uuid.uuid4())+".png" # Get Screen Shot driver.save_screenshot(filepath) pdfimages[fasturl] = filepath.replace("./Python/", "../") ScreenTitle[fasturl] = driver.title # ドライバーのメモリ解法 driver.quit() # 配列の重複した値の削除 参考: https://office54.net/python/data-types/list-duplicate-remove#section2 for key in associative_array.keys(): tmpdict = dict.fromkeys(associative_array[key]) associative_array[key] = list(tmpdict) # print(associative_array) try: os.mkdir("./Python/TransitionImages/"+str(SCANID)) except FileExistsError: pass # 巡回ページの連想配列と撮影したスクショをもとに画面遷移図を作成する pdffilepath = create_graph(associative_array, pdfimages, ORIGIN, SCANID, ScreenTitle) # scanonlyがTrueの場合は画面遷移図のzipファイルを作成して、元のファイル群は削除する if(scanonly): # 画像とPDFファイルをzipにまとめる with zipfile.ZipFile('./Python/ZipPDFFiles/transition_diagram.zip', 'w') as zipf: zipf.write(pdffilepath) for image_file in pdfimages.values(): zipf.write(str(image_file).replace("../", "./Python/")) # 不要なファイルを削除 os.remove(pdffilepath) os.remove(pdffilepath.replace(".pdf", "")) for image_file in pdfimages.values(): os.remove(str(image_file).replace("../", "./Python/")) pdffilepath = "./Python/ZipPDFFiles/transition_diagram.zip" return pdffilepath
<mat-card class="product"> <img mat-card-xl-image [src]="product.image || '/assets/landscape-placeholder.svg'" class="product-img" /> <mat-card-header> <mat-card-title-group> <mat-card-title> <span style="font-size: 2rem">{{ product.name }}</span> / <small> <b>{{ product.stock }} Units</b> </small> </mat-card-title> <mat-card-subtitle> SKU: {{ product._id }} </mat-card-subtitle> </mat-card-title-group> </mat-card-header> <mat-card-content> <p style="font-size: 1rem">{{ product.description }}</p> <p class="product-price"> $ {{ product.price | currency : "COP" : "" : ".0-0" }} </p> <mat-card-actions align="end"> @if (isAdmin) { <button mat-icon-button type="button" color="accent" matTooltip="Edit product" aria-label="Edit product" [routerLink]="'/app/product/' + product._id" > <mat-icon>edit</mat-icon> </button> <button color="accent" mat-icon-button type="button" (click)="onDelete.emit()" matTooltip="Delete product" aria-label="Delete product" > <mat-icon>delete</mat-icon> </button> } <span class="example-spacer" style="flex: 1 1 auto"></span> <button mat-stroked-button type="button" (click)="onAddToCart.emit()" [disabled]="product.stock === 0" matTooltip="Add to cart" aria-label="Add to cart" > <mat-icon>add_shopping_cart</mat-icon> Add </button> </mat-card-actions> </mat-card-content> </mat-card>
import numpy as np import matplotlib.pyplot as plt # 定义网格范围和步长 x = np.linspace(-5, 5, 400) y = np.linspace(-5, 5, 400) X, Y = np.meshgrid(x, y) # 定义不同的 a 值 a_values = [1, 4, 8, 12] # 计算所有图像的最大最小值,以确定统一的颜色范围 z_min = min(np.min(a * (X**2 + Y**2)) for a in a_values) z_max = max(np.max(a * (X**2 + Y**2)) for a in a_values) # 创建子图布局 fig, axs = plt.subplots(2, 2, figsize=(10, 8)) axs = axs.ravel() # 循环绘制每个图像 for i, a in enumerate(a_values): Z = a * (X**2 + Y**2) im = axs[i].imshow(Z, cmap='viridis', extent=(-5, 5, -5, 5), vmin=z_min, vmax=z_max) axs[i].set_title(f'a = {a}') fig.colorbar(im, ax=axs[i]) plt.tight_layout() plt.show()
"use client"; import React, { useEffect, useRef } from 'react'; const AudioListener = () => { const socket = useRef(null); const audioRef = useRef(new Audio()); useEffect(() => { // Initialize WebSocket connection socket.current = new WebSocket('ws://localhost:3001'); socket.current.onopen = () => { console.log('WebSocket connection opened'); }; socket.current.onmessage = (event) => { // Handle incoming audio data const audioBlob = new Blob([event.data], { type: 'audio/wav' }); const audioUrl = URL.createObjectURL(audioBlob); // Play the audio audioRef.current.src = audioUrl; audioRef.current.play(); }; socket.current.onclose = (event) => { console.log('WebSocket connection closed:', event); }; socket.current.onerror = (error) => { console.error('WebSocket error:', error); }; return () => { // Cleanup resources if component unmounts if (socket.current && socket.current.readyState === WebSocket.OPEN) { socket.current.close(); } }; }, []); return ( <div> <h2>Listening to Audio</h2> <audio ref={audioRef} controls /> </div> ); }; export default AudioListener; // "use client" // import React, { useEffect, useRef } from 'react'; // import io from 'socket.io-client'; // const AudioListener = () => { // const socket = useRef(null); // const audioRef = useRef(new Audio()); // useEffect(() => { // // Initialize Socket.IO connection // socket.current = io('https://localhost:3001'); // socket.current.on('connect', () => { // console.log('Socket.IO connection opened'); // }); // socket.current.on('audioData', (data) => { // const audioBlob = new Blob([data], { type: 'audio/wav' }); // const audioUrl = URL.createObjectURL(audioBlob); // // Play the audio // audioRef.current.src = audioUrl; // audioRef.current.play(); // }); // socket.current.on('disconnect', () => { // console.log('Socket.IO connection closed'); // }); // return () => { // socket.current.disconnect(); // }; // }, []); // return ( // <div> // <h2>Listening to Real-Time Audio</h2> // <audio ref={audioRef} controls /> // </div> // ); // }; // export default AudioListener;
import 'package:flutter/material.dart'; class MyTextField extends StatelessWidget { final String hintText; final IconData icon; final TextEditingController controller; const MyTextField({ super.key, required this.controller, required this.hintText, required this.icon }); @override Widget build(BuildContext context) { return TextField( controller: controller, keyboardType: TextInputType.number, decoration: InputDecoration( icon: Icon(icon), hintText: hintText, enabledBorder: const OutlineInputBorder(), focusedBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.teal.shade400 ) ) ), ); } }
//import module const express = require('express'); const app = express(); const path = require('path'); const dotenv = require('dotenv'); const session = require('express-session'); //import file const db = require('./config/mongoose'); const passport = require('passport'); const passportLocal = require('./config/passport-local-startegy'); const routes = require('./routes') const port = process.env.PORT || 8001; dotenv.config({ path: 'config/.env' }); // ejs as view engine app.set('view engine', 'ejs'); app.set('views', './views'); //session app.use( session({ secret: "deadpool", // SECRET is stored in the system veriable resave: false,//if the session data is alredy stored we dont need to rewrite it again and again so this is set to false //when the user is not logged in or identity is not establish in that case we dont need to save extra data in saveUninitialized: false, cookie: { maxAge: 1000 * 60 * 100 }, }) ); //extract styles and scripts from sub pages into the layout app.set('layout extractStyles', true); app.set('layout extractScripts', true); app.use(express.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, 'public'))); // for authentication app.use(passport.initialize()); app.use(passport.session()); app.use(passport.setAuthenticatedUser); // express router app.use('/', routes); // listen on port app.listen(port, () =>{ console.log(`server is running on port : ${port}`) })
use std::path::Path; use tempfile::NamedTempFile; use super::*; #[test] fn adds_keys() { let encrypted_temp_file = encrypted_tempfile(); add_age_key_command(encrypted_temp_file.path()); let updated_rops_file = updated_rops_file(encrypted_temp_file.path()); assert_eq!(2, updated_rops_file.metadata().intregation.age.len()) } #[test] fn removes_keys() { let encrypted_temp_file = encrypted_tempfile(); add_age_key_command(encrypted_temp_file.path()); assert_eq!(2, updated_rops_file(encrypted_temp_file.path()).metadata().intregation.age.len()); remove_age_key_command(encrypted_temp_file.path()); assert_eq!(1, updated_rops_file(encrypted_temp_file.path()).metadata().intregation.age.len()); } fn add_age_key_command(file_path: &Path) { let mut cmd = base(); cmd.arg("add"); finish(cmd, file_path) } fn remove_age_key_command(file_path: &Path) { let mut cmd = base(); cmd.arg("remove"); finish(cmd, file_path) } fn base() -> Command { AgeIntegration::set_mock_private_key_env_var(); let mut cmd = Command::package_command(); cmd.arg("keys"); cmd } fn finish(mut cmd: Command, file_path: &Path) { cmd.args(["--age", &<AgeIntegration as Integration>::KeyId::mock_other().to_string()]); let mut cmd = cmd.format_args(); cmd.arg(file_path); cmd.run_tty().assert_success(); } fn encrypted_tempfile() -> NamedTempFile { let temp_file = NamedTempFile::new().unwrap(); std::fs::write(temp_file.path(), sops_yaml_str!("age_example")).unwrap(); temp_file } fn updated_rops_file(updated_rops_file_path: &Path) -> RopsFile<EncryptedFile<DefaultCipher, DefaultHasher>, YamlFileFormat> { std::fs::read_to_string(updated_rops_file_path) .unwrap() .parse::<RopsFile<EncryptedFile<DefaultCipher, DefaultHasher>, YamlFileFormat>>() .unwrap() }
******** Ex 3, Task 2: Create a timer job definition ******** ******** Step 6 ******** public ContosoExpensesOverviewTimerJob() { } ******** Ex 3, Task 2: Create a timer job definition ******** ******** Step 7 ******** public ContosoExpensesOverviewTimerJob(string name, SPWebApplication webApplication, SPServer server, SPJobLockType lockType) : base(name, webApplication, server, lockType) { } ******** Ex 3, Task 2: Create a timer job definition ******** ******** Step 8 ******** public override void Execute(Guid targetInstanceId) { // Obtain a reference to the managers site collection. using (SPSite managerSite = new SPSite("http://managers.contoso.com")) { // Obtain a reference to the managers site. using (SPWeb managerWeb = managerSite.RootWeb) { // Obtain a reference to the expense overview list. SPList overviewList = managerWeb.Lists["Expenses Overview"]; // Remove all existing items from the list. while (overviewList.Items.Count > 0) { overviewList.Items[0].Delete(); overviewList.Update(); } // Iterate through each site collection in the current web application. foreach (SPSite departmentSite in this.WebApplication.Sites) { using (SPWeb departmentWeb = departmentSite.RootWeb) { // Get the Contoso Expenses list, if one exists. SPList expensesList = departmentWeb.Lists.TryGetList("Contoso Expenses"); if (expensesList != null) { // Calculate the total for the department. double departmentTotal = 0; foreach (SPListItem expense in departmentWeb.Lists["Contoso Expenses"].Items) { departmentTotal += (double)expense["InvoiceTotal"]; } // Use the site URL to determine the department name. Uri url = new Uri(departmentWeb.Url); string hostName = url.GetComponents(UriComponents.Host, UriFormat.Unescaped); string[] hostNameComponents = hostName.Split('.'); // Create a new item in the expense overview list. SPListItem overviewItem = overviewList.Items.Add(); overviewItem["Title"] = hostNameComponents[0]; overviewItem["Expense Total"] = departmentTotal; overviewItem.Update(); overviewList.Update(); } } departmentSite.Dispose(); } } } } ******** Ex 3, Task 3: Deploy the timer job ******** ******** Step 9 ******** private void deleteJob(SPWebApplication webApplication) { foreach(SPJobDefinition job in webApplication.JobDefinitions) { if(job.Name.Equals(timerJobName)) { job.Delete(); } } } ******** Ex 3, Task 3: Deploy the timer job ******** ******** Step 11 ******** SPWebApplication webApplication = ((SPSite)properties.Feature.Parent).WebApplication; deleteJob(webApplication); ContosoExpensesOverviewTimerJob timerJob = new ContosoExpensesOverviewTimerJob(timerJobName,webApplication, null, SPJobLockType.Job); SPMinuteSchedule schedule = new SPMinuteSchedule(); schedule.BeginSecond = 1; schedule.EndSecond = 5; schedule.Interval = 2; timerJob.Schedule = schedule; timerJob.Update(); ******** Ex 3, Task 3: Deploy the timer job ******** ******** Step 13 ******** SPWebApplication webApplication = ((SPSite)properties.Feature.Parent).WebApplication; deleteJob(webApplication);
pub mod outlook { use anyhow::{ anyhow, Context }; use windows::{ core::{ HSTRING, BSTR, PCWSTR, GUID, VARIANT }, Win32::System::{ Com::{ DISPATCH_PROPERTYPUT, DISPATCH_METHOD, CLSCTX_LOCAL_SERVER, DISPATCH_PROPERTYGET, IDispatch, DISPATCH_FLAGS, DISPPARAMS, CoInitialize, CLSIDFromProgID, CoCreateInstance }, Ole::{ DISPID_PROPERTYPUT } }, }; const LOCALE_USER_DEFAULT: u32 = 0x0400; const LOCALE_SYSTEM_DEFAULT: u32 = 0x0800; pub struct Variant(VARIANT); impl From<bool> for Variant { fn from(value: bool) -> Self { Self(value.into()) } } impl From<i32> for Variant { fn from(value: i32) -> Self { Self(value.into()) } } impl From<&str> for Variant { fn from(value: &str) -> Self { Self(BSTR::from(value).into()) } } impl From<&String> for Variant { fn from(value: &String) -> Self { Self(BSTR::from(value).into()) } } impl Variant { pub fn int(&self) -> anyhow::Result<i32> { Ok(i32::try_from(&self.0)?) } pub fn string(&self) -> anyhow::Result<String> { Ok(BSTR::try_from(&self.0)?.to_string()) } pub fn idispatch(&self) -> anyhow::Result<IDispatchWrapper> { Ok(IDispatchWrapper(IDispatch::try_from(&self.0)?)) } } pub struct IDispatchWrapper(pub IDispatch); impl IDispatchWrapper { // // refer: https://learn.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatcher.invoke?view=windowsdesktop-8.0 // pub fn invoke(&self, flags: DISPATCH_FLAGS, name: &str, mut args: Vec<Variant>) -> anyhow::Result<Variant> { unsafe { let mut dispid = 0; self.0 .GetIDsOfNames(&GUID::default(), &PCWSTR::from_raw(HSTRING::from(name).as_ptr()), 1, LOCALE_USER_DEFAULT, &mut dispid,) .with_context(|| "GetIDsOfNames")?; let mut dp = DISPPARAMS::default(); let mut dispid_named = DISPID_PROPERTYPUT; if !args.is_empty() { args.reverse(); dp.cArgs = args.len() as u32; dp.rgvarg = args.as_mut_ptr() as *mut VARIANT; // Handle special-case for property "put" if (flags & DISPATCH_PROPERTYPUT) != DISPATCH_FLAGS(0) { dp.cNamedArgs = 1; dp.rgdispidNamedArgs = &mut dispid_named; } } let mut result = VARIANT::default(); self.0 .Invoke(dispid, &GUID::default(), LOCALE_SYSTEM_DEFAULT, flags, &dp, Some(&mut result), None, None,) .with_context(|| "Invoke")?; Ok(Variant(result)) } } pub fn get(&self, name: &str) -> anyhow::Result<Variant> { self.invoke(DISPATCH_PROPERTYGET, name, vec![]) } pub fn put(&self, name: &str, args: Vec<Variant>) -> anyhow::Result<Variant> { self.invoke(DISPATCH_PROPERTYPUT, name, args) } pub fn call(&self, name: &str, args: Vec<Variant>) -> anyhow::Result<Variant> { self.invoke(DISPATCH_METHOD, name, args) } } pub fn mail(to: String, cc: String, subject: String, body: String) -> anyhow::Result<()> { // // Refer: // https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem // https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.to // https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.cc // https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.subject // https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.htmlbody // https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.display // unsafe { let res = CoInitialize(None); if res.is_err() { return Err(anyhow!("error: {}", res.message())); } let clsid = CLSIDFromProgID(PCWSTR::from_raw( HSTRING::from("Outlook.Application").as_ptr(), )) .with_context(|| "CLSIDFromProgID")?; // println!("{:?}", clsid); let outlook = CoCreateInstance(&clsid, None, CLSCTX_LOCAL_SERVER) .with_context(|| "CoCreateInstance")?; let outlook = IDispatchWrapper(outlook); let new_mail_item: i32 = 0; let result = outlook.call("CreateItem", vec![new_mail_item.into()]).with_context(|| "call CreateItem")?; let create_item = result.idispatch().with_context(|| "idispatch CreateItem")?; let to = to.as_str(); create_item.put("To", vec![to.into()]).with_context(|| "put recipients")?; let cc = cc.as_str(); create_item.put("CC", vec![cc.into()]).with_context(|| "put recipients")?; let subject = subject.as_str(); create_item.put("Subject", vec![(subject).into()]).with_context(|| "put subject")?; let mailbody = body.as_str(); create_item.put("HTMLBody", vec![(mailbody).into()]).with_context(|| "put html body")?; create_item.call("Display", vec![0.into()]).with_context(|| "call Dsiplay")?; Ok(()) } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../vue.js"></script> </head> <body> <div id="app"> <div>{{msg}}</div> <!-- v-once 只编译一次,不再具有响应式功能 如果显示的信息后续不需要在修改,可以使用v-once 可以提高性能 --> <div v-once>{{msg}}</div> </div> <script> var vm = new Vue({ el: '#app', data: { msg: 'hello vue' } }) </script> </body> </html>
import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faFacebook, faTwitter } from '@fortawesome/free-brands-svg-icons'; import { faEnvelope } from '@fortawesome/free-solid-svg-icons'; import salir from "../../public/imagenes/salir.png" const ShareModal = ({ producto, onClose }) => { const shareOnFacebook = () => { const description = encodeURIComponent(`Echa un vistazo a este increíble producto: ${producto.description}`); const imageUrl = encodeURIComponent(producto.img[0].url); const shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(window.location.href)}&quote=${description}&picture=${imageUrl}`; window.open(shareUrl, '_blank'); }; const shareOnTwitter = () => { const description = encodeURIComponent(`Echa un vistazo a este increíble producto: ${producto.description}`); const imageUrl = encodeURIComponent(producto.img[0].url); const shareUrl = `https://twitter.com/intent/tweet?url=${encodeURIComponent(window.location.href)}&text=${description}&media=${imageUrl}`; window.open(shareUrl, '_blank'); }; const shareOnEmail = () => { const subject = encodeURIComponent('Echa un vistazo a este producto'); const body = encodeURIComponent(`Te recomiendo este producto: ${window.location.href}\n\n${producto.description}`); const shareUrl = `mailto:?subject=${subject}&body=${body}`; window.location.href = shareUrl; }; return ( <div className="modal-overlay"> <div className="modal"> <img className="close-button" src={salir} alt="Cerrar" onClick={onClose} /> <img className="modalimg" src={producto.img[0].url} alt={producto.name} /> <p>{producto.description}</p> <a href={window.location.href} target="_blank" rel="noopener noreferrer">Enlace al producto</a> <div className="social-buttons"> <button onClick={shareOnFacebook}><FontAwesomeIcon icon={faFacebook} /></button> <button onClick={shareOnTwitter}><FontAwesomeIcon icon={faTwitter} /></button> <button onClick={shareOnEmail}><FontAwesomeIcon icon={faEnvelope} /></button> </div> </div> </div> ); }; export default ShareModal;
"use client"; import React from "react"; import { Box, Typography } from "@mui/material"; import Image from "next/image"; import AboutUsImage from "../../../../public/Assets/HomePage/AboutUsImage.png"; import AboutUsShoeImage from "../../../../public/Assets/HomePage/AboutUsShoeImage.png"; import { AboutUsCarouseldata } from "./helper"; import { useState } from "react"; import { useRouter } from "next/navigation"; import CustomButton from "@/components/Buttons/CustomButton"; import Link from "next/link"; const style = { rootContainer: { background: "#FAFAFA", display: "flex", flexDirection: "column", position: "relative", justifyContent: "center", alignItems: "center", pb: "4rem", }, subContainer: { height: { xs: "", md: "350px", lg: "500px" }, }, subContainer2: { width: "33%", height: "auto", position: "absolute", top: { xs: "calc(10rem + 17%)", sm: "calc(10rem + 18%)", md: "calc(10rem + 25%)", lg: "calc(10rem + 28%)", xl: "calc(10rem + 30%)", }, left: "33%", // right: "auto", }, title: { fontSize: { xs: "24px", md: "46px" }, fontWeight: "400", textAlign: "center", padding: "1rem", fontFamily: "Volkhov", mb: "3rem", mt: "8rem", }, carouselDiv: { display: "flex", flexDirection: "row", overflowX: "auto", justifyContent: "space-evenly", maxWidth: "100%", mt: "3rem", mb: "2rem", }, carouselInnerDiv: { padding: "5% 2%", minWidth: "200px", // mx: "10px", borderRadius: "10px", backgroundColor: "#FAFAFA", }, carouselInnerLabel: { // fontFamily: "Inter", fontSize: "1.25rem", fontWeight: "700", textAlign: "center", color: "#8A8A8A", }, button: { padding: "23px 61px", textAlign: "center", background: "#000000", color: "#FFFFFF", maxWidth: "234px", mb: "5rem", }, }; const AboutUs = () => { const [selectedData, setSelectedData] = useState(1); const router = useRouter(); const handleClick = (id) => { setSelectedData(id); }; return ( <Box sx={style.rootContainer}> <Typography sx={style.title}>GET KNOW MORE ABOUT US</Typography> <Box sx={style.subContainer}> <Image src={AboutUsImage} alt="About Us" style={{ maxWidth: "100%", height: "auto" }} /> </Box> <Box sx={style.subContainer2}> <Image src={AboutUsShoeImage} alt="About Us Shoe" style={{ maxWidth: "100%", height: "auto" }} /> </Box> <Box sx={style.carouselDiv}> {AboutUsCarouseldata.map((data) => { return ( <Box key={data.id} sx={style.carouselInnerDiv} onClick={() => handleClick(data.id)} > <Typography sx={style.carouselInnerLabel} style={{ color: selectedData === data.id && "#000000" }} > {data.label} </Typography> </Box> ); })} </Box> <Link href={`/shoppage/${AboutUsCarouseldata[selectedData - 1]?.label}`} style={{ textDecoration: "none" }} > <CustomButton content="SHOP NOW" /> </Link> </Box> ); }; export default AboutUs;
/* eslint-disable react-hooks/exhaustive-deps */ // eslint-disable-next-line no-unused-vars import React from 'react'; import { useState, useEffect } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import Swal from 'sweetalert2'; import { useDispatch, useSelector } from 'react-redux'; import { getCategory } from '../../redux/actions/category'; import { getDetailRecipe, updateRecipe } from '../../redux/actions/recipes'; import Navbar from '../../components/Navbar'; import Footer from '../../components/Footer'; import '../../assets/styles/utility.css'; import '../../assets/styles/editRecipe.css'; export default function EditRecipe() { const [photo, setPhoto] = useState(); const [form, setForm] = useState({ photo: '', title: '', ingredients: '', id_category: '', }); const dispatch = useDispatch(); const category = useSelector((state) => state.category); const detailRecipe = useSelector((state) => state.detailRecipe); const editRecipe = useSelector((state) => state.editRecipe); const navigate = useNavigate(); const { id } = useParams(); if (editRecipe.isLoading) { Swal.fire({ title: 'Updating...', html: 'Please wait...', allowEscapeKey: false, allowOutsideClick: false, didOpen: () => { Swal.showLoading(); }, }); } useEffect(() => { dispatch(getCategory()); dispatch(getDetailRecipe(id)); }, [dispatch]); useEffect(() => { setForm({ ...form, photo: detailRecipe.data?.photo, title: detailRecipe.data?.title, ingredients: detailRecipe.data?.ingredients, id_category: detailRecipe.data?.id_category, }); }, [detailRecipe]); const putData = () => { let bodyData = new FormData(); bodyData.append('photo', photo); bodyData.append('title', form.title); bodyData.append('ingredients', form.ingredients); bodyData.append('id_category', form.id_category); dispatch(updateRecipe(id, bodyData, navigate)); }; const handleUpdate = (event) => { event.preventDefault(); Swal.fire({ icon: 'warning', title: 'Confirmation', text: 'Are you sure want to update this recipe?', showCancelButton: true, confirmButtonText: 'Yes', cancelButtonText: 'No', reverseButtons: true, }).then((result) => { if (result.isConfirmed) { putData(); } else if (result.dismiss === Swal.DismissReason.cancel) { return false; } }); }; const onChangePhoto = (e) => { setPhoto(e.target.files[0]); e.target.files[0] && setForm({ ...form, photo: URL.createObjectURL(e.target.files[0]) }); console.log(e.target.files[0]); }; return ( <div> <Navbar /> <section className='container edit-recipe'> <form onSubmit={handleUpdate}> <div className='d-flex edit-photo align-items-center justify-content-center mb-4 ps-0'> {form.photo && <img src={form?.photo} alt='image-recipe' className='rounded' />} <button className='btn btn-change-photo fw-medium'> Change Photo <input type='file' className='background-primary' width='100%' height='100%' onChange={onChangePhoto} /> </button> </div> <div className='mb-3'> <input type='text' className='form-control p-3' placeholder='Title' value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} /> </div> <div className='mb-3'> <textarea className='form-control p-3' placeholder='Ingredients' rows='10' value={form.ingredients} onChange={(e) => setForm({ ...form, ingredients: e.target.value })}></textarea> </div> <div className='mb-3'> <select name='category_id' id='category' className='btn py-3' value={form.id_category} onChange={(e) => setForm({ ...form, id_category: e.target.value })}> {category.isSuccess ? category.data?.map((items, index) => { return ( <option value={parseInt(items.id_category)} key={index + 1}> {items.name} </option> ); }) : null} </select> </div> <div className='mb-3 d-flex justify-content-center'> <button type='submit' className='btn btn-update background-primary py-2 fw-medium text-white'> Update </button> </div> </form> </section> <Footer /> </div> ); }
const express = require("express"); const router = express.Router(); const bcrypt = require("bcrypt"); const jwt = require("jsonwebtoken"); require("dotenv").config(); const User = require("../../models/User"); const Review = require("../../models/Review"); const Order = require("../../models/Order"); router.get("/test", (req, res) => res.send("users route test")); const authenticateToken = (req, res, next) => { const authHeader = req.headers["authorization"]; const token = authHeader && authHeader.split(" ")[1]; if (token == null) { return res.sendStatus(401); } jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => { if (err) { return res.sendStatus(403); } req.user = user; next(); }); }; router.get("/", authenticateToken, (req, res) => { const user = req.user; if (!user.isAdmin) { res.sendStatus(403); } User.find() .then((users) => res.json(users)) .catch((err) => res.status(404).json({ error: "no users found" })); }); router.post("/register", async (req, res) => { const hashedPassword = await bcrypt.hash(req.body.password, 10); const user = { username: req.body.username, password: hashedPassword, isAdmin: false, isManager: false, isBanned: false, }; User.create(user) .then((user) => { res.json({ msg: "User added successfully😎" }); }) .catch((err) => { console.log(err); res.status(400).json({ error: "Unable to add this user" }); }); }); router.post("/login", async (req, res) => { User.find({ username: req.body.username }).then(async (user) => { if (user.length === 0) { res.status(400).json({ error: "no user found" }); } else { user = user[0]; try { if (await bcrypt.compare(req.body.password, user.password)) { const accessToken = jwt.sign( { username: user.username, isAdmin: user.isAdmin, isManager: user.isManager, isBanned: user.isBanned, }, process.env.ACCESS_TOKEN_SECRET ); const userReviews = await Review.find({ username: user.username, }); const userOrders = await Order.find({ username: user.username, }); res.status(200).json({ accessToken: accessToken, isAdmin: user.isAdmin, isManager: user.isManager, isBanned: user.isBanned, reviews: userReviews, orders: userOrders, }); } else { res.status(403).json({ message: "Not allowed" }); } } catch (error) { res.status(500); } } }); }); router.put("/:id", authenticateToken, (req, res) => { if (!req.user.isAdmin) { res.sendStatus(403); } User.findByIdAndUpdate(req.params.id, { $set: req.body }) .then((user) => res.json({ msg: "updated successfully😎" })) .catch((err) => res.status(400).json({ error: "Unable to update user" }) ); }); module.exports = router; module.exports.authenticateToken = authenticateToken;
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) from ansible.module_utils.basic import AnsibleModule __metaclass__ = type DOCUMENTATION = ''' --- module: dedicated_server_info short_description: Retrieve all info for a OVH dedicated server description: - This module retrieves all info for a OVH dedicated server author: Maxime Dupré requirements: - ovh >= 0.5.0 options: service_name: required: true description: The service_name ''' EXAMPLES = r''' - name: Retrieve all info for an OVH dedicated server synthesio.ovh.dedicated_server_info: service_name: "{{ service_name }}" delegate_to: localhost register: dedicated_info ''' RETURN = ''' # ''' from ansible_collections.synthesio.ovh.plugins.module_utils.ovh import OVH, ovh_argument_spec def run_module(): module_args = ovh_argument_spec() module_args.update(dict( service_name=dict(required=True) )) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) client = OVH(module) service_name = module.params['service_name'] result = client.wrap_call("GET", f"/dedicated/server/{service_name}") module.exit_json(changed=False, **result) def main(): run_module() if __name__ == '__main__': main()
import React from "react" import {InputNoIcon, InputIcon} from "./components/Input/Input" import "./Form.module.css" import {ButtonNavigate, ButtonSubmit } from "./components/Button/Button" import icoUser from "../img/svg/icoUser.svg" import icoEmail from "../img/svg/icoEmail.svg" import icoPassword from "../img/svg/icoPassword.svg" import { useNavigate } from "react-router-dom" function constructor(name, email, password) { return { user:{ name: name, email: email, password: password } } } export const FormSigin = () => { const go = useNavigate() const [email, setEmail ] = React.useState("") const [password, setPassword] = React.useState("") const [name, setName] = React.useState("") function HandleSubmit(event){ event.preventDefault() const formData = constructor(name, email, password) fetch("http://localhost:8080/sigin", { method: "post", headers:{ 'Content-Type': 'application/json' }, body : JSON.stringify(formData) }) .then((response) => response.json()) .then((response) => { alert(response.message) if(response.status.OK) { go("/home") } }) .catch((error) => { alert(error.message) }) } return <form onSubmit={HandleSubmit}> <InputIcon classCon={"content-input-icon"} classN={"input-icon"} type={"text"} img={icoUser} name={"name"} placeHolder={"Nome"} id={"1"} value={name} setValue={setName} /> <InputIcon classCon={"content-input-icon"} classN={"input-icon"} type={"email"} img={icoEmail} name={"email"} placeHolder={"Email"} id={"1"} value={email} setValue={setEmail} /> <InputIcon classCon={"content-input-icon"} classN={"input-icon"} type={"password"} img={icoPassword} name={"password"} placeHolder={"Senha"} id={"2"} value={password} setValue={setPassword} /> <ButtonSubmit text={"Criar Conta"} /> </form> } export const FormLogin = () => { const go = useNavigate() const [email, setEmail ] = React.useState("") const [password, setPassword] = React.useState("") const [name, setName] = React.useState("") function HandleSubmit(event){ event.preventDefault() const formData = constructor("Login", email, password) fetch("http://localhost:8080/login", { method: "post", headers: { 'Content-Type' : 'application/json' }, body : JSON.stringify(formData) }) .then(response => response.json()) .then(data => { if(data == "criado") go("/home") else alert("senha ou email errada!") }).catch((error)=> alert("Algo inesperado ocorreu!")) .finally(() => console.log("a requisição terminou!")) } return <form onSubmit={HandleSubmit}> <InputIcon classCon={"content-input-icon"} classN={"input-icon"} type={"email"} img={icoEmail} name={"email"} placeHolder={"Email"} id={"1"} value={email} setValue={setEmail} /> <InputIcon classCon={"content-input-icon"} classN={"input-icon"} type={"password"} img={icoPassword} name={"password"} placeHolder={"Senha"} id={"2"} value={password} setValue={setPassword} /> <ButtonSubmit text={"Entrar"} /> </form> }
import {MatchData} from "./MatchData" import { WinsAnalysis } from './analyzers/WinsAnalysis' import { HtmlReport } from './reportTargets/HtmlReports' export interface Analyzer { run(matches: MatchData[]):string } export interface OutputTarget { print(report: string): void; } export class Summary { constructor(public analyzer: Analyzer, public outputTarget: OutputTarget) {} static winAnalysisWithReportSummary(team: string): Summary { return new Summary( new WinsAnalysis(team), new HtmlReport() ) } buildAndPrintReport(matches: MatchData[]): void { const output = this.analyzer.run(matches) this.outputTarget.print(output) } }
import { useState } from 'react'; import { ButtonCrement } from 'components/ButtonCrement/ButtonCrement'; import { addWorckDay } from 'service/api'; import { FormContainer, Input, ButtonDrupContainer, Buttons, } from './AddLessons.styled'; export const AddLessons = ({ pushNewWorckEl }) => { const [individualLesson, setIndividualLesson] = useState(0); const [integralLesson, setIntegralLesson] = useState(0); const [dateWorck, setDateWorck] = useState(0); const chengValue = (operation, { type }) => { if (type === 'individual') { operation === 'incr' ? setIndividualLesson(individualLesson > 0 ? individualLesson - 1 : 0) : setIndividualLesson(individualLesson + 1); } else if (type === 'integral') { operation === 'incr' ? setIntegralLesson(integralLesson > 0 ? integralLesson - 1 : 0) : setIntegralLesson(integralLesson + 1); } else { console.log('Dont have type'); } }; const handleSubmit = () => { if (!dateWorck) { alert('Вибери дату!'); return; } addWorckDay({ date: dateWorck, individual: individualLesson, integral: integralLesson, }).then(r => pushNewWorckEl(r)); reset(); }; const reset = () => { setIntegralLesson(0); setIndividualLesson(0); }; return ( <FormContainer> <Input type="date" label="Date mobile" required onChange={e => setDateWorck(e.currentTarget.value)} /> <ButtonCrement title={'Індивідуальне заняття'} value={individualLesson} type={'individual'} setValue={chengValue} /> <ButtonCrement title={'Інтегративна сесія'} value={integralLesson} type={'integral'} setValue={chengValue} /> <ButtonDrupContainer> <Buttons type="button" onClick={() => handleSubmit()}> Додати </Buttons> <Buttons type="button" onClick={() => reset()}> Скинути </Buttons> </ButtonDrupContainer> </FormContainer> ); };
<?php /** @var yii\web\View $this */ use yii\helpers\Url; use app\assets\fullcalendar\FullCalendarAsset; use app\modules\meeting\assets\MeetingAsset; use kartik\date\DatePicker; FullCalendarAsset::register($this); MeetingAsset::register($this); $this->title = 'По месту проведения'; $this->params['breadcrumbs'][] = $this->title; $url = Url::to(['/meeting/calendar/data']); $urlResources = Url::to(['/meeting/location/data']); ?> <p class="display-4 border-bottom"> <?= $this->title ?> </p> <div class=""> <div class="card card-body" style="width:285px;"> <div> <b>Дата</b> <?= DatePicker::widget([ 'name' => 'date-picker', 'id' => 'date-picker', 'pluginOptions' => [ 'autoclose' => true, 'todayHighlight' => true, ], 'options' => [ 'autocomplete' => 'off', ], ]) ?> </div> </div> </div> <div id="loading"> <i class="fas fa-circle-notch fa-spin"></i> Загрузка событий... </div> <div id="script-warning" class="alert alert-danger mt-2"></div> <div id="calendar"></div> <?php $this->registerJs(<<<JS const calendarEl = document.getElementById('calendar') function convertUrl(date1, date2) { date1 = date1.toLocaleDateString(); date2 = date2.toLocaleDateString(); let url = '$url'; if (url.indexOf('?') >= 0) { url += '&'; } else { url += '?'; } url += 'start=' + date1 + '&end=' + date2; return url; } function asDate(str) { const arr = str.split('.') return new Date(arr[2], arr[1]-1, arr[0]) } function addDay(date) { const result = new Date(date) result.setDate(result.getDate() + 1) return result } $('#date-picker').on('change', function() { const start = asDate($(this).val()); const end = addDay(start); const url = convertUrl(start, end); calendar.gotoDate(start); }) const modalCalendarLocation = new ModalViewer() const calendar = new FullCalendar.Calendar(calendarEl, { locale: 'ru', initialView: 'resourceTimelineDay', eventClick: function(info) { const item = info.event if (item.url) { modalCalendarLocation.showModal(item.url) info.jsEvent.preventDefault() } }, // событие добавления каждого события eventDidMount: function(event) { const el = $(event.el) el.popover({ container: 'body', trigger: 'hover', placement: 'auto', title: event.event.extendedProps.fullTitle, content: event.event.extendedProps.description, html: true }) el.find('.fc-event-title').html(event.event.title) el.find('.fc-list-event-title').find('a').html(event.event.title) }, events: { url: '$url', success: function(content, xhr) { $('#date-picker').val(calendar.getDate().toLocaleDateString()) }, failure: function(e) { const cont = $('#script-warning') cont.html( 'Error: ' + e.message + '<br />' + 'Status: ' + e.xhr.status + '<br />' + 'Status text: ' + e.xhr.statusText) cont.show() console.log(e) }, }, headerToolbar: { left: 'prev,next today', center: 'title', right: 'resourceTimelineDay,resourceTimelineWeek' }, editable: false, navLinks: true, // can click day/week names to navigate views dayMaxEvents: true, // allow "more" link when too many events selectable: true, businessHours: { daysOfWeek: [1,2,3,4,5,6,7], startTime: '09:00', endTime: '18:00', }, nowIndicator: true, slotMinTime: '08:00:00', slotMaxTime: '20:00:00', resourceAreaColumns: [ { field: 'title', headerContent: 'Кабинеты' } ], resources: '$urlResources', loading: function(bool) { $('#loading').toggle(bool) } }); calendar.render() $('.fc-license-message').hide() JS ); ?>
// 约束class的类型 { class Person { protected name: string; public age: number; protected info(): string { return `${this.name}的年龄是${this.age}`; } } class User extends Person { // public 表示属性公开 protected 表示属性保护 外部无法访问 constructor(n: string, a: number) { super(); this.name = n; this.age = a; } public show() { return this.info(); } } const bh = new User('steven', 2); console.log(bh.age); }
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.xray import io.cloudshiftdev.awscdk.CfnResource import io.cloudshiftdev.awscdk.IInspectable import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.TreeInspector import io.cloudshiftdev.awscdk.common.CdkDslMarker import kotlin.Any import kotlin.Boolean import kotlin.String import kotlin.Unit import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct import software.constructs.Construct as SoftwareConstructsConstruct /** * Use `AWS::XRay::ResourcePolicy` to specify an X-Ray resource-based policy, which grants one or * more AWS services and accounts permissions to access X-Ray . * * Each resource-based policy is associated with a specific AWS account. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.xray.*; * CfnResourcePolicy cfnResourcePolicy = CfnResourcePolicy.Builder.create(this, * "MyCfnResourcePolicy") * .policyDocument("policyDocument") * .policyName("policyName") * // the properties below are optional * .bypassPolicyLockoutCheck(false) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-xray-resourcepolicy.html) */ public open class CfnResourcePolicy( cdkObject: software.amazon.awscdk.services.xray.CfnResourcePolicy, ) : CfnResource(cdkObject), IInspectable { public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnResourcePolicyProps, ) : this(software.amazon.awscdk.services.xray.CfnResourcePolicy(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap), id, props.let(CfnResourcePolicyProps.Companion::unwrap)) ) public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnResourcePolicyProps.Builder.() -> Unit, ) : this(scope, id, CfnResourcePolicyProps(props) ) /** * A flag to indicate whether to bypass the resource-based policy lockout safety check. */ public open fun bypassPolicyLockoutCheck(): Any? = unwrap(this).getBypassPolicyLockoutCheck() /** * A flag to indicate whether to bypass the resource-based policy lockout safety check. */ public open fun bypassPolicyLockoutCheck(`value`: Boolean) { unwrap(this).setBypassPolicyLockoutCheck(`value`) } /** * A flag to indicate whether to bypass the resource-based policy lockout safety check. */ public open fun bypassPolicyLockoutCheck(`value`: IResolvable) { unwrap(this).setBypassPolicyLockoutCheck(`value`.let(IResolvable.Companion::unwrap)) } /** * Examines the CloudFormation resource and discloses attributes. * * @param inspector tree inspector to collect and process attributes. */ public override fun inspect(inspector: TreeInspector) { unwrap(this).inspect(inspector.let(TreeInspector.Companion::unwrap)) } /** * The resource-based policy document, which can be up to 5kb in size. */ public open fun policyDocument(): String = unwrap(this).getPolicyDocument() /** * The resource-based policy document, which can be up to 5kb in size. */ public open fun policyDocument(`value`: String) { unwrap(this).setPolicyDocument(`value`) } /** * The name of the resource-based policy. */ public open fun policyName(): String = unwrap(this).getPolicyName() /** * The name of the resource-based policy. */ public open fun policyName(`value`: String) { unwrap(this).setPolicyName(`value`) } /** * A fluent builder for [io.cloudshiftdev.awscdk.services.xray.CfnResourcePolicy]. */ @CdkDslMarker public interface Builder { /** * A flag to indicate whether to bypass the resource-based policy lockout safety check. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-xray-resourcepolicy.html#cfn-xray-resourcepolicy-bypasspolicylockoutcheck) * @param bypassPolicyLockoutCheck A flag to indicate whether to bypass the resource-based * policy lockout safety check. */ public fun bypassPolicyLockoutCheck(bypassPolicyLockoutCheck: Boolean) /** * A flag to indicate whether to bypass the resource-based policy lockout safety check. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-xray-resourcepolicy.html#cfn-xray-resourcepolicy-bypasspolicylockoutcheck) * @param bypassPolicyLockoutCheck A flag to indicate whether to bypass the resource-based * policy lockout safety check. */ public fun bypassPolicyLockoutCheck(bypassPolicyLockoutCheck: IResolvable) /** * The resource-based policy document, which can be up to 5kb in size. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-xray-resourcepolicy.html#cfn-xray-resourcepolicy-policydocument) * @param policyDocument The resource-based policy document, which can be up to 5kb in size. */ public fun policyDocument(policyDocument: String) /** * The name of the resource-based policy. * * Must be unique within a specific AWS account. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-xray-resourcepolicy.html#cfn-xray-resourcepolicy-policyname) * @param policyName The name of the resource-based policy. */ public fun policyName(policyName: String) } private class BuilderImpl( scope: SoftwareConstructsConstruct, id: String, ) : Builder { private val cdkBuilder: software.amazon.awscdk.services.xray.CfnResourcePolicy.Builder = software.amazon.awscdk.services.xray.CfnResourcePolicy.Builder.create(scope, id) /** * A flag to indicate whether to bypass the resource-based policy lockout safety check. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-xray-resourcepolicy.html#cfn-xray-resourcepolicy-bypasspolicylockoutcheck) * @param bypassPolicyLockoutCheck A flag to indicate whether to bypass the resource-based * policy lockout safety check. */ override fun bypassPolicyLockoutCheck(bypassPolicyLockoutCheck: Boolean) { cdkBuilder.bypassPolicyLockoutCheck(bypassPolicyLockoutCheck) } /** * A flag to indicate whether to bypass the resource-based policy lockout safety check. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-xray-resourcepolicy.html#cfn-xray-resourcepolicy-bypasspolicylockoutcheck) * @param bypassPolicyLockoutCheck A flag to indicate whether to bypass the resource-based * policy lockout safety check. */ override fun bypassPolicyLockoutCheck(bypassPolicyLockoutCheck: IResolvable) { cdkBuilder.bypassPolicyLockoutCheck(bypassPolicyLockoutCheck.let(IResolvable.Companion::unwrap)) } /** * The resource-based policy document, which can be up to 5kb in size. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-xray-resourcepolicy.html#cfn-xray-resourcepolicy-policydocument) * @param policyDocument The resource-based policy document, which can be up to 5kb in size. */ override fun policyDocument(policyDocument: String) { cdkBuilder.policyDocument(policyDocument) } /** * The name of the resource-based policy. * * Must be unique within a specific AWS account. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-xray-resourcepolicy.html#cfn-xray-resourcepolicy-policyname) * @param policyName The name of the resource-based policy. */ override fun policyName(policyName: String) { cdkBuilder.policyName(policyName) } public fun build(): software.amazon.awscdk.services.xray.CfnResourcePolicy = cdkBuilder.build() } public companion object { public val CFN_RESOURCE_TYPE_NAME: String = software.amazon.awscdk.services.xray.CfnResourcePolicy.CFN_RESOURCE_TYPE_NAME public operator fun invoke( scope: CloudshiftdevConstructsConstruct, id: String, block: Builder.() -> Unit = {}, ): CfnResourcePolicy { val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id) return CfnResourcePolicy(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.xray.CfnResourcePolicy): CfnResourcePolicy = CfnResourcePolicy(cdkObject) internal fun unwrap(wrapped: CfnResourcePolicy): software.amazon.awscdk.services.xray.CfnResourcePolicy = wrapped.cdkObject as software.amazon.awscdk.services.xray.CfnResourcePolicy } }
/* ! tailwindcss v3.3.3 | MIT License | https://tailwindcss.com */ /* 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) 2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) */ *, ::before, ::after { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ border-color: #e5e7eb; /* 2 */ } ::before, ::after { --tw-content: ''; } /* 1. Use a consistent sensible line-height in all browsers. 2. Prevent adjustments of font size after orientation changes in iOS. 3. Use a more readable tab size. 4. Use the user's configured `sans` font-family by default. 5. Use the user's configured `sans` font-feature-settings by default. 6. Use the user's configured `sans` font-variation-settings by default. */ html { line-height: 1.5; -webkit-text-size-adjust: 100%; tab-size: 4; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; -webkit-font-feature-settings: normal; font-feature-settings: normal; font-variation-settings: normal; } body { margin: 0; line-height: inherit; } hr { height: 0; color: inherit; border-top-width: 1px; } abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } button, input, optgroup, select, textarea { font-family: inherit; -webkit-font-feature-settings: inherit; font-feature-settings: inherit; font-variation-settings: inherit; font-size: 100%; font-weight: inherit; line-height: inherit; color: inherit; margin: 0; padding: 0; } button, select { text-transform: none; } button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; background-color: transparent; background-image: none; } :-moz-focusring { outline: auto; } :-moz-ui-invalid { box-shadow: none; } progress { vertical-align: baseline; } ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } [type='search'] { -webkit-appearance: textfield; outline-offset: -2px; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-file-upload-button { -webkit-appearance: button; font: inherit; } summary { display: list-item; } blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre { margin: 0; } fieldset { margin: 0; padding: 0; } legend { padding: 0; } ol, ul, menu { list-style: none; margin: 0; padding: 0; } dialog { padding: 0; } textarea { resize: vertical; } input::-webkit-input-placeholder, textarea::-webkit-input-placeholder { opacity: 1; color: #9ca3af; } input::placeholder, textarea::placeholder { opacity: 1; color: #9ca3af; } button, [role="button"] { cursor: pointer; } :disabled { cursor: default; } img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } img, video { max-width: 100%; height: auto; } [hidden] { display: none; } *, ::before, ::after { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } ::-webkit-backdrop { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } ::backdrop { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } .absolute { position: absolute; } .relative { position: relative; } .right-0 { right: 0px; } .top-0 { top: 0px; } .-top-full { top: -100%; } .z-50 { z-index: 50; } .ml-auto { margin-left: auto; } .flex { display: flex; } .hidden { display: none; } .h-screen { height: 100vh; } .h-2 { height: 0.5rem; } .h-1 { height: 0.25rem; } .h-full { height: 100%; } .w-screen { width: 100vw; } .w-6 { width: 1.5rem; } .w-full { width: 100%; } .w-5 { width: 1.25rem; } .w-fit { width: -webkit-fit-content; width: -moz-fit-content; width: fit-content; } .-rotate-45 { --tw-rotate: -45deg; -webkit-transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .rotate-45 { --tw-rotate: 45deg; -webkit-transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .rotate-\[135\] { --tw-rotate: 135; -webkit-transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .rotate-\[135deg\] { --tw-rotate: 135deg; -webkit-transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .flex-col { flex-direction: column; } .items-center { align-items: center; } .justify-end { justify-content: flex-end; } .justify-center { justify-content: center; } .justify-between { justify-content: space-between; } .space-y-1 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(0.25rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(0.25rem * var(--tw-space-y-reverse)); } .space-y-3 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(0.75rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(0.75rem * var(--tw-space-y-reverse)); } .space-x-5 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(1.25rem * var(--tw-space-x-reverse)); margin-left: calc(1.25rem * calc(1 - var(--tw-space-x-reverse))); } .overflow-hidden { overflow: hidden; } .bg-\[\#181818\] { --tw-bg-opacity: 1; background-color: rgb(24 24 24 / var(--tw-bg-opacity)); } .bg-\[\#252525\] { --tw-bg-opacity: 1; background-color: rgb(37 37 37 / var(--tw-bg-opacity)); } .bg-white { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } .bg-purple-950 { --tw-bg-opacity: 1; background-color: rgb(59 7 100 / var(--tw-bg-opacity)); } .px-10 { padding-left: 2.5rem; padding-right: 2.5rem; } .py-5 { padding-top: 1.25rem; padding-bottom: 1.25rem; } .px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } .px-7 { padding-left: 1.75rem; padding-right: 1.75rem; } .py-3 { padding-top: 0.75rem; padding-bottom: 0.75rem; } .py-4 { padding-top: 1rem; padding-bottom: 1rem; } .py-10 { padding-top: 2.5rem; padding-bottom: 2.5rem; } .px-5 { padding-left: 1.25rem; padding-right: 1.25rem; } .py-8 { padding-top: 2rem; padding-bottom: 2rem; } .px-20 { padding-left: 5rem; padding-right: 5rem; } .px-64 { padding-left: 16rem; padding-right: 16rem; } .py-7 { padding-top: 1.75rem; padding-bottom: 1.75rem; } .py-6 { padding-top: 1.5rem; padding-bottom: 1.5rem; } .pb-10 { padding-bottom: 2.5rem; } .text-lg { font-size: 1.125rem; line-height: 1.75rem; } .font-semibold { font-weight: 600; } .text-neutral-300 { --tw-text-opacity: 1; color: rgb(212 212 212 / var(--tw-text-opacity)); } .text-neutral-200 { --tw-text-opacity: 1; color: rgb(229 229 229 / var(--tw-text-opacity)); } .duration-150 { transition-duration: 150ms; } .hover\:bg-\[\#202020\]:hover { --tw-bg-opacity: 1; background-color: rgb(32 32 32 / var(--tw-bg-opacity)); } .group:focus .group-focus\:top-0 { top: 0px; } @media (min-width: 640px) { .sm\:hidden { display: none; } } @media (min-width: 768px) { .md\:flex { display: flex; } .md\:hidden { display: none; } } @media (min-width: 1024px) { .lg\:px-64 { padding-left: 16rem; padding-right: 16rem; } } .mySticky { position: fixed; top: 0; width: 100%; z-index: 1000; } .my-masonry-grid { display: -webkit-box; display: -ms-flexbox; display: flex; width: auto; } .my-masonry-grid_column { background-clip: padding-box; } .my-masonry-grid_column > div { margin-bottom: 30px; }
import 'package:contact_bud/Pages/addNewUser.dart'; import 'package:motion_toast/motion_toast.dart'; import 'DB/db_connec.dart'; import 'Pages/EditUser.dart'; import 'Pages/ViewContact.dart'; import 'package:contact_bud/Services/services.dart'; import 'package:flutter/material.dart'; import 'models/AddUser.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Contact App', //remove debug lable debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.deepOrange, // scaffoldBackgroundColor: Colors.black87, ), home: const MyHomePage(), ); } } // creating a Stateful widget class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { // creating a List variable in user model late List<User> _contactList = <User>[]; // accessing user service final _userService = UserService(); // get user detials getAllUserDetails() async { var users = await _userService.readAllUsers(); _contactList = <User>[]; // Inserting the details into the model users.forEach((user) { setState(() { var userModel = User(); userModel.id = user['id']; userModel.fname = user['fname']; userModel.lname = user['lname']; userModel.contact = user['contact']; _contactList.add(userModel); }); }); } // init state used ot load the function when the foam is gets loaded @override void initState() { getAllUserDetails(); super.initState(); } _showSuccessSnackBar(String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(message), ), ); } _deleteFormDialog(BuildContext context, userId) { return showDialog( context: context, builder: (param) { return AlertDialog( title: const Text( 'Delete Contact?', style: TextStyle(color: Colors.teal, fontSize: 20), ), actions: [ TextButton( style: TextButton.styleFrom( foregroundColor: Colors.white, // foreground backgroundColor: Colors.red), onPressed: () async { var result = await _userService.deleteUser(userId); if (result != null) { Navigator.pop(context); getAllUserDetails(); _showSuccessSnackBar('Contact Deleted'); } }, child: const Text('Delete')), TextButton( style: TextButton.styleFrom( foregroundColor: Colors.white, // foreground backgroundColor: Colors.teal), onPressed: () { Navigator.pop(context); }, child: const Text('Cancel')) ], ); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Contact Buddy"), ), body: ListView.builder( itemCount: _contactList.length, itemBuilder: (context, index) { return Card( margin: EdgeInsets.fromLTRB(10.0, 10.0, 10.0,0.0), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.10)), color: Color.fromARGB(255, 3, 21, 75), child: ListTile( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ViewContact( user: _contactList[index], ))); }, leading: const Icon(Icons.person, color: Colors.white, ), title: Row( children:<Widget>[ Text(_contactList[index].fname ?? '',textAlign: TextAlign.left,style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w500),), // Spacer(), // const SizedBox(width: 5,), // Text(_contactList[index].lname ?? '',style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w500, ),) ],), subtitle: Text(_contactList[index].contact ?? '', style: TextStyle(color: Colors.white)), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ IconButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => EditUser( user: _contactList[index], ))).then((data) { if (data != null) { getAllUserDetails(); _showSuccessSnackBar('Contact Updated'); } }); ; }, icon: const Icon( Icons.edit, color: Colors.green, )), IconButton( onPressed: () { _deleteFormDialog(context, _contactList[index].id); }, icon: const Icon( Icons.delete, color: Colors.red, )) ], ), ), ); }), // creating a floating action button floatingActionButton: FloatingActionButton.extended( backgroundColor: const Color(0xff03dac6), foregroundColor: Colors.black, onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) => const AddNewUser())) .then((data) { if (data != null) { getAllUserDetails(); _showSuccessSnackBar('Contact created'); } }); }, icon: const Icon(Icons.add), label: Text('Create Contact'), ), ); } }
package get import ( "fmt" "github.com/MakeNowJust/heredoc" "github.com/spf13/cobra" "github.com/algolia/cli/api/crawler" "github.com/algolia/cli/pkg/cmdutil" "github.com/algolia/cli/pkg/config" "github.com/algolia/cli/pkg/iostreams" ) type GetOptions struct { Config config.IConfig IO *iostreams.IOStreams CrawlerClient func() (*crawler.Client, error) ID string ConfigOnly bool PrintFlags *cmdutil.PrintFlags } // NewGetCmd creates and returns a get command for Crawlers. func NewGetCmd(f *cmdutil.Factory, runF func(*GetOptions) error) *cobra.Command { opts := &GetOptions{ IO: f.IOStreams, Config: f.Config, CrawlerClient: f.CrawlerClient, PrintFlags: cmdutil.NewPrintFlags().WithDefaultOutput("json"), } cmd := &cobra.Command{ Use: "get <crawler_id>", Args: cobra.ExactArgs(1), ValidArgsFunction: cmdutil.CrawlerIDs(opts.CrawlerClient), Short: "Get a crawler", Long: heredoc.Doc(` Get the specified crawler. `), Example: heredoc.Doc(` # Get the crawler with the ID "my-crawler" $ algolia crawler get my-crawler # Get the crawler with the ID "my-crawler" and display only its configuration $ algolia crawler get my-crawler --config-only `), RunE: func(cmd *cobra.Command, args []string) error { opts.ID = args[0] if runF != nil { return runF(opts) } return runGetCmd(opts) }, } cmd.Flags().BoolVarP(&opts.ConfigOnly, "config-only", "c", false, "Display only the crawler configuration") return cmd } func runGetCmd(opts *GetOptions) error { client, err := opts.CrawlerClient() if err != nil { return err } opts.IO.StartProgressIndicatorWithLabel(fmt.Sprintf("Fetching crawler %s", opts.ID)) crawler, err := client.Get(opts.ID, true) opts.IO.StopProgressIndicator() if err != nil { return err } var toPrint interface{} if opts.ConfigOnly { toPrint = crawler.Config } else { toPrint = crawler } p, err := opts.PrintFlags.ToPrinter() if err != nil { return err } if err := p.Print(opts.IO, toPrint); err != nil { return err } return nil }
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_application_1/resources/components/setuptextfields.dart'; import 'package:flutter_application_1/serivces/firestore/userdetails.dart'; import 'package:flutter_application_1/serivces/firestore/userpost.dart'; // import 'package:flutter_application_1/resources/components/boxes.dart'; class PostView extends StatefulWidget { const PostView({super.key}); @override State<PostView> createState() => _PostViewState(); } class _PostViewState extends State<PostView> { final posts = FirebaseFirestore.instance.collection('users').snapshots(); UserPosts userPosts = UserPosts(); @override Widget build(BuildContext context) { UserDetails userDetails = UserDetails(); final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Container( width: width * 1, height: height * 1, color: Colors.white, child: SingleChildScrollView( child: Column( // mainAxisAlignment: MainAxisAlignment.center, children: [ FutureBuilder( future: userDetails.getUserDetails(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LinearProgressIndicator( minHeight: 5, ); } if (snapshot.hasError) { return const CircularProgressIndicator(); } return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.all(8.0), child: CircleAvatar( backgroundColor: const Color.fromARGB(255, 236, 184, 245), radius: 45, child: InkWell( onTap: () {}, child: CircleAvatar( backgroundImage: snapshot.data['profile-pic'] != '' ? Image.network(snapshot .data['profile-pic'] .toString()) .image : null, backgroundColor: const Color.fromARGB( 255, 230, 227, 227), radius: 40, ), )), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "${snapshot.data['first-name']} ${snapshot.data['last-name']}", style: const TextStyle( fontWeight: FontWeight.bold), ), const SizedBox( height: 10, ), Text(snapshot.data['email'].toString()), ], ), ], ), Padding( padding: const EdgeInsets.all(8.0), child: Text(" ${snapshot.data['about-me']}"), ) ], ); }), Padding( padding: const EdgeInsets.all(8.0), child: Divider( height: height * 0.02, thickness: 2, ), ), StreamBuilder( stream: posts, builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LinearProgressIndicator( minHeight: 5, ); } if (snapshot.hasError) { return const CircularProgressIndicator(); } return Expanded( child: ListView.builder( itemCount: snapshot.data!.docs.length, itemBuilder: (context, index) { return Card(); })); }), RoundBtn( height: height / 10, width: width / 3, ontap: () { userPosts.postUersPostToFirestore( 'profile', 'postpic', 'postdesc'); }, text: 'PostToUser'), const SizedBox( height: 30, ), ], ), ), ); } }
// Numeric Enums /** * Create a defiend set of named integer values that can be used as a type */ var Day; (function (Day) { Day[Day["Sunday"] = 0] = "Sunday"; Day[Day["Monday"] = 1] = "Monday"; Day[Day["Tuesday"] = 2] = "Tuesday"; Day[Day["Wednesday"] = 3] = "Wednesday"; Day[Day["Thursday"] = 4] = "Thursday"; Day[Day["Friday"] = 5] = "Friday"; Day[Day["Saturday"] = 6] = "Saturday"; // 6 })(Day || (Day = {})); // It by default starts from the number 0 and increments by 1 for additional entry var currentDay = Day.Monday; if (currentDay === Day.Monday) { console.log("It is monday!"); } else { console.log("It is not monday"); } // changing the starting value var Status; (function (Status) { Status[Status["InProgress"] = 1] = "InProgress"; Status[Status["Completed"] = 2] = "Completed"; Status[Status["Cancelled"] = 300] = "Cancelled"; })(Status || (Status = {})); console.log(Status.Cancelled);
import uuid from typing import Optional from pydantic import BaseModel class SpeciesResult(BaseModel): id: int species_name: str latin_name: Optional[str] class SiteResult(BaseModel): id: uuid.UUID top_tier_site: str site_parent_name: str site_name: str geo_water_body: str class SpeciesBySite(BaseModel): species_name: str newest_year_recorded: int oldest_year_recorded: int total_count: Optional[int] class SiteBySpecies(BaseModel): id: str top_tier_site: str site_parent_name: str site_name: str class SurveyResult(BaseModel): id: uuid.UUID survey_id: int event_date_year: int survey_ranked_easting: int survey_ranked_northing: int species_id: int area_id: uuid.UUID fish_count: str
library(shiny) library(tidyverse) library(lubridate) library(tidyr) library(shinythemes) library(glue) bike_unzip <- unzip('week10_biketown.zip') bike <- read_csv(bike_unzip) bike[c('code', 'bike_name')] <- str_split_fixed(bike$BikeName, ' ', 2) bike[c('BikeName2', 'info')] <- str_split_fixed(bike$bike_name, '-', 2) bike[c('BikeName3', 'info')] <- str_split_fixed(bike$BikeName2, '\\(', 2) bike$bikeName <- trimws(bike$BikeName3, which = c("both")) bike <- bike %>% select(-BikeName, -bike_name, -BikeName2, -BikeName3) bike <- bike %>% mutate(Duration = as.numeric(hms(bike$Duration))) %>% mutate(Duration = Duration/3600) %>% mutate(speed = Distance_Miles/Duration) %>% mutate(speed = round(speed, digits = 3)) bike <- bike %>% drop_na(StartLatitude, StartLongitude, StartHub) %>% mutate(StartLatitude = round(StartLatitude, digits = 2)) %>% mutate(StartLongitude = round(StartLongitude, digits = 2)) bike$StartTime <- hms(bike$StartTime) breaks <- hour(hm("00:00", "6:00", "12:00", "18:00", "23:59")) labels <- c("Night", "Morning", "Afternoon", "Evening") bike$Time_of_day <- cut(x=hour(bike$StartTime), breaks = breaks, labels = labels, include.lowest=TRUE) ui <- fluidPage(theme = shinytheme("journal"), titlePanel(div(column(width = 6, h2("Biketown Bikeshare Analysis")), column(width = 6, tags$img(src = "https://i.pinimg.com/originals/24/ae/8d/24ae8def288851503cf68340df174963.gif", height="50%", width="50%", align="centre"))), ), h3("This app gives you insight into speeds of various bikes, riders in your area and general time trends. Visit the different tabs for more information!"), tags$style(HTML(" .tabbable > .nav > li > a {background-color: aqua; color:black} ")), tabsetPanel( tabPanel(h3("Speed and Area"), h3("1. Compare the average speed of the bikes."), fluidRow( sidebarLayout( sidebarPanel(h2("Bike Speed Comparison"), selectizeInput("bikes_compare1", "Select bike 1", choices = unique(bike$bikeName)), selectizeInput("bikes_compare2", "Select bike 2", choices = unique(bike$bikeName)) ), mainPanel( plotOutput("compare_bike") ) ) ), h3("2. Find the bikers' general attributes 10km around your Area."), fluidRow( sidebarLayout( sidebarPanel(h3("Find your latitude and longitude if you are unsure."), selectizeInput("find_latitude", "Choose your Area", choices = unique(bike$StartHub)), numericInput("lat", "Enter your latitude", value = 45.52), numericInput("long", "Enter your longitude", value = -122.65), actionButton("submit", "Submit") ), mainPanel( textOutput("latitude"), br(), tableOutput("paymentTable"), br(), tableOutput("summary") ) ) )), tabPanel(h3("Time"), h3("3. What time of day do most people ride? Take a guess!"), fluidRow( sidebarLayout( sidebarPanel( selectizeInput("time", "Guess the time", choices = unique(bike$Time_of_day)), actionButton("guess", "Guess") ), mainPanel( textOutput("answer"), uiOutput("Morning"), ) ) )), tabPanel(h3("About the app"), fluidRow( column(10, div(class = "about", uiOutput('about')) ) ), includeCSS("styles.css") ))) server <- function(input, output, session) { observe({ updateSelectInput(session, "bikes_compare2", choices = setdiff(unique(bike$bikeName), input$bikes_compare1)) }) output$compare_bike <- renderPlot({ bike %>% filter(bikeName == input$bikes_compare1 | bikeName == input$bikes_compare2) %>% ggplot(aes(bikeName, speed, fill = bikeName)) + geom_boxplot(show.legend = FALSE) + labs(title = "Average Speed in miles per hour") + ylab("Average Speed in miles/hour") + xlab("Bike Name") + theme_minimal() + theme(axis.text.x = element_text(color = "blue")) + theme(text = element_text(size = 20)) }) output$latitude <- renderText({ lat <- unique(bike$StartLatitude[bike$StartHub== input$find_latitude]) lat long <- unique(bike$StartLongitude[bike$StartHub== input$find_latitude]) long glue("Latitude is ", lat, " and longitude is ", long) }) output$paymentTable <- renderTable({ if(input$submit) { bike1 <- bike %>% filter(StartLatitude == input$lat & StartLongitude == input$long) %>% count(PaymentPlan, sort = TRUE) %>% drop_na() bike1 } }) output$summary <- renderTable({ if(input$submit) { bike2 <- bike %>% filter(StartLatitude == input$lat & StartLongitude == input$long) %>% summarise(average_speed_milesPerHour = mean(speed, na.rm = TRUE), average_duration_seconds = mean((Duration*3600), na.rm = TRUE)) bike2 } }) time_msg <- reactive({ if(input$guess){ case_when(input$time == "Morning" ~ "This is not the correct answer. ", input$time == "Afternoon" ~ "This is the correct answer. ", input$time == "Evening" ~ "Unfortunately, you are wrong. ", input$time == "Night" ~ "Uhoh!. " )} }) output$answer <- renderText({ bike2 <- bike %>% select(Time_of_day) %>% count(Time_of_day, sort = TRUE) %>% mutate(percentage = (n/sum(n))*100) %>% mutate(percentage = round(percentage, digits =2)) if(input$guess) { glue(time_msg(), bike2$percentage[1], "% people ride in the afternoon.") } }) output$Morning <- renderUI({ if(input$guess) { if(input$time == "Morning"){ tags$img(src = "https://hdclipartall.com/images/good-morning-animated-clip-art-good-morning-clip-art-free-2-image-3-morning-clipart-550_400.jpg", height="50%", width="50%", align="centre") } else if(input$time == "Afternoon") { tags$img(src = "https://www.seekpng.com/png/detail/457-4571607_happy-sun-free-download-clip-art-on-clipart.png", height="50%", width="50%", align="centre") } else if(input$time == "Evening") { tags$img(src = "https://img.freepik.com/premium-vector/sunset-sky-cartoon-summer-sunrise-with-pink-clouds-sunshine-evening-cloudy-heaven-panorama_461812-70.jpg?w=360", height="50%", width="50%", align="centre") } else if(input$time == "Night") { tags$img(src = "https://thumbs.dreamstime.com/b/cute-moon-character-sad-expression-cute-moon-character-sad-expression-your-commercial-project-others-182038820.jpg", height="50%", width="50%", align="centre") } } }) %>% bindEvent(input$guess) output$about <- renderUI({ knitr::knit("about.Rmd", quiet = TRUE) %>% markdown::markdownToHTML(fragment.only = TRUE) %>% HTML() }) } shinyApp(ui = ui, server = server)
# Copyright 2023 Nod Labs, Inc # # Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception from typing import Optional, cast from iree.compiler.ir import ( InsertionPoint, Operation, Type as IrType, ) from ..rewriter import * from iree.compiler.ir import Context class TransposedMMResult(OpMatchResult): def __init__( self, op: Operation, *, weight_global: Operation, param_name: str, m: Optional[int], n: Optional[int], k: Optional[int], element_type: IrType, ): super().__init__(op) self.weight_global = weight_global self.param_name = param_name self.m = m self.n = n self.k = k self.element_type = element_type def __repr__(self): return f"TransposedMM(weight={self.param_name}, m={self.m}, n={self.n}, k={self.k}, element_type={self.element_type})" class TransposedMMMatcher(NamedOpMatcher): def __init__(self, globals: GlobalsDict, builder: Builder): super().__init__("torch.aten.mm") self.globals = globals self.builder = builder def match(self, op: Operation): weight_transpose = Transpose2DMatcher()(op.operands[1]) if not weight_transpose: return None weight_load = GlobalLoadMatcher(self.globals)(weight_transpose.input) if not weight_load or not weight_load.resolved_global: return None m, n = self.builder.get_tensor_dims(op.operands[0].type) _, k = self.builder.get_tensor_dims(op.operands[1].type) return TransposedMMResult( op, weight_global=weight_load.resolved_global, param_name=weight_load.global_ref, m=m, n=n, k=k, element_type=self.builder.get_tensor_element_type( op.operands[0].type ), ) # TODO (ian): Make more generalizable using RenameParametersPass. Currently hardcoded for brevitas quantization GROUP_MATMUL_TEMPLATE = r""" module {{ util.global private @{param_name} {{noinline}} = #stream.parameter.named<"model"::"{param_name}"> : tensor<{k}x{n_div}xi8> util.global private @{param_name}.quant.scale {{noinline}} = #stream.parameter.named<"model"::"{param_name}_scale"> : tensor<{k}x{group0}x{element_type}> util.global private @{param_name}.quant.zero_point {{noinline}} = #stream.parameter.named<"model"::"{param_name}_zp"> : tensor<{k}x{group0}x{element_type}> func.func private @compute_mm_group_quant(%a : tensor<{m}x{n}x{element_type}>) -> tensor<{m}x{k}x{element_type}> {{ %c0 = arith.constant 0 : index %weight_raw = util.global.load @{param_name} : tensor<{k}x{n_div}xi8> %m = tensor.dim %a, %c0 : tensor<{m}x{n}x{element_type}> %k = tensor.dim %weight_raw, %c0 : tensor<{k}x{n_div}xi8> %scale = util.global.load @{param_name}.quant.scale : tensor<{k}x{group0}x{element_type}> %zp = util.global.load @{param_name}.quant.zero_point : tensor<{k}x{group0}x{element_type}> %weight = flow.tensor.bitcast %weight_raw : tensor<{k}x{n_div}xi8> -> tensor<{k}x{n}x{lowp_type}> %a_exp = tensor.expand_shape %a [[0], [1, 2]] : tensor<{m}x{n}x{element_type}> into tensor<{m}x{group0}x{group1}x{element_type}> %weight_exp = tensor.expand_shape %weight [[0], [1, 2]] : tensor<{k}x{n}x{lowp_type}> into tensor<{k}x{group0}x{group1}x{lowp_type}> %empty_0 = tensor.empty() : tensor<{k}x{group0}x{group1}x{element_type}> %weight_cast = linalg.generic {{ indexing_maps = [ affine_map<(d0, d1, d2) -> (d0, d1, d2)>, affine_map<(d0, d1, d2) -> (d0, d1)>, affine_map<(d0, d1, d2) -> (d0, d1)>, affine_map<(d0, d1, d2) -> (d0, d1, d2)>], iterator_types = ["parallel", "parallel", "parallel"] }} ins(%weight_exp, %scale, %zp : tensor<{k}x{group0}x{group1}x{lowp_type}>, tensor<{k}x{group0}x{element_type}>, tensor<{k}x{group0}x{element_type}>) outs(%empty_0 : tensor<{k}x{group0}x{group1}x{element_type}>) {{ ^bb0(%in: {lowp_type}, %in_1: {element_type}, %in_2: {element_type}, %out: {element_type}): %16 = arith.extui %in : {lowp_type} to i32 %17 = arith.uitofp %16 : i32 to {element_type} %18 = arith.subf %17, %in_2 : {element_type} %19 = arith.mulf %18, %in_1 : {element_type} linalg.yield %19 : {element_type} }} -> tensor<{k}x{group0}x{group1}x{element_type}> %cst = arith.constant 0.000000e+00 : {element_type} %empty_1_dyn = tensor.empty(%m, %k) : tensor<?x?x{element_type}> %empty_1 = tensor.cast %empty_1_dyn : tensor<?x?x{element_type}> to tensor<{m}x{k}x{element_type}> %zero_init = linalg.fill ins(%cst : {element_type}) outs(%empty_1 : tensor<{m}x{k}x{element_type}>) -> tensor<{m}x{k}x{element_type}> %result = linalg.generic {{ indexing_maps = [ affine_map<(d0, d1, d2, d3) -> (d0, d2, d3)>, affine_map<(d0, d1, d2, d3) -> (d1, d2, d3)>, affine_map<(d0, d1, d2, d3) -> (d0, d1)>], iterator_types = ["parallel", "parallel", "reduction", "reduction"] }} ins(%a_exp, %weight_cast : tensor<{m}x{group0}x{group1}x{element_type}>, tensor<{k}x{group0}x{group1}x{element_type}>) outs(%zero_init : tensor<{m}x{k}x{element_type}>) {{ ^bb0(%in: {element_type}, %in_1: {element_type}, %out: {element_type}): %16 = arith.mulf %in, %in_1 : {element_type} %17 = arith.addf %16, %out : {element_type} linalg.yield %17 : {element_type} }} -> tensor<{m}x{k}x{element_type}> return %result : tensor<{m}x{k}x{element_type}> }} }} """ class MMGroupQuantRewriterPass(Pass): def __init__(self, root_op: Operation, *, group_size: int = 128): super().__init__(root_op) self.group_size = group_size self.context = root_op.context def run(self): globals = self.globals mms = match_children( self.funcs, TransposedMMMatcher(globals, self.builder) ) for mr in mms: if mr.k is None or mr.n is None: continue if (mr.k % self.group_size) != 0: continue self.rewrite(mr) self.inline() self.cleanup() def rewrite(self, mr: TransposedMMResult): none_to_q = lambda x: "?" if x is None else x # TODO (ian): make generalizable and not specific for brevitas if "lm_head.weight" not in mr.param_name: inline_module_asm = GROUP_MATMUL_TEMPLATE.format( # TODO (ian): Fix skipping the "_params." portion of the name to match safetensor format with RenameParametersPass param_name=mr.param_name[8:], lowp_type="i4", m=none_to_q(mr.m), n=none_to_q(mr.n), k=none_to_q(mr.k), n_div=mr.n // 2, group0=mr.n // self.group_size, group1=self.group_size, element_type=mr.element_type, ) inline_module = Operation.parse( inline_module_asm, context=self.context ) actual_callee_name = self.merge_module( inline_module ).translate_symbol("compute_mm_group_quant") with InsertionPoint(mr.op), mr.op.location: results = self.builder.call_native( actual_callee_name, [mr.op.result.type], mr.op.operands[0] ) self.replace_op(mr.op, *results) if __name__ == "__main__": pass_main(MMGroupQuantRewriterPass)
"use client"; import React, { useEffect, useState } from "react"; import { Card } from "@/components"; import useMovies from "@/hooks/useMovies"; import { Button, FavoritePopUp } from "@/components"; import { useFaveContext } from "@/providers/favoritesProvider"; import { MovieProps } from "@/interfaces"; const Home = () => { const { movieData } = useMovies(); const { fave, setFave } = useFaveContext(); const [btnDisable, setBtndisable] = useState(false); const { loading } = useMovies(); const faveSetter = () => { setFave((prev: Array<string>) => [...prev, movieData]); }; useEffect(() => { const temp = fave.some( (data: MovieProps) => movieData?.imdbID == data.imdbID ); if (temp) { setBtndisable(temp); } else { setBtndisable(false); } }, [fave, movieData]); if (!loading) { return ( <> {movieData ? ( <div className="flex flex-col items-center mx-10"> <Card className="flex flex-col w-[90%] gap-2"> <div className="border border-black-500 flex flex-col items-center p-2"> <img src={movieData.Poster} alt="" className="w-[200px] h-[250px]" /> <p>{movieData.Title}</p> <p>{movieData.Genre}</p> <p>{movieData.Language}</p> </div> <div className="border border-black-500 p-10 flex flex-col items-center"> <p></p> <Button name={ btnDisable ? "Already Addded to favorites" : "Add to favorites" } className={`border border-black-500 p-2 rounded ${ btnDisable ? "bg-slate-300" : "" }`} disabled={btnDisable ? true : false} onClick={faveSetter} ></Button> </div> </Card> </div> ) : ( <div className="flex justify-center"> <p>Try Searching</p> </div> )} </> ); } else { return <p className="flex justify-center">Loading..........</p>; } }; export default Home;
package com.nhat.demoSpringbooRestApi.services.impl; import com.nhat.demoSpringbooRestApi.dtos.CategoryRequestDTO; import com.nhat.demoSpringbooRestApi.exceptions.ResourceNotFoundException; import com.nhat.demoSpringbooRestApi.models.Category; import com.nhat.demoSpringbooRestApi.repositories.CategoryRepo; import com.nhat.demoSpringbooRestApi.services.CategoryService; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CategoryServiceServiceImpl implements CategoryService { @Autowired private CategoryRepo categoryRepo; @Autowired ModelMapper modelMapper; @Override public List<Category> getAllCategories() { return categoryRepo.findAll(); } @Override public Category findCategoryById(int categoryId) { return categoryRepo.findById(categoryId) .orElseThrow(() -> new ResourceNotFoundException("Category not found with id: " + categoryId)); } @Override public List<Category> findCategoryByName(String name) { return categoryRepo.findByNameLike(name); } @Override public Category createCategory(CategoryRequestDTO categoryRequestDTO) { Category category = modelMapper.map(categoryRequestDTO, Category.class); return categoryRepo.save(category); } @Override public Category updateCategory(int categoryId, CategoryRequestDTO categoryRequestDTO) { Category existingCategory = findCategoryById(categoryId); existingCategory.setName(categoryRequestDTO.getName()); existingCategory.setCode(categoryRequestDTO.getCode()); return categoryRepo.save(existingCategory); } @Override public String deleteCategory(int categoryId) { Category existingCategory = findCategoryById(categoryId); categoryRepo.delete(existingCategory); return "Categoty has id =" + categoryId + ": is deleted"; } }
local hyperFurnace = table.deepcopy(data.raw["item"]["electric-furnace"]) hyperFurnace.name = "hyper-furnace" hyperFurnace.place_result = "hyper-furnace" hyperFurnace.icons = { { icon_size = 64, icon = "__FactorioEndgameProduction__/graphics/item_hyperFurnace_image.png" }, } local placeableHyperFurnace = table.deepcopy(data.raw["furnace"]["electric-furnace"]) placeableHyperFurnace.name = "hyper-furnace" placeableHyperFurnace.energy_usage = "640kW" placeableHyperFurnace.max_health = 700 placeableHyperFurnace.crafting_speed = 4.0 placeableHyperFurnace.module_specification["module_slots"] = 6 placeableHyperFurnace.animation = { layers = { { filename = "__FactorioEndgameProduction__/graphics/entity_hyperFurnace_image.png", priority = "high", width = 204, height = 199, frame_count = 1, shift = util.by_pixel(-1.5, 1.5), scale = 0.5, hr_version = { filename = "__FactorioEndgameProduction__/graphics/entity_hyperFurnace_image.png", priority = "high", width = 204, height = 199, frame_count = 1, shift = util.by_pixel(-1.25, 2), scale = 0.5 } }, { filename = "__base__/graphics/entity/electric-furnace/electric-furnace-shadow.png", priority = "high", width = 129, height = 100, frame_count = 1, shift = {0.421875, 0}, draw_as_shadow = true, hr_version = { filename = "__base__/graphics/entity/electric-furnace/hr-electric-furnace-shadow.png", priority = "high", width = 227, height = 171, frame_count = 1, draw_as_shadow = true, shift = util.by_pixel(11.25, 7.75), scale = 0.5 } } } } placeableHyperFurnace.working_visualisations = { animation = { { filename = "__base__/graphics/entity/electric-furnace/electric-furnace-heater.png", priority = "high", width = 25, height = 15, frame_count = 12, animation_speed = 0.5, shift = {0.015625, 0.890625}, tint = {r=0, g=0.5, b=1.0, a=1.0}, hr_version = { filename = "__base__/graphics/entity/electric-furnace/hr-electric-furnace-heater.png", priority = "high", width = 60, height = 56, frame_count = 12, animation_speed = 0.5, shift = util.by_pixel(1.75, 32.75), tint = {r=0, g=0.5, b=1.0, a=1.0}, scale = 0.5 } } } } local recipeHyperFurnace = table.deepcopy(data.raw["recipe"]["electric-furnace"]) recipeHyperFurnace.enabled = true recipeHyperFurnace.name = "hyper-furnace" recipeHyperFurnace.ingredients = { { type = "item", name = "steel-plate", amount = 100 }, { type = "item", name = "processing-unit", amount = 20 }, { type = "item", name = "advanced-circuit", amount = 20 }, { type = "item", name = "sulfuric-acid-barrel", amount = 5 } } recipeHyperFurnace.result = "hyper-furnace" local techHyperFurnace = table.deepcopy(data.raw["technology"]["automation-3"]) techHyperFurnace.name = "hyper-production" techHyperFurnace.icon = "__FactorioEndgameProduction__/graphics/item_hyperFurnace_image_x256.png" techHyperFurnace.effects = { { type = "unlock-recipe", recipe = "hyper-furnace" } } techHyperFurnace.prerequisites = {"automation-3","mining-productivity-3","productivity-module-3","speed-module-3"} techHyperFurnace.unit = { ingredients = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"production-science-pack", 1}, {"utility-science-pack", 1} }, time = 45, count = 1000 } data:extend{hyperFurnace, placeableHyperFurnace, recipeHyperFurnace, techHyperFurnace}
import 'package:flutter/material.dart'; import 'package:san_na_ko/screens/tabs/maintenance_tab.dart'; import 'package:san_na_ko/screens/tabs/profile_tab.dart'; import 'package:san_na_ko/screens/tabs/schedule_tab.dart'; import 'package:flutter/cupertino.dart'; class MainPage extends StatelessWidget { const MainPage({super.key}); @override Widget build(BuildContext context) { List<Widget> tabs = [ScheduleTab(), ProfileTab(), MaintentanceTab()]; return SafeArea( child: CupertinoPageScaffold( child: CupertinoTabScaffold( tabBar: CupertinoTabBar(items: [ BottomNavigationBarItem(icon: Icon(Icons.calendar_month)), BottomNavigationBarItem(icon: Icon(Icons.person)), BottomNavigationBarItem( icon: Icon(Icons.drive_file_rename_outline)), ]), tabBuilder: (BuildContext context, int index) => CupertinoTabView(builder: (context) { return tabs[index]; }), ), ), ); // return SafeArea( // child: CupertinoPageScaffold( // child: CustomScrollView( // slivers: [ // CupertinoSliverNavigationBar( // largeTitle: Text('Scheduler'), // trailing: Icon(Icons.settings), // ), // SliverFillRemaining( // child: CupertinoTabScaffold( // tabBar: CupertinoTabBar(items: [ // BottomNavigationBarItem(icon: Icon(Icons.calendar_month)), // BottomNavigationBarItem(icon: Icon(Icons.person)), // BottomNavigationBarItem( // icon: Icon(Icons.drive_file_rename_outline)), // ]), // tabBuilder: (BuildContext context, int index) => // CupertinoTabView(builder: (context) { // return tabs[index]; // }), // ), // ), // ], // ), // ), // ); } }
package model_test import ( "encoding/hex" "fmt" "testing" "github.com/landru29/adsb1090/internal/model" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSurfacePosition(t *testing.T) { t.Parallel() for idx, fixtureElt := range []struct { input string groundTrack float64 timeUTC bool oddFrame bool encodedLatitude uint32 encodedLongitude uint32 speed float64 }{ { input: "8C4841753AAB238733C8CD4020B1", groundTrack: 140.625, timeUTC: false, oddFrame: false, encodedLatitude: 0x1c399, encodedLongitude: 0x1c8cd, speed: 18, }, { input: "8C4841753A8A35323FAEBDAC702D", groundTrack: 98.4375, timeUTC: false, oddFrame: true, encodedLatitude: 0x991f, encodedLongitude: 0x1aebd, speed: 16, }, } { fixture := fixtureElt t.Run(fmt.Sprintf("%d: %s", idx, fixture.input), func(t *testing.T) { t.Parallel() dataByte, err := hex.DecodeString(fixture.input) require.NoError(t, err) require.NoError(t, model.ModeS(dataByte).CheckSum()) squitter, err := model.ModeS(dataByte).QualifiedMessage() require.NoError(t, err) require.Equal(t, "extended squitter", squitter.Name()) extendedSquitter, ok := squitter.(model.ExtendedSquitter) assert.True(t, ok) msg, err := extendedSquitter.Decode() require.NoError(t, err) assert.Equal(t, "surface position", msg.Name()) position, ok := msg.(model.SurfacePosition) assert.True(t, ok) assert.Equal(t, fixture.groundTrack, position.GroundTrack()) //nolint: testifylint assert.Equal(t, fixture.timeUTC, position.TimeUTC()) assert.Equal(t, fixture.oddFrame, position.OddFrame()) assert.Equal(t, fixture.encodedLatitude, position.EncodedLatitude()) assert.Equal(t, fixture.encodedLongitude, position.EncodedLongitude()) assert.Equal(t, fixture.speed, position.Speed()) //nolint: testifylint }) } }
--- import BaseHead from "../../components/BaseHead.astro"; import Header from "../../components/Header.astro"; import { SITE_TITLE, SITE_DESCRIPTION } from "../../consts"; import { getCollection } from "astro:content"; import FormattedDate from "../../components/FormattedDate.astro"; const posts = (await getCollection("blog")).sort( (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf() ); --- <!DOCTYPE html> <html lang="en"> <head> <BaseHead title={SITE_TITLE} description={SITE_DESCRIPTION} /> </head> <body> <div class="mx-auto relative"> <main class="mx-4 text-gray-900"> <div class="sm:px-8 mb-16"> <div class="mx-auto max-w-7xl lg:px-8"> <div class="relative px-4 lg:px-12"> <div class="mb-20"> <Header title={SITE_TITLE} /> </div> <div> <svg class="absolute inset-x-0 top-0 -z-10 h-[64rem] w-full stroke-gray-200 [mask-image:radial-gradient(32rem_32rem_at_center,white,transparent)]" aria-hidden="true" > <defs> <pattern id="1f932ae7-37de-4c0a-a8b0-a6e3b4d44b84" width="200" height="200" x="50%" y="-1" patternUnits="userSpaceOnUse" > <path d="M.5 200V.5H200" fill="none"></path> </pattern> </defs> <svg x="50%" y="-1" class="overflow-visible fill-gray-50"> <path d="M-200 0h201v201h-201Z M600 0h201v201h-201Z M-400 600h201v201h-201Z M200 800h201v201h-201Z" stroke-width="0"></path> </svg> <rect width="100%" height="100%" stroke-width="0" fill="url(#1f932ae7-37de-4c0a-a8b0-a6e3b4d44b84)"></rect> </svg> <h1 class="text-4xl font-bold tracking-tight sm:text-5xl"> <span class="ml-1 text-transparent bg-clip-text bg-gradient-to-br from-red-400 to-red-600" >From the Blog</span > </h1> <div class="mt-16 space-y-20 lg:mt-20 lg:space-y-20"> { posts.map((post) => ( <a href={`/blog/${post.slug}/`}> <span class="hidden">{post.data.description}</span> <article class="relative isolate flex flex-col gap-8 lg:flex-row"> <div class="relative aspect-[16/9] sm:aspect-[2/1] lg:aspect-square lg:w-64 lg:shrink-0"> <img src={post.data.bannerUrl} alt="" class="absolute inset-0 h-full w-full rounded-2xl bg-gray-50 object-cover" /> <div class="absolute inset-0 rounded-2xl ring-1 ring-inset ring-gray-900/10" /> </div> <div> <div class="flex items-center gap-x-4 text-xs"> <span class="text-gray-500"> <FormattedDate date={post.data.pubDate} /> </span> <a href={`/blog/${post.slug}/`} class="relative z-10 rounded-full bg-gray-50 px-3 py-1.5 font-medium text-gray-600 hover:bg-gray-100" > Marketing </a> </div> <div class="group relative max-w-xl"> <h3 class="mt-3 text-lg font-semibold leading-6 text-gray-900 group-hover:text-brand-red"> <a href={`/blog/${post.slug}/`}> {post.data.title} </a> </h3> <p class="mt-5 text-sm leading-6 text-gray-600"> {post.data.description} </p> </div> </div> </article> </a> )) } </div> </div> </div> </div> </div> </main> </div> </body> </html>
#ifndef _IResourceManager_H #define _IResourceManager_H #include <FBCore/FBCorePrerequisites.h> #include <FBCore/Interface/Memory/ISharedObject.h> #include <FBCore/Core/StringTypes.h> #include <FBCore/Core/UtilityTypes.h> namespace fb { /** Interface for a resource manager. */ class IResourceManager : public ISharedObject { public: /** Virtual destructor. */ ~IResourceManager() override = default; /** Creates a resource. @param name The name of the resource. @returns The resource instance. Can be null if the resource does not exist. */ virtual SmartPtr<IResource> create( const String &name ) = 0; /** Creates a resource. @param name The name of the resource. @returns The resource instance. Can be null if the resource does not exist. */ virtual SmartPtr<IResource> create( const String &uuid, const String &name ) = 0; /** Creates a resource or retrieves an existing a resource. @param uuid The uuid of the resource. @param path The path of the resource. @param type The type of the resource. @returns The resource instance. Can be null if the resource does not exist. */ virtual Pair<SmartPtr<IResource>, bool> createOrRetrieve( const String &uuid, const String &path, const String &type ) = 0; /** Creates a resource or retrieves an existing a resource. @param uuid The uuid of the resource. @param path The path of the resource. @param type The type of the resource. @returns The resource instance. Can be null if the resource does not exist. */ virtual Pair<SmartPtr<IResource>, bool> createOrRetrieve( const String &path ) = 0; /** Saves a resource to file. @param filePath The filePath of the resource. @param resource The resource instance. */ virtual void saveToFile( const String &filePath, SmartPtr<IResource> resource ) = 0; /** Loads a resource from a file. @param filePath The file path of the resource. @returns The resource instance. Can be null if the resource does not exist. */ virtual SmartPtr<IResource> loadFromFile( const String &filePath ) = 0; /** Loads a resource. @param name The name of the resource. @returns The resource instance. Can be null if the resource does not exist. */ virtual SmartPtr<IResource> load( const String &name ) = 0; /** Gets an existing resource. @param name The name of the resource. @returns The resource instance. Can be null if the resource does not exist. */ virtual SmartPtr<IResource> getByName( const String &name ) = 0; /** Gets an existing resource by passing the hash id. @param hash The name of the resource as a hash value. @returns The resource instance. Can be null if the resource does not exist. */ virtual SmartPtr<IResource> getById( const String &uuid ) = 0; /** Gets a pointer to the underlying object. @param ppObject A pointer to store the object. */ virtual void _getObject( void **ppObject ) const = 0; FB_CLASS_REGISTER_DECL; }; } // end namespace fb #endif
import React from 'react'; import { Image, Text, View, StyleSheet, FlatList } from 'react-native'; import { } from '../ScreenStylings/MainStylings'; import { Container, UserImage, UserImageWrapper, UserInfo, Card, UserInfoText, UserName, MessageContents, TextSection } from '../ScreenStylings/ChatsStyles'; import spotlight from '../assets/spotlight.png'; import { EvilIcons } from '@expo/vector-icons'; const listOfEvents = [ { id: '1', name: 'NYIT School of Engineering', userImage: <EvilIcons name="user" size={200} color={"black"} />, date: '11/7/2022', message: "Join us for a seminar next tuesday!" }, { id: '2', name: "President's Office", //userImage: <EvilIcons name="user" size={15} color="black"/>, date: '11/7/2022', message: "Join the president for lunch tomorrow" }, { id: '3', name: 'Handshake', //userImage: <EvilIcons name="user" size={15} color="black"/>, date: '11/7/2022', message: "Reminder - Career Fair on Friday." }, ] function Events({props, navigation}) { return ( <Container> <FlatList data={listOfEvents} keyExtractor={item => item.id} renderItem={({ item }) => ( <Card onPress={() => alert("Open event link in new window")}> <UserInfo> <UserImageWrapper> <UserImage source={spotlight} /> </UserImageWrapper> <TextSection> <UserInfoText> <UserName>{item.name}</UserName> <Text>{item.date}</Text> </UserInfoText> <MessageContents>{item.message}</MessageContents> </TextSection> </UserInfo> </Card> )} /> </Container> ) } export default Events;
import { Button, Text, TextArea, TextInput } from '@xunito-ui/react' import { ConfirmForm, FormActions, FormError, FormHeader } from './styles' import { CalendarBlank, Clock } from 'phosphor-react' import { z } from 'zod' import { useForm } from 'react-hook-form' import { zodResolver } from '@hookform/resolvers/zod' import dayjs from 'dayjs' import { api } from '@/lib/axios' import { useRouter } from 'next/router' const confirmFormSchema = z.object({ name: z.string().min(3, { message: 'Name needs at least 3 characters' }), email: z.string().email({ message: 'Invalid e-mail' }), observations: z.string().nullable(), }) type ConfirmFormData = z.infer<typeof confirmFormSchema> interface ConfirmStepProps { schedulingDate: Date onGoBackToCalendarStep: () => void } export function ConfirmStep({ schedulingDate, onGoBackToCalendarStep, }: ConfirmStepProps) { const { register, handleSubmit, formState: { isSubmitting, errors }, } = useForm<ConfirmFormData>({ resolver: zodResolver(confirmFormSchema), }) const router = useRouter() const username = String(router.query.username) const describedDate = dayjs(schedulingDate).format('MMM Do YYYY') const describedTime = dayjs(schedulingDate).format('h:mm A') async function handleConfirmScheduling(data: ConfirmFormData) { const { name, email, observations } = data await api.post(`/users/${username}/schedule`, { name, email, observations, date: schedulingDate, }) onGoBackToCalendarStep() } return ( <ConfirmForm as="form" onSubmit={handleSubmit(handleConfirmScheduling)}> <FormHeader> <Text> <CalendarBlank /> {describedDate} </Text> <Text> <Clock /> {describedTime} </Text> </FormHeader> <label> <Text size="sm">Full name</Text> <TextInput placeholder="Your name" {...register('name')} /> {errors.name && <FormError size="sm">{errors.name.message}</FormError>} </label> <label> <Text size="sm">Email address</Text> <TextInput type="email" placeholder="Your email" {...register('email')} /> {errors.email && ( <FormError size="sm">{errors.email.message}</FormError> )} </label> <label> <Text size="sm">Observations</Text> <TextArea {...register('observations')} /> </label> <FormActions> <Button type="button" variant="tertiary" onClick={onGoBackToCalendarStep} > Cancel </Button> <Button type="submit" disabled={isSubmitting}> Submit </Button> </FormActions> </ConfirmForm> ) }
#include <Arduino.h> #include <WiFi.h> #include <WiFiClient.h> #include <HTTPClient.h> #if CONFIG_FREERTOS_UNICORE static const BaseType_t app_cpu = 0; #else static const BaseType_t app_cpu = 1; #endif const char *ssid = "AFTERMATH"; const char *password = "YLLEQGQG72F"; static const int LED_PIN = LED_BUILTIN; static const uint8_t buf_len = 255; static const uint8_t msg_queue_len = 90; static QueueHandle_t queue; // typedef struct Message // { // int id; // char *text; // } Message; void initWeb() { WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println("Connected to the WiFi network: " + String(ssid) + " with IP: " + WiFi.localIP().toString()); } void sendData(int data) { HTTPClient http; WiFiClient client; http.begin(client, "http://192.168.8.133:5500/data"); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); String httpRequestData = "data=" + String(data); int httpResponseCode = http.POST(httpRequestData); if (httpResponseCode > 0) { String response = http.getString(); Serial.println(httpResponseCode); Serial.println(response); } else { Serial.print("Error on sending POST: "); Serial.println(httpResponseCode); } } void task1(void *parameter) { while (true) { digitalWrite(LED_PIN, HIGH); vTaskDelay(1000 / portTICK_PERIOD_MS); digitalWrite(LED_PIN, LOW); vTaskDelay(1000 / portTICK_PERIOD_MS); Serial.print("Task 1 with cpu: "); Serial.println(xPortGetCoreID()); } } void task2(void *parameter) { while (true) { digitalWrite(LED_PIN, HIGH); vTaskDelay(100 / portTICK_PERIOD_MS); digitalWrite(LED_PIN, LOW); vTaskDelay(100 / portTICK_PERIOD_MS); Serial.print("Task 2 with cpu: "); Serial.println(xPortGetCoreID()); } } void task3(void *parameter) { static int num = 0; while (true) { char msg[buf_len]; if (Serial.available() > 0) { String data = Serial.readStringUntil('\n'); int num = atoi(data.c_str()); if (xQueueSend(queue, &num, 10) == pdTRUE) { Serial.println("Send to queue success"); } else { Serial.println("Send to queue fail"); } } vTaskDelay(100 / portTICK_PERIOD_MS); } } void task4(void *parameter) { while (true) { char *rcvmsg; int id; if (xQueueReceive(queue, &id, 0) == pdTRUE) { // Serial.println(id); sendData(id); } vTaskDelay(100 / portTICK_PERIOD_MS); } } // void task4(void *parameter) // { // while (1) // { // char rcvmsg[10]; // if (xQueueReceive(queue, (void *)&rcvmsg, 0) == pdTRUE) // { // Serial.println(rcvmsg); // } // vTaskDelay(1000 / portTICK_PERIOD_MS); // } // } // SoftwareSerial mySerial(2, 3); // RX, TX void setup() { // put your setup code here, to run once: Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); initWeb(); queue = xQueueCreate(msg_queue_len, sizeof(int)); // xTaskCreate( // task1, /* Task function. */ // "task 1", /* String with name of task. */ // 1500, /* Stack size in bytes. */ // NULL, /* Parameter passed as input of the task */ // 1, /* Priority of the task. */ // NULL /* Task handle. */ // ); // xTaskCreate( // task2, // "task 2", // 1500, // NULL, // 1, // NULL); xTaskCreate( task3, "task 3", 1500, NULL, 2, NULL); xTaskCreate( task4, "task 4", 2500, NULL, 2, NULL); } void loop() { // put your main code here, to run repeatedly: // digitalWrite(LED_BUILTIN, HIGH); // Serial.println("Hello World"); // delay(1000); // digitalWrite(LED_BUILTIN, LOW); // Serial.println("Goodbye World"); // delay(1000); }
import { Component, OnInit } from '@angular/core'; import { MenubarModule, MenuItem } from 'primeng/primeng'; @Component({ selector: 'app-toolbat', templateUrl: './toolbat.component.html', styleUrls: ['./toolbat.component.scss'] }) export class ToolbatComponent implements OnInit { constructor() { } items: MenuItem[]; ngOnInit() { this.items = [ { label: 'File', icon: 'fa-file-o', items: [{ label: 'New', icon: 'fa-plus', items: [ { label: 'Project' }, { label: 'Other' }, ] }, { label: 'Open' }, { separator: true }, { label: 'Quit' } ] }, { label: 'Edit', icon: 'fa-edit', items: [ { label: 'Undo', icon: 'fa-mail-forward' }, { label: 'Redo', icon: 'fa-mail-reply' } ] }, { label: 'Help', icon: 'fa-question', items: [ { label: 'Contents' }, { label: 'Search', icon: 'fa-search', items: [ { label: 'Text', items: [ { label: 'Workspace' } ] }, { label: 'File' } ] } ] }, { label: 'Actions', icon: 'fa-gear', items: [ { label: 'Edit', icon: 'fa-refresh', items: [ { label: 'Save', icon: 'fa-save' }, { label: 'Update', icon: 'fa-save' }, ] }, { label: 'Other', icon: 'fa-phone', items: [ { label: 'Delete', icon: 'fa-minus' } ] } ] }, { label: 'Quit', icon: 'fa-minus' } ]; } }
import Camera from "ts/Camera"; import Canvas from "ts/Canvas"; import CanvasPainter from "ts/CanvasPainter"; import Color from "ts/Color"; import Constants from "ts/Constants"; import Matrix from "ts/Matrix"; import Point from "ts/Point"; import Ray from "ts/Ray"; import Sphere from "ts/shapes/Sphere"; import World from "ts/World"; import IChapter from "./IChapter"; class Chapter05 implements IChapter { getCamera = (_width: number, _height: number): Camera => { throw new Error("Chapter doesn't use a camera"); }; getWorld = (): World => { throw new Error("Chapter doesn't use a world"); }; run = (): void => { const canvasSize = 501; const wallZ = 10; const wallSize = 7; const canvas = new Canvas(canvasSize, canvasSize); const rayOrigin = new Point(0, 0, -5); const pixelSize = wallSize / canvasSize; const half = wallSize / 2; const sphere = new Sphere(); sphere.transformation = Matrix.getRotationMatrixZ(Constants.pi_4).scale(1, 0.75, 1); for (let y = 0; y < canvasSize; y++) { const worldY = half - pixelSize * y; for (let x = 0; x < canvasSize; x++) { const worldX = -half + pixelSize * x; const p = new Point(worldX, worldY, wallZ); const ray = new Ray(rayOrigin, p.subtractPoint(rayOrigin).normalize()); const intersections = sphere.getIntersectionsWith(ray); if (intersections.hasHit) { canvas.writePixel(x, y, Color.red); } } } const painter = new CanvasPainter("canvas5", canvasSize, canvasSize); painter.paint(canvas); }; } export default new Chapter05();
'use strict'; import chalk from 'chalk'; import { pluralize } from 'jest-util'; export function getSnapshotStatus( snapshot: { added: number; updated: number; unmatched: number; unchecked: number; uncheckedKeys: string[]; fileDeleted: boolean; }, afterUpdate: boolean ): string[] { /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const ARROW = ' \u203A '; const DOT = ' \u2022 '; const FAIL_COLOR = chalk.bold.red; const SNAPSHOT_ADDED = chalk.bold.green; const SNAPSHOT_UPDATED = chalk.bold.green; const SNAPSHOT_OUTDATED = chalk.bold.yellow; const statuses: string[] = []; if (snapshot.added) { statuses.push( `${SNAPSHOT_ADDED( ARROW + pluralize('snapshot', snapshot.added) + ' written.' )}` ); } if (snapshot.updated) { statuses.push( `${SNAPSHOT_UPDATED( ARROW + pluralize('snapshot', snapshot.updated) + ' updated.' )}` ); } if (snapshot.unmatched) { statuses.push( `${FAIL_COLOR( ARROW + pluralize('snapshot', snapshot.unmatched) + ' failed.' )}` ); } if (snapshot.unchecked) { if (afterUpdate) { statuses.push( `${SNAPSHOT_UPDATED( ARROW + pluralize('snapshot', snapshot.unchecked) + ' removed.' )}` ); } else { statuses.push( `${SNAPSHOT_OUTDATED( ARROW + pluralize('snapshot', snapshot.unchecked) + ' obsolete' )}.` ); } if (snapshot.uncheckedKeys.length > 0) { snapshot.uncheckedKeys.forEach(key => { statuses.push(` ${DOT}${key}`); }); } } if (snapshot.fileDeleted) { statuses.push(`${SNAPSHOT_UPDATED(ARROW + 'snapshot file removed.')}`); } return statuses; }
import {StyleSheet, Dimensions} from 'react-native'; import React from 'react'; import { makeObservable, action, observable, computed, comparer, reaction, runInAction} from 'mobx'; import AsyncStorage from '@react-native-community/async-storage'; import {makePersistable, getPersistedStore} from 'mobx-persist-store'; const screen = Dimensions.get('window'); class ThemeStore { @observable _Scheme1 = ''; @observable _Scheme2 = ''; @observable _Scheme3 = ''; @observable _Scheme4 = ''; @observable _Scheme5 = ''; @observable _Scheme6 = ''; @observable _Scheme7 = ''; @observable _Scheme8 = ''; @observable fontName = 'Poppins'; @observable theme = 'light'; // count is now persistent. constructor() { makeObservable(this); makePersistable(this, { name: 'themePersistor', properties: ['fontName','theme'], storage: AsyncStorage, debugMode:false }).then( action((hydratedStore)=>{ this.setDefaultThemes(hydratedStore.target.theme); }) ); } @action.bound setDefaultfontName(fontName:string){ this.fontName = fontName; } @action.bound setDefaultThemes(theme:string){ this.theme = theme; runInAction(() => { if(theme === 'light'){ this._Scheme1 = '#F07120'; this._Scheme2 = '#121C78'; this._Scheme3 = '#424141'; this._Scheme4 = '#6C6B6B'; this._Scheme5 = '#FFFFFF'; this._Scheme6 = '#121C78'; this._Scheme7 = '#000000'; this._Scheme8 = '#FFFFFF'; } else { this._Scheme1 = '#F07120'; this._Scheme2 = '#121C78'; this._Scheme3 = '#FFFFFF'; this._Scheme4 = '#EFEFEF'; this._Scheme5 = '#424141'; this._Scheme6 = '#EFEFEF'; this._Scheme7 = '#EFEFEF'; this._Scheme8 = '#6C6B6B'; } }) } @computed({equals:comparer.structural,keepAlive:true}) get styleSheet() { const _font = this.fontName; return StyleSheet.create({ bgButtonPrimary: { backgroundColor: '#F07120', }, h1: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'bold', fontSize: 24, lineHeight: 48, letterSpacing: 0.2, }, h2: { fontFamily: _font, fontStyle: 'normal', fontWeight: '600', fontSize: 24, lineHeight: 48, letterSpacing: 0.2, }, h3: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'normal', fontSize: 24, lineHeight: 48, letterSpacing: 0.2, }, h4: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'bold', fontSize: 18, lineHeight: 36, letterSpacing: 0.2, }, h5: { fontFamily: _font, fontStyle: 'normal', fontWeight: '600', fontSize: 18, lineHeight: 36, letterSpacing: 0.2, }, h6: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'normal', fontSize: 18, lineHeight: 36, letterSpacing: 0.2, }, subtitle1: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'bold', fontSize: 14, lineHeight: 28, letterSpacing: 0.2, }, subtitle2: { fontFamily: _font, fontStyle: 'normal', fontWeight: '500', fontSize: 14, lineHeight: 28, letterSpacing: 0.2, }, subtitle3: { fontFamily: _font, fontStyle: 'normal', fontWeight: '600', fontSize: 14, lineHeight: 28, letterSpacing: 0.2, }, body1: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'normal', fontSize: 14, lineHeight: 28, letterSpacing: 0.2, }, body2: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'bold', fontSize: 12, lineHeight: 24, letterSpacing: 0.2, }, body3: { fontFamily: _font, fontStyle: 'normal', fontWeight: '600', fontSize: 12, lineHeight: 24, letterSpacing: 0.2, }, small1: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'normal', fontSize: 12, lineHeight: 24, letterSpacing: 0.2, }, small2: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'bold', fontSize: 10, lineHeight: 20, letterSpacing: 0.2, }, small3: { fontFamily: _font, fontStyle: 'normal', fontWeight: '600', fontSize: 10, lineHeight: 20, letterSpacing: 0.2, }, button: { fontFamily: _font, fontStyle: 'normal', fontWeight: 'normal', fontSize: 10, lineHeight: 20, letterSpacing: 0.2, }, verticalBarExpand: { width: screen.width * 0.6, }, verticalBarPadding: { paddingVertical: 32, }, verticalBarMargin: { marginHorizontal: 20, marginVertical: 0, }, verticalBarExpandText: { marginHorizontal: 20, marginVertical: 11, }, verticalBarExpandIcon: { marginHorizontal: 20, }, lineInputDefaultContainer: { borderBottomWidth: 2, marginVertical: 8, borderBottomColor: '#ABABAB', }, lineInputDefaultStyle: { marginVertical: 0, paddingVertical: 0, marginHorizontal: 9, color: '#ABABAB', }, lineInputDefaultLabel: { padding: 0, margin: 0, color: '#000000', }, lineInputDefaultLeftIcon: { padding: 0, margin: 0, }, lineInputDefaultRightIcon: { padding: 0, margin: 0, }, lineInputFocusedContainer: { borderBottomWidth: 2, borderBottomColor: '#F07120', marginVertical: 8, }, lineInputFocusedStyle: { marginVertical: 0, paddingVertical: 0, marginHorizontal: 9, color: '#D5D5D5', }, lineInputFocusedLabel: { padding: 0, margin: 0, color: '#F07120', }, lineInputFocusedLeftIcon: { padding: 0, margin: 0, }, lineInputFocusedRightIcon: { padding: 0, margin: 0, }, lineInputFilledContainer: { borderBottomWidth: 2, borderBottomColor: '#6C6B6B', marginVertical: 8, }, lineInputFilledStyle: { marginVertical: 0, paddingVertical: 0, marginHorizontal: 9, color: '#6C6B6B', }, lineInputFilledLabel: { padding: 0, margin: 0, color: '#6C6B6B', }, lineInputFilledLeftIcon: { padding: 0, margin: 0, }, lineInputFilledRightIcon: { padding: 0, margin: 0, }, lineInputErrorContainer: { borderBottomWidth: 2, borderBottomColor: '#E03B3B', marginVertical: 8, }, lineInputErrorStyle: { marginVertical: 0, paddingVertical: 0, marginHorizontal: 9, color: '#6C6B6B', }, lineInputErrorLabel: { padding: 0, margin: 0, color: '#E03B3B', }, lineInputErrorLeftIcon: { padding: 0, margin: 0, }, lineInputErrorRightIcon: { padding: 0, margin: 0, }, lineInputDisabledContainer: { borderBottomWidth: 2, borderBottomColor: '#D5D5D5', marginVertical: 8, }, lineInputDisabledStyle: { marginVertical: 0, paddingVertical: 0, marginHorizontal: 9, color: '#D5D5D5', }, lineInputDisabledLabel: { padding: 0, margin: 0, color: '#D5D5D5', }, lineInputDisabledLeftIcon: { padding: 0, margin: 0, }, lineInputDisabledRightIcon: { padding: 0, margin: 0, }, containedInputDefaultContainer: { borderWidth: 1, borderColor: '#414993', borderRadius: 5, paddingHorizontal: 15, paddingVertical: 9, }, containedInputDefaultStyle: { marginVertical: 0, paddingVertical: 0, marginHorizontal: 9, color: '#ABABAB', }, containedInputDefaultLabel: { padding: 0, margin: 0, color: '#000000', }, containedInputDefaultLeftIcon: { padding: 0, margin: 0, }, containedInputDefaultRightIcon: { padding: 0, margin: 0, }, containedInputFocusedContainer: { borderWidth: 1, borderColor: '#414993', borderRadius: 5, paddingHorizontal: 15, paddingVertical: 9, }, containedInputFocusedStyle: { marginVertical: 0, paddingVertical: 0, marginHorizontal: 9, color: '#000000', }, containedInputFocusedLabel: { padding: 0, margin: 0, color: '#000000', }, containedInputFocusedLeftIcon: { padding: 0, margin: 0, }, containedInputFocusedRightIcon: { padding: 0, margin: 0, }, containedInputFilledContainer: { borderWidth: 1, borderColor: '#414993', borderRadius: 5, paddingHorizontal: 15, paddingVertical: 9, }, containedInputFilledStyle: { paddingVertical: 0, marginVertical: 0, marginHorizontal: 9, color: '#000000', }, containedInputFilledLabel: { padding: 0, margin: 0, color: '#000000', }, containedInputFilledLeftIcon: { padding: 0, margin: 0, }, containedInputFilledRightIcon: { padding: 0, margin: 0, }, containedInputErrorContainer: { borderWidth: 1, borderColor: '#414993', borderRadius: 5, paddingHorizontal: 15, paddingVertical: 9, }, containedInputErrorStyle: { marginVertical: 0, paddingVertical: 0, marginHorizontal: 9, color: '#6C6B6B', }, containedInputErrorLabel: { padding: 0, margin: 0, color: '#000000', }, containedInputErrorLeftIcon: { padding: 0, margin: 0, }, containedInputErrorRightIcon: { padding: 0, margin: 0, }, containedInputDisabledContainer: { borderWidth: 1, borderColor: '#D5D5D5', borderRadius: 5, paddingHorizontal: 15, paddingVertical: 9, backgroundColor: '#F5F5FB', }, containedInputDisabledStyle: { marginVertical: 0, paddingVertical: 0, marginHorizontal: 9, color: '#D5D5D5', backgroundColor: 'transparent', }, containedInputDisabledLabel: { padding: 0, margin: 0, color: '#D5D5D5', }, containedInputDisabledLeftIcon: { padding: 0, margin: 0, }, containedInputDisabledRightIcon: { padding: 0, margin: 0, }, rectDefaultButtonContainerStyle: { borderRadius: 5, }, rectDefaultButtonStyle: { backgroundColor: '#F07120', }, rectDefaultButtonIconStyle: { marginRight: 8, }, rectDefaultButtonTitleStyle: { color: '#FFFFFF', }, rectDisabledButtonContainerStyle: { borderRadius: 5, }, rectDisabledButtonStyle: { backgroundColor: '#E7E8F2', }, rectDisabledButtonIconStyle: { marginRight: 8, }, rectDisabledButtonTitleStyle: { color: '#FFFFFF', }, rectOutlineDefaultButtonContainerStyle: { borderRadius: 5, borderWidth: 1, borderColor: '#D5D5D5', }, rectOutlineDefaultButtonStyle: { backgroundColor: 'transparent', }, rectOutlineDefaultButtonIconStyle: { marginRight: 8, }, rectOutlineDefaultButtonTitleStyle: { color: '#4E4E4E', }, rectOutlineDisabledButtonContainerStyle: { borderRadius: 5, borderWidth: 1, borderColor: '#D5D5D5', }, rectOutlineDisabledButtonStyle: { backgroundColor: 'transparent', }, rectOutlineDisabledButtonIconStyle: { marginRight: 8, }, rectOutlineDisabledButtonTitleStyle: { color: '#D5D5D5', }, roundDefaultButtonContainerStyle: { borderRadius: 10, }, roundDefaultButtonStyle: { backgroundColor: '#F07120', }, roundDefaultButtonIconStyle: { marginRight: 8, }, roundDefaultButtonTitleStyle: { color: '#FFFFFF', }, roundDisabledButtonContainerStyle: { borderRadius: 5, }, roundDisabledButtonStyle: { backgroundColor: '#E7E8F2', }, roundDisabledButtonIconStyle: { marginRight: 8, }, roundDisabledButtonTitleStyle: { color: '#FFFFFF', }, roundOutlineDefaultButtonContainerStyle: { borderRadius: 10, borderWidth: 1, borderColor: '#D5D5D5', }, roundOutlineDefaultButtonStyle: { backgroundColor: 'transparent', }, roundOutlineDefaultButtonIconStyle: { marginRight: 8, }, roundOutlineDefaultButtonTitleStyle: { color: '#4E4E4E', }, roundOutlineDisabledButtonContainerStyle: { borderRadius: 10, borderWidth: 1, borderColor: '#D5D5D5', }, roundOutlineDisabledButtonStyle: { backgroundColor: 'transparent', }, roundOutlineDisabledButtonIconStyle: { marginRight: 8, }, roundOutlineDisabledButtonTitleStyle: { color: '#D5D5D5', }, //use avatar for this classes buttonAvatarDefaultIconStyle: { alignItems: 'center', paddingTop: 18, paddingBottom: 21, }, buttonAvatarDefaultOverlayStyle: { backgroundColor: '#F07120', flex: 2, borderRadius: 5, }, buttonAvatarDefaultContainerStyle: { alignSelf: 'center', }, buttonAvatarDisabledIconStyle: { alignItems: 'center', paddingTop: 18, paddingBottom: 21, }, buttonAvatarDisabledOverlayStyle: { backgroundColor: '#E7E8F2', flex: 2, borderRadius: 5, }, buttonAvatarDisabledContainerStyle: { alignSelf: 'center', }, buttonFloatedAvatarDefaultIconStyle: { alignItems: 'center', paddingTop: 18, paddingBottom: 13, }, buttonFloatedAvatarDefaultOverlayStyle: { backgroundColor: '#FFFFFF', flex: 2, borderRadius: 5, shadowColor: '#000', shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.22, shadowRadius: 2.22, elevation: 3, }, buttonFloatedAvatarDefaultContainerStyle: { alignSelf: 'center', }, buttonFloatedAvatarDefaultPlaceholderStyle: { position: 'absolute', bottom: 10, left: 0, right: 0, }, buttonFloatedAvatarDefaultTitleStyle: { color: '#121C78', }, buttonFloatedAvatarHoverIconStyle: { alignItems: 'center', paddingTop: 18, paddingBottom: 13, }, buttonFloatedAvatarHoverOverlayStyle: { backgroundColor: '#2A3386', flex: 2, borderRadius: 5, shadowColor: '#000', shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.22, shadowRadius: 2.22, elevation: 3, }, buttonFloatedAvatarHoverContainerStyle: { alignSelf: 'center', }, buttonFloatedAvatarHoverPlaceholderStyle: { position: 'absolute', bottom: 10, left: 0, right: 0, }, buttonFloatedAvatarHoverTitleStyle: { color: '#FFFFFF', }, buttonFloatedAvatarDisabledIconStyle: { alignItems: 'center', paddingTop: 18, paddingBottom: 13, }, buttonFloatedAvatarDisabledOverlayStyle: { backgroundColor: '#FFFFFF', flex: 2, borderRadius: 5, shadowColor: '#000', shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.22, shadowRadius: 2.22, elevation: 3, }, buttonFloatedAvatarDisabledContainerStyle: { alignSelf: 'center', }, buttonFloatedAvatarDisabledPlaceholderStyle: { position: 'absolute', bottom: 10, left: 0, right: 0, }, buttonFloatedAvatarDisabledTitleStyle: { color: '#F5F5FB', }, buttonGroupContainerStyle: { borderRadius: 10, borderColor: '#ABABAB', }, buttonGroupInnerBorderStyle: { borderColor: '#ABABAB', }, buttonGroupButtonStyle: { backgroundColor: '#FFFFFF', color: '#000000', }, buttonGroupSelectedStyle: { backgroundColor: '#F07120', color: '#FFFFFF', }, }); } } export const themeStore = new ThemeStore(); // You need to export the counterStore instance. export const themeStoreContext = React.createContext(themeStore); export const useThemeStore = () => { const _ctx = React.useContext(themeStoreContext); const _disposer = reaction( () => _ctx.theme, theme => { if (theme === 'light') { _ctx._Scheme1 = ''; _ctx._Scheme2 = ''; _ctx._Scheme3 = ''; } else { _ctx._Scheme1 = ''; _ctx._Scheme2 = ''; _ctx._Scheme3 = ''; } } ); React.useEffect(() => { return () => _disposer(); }, []); return _ctx; } export default themeStore.styleSheet;
package src.other; import static org.junit.jupiter.api.Assertions.assertEquals; import static src.other.StripTags.solveWithLoop; import static src.other.StripTags.solveWithRegex; import org.junit.jupiter.api.Test; /** * Create a function called stripTags that takes a string as input and removes all HTML tags from it. A HTML tag starts with < and ends with >. * You <b>cannot</b> use regular expressions to solve this exercise. */ public class StripTags { public static String solveWithRegex(String input) { return input.replaceAll("(<[^<]*>)", ""); } public static String solveWithLoop(String input) { /* + remove tags' content including the attributes etc. * for each char c in input * if '<' toggle isInTag to true; else if '>' toggle isInTag to false * if not inside teg * append to filtered string */ StringBuilder output = new StringBuilder(); boolean isTag = false; for (char c : input.toCharArray()) { if (c == '<') { isTag = true; } else if (c == '>') { isTag = false; } else if (!isTag) { output.append(c); } } return output.toString(); } } class TestStripTags { @Test public void testSolveWithLoop() { assertEquals("I'm a teapot.", solveWithLoop("<p class=\"lead\">I'm a <i>teapot</i>.</p>")); assertEquals("Nothing to strip", solveWithLoop("Nothing to strip")); } @Test public void testSolveWithRegex() { assertEquals("I'm a teapot.", solveWithRegex("<p class=\"lead\">I'm a <i>teapot</i>.</p>")); assertEquals("Nothing to strip", solveWithRegex("Nothing to strip")); } }
# Features This section details all the app's existing features and behaviors. <note> <p> Some features are only available on mobile and will be marked <a href="FAQ.md#tv-features-faq"><emphasis>(Mobile only)</emphasis></a>. </p> </note> ## Adding tunnel configs There are multiple ways tunnel configs can be added to the app. After clicking the floating action button on the main screen, the following options are available: 1. Upload a <path>.conf</path> file 2. Upload a zip containing <path>.conf</path> files (like an export from %product% or the official app) 3. Scan a QR code <a href="FAQ.md#tv-features-faq"><emphasis>(Mobile only)</emphasis></a> - This option will upload the tunnel with a randomly generated name. 4. Create one from scratch ## AmneziaWG Support %product% fully supports a fork of WireGuard called [AmneziaWG](https://docs.amnezia.org/documentation/amnezia-wg). [AmneziaWG](https://docs.amnezia.org/documentation/amnezia-wg) is based off of WireGuard, but adds obfuscation to WireGuard's packet signatures to prevent deep packet inspection (DPI) systems from censoring WireGuard traffic. One of the key differences (from a user perspective) between WireGuard and Amnezia is Amnezia adds additional properties to the standard WireGuard configuration format. Without these properties populated, Amnezia will fall back to using standard WireGuard and the packet signature obfuscation will not be applied. > It is important to note that Amnezia only supports userspace mode on Android and not kernel mode. ### How to convert an existing WireGuard config to Amnezia 1. Open the tunnel setting screen by long pressing on a tunnel and clicking the gear icon. 2. Click the edit tunnel floating action button and select the Amnezia option. 3. The shared WireGuard properties will already be populated. Populate the addition empty Amnezia properties with the follwing data: Junk packet count: 7 (can be anywhere between 1-128) \ Junk packet minimum size: 50 (must be less than junk packet maximum size) \ Junk packet maximum size: 1000 (must be less than 1280) \ Init packet junk size: 0 \ Response packet junk size: 0 \ Init magic packet header: 1 \ Response packet magic header: 2 \ Underload packet magic header: 3 \ Transport packet magic header: 4 Alternatively, these values can be added to the .conf file before import: ``` [Interface] Address = *** PrivateKey = *** DNS = *** MTU = *** Jc = between 1-128 Jmin = must be less than Jmax Jmax = less than 1280 S1 = 0 S2 = 0 H1 = 1 H2 = 2 H3 = 3 H4 = 4 ``` When using an Amnezia server, this values will be different and should match the server values. ## Auto-tunneling Auto-tunneling is the core feature of the application. It allows users to automate which tunnel will be active under certain network circumstances. A core concept when using auto-tunneling is setting a <tooltip term="primary_tunnel">primary tunnel</tooltip>. Setting a primary tunnel can be accomplished by doing a long-press on the desired tunnel config on the main screen and clicking the <emphasis>gear icon</emphasis>. <note> <p> Setting a <tooltip term="primary_tunnel">primary tunnel</tooltip> is not strictly required as the app will automatically select a default tunnel if one does not already exist. Additionally, <a anchor="always-on-feature">Always-On VPN</a> is disabled in this mode to prevent conflicts. </p> </note> There are three auto-tunneling modes that can be used in combination or individually: 1. <control> Tunnel on mobile data </control> - The app detects when the device has switched to using mobile data and turns on the tunnel. - <emphasis>Common use case:</emphasis> Connecting to home server whenever leaving the house 2. <control> Tunnel on ethernet </control>. - The app detects when a device has switched to an ethernet connection and turns on the tunnel. - <emphasis>Common use case:</emphasis> AndroidTV devices (especially portable ones) 3. <control> Tunnel on untrusted wifi </control> <emphasis>(Location required)</emphasis> - The app detects when the device has connected to a new Wi-Fi network. If the network name (SSID) is not in the list of trusted network names, start the tunnel. - <emphasis>Common use case:</emphasis> Disable the tunnel on my home (trusted) network, but enable it when I connect to any public Wi-Fi network. ### Auto-tunneling to a specific tunnel by wifi name and/or mobile data A common scenario is when a user wants to use a specific tunnel config when they are connected to certain networks. > For example, a user might want to connect to their home VPN server when they are away from home and then want to connect to their VPN provider's server while at home. %product% now allows users to configure each tunnel to be used on specific Wi-Fi networks and/or mobile data. Tunnels configured with these settings will be prioritized over the primary tunnel if the app detects a match. To configure: - Long press on the tunnel config you would like to configure from the main screen - Click the gear icon - Add a Wi-Fi name where you would like to prioritize using this tunnel or turn on mobile data if this is your mobile data specific tunnel. %product% auto-tunneling will now prioritize using this specific tunnel if it detects a matching network scenario. ### Auto-tunneling override Auto-tunnel override is a feature of %product% that allows users to temporarily pause (override) [auto-tunneling](#auto-tunneling) to toggle a tunnel. The status of the override can be viewed on the main screen of the app when [auto-tunneling](#auto-tunneling) is enabled. <img src="override.png" alt="override" border-effect="line"/> There are two statuses: - <control>active</control>: [auto-tunneling](#auto-tunneling) is active and controlling tunnel state - <control>paused</control>: [auto-tunneling](#auto-tunneling) is paused by the user who can now toggle tunnels freely without fully turning off [auto-tunneling](#auto-tunneling) from the settings screen. This feature can be activated three different ways: 1. Clicking the <emphasis>pause</emphasis> button from the main screen 2. Toggling a tunnel via [quick tile](#quick-tile-settings) 3. Toggling a tunnel via [shortcut/intent](Integrations.md) It is common for users to need to manually toggle a tunnel quickly in certain situations when auto-tunneling is active. This temporary override was created to meet this need. ## Split tunneling {collapsible="true"} {id="split"} Split tunneling is a feature that allows a user to route only selected app's traffic through the tunnel. Currently, this is configured on a per-tunnel basis. A common use-case could be that a user wants apps that only function in another country to be tunneled to a VPN server in that country while all other apps use the normal network. To configure split tunneling: 1. Long press on a tunnel config to show options 2. Press the gear icon to navigate to the tunnel setting screen 3. Press the pencil floating action button to edit the tunnel config values 4. At the bottom of the Interface section is a <emphasis>Tunneling apps</emphasis> to open the tunneling apps selection dialog. 5. Select which apps to either include or exclude from the tunnel 6. Click <emphasis>Done</emphasis> 7. Click the floating action button to save ## Auto restart on boot Auto start on boot happens automatically under the following conditions: 1. Auto-tunneling enabled with auto start auto tunneling again on reboot. 2. A tunnel was manually activated before reboot will restart that tunnel after reboot. 3. Always-on VPN is enabled will auto start your primate tunnel on reboot. This feature will automatically restart the auto-tunneling service on boot if the phone has been shutdown or rebooted. <note> <p> It can sometimes take up to a few minutes after boot to start the service. </p> </note> ## Restart on ping fail (beta) This feature attempts to restart the tunnel if it is failing to ping your server. This feature is still in beta and will likely change in the future. - Pings vpn server address on an interval: 1-minute(s) - Cooldown after a failed ping/restart is triggered: 60-minute(s) ## Enable app lock This feature allows the user to set an app-specific pin when launching WG Tunnel. The primary use case for this feature is to serve as a parental control mechanism to prevent phone users from being able to disable auto-tunneling. To config: - Navigate to app settings - Toggle "Enable app lock" - Set your pin <warning> <p> Do not forget your pin as there is not a reset feature in the app. If you forget your pin, you will have to uninstall and reinstall the app. </p> </warning> ## Tunnel statistics Clicking on a tunnel while it is running will show per peer tunnel statistics including: - Rx in MB - Tx in MB - Last successful handshake in seconds - First characters of peer public key <img src="statistics.png" alt="statistics" border-effect="line"/> ## Quick tile settings Quick tile settings is a feature of %product% that allows users to quickly control and see the status of the active tunnel without opening the app. <img src="quick-tile.png" alt="quick-tile" border-effect="line"/> There are two tiles available. One is for toggling the currently active and/or primary tunnel. The other tile is for toggling the state of auto-tunneling from pause/resume. ## Always-on VPN {id="always-on-feature"} Turning on the Always-On VPN setting [(mobile only)](FAQ.md#tv-features-faq) in %product% allows the Android OS to control your <tooltip term="primary_tunnel">primary tunnel</tooltip> (or an app selected tunnel if no primary is set) through the Android OS Always-On VPN feature. Android will attempt to keep the tunnel always connected. <note> <p> Auto-tunneling is disabled in this mode as it would conflict with the Always-On VPN functionality. </p> </note> An added benefit to Always-On VPN is the ability to use the <emphasis>Block connections without VPN</emphasis> native Android feature for added security, but this will prevent split tunneling from working properly. ## Exporting tunnel configs {id="export-feature"} %product% offers the ability to export all of your tunnel configurations to a zip folder [(mobile only)](FAQ.md#tv-features-faq). 1. Navigate to the <emphasis>Settings</emphasis> screen. 2. Click `Export configs` near the bottom of the screen. 3. Complete the biometrics prompt. 4. All configs are now saved to the <emphasis>Downloads</emphasis> folder on your device in a zip folder called `wg-export_<timestamp>.zip`. ## Kernel Module Support If you are on a rooted device, %product% also supports the use of WireGuard's native kernel implementation on Android [(mobile only)](FAQ.md#tv-features-faq). This has some performance benefits, but it has been known to be less reliable than the userspace implementation. <seealso> <category ref="wrs"> <a href="https://github.com/zaneschepke/wgtunnel">GitHub project</a> <a href="https://github.com/zaneschepke/wgtunnel/releases">Changelog</a> </category> </seealso>
package com.lyvetech.transnature.features.feed.data.local.dao import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.lyvetech.transnature.core.data.local.TransNatureDatabase import com.lyvetech.transnature.fakeTrailEntity import com.lyvetech.transnature.fakeUpdatedTrailEntity import com.lyvetech.transnature.features.feed.data.local.entity.TrailEntity import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @ExperimentalCoroutinesApi @RunWith(AndroidJUnit4::class) @SmallTest class FeedDaoTest { private lateinit var database: TransNatureDatabase private lateinit var systemUnderTest: FeedDao @get:Rule var instantTaskExecutor = InstantTaskExecutorRule() @get:Rule var mainCoroutineRule = MainCoroutineRule() @Before fun setup() { database = Room.inMemoryDatabaseBuilder( ApplicationProvider.getApplicationContext(), TransNatureDatabase::class.java ).allowMainThreadQueries().build() systemUnderTest = database.feedDao } @After fun tearDown() { database.close() } @Test fun insertTrail_getTrailByIdAndVerifyItsInserted() = runBlocking { systemUnderTest.insertTrails(listOf(fakeTrailEntity)) val loaded = systemUnderTest.getTrailById(fakeTrailEntity.id.toString()) assertThat(loaded as TrailEntity, notNullValue()) assertThat(loaded.id, `is`(fakeTrailEntity.id)) assertThat(loaded.tag, `is`(fakeTrailEntity.tag)) assertThat(loaded.name, `is`(fakeTrailEntity.name)) assertThat(loaded.desc, `is`(fakeTrailEntity.desc)) assertThat(loaded.isFav, `is`(fakeTrailEntity.isFav)) assertThat(loaded.warning, `is`(fakeTrailEntity.warning)) assertThat(loaded.imgRefs, `is`(fakeTrailEntity.imgRefs)) assertThat(loaded.location, `is`(fakeTrailEntity.location)) assertThat(loaded.accession, `is`(fakeTrailEntity.accession)) assertThat(loaded.endLatitude, `is`(fakeTrailEntity.endLatitude)) assertThat(loaded.endLongitude, `is`(fakeTrailEntity.endLongitude)) assertThat(loaded.startLatitude, `is`(fakeTrailEntity.startLatitude)) assertThat(loaded.startLatitude, `is`(fakeTrailEntity.startLatitude)) assertThat(loaded.difficultyLevel, `is`(fakeTrailEntity.difficultyLevel)) assertThat(loaded.distanceInMeters, `is`(fakeTrailEntity.distanceInMeters)) assertThat(loaded.peakPointInMeters, `is`(fakeTrailEntity.peakPointInMeters)) assertThat( loaded.averageTimeInMillis, `is`(fakeTrailEntity.averageTimeInMillis) ) } @Test fun deleteTrails_getTrailsVerifyItsEmpty() = runBlocking { systemUnderTest.insertTrails(listOf(fakeTrailEntity)) systemUnderTest.deleteTrails(listOf(fakeTrailEntity.name)) val allTrails = systemUnderTest.getAllTrails() assertThat(allTrails, `is`(emptyList())) } @Test fun updateTrail_getByIdAndVerifyItsUpdated() = runBlocking { systemUnderTest.insertTrails(listOf(fakeTrailEntity)) systemUnderTest.updateTrail(fakeUpdatedTrailEntity) val loaded = systemUnderTest.getTrailById(fakeTrailEntity.id.toString()) assertThat(loaded as TrailEntity, notNullValue()) assertThat(loaded.desc, `is`("Updated desc")) } @Test fun getFavoriteTrails() = runBlocking { systemUnderTest.insertTrails(listOf(fakeTrailEntity)) val favTrails = systemUnderTest.getFavoriteTrails() for (i in favTrails.indices) { assertThat(favTrails[i].isFav, `is`(true)) } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Instagram Clone</title> <link rel="stylesheet" href="style.css"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/fonts/remixicon.css" rel="stylesheet"> <link rel="shortcut icon" href="./icon.webp" type="image/x-icon"> </head> <body> <!-- sidebar --> <div class="sidebar"> <div class="logo"> <img src="./logo.png"alt="logo"> </div> <!-- profile image --> <div class="profile"> <div class="profile-img"> <img src="./profile.jpg" alt="profile"> </div> <div class="name"> <h1>Natasha Romanoff</h1> <img src="./verify.png" alt="verify"> </div> <span>@Natasha</span> </div> <!-- About --> <div class="about"> <!-- Box-1 --> <div class="box"> <h3>253</h3> <span>Posts</span> </div> <!-- Box-2 --> <div class="box"> <h3>23.5M</h3> <span>Followers</span> </div> <!-- Box-3 --> <div class="box"> <h3>362</h3> <span>Following</span> </div> </div> <!-- Menu --> <div class="menu"> <a href="#"> <span class="icon"> <i class="ri-function-line"></i> </span> Feed </a> <a href="#"> <span class="icon"> <i class="ri-notification-4-line"></i> </span> Notification </a> <a href="#"> <span class="icon"> <i class="ri-search-eye-fill"></i> </span> Explore </a> <a href="#"> <span class="icon"> <i class="ri-mail-unread-fill"></i> </span> Message </a> <a href="#"> <span class="icon"> <i class="ri-send-plane-fill"></i> </span> Direct </a> <a href="#"> <span class="icon"> <i class="ri-bar-chart-fill"></i> </span> Stats </a> <a href="#"> <span class="icon"> <i class="ri-settings-3-fill"></i> </span> Settings </a> <a href="#"> <span class="icon"> <i class="ri-logout-circle-r-fill"></i> </span> Logout </a> </div> </div> <!-- Main Home --> <div class="main-home"> <div class="header"> <!-- Search --> <div class="search"> <i class="ri-search-eye-line"></i> <input type="text" name="" id="" placeholder="Search"> </div> <div class="header-content"> <i class="ri-notification-3-line"></i> <i class="ri-mail-unread-fill"></i> <!-- Button --> <a href="#" class="btn"> <i class="ri-add-circle-line"></i> <div class="btn-text"> Add Photos </div> </a> </div> </div> <div class="story-tittle"> <h1>Stories</h1> <a href="#" class="btn"> <i class="ri-play-circle-line"></i> <div class="text"> Watch All </div> </a> </div> <div class="stories"> <!-- Stories 1 --> <div class="stories-img color"> <img src="./post1.jpg" alt="profile"> <div class="add">+</div> </div> <!-- Stories 2 --> <div class="stories-img "> <img src="./profile2.jpg" alt="profile"> <!-- <div class="add">+</div> --> </div> <!-- Stories 3 --> <div class="stories-img "> <img src="./profile3.jpg" alt="profile"> <!-- <div class="add">+</div> --> </div> <!-- Stories 4 --> <div class="stories-img "> <img src="./profile4.jpg" alt="profile"> <!-- <div class="add">+</div> --> </div> <!-- Stories 5 --> <div class="stories-img"> <img src="./profile5.jpg" alt="profile"> <!-- <div class="add">+</div> --> </div> <!-- Stories 6 --> <div class="stories-img "> <img src="./profile6.jpg" alt="profile"> <!-- <div class="add">+</div> --> </div> <!-- Stories 7 --> <div class="stories-img "> <img src="./profile7.jpg" alt="profile"> <!-- <div class="add">+</div> --> </div> <!-- Stories 8 --> <div class="stories-img "> <img src="./profile8.jpg" alt="profile"> <!-- <div class="add">+</div> --> </div> <!-- Stories 9 --> <div class="stories-img "> <img src="./profile9.jpg" alt="profile"> <!-- <div class="add">+</div> --> </div> <!-- Stories 10 --> <div class="stories-img "> <img src="./profile10.jpg" alt="profile"> <!-- <div class="add">+</div> --> </div> </div> <div class="feed"> <h1>Feed</h1> <div class="feed-text"> <h2>Latest</h2> <span>Popular</span> </div> </div> <div class="main-post"> <!-- Box-1 --> <div class="post-box"> <img src="./marvel.jpg" alt="marvel"> <div class="post-info"> <div class="post-profile"> <div class="post-img"> <img src="./profile10.jpg" alt="profile"> </div> <h3>Marquene B</h3> </div> <div class="likes"> <i class="ri-heart-line"></i> <span>1.4M</span> <i class="ri-chat-3-line"></i> <span>2.4k</span> </div> </div> </div> <!-- Box-1 --> <div class="post-box"> <img src="./post2.jpg" alt="marvel"> <div class="post-info"> <div class="post-profile"> <div class="post-img"> <img src="./post3.jpg" alt="profile"> </div> <h3>Marquene B</h3> </div> <div class="likes"> <i class="ri-heart-line"></i> <span>1.4M</span> <i class="ri-chat-3-line"></i> <span>2.4k</span> </div> </div> </div> <!-- Box-1 --> <div class="post-box"> <img src="./DC.jpg" alt="marvel"> <div class="post-info"> <div class="post-profile"> <div class="post-img"> <img src="./profile9.jpg" alt="profile"> </div> <h3>Marquene B</h3> </div> <div class="likes"> <i class="ri-heart-line"></i> <span>1.4M</span> <i class="ri-chat-3-line"></i> <span>2.4k</span> </div> </div> </div> </div> </div> </body> </html>
## 引导过程介绍 我们的FarmOS使用OpenSBI作为BIOS引导程序。OpenSBI的主要功能就是在M态初始化硬件,然后以S态跳转到内核的位置,完成整个启动过程。此外,OpenSBI作为S态内核的执行环境(EEI),可以以 `ecall` 的方式为S态内核提供一些只有M态才能实现的功能。 ### OpenSBI的引导过程 OpenSBI会先做初始化,然后以 **S 态**跳转到编译时指定的位置(默认为`0x80200000`),并将Hartid、设备树地址分别放在`a0`、`a1`中传递给OS。如下所示: ![image-20230501203900943](./assets/image-20230501203900943.png) reference: https://blog.csdn.net/dai_xiangjun/article/details/123524264 运行过程截图: ![image-20230501204832563](./assets/image-20230501204832563.png) OpenSBI启动时打印的信息包含当前的核数、设备信息、下一个阶段(内核运行的环境)的状态、启动核信息等。其中最重要的就是启动核号(Boot Hart ID)。OpenSBI并不会以固定的核启动,而是会**随机选择一个核启动**,在我的环境中(Ubuntu 22.04虚拟机),OpenSBI最常以 0核启动,不过也有时会从其他核启动。这就要求内核的boot部分需要屏蔽启动核的差异,无论用什么核都能正常启动。 ### 内核链接脚本 `linker/kernel.ld`:用于将内核ELF的各段加载到正确的位置 ```lds OUTPUT_ARCH( "riscv" ) ENTRY( _entry ) SECTIONS { . = 0x80200000; .text : { *(.text .text.*) . = ALIGN(0x1000); /* 需要定义一个trampsec: .section trampsec。 此section是用户态下的中断入口程序,与内核共享, 需要单独占据一个页的长度(参考trampoline.S) */ _trampoline = .; *(trampSec) . = ALIGN(0x1000); ASSERT(. - _trampoline == 0x1000, "error: trampoline larger than one page"); . = ALIGN(0x1000); PROVIDE(end_text = .); } .rodata : { . = ALIGN(16); *(.srodata .srodata.*) /* do not need to distinguish this from .rodata */ . = ALIGN(16); *(.rodata .rodata.*) } .data : { . = ALIGN(16); *(.sdata .sdata.*) /* do not need to distinguish this from .data */ . = ALIGN(16); *(.data .data.*) } .bss : { . = ALIGN(16); *(.sbss .sbss.*) /* do not need to distinguish this from .bss */ . = ALIGN(16); *(.bss .bss.*) } . = ALIGN(0x1000); PROVIDE(end = .); } ``` 物理内存布局:(摘自xv6-riscv指导书) <img src="assets/image-20230606213748284.png" alt="image-20230606213748284" style="zoom:67%;" /> 我们的内核布局与xv6相近,只不过内核的起始位置为 `0x80200000`。为什么不选择 `0x80000000` 呢?这是因为 `0x80000000` 是OpenSBI放置的位置,将内核加载到此位置会与OpenSBI冲突。xv6是从M态启动的,其启动并不依赖OpenSBI,所以可以加载到`0x80000000` 位置。 在物理内存布局中,`0~0x80000000` 段是设备的MMIO映射区域;`0x80000000~MAXPA` 是物理内存的位置。也就是说,物理内存的第一个字节对应物理地址 `0x80000000`。 在启动阶段,没有开启分页,所以我们可以暂时使用物理地址访问物理内存。等到了虚拟内存初始化阶段,会将物理内存一对一地映射到内核页表,仍然能做到与启动阶段详细的内存访问方式。 ### 启动过程 1. 入口点 `_entry` 位于`boot/entry.S` 中。下面的汇编代码根据hartid设置当前cpu对应的栈顶指针,并跳转到start函数。 ```assembly _entry: # set up a stack for C. # stack0 is declared in start.c, # with a 4096-byte stack per CPU. # sp = stack0 + ((hartid+1) * 4096) # status = Supervisor, a0 = hartid, a1 = dtb la sp, stack0 li t0, KSTACKSIZE mv t1, a0 addi t1, t1, 1 mul t0, t0, t1 add sp, sp, t0 # jump to start() in start.c # pass a0 as hartid call start spin: j spin ``` 2. `start.c` 中,定义了内核栈和 `start` 函数。每个hart可以分到4页的栈空间,这对内核来说足够用了。 ```c void start(long hartid, uint64 _dtb_entry) { // 设置dtb_entry extern uint64 dtbEntry; if (dtbEntry == 0) { dtbEntry = _dtb_entry; } // Supervisor: disable paging for now. w_satp(0); // enable some supervisor interrupt w_sie(r_sie() | SIE_SEIE | SIE_STIE | SIE_SSIE); // 在每个CPU的tp寄存器中保存hartid w_tp(hartid); main(); } ``` `start` 函数的参数来源于openSBI设置的 `a0` 和 `a1`,分别对应hartid和设备树的起始地址。start函数主要作用是记录了设备树的地址,关闭分页,开启S态的外部中断、核内时钟中断和软中断。之后在 `tp` 寄存器中设置hartid。注意,我们之后**始终**要保持内核态下 `tp` 寄存器为 hartid,因此在进入用户态和回到内核态时需要维护这个寄存器的值。 3. `main.c` 中的 `main` 函数主要进行各项初始化工作。对于第一个启动的核,需要依次进行以下工作: * 初始化printf(printf使用SBI_PUTCHAR实现) * 解析设备树,获得内存大小信息 * 虚拟内存和物理内存初始化 * 块缓存初始化 * **开启分页** * 初始化中断处理和核内时钟 * 初始化中断控制器 * 使用 `SBI_HART_START` 启动其他核 * **等待其他核启动完毕** * 初始化virtio驱动 * 初始化根文件系统 * **开启 `init` 进程** 要求等待其它核启动完毕之后才能初始化virtio驱动,是考虑到了virtio驱动在读写时会产生中断,而virtio中断会随机分配到一个核上。当收到中断的核处于未启动的M态时,没有配置virtio中断处理程序,会导致virtio初始化失败。所以我们需要在初始化virtio之前保证所有核都已启动。 虽然说一个核就能完成大部分初始化工作,但因为架构要求,多核还是有一些需要各自初始化的代码。多核环境下需要注意这些事项: * 每个核需要设置独立的页表。允许各个核在运行阶段使用不同的页表 * 每个核有独立的核内时钟,为每个核单独计时 * 每个核有独立的中断处理向量,我们一般将其设为同一个位置 * 每个核有独立的外部中断控制器 * 当一个核与其他核访问同一个变量或同一块内存时,为了缓存能够及时同步,需要加 `fence` 指令,保证之前的所有读写指令在fence之后都已同步到内存。对应gcc的语法为 `__sync_synchronize()` 下面是其他核初始化阶段完成的功能: * **开启分页** * 初始化中断处理向量 * 初始化核内时钟 * 初始化中断控制器 至此,启动阶段结束。 ### 附录 OpenSBI支持使用下列三种方式编译固件: 1. 带有动态信息的固件(FW_DYNMIC): FW_DYNAMIC固件在运行时从**上一个引导阶段**获取**下一个引导阶段入口**的信息(可以理解为承上启下的作用 (#^.^#) ),下一个引导阶段为:引导加载程序或操作系统内核。 * 下一个启动阶段(如bootloader)和FW_DYNAMIC被上一个启动阶段加载(如LOADER) * 上一个启动阶段(即LOADER)通过 `a2` 寄存器将 `struct fw_dynamic_info` 的位置传递给FW_DYNAMIC * 之前的启动阶段(即LOADER)需要知道 `struct fw_dynamic_info`(这个结构体包含下一个阶段的起始地址、特权级状态等) ![img](./assets/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAcmljaGFyZC5kYWk=,size_20,color_FFFFFF,t_70,g_se,x_16.png) 2. 带跳转地址的固件(FW_JUMP)(我们正在用的) ![img](./assets/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAcmljaGFyZC5kYWk=,size_20,color_FFFFFF,t_70,g_se,x_16-1683351875424-10.png) FW_JUMP固件假设下一个引导阶段入口的地址是固定的,例如引导加载程序或操作系统内核,而不直接包含下一个阶段的二进制代码。 * 下一个启动阶段(bootloader), 上一个启动阶段(LOADER)加载FW_JUMP * 这对**QEMU**非常有用,因为我们可以使用预编译的FW_JUMP * 上一个启动阶段(即LOADER)必须在一个固定的位置加载下一个启动阶段(即bootloader) * 没有机制将参数从之前的启动阶段(即LOADER)传递给FW_JUMP 3. 带负载的固件(FW_PAYLOAD) ![img](./assets/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAcmljaGFyZC5kYWk=,size_20,color_FFFFFF,t_70,g_se,x_16-1683351880927-13.png) FW_PAYLOAD固件直接包含了OpenSBI固件执行后启动阶段的二进制代码。通常,这个有效负载将是一个引导加载程序或一个OS内核。 1. OpenSBI FW_PAYLOAD可以是任何 S-mode的 bootloader/os 镜像文件。 2. 允许重写设备树blob(即DTB) 3. **非常适合sifve unmached板子** 4. 每当OpenSBI或BOOTLOADER (U-Boot)改变时,我们必须重新创建FW_PAYLOAD映像 5. 上一个启动阶段(LOADER)不会传递参数给下一个启动阶段
#pragma once #include <stdbool.h> #include "session.h" typedef enum { CELL_EMPTY, CELL_BEEPER, CELL_ENERGIZER } CellType; typedef struct { bool exists; bool is_vertical; } WallState; typedef struct { int label_pos_x, label_pos_y; int beepers_count; int width, height; CellType **cell_matrix; WallState **wall_matrix; EntityState player; EntityState player_home_state; EntityState hunters[HUNTERS_COUNT]; EntityState hunters_home_states[HUNTERS_COUNT]; } World; void world_init(World *world, const char *world_path); int world_read_name(char *name_buffer, const char *world_path); void world_free(World *world); CellType* world_get_cell(World *world, int x, int y); WallState* world_get_wall(World *world, int wall_x, int wall_y); WallState* world_get_wall_dir(World *world, int cell_x, int cell_y, Direction dir); bool world_get_wall_coords(World *world, int *cell_x, int *cell_y, Direction dir); bool world_get_cell_neighbour(World *world, int *cell_x, int *cell_y, Direction dir); bool world_cell_in_bounds(World *world, int x, int y); bool world_wall_in_bounds(World *world, int x, int y); float world_cell_distance(int x_1, int y_1, int x_2, int y_2); bool char_to_dir(int c, Direction *dir); Direction direction_opposite(Direction dir); bool entity_front_is_clear(EntityState *entity, World *world); bool entity_dir_is_clear(EntityState *entity, World *world, Direction dir); void entity_step(EntityState *entity, World *world); void entity_reset_prev_pos(EntityState *entity);
import cv2 import mediapipe as mp import math from pyfirmata import Arduino, SERVO # Connect to Arduino board = Arduino('com10') # Replace '/dev/ttyUSB0' with the serial port of your Arduino # Define servo pins servo_pin_x = 8 # Example pin for horizontal servo servo_pin_y = 10 # Example pin for vertical servo # Configure servo pins board.digital[servo_pin_x].mode = SERVO board.digital[servo_pin_y].mode = SERVO # Initialize PWM signal for servo motors pwm_x = board.get_pin('d:{}:s'.format(servo_pin_x)) pwm_y = board.get_pin('d:{}:s'.format(servo_pin_y)) # Load Mediapipe solutions mp_drawing = mp.solutions.drawing_utils mp_holistic = mp.solutions.holistic # Initialize Holistic model holistic = mp_holistic.Holistic(static_image_mode=False, min_detection_confidence=0.5, min_tracking_confidence=0.5) # Initialize video capture cap = cv2.VideoCapture(0) while cap.isOpened(): ret, frame = cap.read() if not ret: break # Convert the image to RGB frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Process the image to detect landmarks results = holistic.process(frame_rgb) # Draw landmarks on the image if results.pose_landmarks: # Get landmarks for right shoulder, elbow, and wrist right_shoulder = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_SHOULDER] right_elbow = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_ELBOW] right_wrist = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_WRIST] # Convert landmarks to pixel coordinates h, w, _ = frame.shape right_shoulder_px = int(right_shoulder.x * w), int(right_shoulder.y * h) right_elbow_px = int(right_elbow.x * w), int(right_elbow.y * h) right_wrist_px = int(right_wrist.x * w), int(right_wrist.y * h) # Draw points for right shoulder, elbow, and wrist cv2.circle(frame, right_shoulder_px, 5, (255, 0, 0), -1) cv2.circle(frame, right_elbow_px, 5, (0, 255, 0), -1) cv2.circle(frame, right_wrist_px, 5, (0, 0, 255), -1) # Draw line between right shoulder and right elbow cv2.line(frame, right_shoulder_px, right_elbow_px, (0, 255, 0), 2) # Calculate angle between right shoulder, elbow, and wrist shoulder_elbow_vec = (right_shoulder_px[0] - right_elbow_px[0], right_shoulder_px[1] - right_elbow_px[1]) elbow_wrist_vec = (right_elbow_px[0] - right_wrist_px[0], right_elbow_px[1] - right_wrist_px[1]) # Calculate angle using dot product formula dot_product = shoulder_elbow_vec[0] * elbow_wrist_vec[0] + shoulder_elbow_vec[1] * elbow_wrist_vec[1] shoulder_elbow_length = math.sqrt(shoulder_elbow_vec[0] ** 2 + shoulder_elbow_vec[1] ** 2) elbow_wrist_length = math.sqrt(elbow_wrist_vec[0] ** 2 + elbow_wrist_vec[1] ** 2) if shoulder_elbow_length != 0 and elbow_wrist_length != 0: angle_radians = math.acos(dot_product / (shoulder_elbow_length * elbow_wrist_length)) angle_degrees = math.degrees(angle_radians) cv2.putText(frame, f'Angle: {angle_degrees:.2f} degrees', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) # Move servo motors based on angle pwm_x.write(angle_degrees) pwm_y.write(angle_degrees) # Display the resulting image cv2.imshow('Pose Detection and Servo Control', frame) # Break the loop if 'q' key is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # Release resources cap.release() cv2.destroyAllWindows()
import { z } from "zod"; export const createLinkFormSchema = z.object({ target: z.string().url({ message: "target needs to be a valid URL", }), slug: z .string() .min(2, { message: "slug has to be longer than 2 characters", }) .max(128, { message: "slug has to be shorter than 128 characters", }) .regex(/^[a-zA-Z1-9_-]+$/, { message: "slug cannot have any special characters", }), }); export type CreateLinkFormSchema = typeof createLinkFormSchema;
import { createStore } from "zustand/vanilla"; import { type User } from "@/types"; // Modal types export enum ModalType { addUser = "AddUser", editUser = "EditUser", } // Data for the modal export interface ModalData { user?: User; } // Modal state export type ModalState = { type: ModalType | null; isOpen: boolean; data?: ModalData; }; // Modal actions export type ModalActions = { onOpen: (type: ModalType, data?: ModalData) => void; onClose: () => void; }; // Combining modal state and actions to create modal store type export type ModalStore = ModalState & ModalActions; // Initial state for modal store export const initModalStore = (): ModalState => { return { type: null, isOpen: false }; }; // Default initial state for modal store export const defaultInitState: ModalState = { type: null, isOpen: false, }; // Creating function to create modal store export const createModalStore = (initState: ModalState = defaultInitState) => { return createStore<ModalStore>()((set) => ({ ...initState, onOpen: (type, data) => { set({ isOpen: true, type, data }); }, onClose: () => { set({ isOpen: false }); }, })); };
<!DOCTYPE html> <meta charset="utf-8"> <html> <head> <title>Cities I've Been To</title> <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" /> <!--[if lte IE 8]> <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.ie.css" /> <![endif]--> <script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <style type="text/css"> #map { width: 1000px; height: 650px; } </style> </head> <body> <h1></h1> <div id="map"></div> <script type="text/javascript"> var visitedIcon = L.icon({ iconUrl: 'visited.png', iconSize: [32, 37], shadowSize: [0, 0], iconAnchor: [16, 37], shadowAnchor: [0, 0], popupAnchor: [0, -37] }); var uncertainIcon = L.icon({ iconUrl: 'uncertain.png', iconSize: [32, 37], shadowSize: [0, 0], iconAnchor: [16, 37], shadowAnchor: [0, 0], popupAnchor: [0, -37] }); var map = L.map('map') .setView([37.857507, -85.632935], 7); var basemap = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>', subdomains: 'abcd', maxZoom: 19 }).addTo(map); // map function onEachFeature(feature, layer) { layer.bindPopup(feature.properties.City + ", " + feature.properties.State + ", " + feature.properties.Country); } $.getJSON("buffer.geoJSON", function (cities) { // pull data from external file L.geoJson(cities, { onEachFeature: onEachFeature, pointToLayer: function (feature, latlng) { switch (feature.properties.Remember) { case '1': return L.marker(latlng, {icon: visitedIcon}); case '?': return L.marker(latlng, {icon: uncertainIcon}); case '0': return L.marker(latlng, {icon: uncertainIcon}); } } }).addTo(map); }) L.tileLayer('http://tile.cloudmade.com/[api-key]/7/256/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>', maxZoom: 18 }).addTo(map); </script> </body> </html>
import React from 'react'; import {fireEvent, render, waitFor} from '@testing-library/react-native'; import App from '../App'; import 'jest-fetch-mock'; import {Hotels} from '../__mocks__/Hotel'; describe('App', () => { it('renders correctly', async () => { fetchMock.mockOnce(JSON.stringify(Hotels)); const app = render(<App />); await waitFor(() => { app.getAllByTestId('list-item'); }); expect(app.toJSON()).toMatchSnapshot(); }); it('should sort by rating', async () => { fetchMock.mockOnce(JSON.stringify(Hotels)); const Screen = render(<App />); await waitFor(() => { fireEvent.press(Screen.getByTestId('icon-button-sort')); const picker = Screen.getByTestId('sort-picker'); fireEvent(picker, 'onValueChange', 'rating'); fireEvent.press(Screen.getByTestId('apply')); }); const name = Screen.getAllByTestId('list-item-name')[0].children[0]; expect(name).toBe('Park Plaza London Waterloo'); }); it('should sort by stars', async () => { fetchMock.mockOnce(JSON.stringify(Hotels)); const Screen = render(<App />); await waitFor(() => { fireEvent.press(Screen.getByTestId('icon-button-sort')); const picker = Screen.getByTestId('sort-picker'); fireEvent(picker, 'onValueChange', 'stars'); fireEvent.press(Screen.getByTestId('apply')); }); const name = Screen.getAllByTestId('list-item-name')[0].children[0]; expect(name).toBe('Absolute Pleasure Yacht'); }); it('should sort by price ascending', async () => { fetchMock.mockOnce(JSON.stringify(Hotels)); const Screen = render(<App />); await waitFor(() => { fireEvent.press(Screen.getByTestId('icon-button-sort')); const pickerCategory = Screen.getByTestId('sort-picker'); fireEvent(pickerCategory, 'onValueChange', 'price'); const pickerOrder = Screen.getByTestId('order-picker'); fireEvent(pickerOrder, 'onValueChange', 'ascending'); fireEvent.press(Screen.getByTestId('apply')); }); const name = Screen.getAllByTestId('list-item-name')[0].children[0]; expect(name).toBe('Absolute Pleasure Yacht'); }); });
// COPYRIGHT DASSAULT SYSTEMES 2016 // // Usage notes: // // Forked from CATCrvLengths 11/16 to support more measures // Simplified interface to support CATBodyFromLengthOnWire reqs. #ifndef CATCrvMeasures_H #define CATCrvMeasures_H // ExportedBy #include "Y30UIUTI.h" // Base class #include "CATGeoOperator.h" // C++11 #include "CATGeoOpVirtual.h" #include <stdlib.h> #include "CATMathInline.h" #include "CATString.h" #include "CATDataType.h" #include "CATListPV.h" #include "CATListOfInt.h" #include "CATSkillValue.h" #include "CATCurve.h" #include "CATCGMVirtual.h" #include "CATGeoFactory.h" class CATLaw; class CATCurve ; class CATSoftwareConfiguration; #include "CATGeoOpTimer.h" #include "CATExtCGMReplay.h" #include "CATCGMStream.h" #include "CATCGMOutput.h" #include "CATBodyFromLengthOnWireMeasureType.h" //#include "CATCGMOperatorDebug.h" // class CATCrvLengthsDebug; class CATCrvMeasuresImpl; class ExportedByY30UIUTI CATCrvMeasures : public CATGeoOperator { CATCGMVirtualDeclareClass(CATCrvMeasures); public: /** * Creator ... */ static CATCrvMeasures * Create( CATSoftwareConfiguration * iConfig, const CATCurve *iCRV, CATBodyFromLengthOnWireMeasureType iType ) ; virtual ~CATCrvMeasures(); /** * Set relative tolerance w.r.t factory resolution: * Default value is "Factory Resolution". */ virtual void SetRelativeTolerance ( double iTOL ); /** * use the existing engine on a new curve ... */ virtual void SetCurve( const CATCurve *iCRV ); /** * Set curve interval: Default values are the iCRV limits. Empty * argument, i.e. (1.0, 0.0), returns to the iCRV limits. * params are reset if SetCurve is used. */ virtual void SetCurveInterval( double iLowParam = 1.0, double iHighParam = 0.0 ); /** * Return the type of measure used: * Arc length (0) or Integrated turning angle (1) */ virtual int GetMeasureType() const; /** * Run */ virtual int Run(); /** * @nodoc @nocgmitf (internal) RunOperator ... Executes the set methods above. */ virtual int RunOperator(); /** * The measure from iCRV(iLowParam) to iCRV(iParU) will be returned. * iOrder is the order of the requested evaluation: * 0: measure. * 1: the first derivative of measure with respect to the param. * 2: the second derivative of measure with respect to the param. * * The derivatives are evaluated on the polynomial approximation and not * directly on the curve. */ double GetMeasureFromCurveParam ( double iParU , int iOrder = 0); /** * Get measure from iCRV(iLowParam), to iParM. The global curve param (ParU) * will be returned. * iOrder is the order of the requested evaluation: * 0: the param. * 1: the first derivative of the param with respect to the length. * 2: the second derivative of the param with respect to the length. * * The derivatives are evaluated on the polynomial approximation and not * directly on the curve. */ double GetCurveParamFromMeasure ( double iParM , int iOrder = 0); /** * Get measure from iCRV(iLowParam), to iParM. The global curve param (ParU) * will be returned. * iOrder is the order of the requested evaluation: * 0: the param. * 1: the param and the first derivative of the param with respect to the measure. * 2: the param the first and the second derivative of the param with respect to the measure. * iParam the result allcated by caller * iParam[0] : param ; iParam[1] : first derivative ; iParam[2] : second derivative */ void GetCurveParamFromMeasure ( double iParM , int iOrder, double *oMeasure); /** *Get total curve measure */ double GetTotalCurveMeasure(); private: /** * iType=0 enables Arc length spacing measure which specifies the curve length between sample points. * iType=1 enables Integrated turning spacing measure which specifies the total amount the tangent vector * changes between sample points. Jumps in the tangent vector between edges will be ignored. The expectation is that at vertices, edge pairs are G1 continuous. **/ CATCrvMeasures( CATSoftwareConfiguration * iConfig, const CATCurve* iCRV, CATBodyFromLengthOnWireMeasureType iType) ; CATCrvMeasuresImpl* _Impl; public: // CGMReplay Implementation - SKA Creation /** @nodoc @nocgmitf */ virtual const CATString * GetOperatorId(); virtual CATGeoOpTimer * GetTimer(); /** @nodoc @nocgmitf */ virtual CATExtCGMReplay * IsRecordable(short & LevelOfRuntime, short &VersionOfStream); /** @nodoc @nocgmitf */ virtual void WriteInput(CATCGMStream & Str); /** @nodoc @nocgmitf */ virtual void Dump( CATCGMOutput& os ) ; /** @nodoc @nocgmitf */ virtual void WriteOutput(CATCGMStream & Str); /** @nodoc @nocgmitf */ virtual void DumpOutput(CATCGMOutput & os) ; /** @nodoc @nocgmitf */ virtual void DumpOutput(CATCGMStream& Str, CATCGMOutput& os,int VersionNumber=1); /** @nodoc @nocgmitf */ virtual CATBoolean ValidateOutput(CATCGMStream& Str, CATCGMOutput & os,int VersionNumber=1); /** @nodoc @nocgmitf */ virtual CATCGMOperator::CATCheckDiagnostic CheckOutput(CATCGMOutput & os); }; #endif
package br.com.adatask.service.impl; import br.com.adatask.domain.BaseTask; import br.com.adatask.repository.Repository; import br.com.adatask.service.Service; import java.lang.reflect.InvocationTargetException; import java.util.List; public class ServiceImpl implements Service { private final Repository<BaseTask, Long> repository; public ServiceImpl(Repository<BaseTask, Long> repository) { this.repository = repository; } public void createTask(Class<? extends BaseTask> taskClass, String title, String description, String deadline) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { BaseTask task = taskClass.getConstructor(String.class, String.class, String.class).newInstance(title, description, deadline); repository.add(task); } public BaseTask filterTaskByTitle(String title) { return repository.find(title); } public BaseTask filterTaskById(Long id) { return repository.findById(id); } public void editTask(String title, String newTitle, String newDescription, String newDeadline) { BaseTask task = repository.find(title); if (task != null) { task.setTitle(newTitle); task.setDescription(newDescription); task.setDeadline(newDeadline); repository.update(task); } } public void removeTask(String title) { BaseTask task = repository.find(title); if (task != null) { repository.remove(task); } } public List<BaseTask> listAllTasks() { return repository.listAll(); } public List<BaseTask> filterByType(Class<? extends BaseTask> type) { return repository.filterBy(type); } }
import 'dart:convert'; import 'package:flut_api/network/network_enums.dart'; import 'package:flut_api/network/network_typedef.dart'; import 'package:http/http.dart' as http; class NetworkHelper{ const NetworkHelper._(); static String concatUrlQP(String url, Map<String, String>? queryParameters) { if (url.isEmpty) return url; if (queryParameters == null || queryParameters.isEmpty) { return url; } final StringBuffer stringBuffer = StringBuffer("$url?"); queryParameters.forEach((key, value) { if (value.trim() == '') return; if (value.contains(' ')) throw Exception('Invalid Input Exception'); stringBuffer.write('$key=$value&'); }); final result = stringBuffer.toString(); return result.substring(0, result.length - 1); } static bool _isValidResponse(json) { return json != null && json['status'] != null && json['status'] == 'ok' && json['articles'] != null; } static R filterResponse<R>({ required NetworkCallBack callBack, required http.Response? response, required NetworkOnFailureCallBackWithMessage onFailureCallBackWithMessage, CallBackParameterName parameterName = CallBackParameterName.all }) { try { if(response == null || response.body.isEmpty) { return onFailureCallBackWithMessage(NetworkResponseErrorType.responseEmpty, 'empty response'); } var json = jsonDecode(response.body); if(response.statusCode == 200) { if(_isValidResponse(json)) { return callBack(parameterName.getJson(json)); } } else if(response.statusCode == 1708) { return onFailureCallBackWithMessage(NetworkResponseErrorType.socket, 'Socket'); } return onFailureCallBackWithMessage(NetworkResponseErrorType.didNotSucceed, 'Unknown'); } catch(e) { return onFailureCallBackWithMessage(NetworkResponseErrorType.exception, 'Exception $e'); } } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>회원가입</title> <style> .input{width: 150px;} </style> </head> <body> <h2>Practice3</h2> <form> <fieldset> <legend>회원가입</legend> <label for="id">아이디 : </label><input type="text" id="id" class="input" onkeyup="checkId();"> <span id="existId"></span><br><br> <label for="pwd1">비밀번호 : </label><input type="password" id="pwd1" class="input" onblur="checkPwd()"> <br><br> <label for="pwd2">비밀번호 확인 : </label><input type="password" id="pwd2" class="input" onblur="checkPwd()"> <span id="equalPwd"></span><br><br> <label for="name">이름 : </label><input type="text" id="name" class="input"> <br><br> <!-- <input type="submit" value="회원가입" onclick="return enroll();"> --> <input type="button" value="회원가입" onclick="enroll();"> </fieldset> </form> <script> var existId = document.getElementById('existId'); var equalPwd = document.getElementById('equalPwd'); function checkId() { var inputId = document.getElementById('id').value.trim(); var check = checkUser(inputId); if (inputId == '' || inputId.length == 0) { existId.innerHTML = ''; } else if (check != 1) { existId.innerHTML = ' 사용가능한 아이디입니다.'; existId.style.color = 'green'; existId.value = 'success'; // 대신 전역변수 하나 만들어서 true니 false값 줘도 됨 } else { existId.innerHTML = ' 이미 존재하는 아이디입니다.'; existId.style.color = 'red'; existId.value = 'fail'; } } function checkUser(inputId) { var userId = 'user01'; if (inputId == userId) { return 1; } else { return 0; } } function checkPwd() { var inputPwd = document.getElementById('pwd1').value; var inputPwd2 = document.getElementById('pwd2').value; // var result = document.getElementById('result2'); if (inputPwd == inputPwd2) { equalPwd.innerHTML = ' 비밀번호가 일치합니다.' equalPwd.style.color = 'green'; equalPwd.value = 'success'; } else { equalPwd.innerHTML = ' 비밀번호가 일치하지 않습니다.' equalPwd.style.color = 'red'; equalPwd.value = 'fail'; } if (inputPwd2 == '' || inputPwd2.length == 0) { equalPwd.innerHTML = ''; } } /* function checkPwd2() { var inputPwd = document.getElementById('pwd1').value; var inputPwd2 = document.getElementById('pwd2').value; if (inputPwd != inputPwd2) { return 1; } } */ function enroll() { var id = document.getElementById('id'); var pwd1 = document.getElementById('pwd1'); var pwd2 = document.getElementById('pwd2'); var name = document.getElementById('name'); // var checkPwd = checkPwd2(); // 위 변수들 전역변수로 선언 및 초기화(값 할당)해서 이용하는 것이 편함 if (id.value.trim() == '' || id.value.length == 0) { alert('아이디를 입력해주세요.'); id.focus(); } else if (pwd1.value == '' || pwd1.value.length == 0) { alert('비밀번호를 입력해주세요.'); pwd1.focus(); } else if (pwd2.value == '' || pwd2.value.length == 0) { alert('비밀번호 확인을 입력해주세요.'); pwd2.focus(); } else if (name.value == '' || name.value.length == 0) { alert('이름을 입력해주세요.'); name.focus(); } else if (existId.value == 'fail') { alert ('사용할 수 없는 아이디입니다.') id.value = ''; id.focus(); } else if (equalPwd.value == 'fail' || pwd1.value != pwd2.value) { alert ('비밀번호가 일치하지 않습니다.') pwd2.value = ''; pwd2.focus(); } else { alert(name.value + '님, 회원가입이 성공적으로 완료되었습니다^^'); id.value = ''; // button 타입일시 필요/ submit타입일시 필요x pwd1.value = ''; pwd2.value = ''; name.value = ''; existId.innerHTML = ''; // 아이디와 비밀번호확인 옆 span영역도 비워줌 equalPwd.innerHTML = ''; // return true; // submit타입일시 필요 } // return false; // submit타입일시 필요 } </script> </body> </html>
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Character.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ffornes- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/03/18 10:03:07 by ffornes- #+# #+# */ /* Updated: 2024/03/22 11:42:24 by ffornes- ### ########.fr */ /* */ /* ************************************************************************** */ #include "Character.hpp" #include <iostream> void Character::deleteInventory( void ) { for ( int i = 0; i < 4; i++ ) { if (this->_inventory[i]) delete this->_inventory[i]; this->_inventory[i] = NULL; } } Character::Character( void ) { this->_name = "Default_character"; for ( int i = 0; i < 4; i++ ) this->_inventory[i] = NULL; this->_amount = 0; } Character::Character( std::string name ) { this->_name = name; for ( int i = 0; i < 4; i++ ) this->_inventory[i] = NULL; this->_amount = 0; } Character::~Character( void ) { deleteInventory(); } Character::Character( const Character& old ) : ICharacter() { *this = old; } Character& Character::operator=( const Character& old ) { if (this != &old) { this->_name = old._name; this->_amount = old._amount; deleteInventory(); for ( int i = 0; i < 4; i++ ) if (old._inventory[i]) this->_inventory[i] = old._inventory[i]->clone(); } return (*this); } std::string const & Character::getName( void ) const { return (this->_name); } void Character::equip( AMateria *m ) { if (!m) std::cerr << "Materia recieved is NULL\n"; else if (this->_amount >= 4) { std::cerr << "Unable to equip new materia since inventory is full" << std::endl; return ; } else { for ( int i = 0; i < 4; i++ ) { if (this->_inventory[i] == m) { std::cerr << this->_name << " already has this materia\n"; return ; } } for ( int i = 0; i < 4; i++ ) { if (!this->_inventory[i]) { std::cout << "Equipped new materia in slot " << i << std::endl; this->_inventory[i] = m; this->_amount++; return ; } } } std::cout << "Unable to equip new materia since slot is full\n"; } void Character::unequip( int idx ) { if (idx < 0 || idx > 3) { std::cerr << "Index out of range" << std::endl; return ; } else if (!this->_inventory[idx]) { std::cerr << "There's no materias in this inventory slot" << std::endl; } else { std::cout << "Unequipped materia in slot " << idx << std::endl; this->_inventory[idx] = NULL; this->_amount--; } } void Character::use( int idx, ICharacter& target ) { if (idx < 0 || idx > 3) std::cerr << "Index out of range" << std::endl; else if (!this->_inventory[idx]) std::cerr << "There's no materia in index " << idx << std::endl; else if (this->_inventory[idx]->getType() == "ice") std::cout << "* shoots an ice bolt at " << target.getName() << std::endl; else if (this->_inventory[idx]->getType() == "cure") std::cout << "* heals " << target.getName() << "'s wounds *" << std::endl; }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AngularFireModule } from '@angular/fire/compat'; import { AngularFireAuthModule } from '@angular/fire/compat/auth'; import { AngularFirestoreModule } from '@angular/fire/compat/firestore'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { environment } from '../environments/environment'; import { AppComponent } from './app.component'; import { LoginComponent } from './components/login/login.component'; import { RegistroComponent } from './components/registro/registro.component'; import { SharedModule } from './shared/shared.module'; import { EncuestaComponent } from './components/page/encuesta/encuesta.component'; import { RespuestasComponent } from './components/page/respuestas/respuestas.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, RegistroComponent, EncuestaComponent, RespuestasComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, AngularFireModule.initializeApp(environment.firebase), AngularFireAuthModule, AngularFirestoreModule, HttpClientModule, SharedModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
package main import ( "bufio" "encoding/binary" "fmt" "io/ioutil" "log" "os" "strings" ) func main() { // Get image path from user fmt.Print("Enter the image path: ") scanner := bufio.NewScanner(os.Stdin) scanner.Scan() imagePath := scanner.Text() // Read image file into byte slice data, err := ioutil.ReadFile(imagePath) if err != nil { log.Fatal(err) } // Get the base name of the input image without extension imageBaseName := strings.TrimSuffix(imagePath, ".jpg") // Loop through EXIF data and convert endianness for i := 0; i < len(data); i++ { if i >= 6 && string(data[i:i+5]) == "Exif\x00" { data = convertExifByteOrder(data, i+6) break } } // Generate the output image name based on the input image name outputImagePath := fmt.Sprintf("%s-modified.jpg", imageBaseName) // Write modified image back to file err = ioutil.WriteFile(outputImagePath, data, 0644) if err != nil { log.Fatal(err) } fmt.Printf("Modified image saved as %s\n", outputImagePath) } func convertExifByteOrder(data []byte, offset int) []byte { // Read exif byte order marker order := binary.LittleEndian.Uint16(data[offset:]) // If little endian, convert to big endian if order == 0x4949 { binary.BigEndian.PutUint16(data[offset:], 0x4D4D) } // If big endian, convert to little endian if order == 0x4D4D { binary.LittleEndian.PutUint16(data[offset:], 0x4949) } return data }
// // MovieDBAPI.m // MovieDB in Objective-C // // Created by Diego Henrique on 24/03/22. // // #import "MovieDBAPI.h" @interface MovieDBAPI () @end @implementation MovieDBAPI - (void)requestGenres: (void (^)(NSDictionary *, NSError *))completion { NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://api.themoviedb.org/3/genre/movie/list?api_key=2c84bee7ec597369d0b15bc1d8b7d41e&language=en-US"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { // convert the NSData response to a dictionary NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (error) { // there was a parse error...maybe log it here, too completion(nil, error); } else { // success! completion(dictionary[@"genres"], nil); } } else { // error from the session...maybe log it here, too completion(nil, error); } }]; [dataTask resume]; } - (void)requestTotalPagesWithURL:(NSString*)url completion:(void (^)(NSNumber*, NSError *))completion { NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString: url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { // convert the NSData response to a dictionary NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; NSNumber *pages = dictionary[@"total_pages"]; if (error) { // there was a parse error...maybe log it here, too completion(nil, error); } else { // success! completion(pages, nil); } } else { // error from the session...maybe log it here, too completion(nil, error); } }]; [dataTask resume]; } - (void)requestMoviePosterWithURL:(NSString*)url completion:(void (^)(UIImage *, NSError *))completion { NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%s%@", "https://image.tmdb.org/t/p/original", url]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { // convert the NSData response to a dictionary completion([UIImage imageWithData:data], nil); } else { // error from the session...maybe log it here, too completion(nil, error); } }]; [dataTask resume]; } - (void)requestPopularMoviesFromPage:(NSNumber*)page completion:(void (^)(NSArray *, NSError *))completion { NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%s%@", "https://api.themoviedb.org/3/movie/popular?api_key=2c84bee7ec597369d0b15bc1d8b7d41e&language=en-US&page=", page]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { // convert the NSData response to a dictionary NSDictionary *dictionaries = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (error) { // there was a parse error...maybe log it here, too completion(nil, error); } else { // success! completion(dictionaries[@"results"], nil); } } else { // error from the session...maybe log it here, too completion(nil, error); } }]; [dataTask resume]; } - (void)requestNowPlayingMoviesFromPage:(NSNumber*)page completion:(void (^)(NSArray *, NSError *))completion { NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%s%@", "https://api.themoviedb.org/3/movie/now_playing?api_key=2c84bee7ec597369d0b15bc1d8b7d41e&language=en-US&page=", page]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { // convert the NSData response to a dictionary NSDictionary *dictionaries = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (error) { // there was a parse error...maybe log it here, too completion(nil, error); } else { // success! completion(dictionaries[@"results"], nil); } } else { // error from the session...maybe log it here, too completion(nil, error); } }]; [dataTask resume]; } @end
# Title: 2023 Advent of Code -- Day 1 Part 1: Trebuchet?! # Author: Roshan Darji # Date: 2023-12-09 import numpy as np def parse_string(string): # Extract first and last digit from string first_digit = next(char for char in string if char.isdigit()) last_digit = next(char for char in reversed(string) if char.isdigit()) # Concatenate and return digits as integer return int(first_digit + last_digit) # Tests for parse_string assert parse_string("abc123") == 13 assert parse_string("abc123def456") == 16 assert parse_string("1abc2") == 12 assert parse_string("pqr3stu8vwx") == 38 assert parse_string("a1b2c3d4e5f") == 15 assert parse_string("treb7uchet") == 77 # Read input file with open("day-1/d1p1-input.txt", "r") as f: input = f.read().splitlines() # Parse input file input = np.array([parse_string(string) for string in input]) # Sum all integers in input print(np.sum(input))
# Me Meo :doctype: book :docname: Me Meo :author: Paula Pousa y Jorge Sol :revdate: {localdate} :imagesdir: {docdir}/images :toc: left :toclevels: 5 :pdf-theme: themes/my-theme.yml ## Funcionalidades ### ¿En qué Consiste la Aplicación? Nuestra aplicación, apodada *Me Meo* es una aplicación móvil que muestra los cuartos de baño públicos que hay en Madrid. La aplicación localiza tu posición y aparecen en el mapa marcados los cuartos de baño mas cercanos, al pulsar sobre uno de ellos puedes ver una foto de como se encuentra el baño y puedes mostrar la ruta mas corta para llegar andando hasta él. ### Autenticación de Usuarios Para autenticar a los usuarios y poder mantener un registro de quienes se han logado en nuestra aplicación, se ha utilizado *FireBase* de _Google_ el cual ha permitido autenticar a usuarios con correo y contraseña, o si el usuario lo prefiere, con su cuenta de _Google_. En todos los casos, los usuarios reciben un correo electrónico cuando su usuario se crea correctamente. La aplicación es inteligente, y si se abre por segunda vez, se verifica contra firebase para ver si el usuario ya estaba logado y así no se le vuelve a pasar por la página de login. image::login.jpg ### Conexiones a una API La API que se ha utilizado en el proyecto es la API de autobuses de Madrid (link:https://apidocs.emtmadrid.es/[API EMT Madrid]), la cual tiene una funcionalidad que te dice como llegar desde un punto A a un punto B andando. Esta información la devuelve en forma de coordenadas con un texto descriptivo explicando que calle debes tomar o que giro debes realizar. En la aplicación se muestra mediante una línea la ruta y se marca con puntos el detalle de la calle o giro que debes tomar. ### Información de los Cuartos de Baño La información de los cuartos de baño es sacada de un conjunto de datos que se encuentran publicados en link:https://datos.madrid.es/sites/v/index.jsp?vgnextoid=edcaaa8cf6bda510VgnVCM1000001d4a900aRCRD&vgnextchannel=374512b9ace9f310VgnVCM100000171f5a0aRCRD[xxx] donde tienes la opción de descargar un archivo con la información de las coordenadas y calle donde se encuentra el cuarto de baño. Al ser un archivo muy ligero, viene incorporado en la aplicación junto al resto del código. image::mapa-baños.jpg ### Recogida de Datos de Sensores Para los sensores se ha hecho uso de la geolocalización del dispositivo móvil con ayuda de los sensores que tiene incorporados. Y también se ha utilizado la cámara trasera del móvil para tomar fotografías. ### GPS y Mapa Con ayuda de la latitud y longitud que se recuperan de los sensores, se ha podido geolocalizar al usuario autenticado, y con ayuda de link:https://www.openstreetmap.org[Open Street Map] se muestra al usuario un mapa con su localización. En este mismo mapa se muestran también los cuartos de baño, y cuando un usuario desea obtener indicaciones para llegar a alguno de los cuartos de baño, es en este mismo mapa donde se le muestra la ruta que debe seguir. [cols="a,a", frame=none, grid=none] |=== | image::mapa-direcciones.jpg | image::baños-resultado.jpg |=== ### Persistencia de Datos en la Nube de Google De los datos que se gestionan en la aplicación, se persisten en la nube tanto los datos de los usuarios, como la última fotografía que se ha tomado de un cuarto de baño. Para ello se hace uso del *Storage* que proporciona _Firebase_. Cada imágen se guarda con el nombre de la calle en la que se encuentra, y cuando un usuario quiere ver la imágen lo único que tiene que hacer es pulsar sobre un cuarto de baño y la imágen se carga en la pantalla. ## Enlaces * Enlace al vídeo con audio (mp4): https://upm365-my.sharepoint.com/:v:/g/personal/jorge_sol_gonzalez_alumnos_upm_es/ERMNE4vMikhCqBtStLcc8tMBOZyQ691JckDW5fvUjp6cPg?e=cMX4on * Enlace al vídeo con audio (mkv): https://upm365-my.sharepoint.com/:v:/g/personal/jorge_sol_gonzalez_alumnos_upm_es/Ec1An43qLPJNm2V-Vi3UQGEBsfu8adeOrIMcaOoOm6PDEg?e=osqqtS * Enlace al repositorio de github: https://github.com/FORGIS98/master-android-sensores-api * Enlace a los datos públicos de baños de Madrid: https://datos.madrid.es/sites/v/index.jsp?vgnextoid=edcaaa8cf6bda510VgnVCM1000001d4a900aRCRD&vgnextchannel=374512b9ace9f310VgnVCM100000171f5a0aRCRD * Enlace a la API utilizada: https://apidocs.emtmadrid.es/ * Para poder consumir este API se debe crear un usuario en el portal de la EMT: https://mobilitylabs.emtmadrid.es/ * Una vez creado, se debe crear en el proyecto, el archivo "master-project-app/app/src/main/res/values/api_credentials.xml" * El contenido del archivo debe ser el siguiente, modificando el email y la contraseña por los utilizados en la EMT: [source,xml] ---- <?xml version="1.0" encoding="utf-8"?> <resources> <string name="client_id">[email protected]</string> <string name="client_secret">password</string> </resources> ----
# Vistas y Disparadores ## Vistas ### Horizontal Esta vista muestra todos los datos de los rescatistas, contactos y derrumbes en una fila para cada registro de derrumbe. ```sql CREATE VIEW Vista_Horizontal AS SELECT Rescatista.Nombre AS Nombre_Rescatista, Rescatista.Telefono AS Telefono_Rescatista, Contacto.Nombre AS Nombre_Contacto, Contacto.Telefono AS Telefono_Contacto, Derrumbe.Descripcion, Derrumbe.Necesidades, Derrumbe.Tipo_de_Dano, Derrumbe.Estatus FROM Derrumbe INNER JOIN Rescatista ON Derrumbe.ID_Contacto = Rescatista.ID INNER JOIN Contacto ON Derrumbe.ID_Contacto = Contacto.ID; ``` ```sql SELECT * FROM Vista_Horizontal; ``` ### Vertical Esta vista muestra todos los datos de los rescatistas, contactos y derrumbes en columnas separadas para cada registro de derrumbe. ```sql CREATE VIEW Vista_Vertical AS SELECT 'Rescatista' AS Tipo, ID, Nombre, Telefono, Horas, Puesto, NULL AS Descripcion, NULL AS Necesidades, NULL AS Tipo_de_Dano, NULL AS Estatus FROM Rescatista UNION ALL SELECT 'Contacto' AS Tipo, ID, Nombre, Telefono, NULL AS Horas, NULL AS Puesto, NULL AS Descripcion, NULL AS Necesidades, NULL AS Tipo_de_Dano, NULL AS Estatus FROM Contacto UNION ALL SELECT 'Derrumbe' AS Tipo, ID, NULL AS Nombre, NULL AS Telefono, NULL AS Horas, NULL AS Puesto, Descripcion, Necesidades, Tipo_de_Dano, Estatus FROM Derrumbe; ``` ```sql SELECT * FROM Vista_Vertical; ``` ### Agrupada Esta vista muestra la cantidad de derrumbes por estado. ```sql CREATE VIEW Vista_Agrupada AS SELECT Estado.Nombre AS Estado, COUNT(Derrumbe.ID) AS Cantidad_Derrumbes FROM Derrumbe INNER JOIN Direccion ON Derrumbe.ID_Direccion = Direccion.ID INNER JOIN Estado ON Direccion.ID_Estado = Estado.ID GROUP BY Estado.Nombre; ``` ```sql SELECT * FROM Vista_Agrupada; ``` ## Disparadores ```sql DELIMITER // CREATE TRIGGER UpdateRescatistaHours AFTER INSERT ON Derrumbe FOR EACH ROW BEGIN DECLARE rescatista_id INT; DECLARE horas_derrumbe INT; -- Get the Rescatista ID associated with the Derrumbe SELECT ID_Contacto INTO rescatista_id FROM Derrumbe WHERE ID = NEW.ID_Derrumbe; -- Get the hours associated with the Derrumbe SELECT horas INTO horas_derrumbe FROM Rescatista WHERE ID = rescatista_id; -- Update Rescatista hours UPDATE Rescatista SET Horas = Horas + horas_derrumbe WHERE ID = rescatista_id; END // DELIMITER ; ``` ```sql DELIMITER // CREATE TRIGGER UpdateDerrumbeStatus AFTER UPDATE ON Direccion FOR EACH ROW BEGIN DECLARE derrumbe_id INT; DECLARE estatus_actual VARCHAR(30); -- Get the Derrumbe ID associated with the updated Direccion SELECT ID_Derrumbe INTO derrumbe_id FROM Direccion WHERE ID = NEW.ID_Direccion; -- Get the current Estatus of the Derrumbe SELECT Estatus INTO estatus_actual FROM Derrumbe WHERE ID = derrumbe_id; -- Update Derrumbe Estatus based on Direccion update IF NEW.Colonia IS NULL THEN UPDATE Derrumbe SET Estatus = 'Dirección actualizada sin colonia' WHERE ID = derrumbe_id; ELSE UPDATE Derrumbe SET Estatus = 'Dirección actualizada con colonia' WHERE ID = derrumbe_id; END IF; END // DELIMITER ; ``` ```sql DELIMITER // CREATE TRIGGER set_default_ids AFTER INSERT ON Direccion FOR EACH ROW BEGIN SET NEW.ID_Ubicacion = NEW.ID; SET NEW.ID_Municipio = NEW.ID; SET NEW.ID_Estado = NEW.ID; END; // DELIMITER ; ```
package com.nbr.trp.agent.entity; import com.nbr.trp.common.entity.Address; import com.nbr.trp.common.entity.BankInformationDetails; import com.nbr.trp.user.entity.Role; import jakarta.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; import java.util.Date; import java.util.HashSet; import java.util.Set; @Entity @Setter @Getter @NoArgsConstructor @Table(name = "agent") public class Agent { @Id @GeneratedValue(strategy = GenerationType.UUID) @Column(columnDefinition = "uniqueidentifier default newid()") public String id; @Column(name = "name",nullable = false) public String name; @Column(name = "tin",nullable = false) public String tin; @Column(name = "phone") public String phone; @Column(name = "registration_type",nullable = false) public String registrationType; @Column(name = "registration_no",nullable = false) public String registrationNo; @Column(name = "registration_date",nullable = false) public Date registrationDate; @Column(name = "contact_person",nullable = false) public String contactPerson; @Column(name = "contact_number",nullable = false) public String contactNumber; @Column(name = "contact_email",nullable = false) public String contactEmail; @Column(name = "contact_designation") public String contactDesignation; @Column(name = "contact_photo") public String contactPhoto; // @Column(name = "business_address_id") // public int businessAddressId; // @Column(name = "current_address_id") // public int currentAddressId; // @Column(name = "permanent_address_id") // public int permanentAddressId; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinTable( name = "agent_bankinformation", joinColumns = @JoinColumn(name = "agent_id"), inverseJoinColumns = @JoinColumn(name = "bank_id") ) private Set<BankInformationDetails> bankinformation = new HashSet<>(); // @Column(name = "bank_information_id") // public String bankInformationId; // @Column(name = "dob") // public Date dob; // @Column(name = "father_name") // public String fatherName; // // @Column(name = "mother_name") // public String motherName; // // @Column(name = "spouse_name") // public String spouseName; @Column(name = "mobile_no") public String mobileNo; @Column(name = "reg_ass_nid") public String regAssNID; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinTable( name = "agent_address", joinColumns = @JoinColumn(name = "agent_id"), inverseJoinColumns = @JoinColumn(name = "address_id") ) private Set<Address> address = new HashSet<>(); // @ManyToMany public Agent(String uuid, String name, String tin, String phone, String registrationType, String regNo, String contactPerson, String contactNumber, String contactEmail, String contactDesignation, String contactPhoto/*, int businessAddressId, int currentAddressId, int permanentAddressId*/, Set<BankInformationDetails> bank, String mobileNo, String regAssNID, Date regDate, Set<Address> address) { this.id = uuid; this.name = name; this.tin = tin; this.phone = phone; this.registrationType = registrationType; this.registrationNo = regNo; this.contactPerson = contactPerson; this.contactNumber = contactNumber; this.contactEmail = contactEmail; this.contactDesignation = contactDesignation; this.contactPhoto = contactPhoto; // this.businessAddressId = businessAddressId; // this.currentAddressId = currentAddressId; // this.permanentAddressId = permanentAddressId; this.bankinformation = bank; // this.fatherName = fatherName; // this.motherName = motherName; // this.spouseName = spouseName; this.mobileNo = mobileNo; this.regAssNID = regAssNID; this.registrationDate = regDate; //this.dob = dob; this.address = address; } }
// // AddView.swift // TodoApp // // Created by Anderson Vanzo on 25/03/23. // import SwiftUI struct AddView: View { @Environment(\.presentationMode) var presentationMode @EnvironmentObject var listViewModel: ListViewModel @State var textFieldText: String = "" @State var alertTitle: String = "" @State var showAlert: Bool = false func saveButtonPressed() { if textIsAppropriate() { listViewModel.addItem(title: textFieldText) presentationMode.wrappedValue.dismiss() } } func textIsAppropriate() -> Bool { if textFieldText.count < 3 { alertTitle = "Your new todo item must be at least 3 characters long!" showAlert.toggle() return false } return true } func getAlert() -> Alert { return Alert(title: Text(alertTitle)) } var body: some View { ScrollView { VStack { TextField("Type something here...", text: $textFieldText) .padding(.horizontal) .frame(height: 48) .background(Color(.systemGray6)) .cornerRadius(8) Button(action: saveButtonPressed ,label: { Text("Save".uppercased()) .foregroundColor(.white) .font(.headline) .frame(height: 48) .frame(maxWidth: .infinity) .background(Color.accentColor) .cornerRadius(8) }) } .padding(16) } .navigationTitle("Add an item 🖋️") .alert(isPresented: $showAlert, content: getAlert) } } struct AddView_Previews: PreviewProvider { static var previews: some View { NavigationView { AddView() } .environmentObject(ListViewModel()) } }
import qs from "qs"; import type { StripeElementLocale } from "@stripe/stripe-js"; import { createContext, useContext, useState, useEffect, useCallback, } from "react"; import { APPEARANCE_OPTIONS } from "../constants/appearanceOptions"; import { PAYMENT_ELEMENT_CONFIGS } from "../pages/sample/payment-element"; import { getStripeJsUrlAlias } from "./WithStripeJs"; import { useStableValue } from "../hooks/useStableValue"; type AppState = { // Generally applicable state stripeJsUrl: "prod" | "edge" | "localhost" | string; betas: string[]; locale: StripeElementLocale; sampleWidth: number | "full"; appearance: string; layout: "auto" | "tabs" | "accordion" | "horizontal" | "vertical"; // Card Element enableLiceBetas: boolean; // Split Card Elements showPostalCodeElement: boolean; // Payment Element paymentElementConfig: string; radios: boolean; spacedAccordionItems: boolean; defaultCollapsed: boolean; }; const DEFAULT_APP_STATE: AppState = { stripeJsUrl: getStripeJsUrlAlias(process.env.NEXT_PUBLIC_STRIPE_JS_URL), betas: [], locale: "auto", appearance: APPEARANCE_OPTIONS[0].label, sampleWidth: "full", showPostalCodeElement: false, paymentElementConfig: PAYMENT_ELEMENT_CONFIGS[0].label, layout: "auto", radios: true, spacedAccordionItems: false, defaultCollapsed: false, enableLiceBetas: false, }; const AppStateContext = createContext(null); const parseSearchString = (search: string) => { if (search.startsWith("?")) { search = search.slice(1); } const result: Record<string, any> = qs.parse(search); // Auto convert boolean string values for (const key of Object.keys(result)) { if (result[key] === "true") { result[key] = true; } if (result[key] === "false") { result[key] = false; } if (/^\d+$/.test(result[key])) { result[key] = +result[key]; } } return result; }; export const AppState = ({ children }: { children: React.ReactNode }) => { const [appState, setAppState] = useState<AppState>(null); // Read options state from query params on initial load useEffect(() => { const queryParamData = parseSearchString(window.location.search); const initialAppState = { ...DEFAULT_APP_STATE }; for (const key of Object.keys(queryParamData)) { if (key in DEFAULT_APP_STATE) { initialAppState[key] = queryParamData[key]; } } setAppState(initialAppState); // TODO: Clear query params, probably? }, []); return ( <AppStateContext.Provider value={{ appState, setAppState }}> {appState && children} </AppStateContext.Provider> ); }; const appStateKeysInUse: { [appStateKey: string]: number } = {}; // lol export const useAppState = <T extends Array<keyof AppState>>( keysArg: T ): { [K in T[number]]: AppState[K] } => { const { appState: unstableAppState } = useContext(AppStateContext); const appState = useStableValue(unstableAppState); const keys = useStableValue(keysArg); // Track what keys are currently being used from app state useEffect(() => { for (const k of keys) { if (!appStateKeysInUse[k]) { appStateKeysInUse[k] = 0; } appStateKeysInUse[k] += 1; } return () => { for (const k of keys) { appStateKeysInUse[k] -= 1; } }; }, [keys]); // For keys with non-default values currently in use, store the keys as a query param useEffect(() => { const queryParams = parseSearchString(window.location.search); // Add app state keys in use that are not the default value for (const k of Object.keys(appStateKeysInUse)) { if (appStateKeysInUse[k] && queryParams[k] !== DEFAULT_APP_STATE[k]) { queryParams[k] = appState[k]; } } // Delete app state keys not in use or app state keys in use that are the default value for (const k of Object.keys(queryParams)) { if ( k in DEFAULT_APP_STATE && (!appStateKeysInUse[k] || queryParams[k] === DEFAULT_APP_STATE[k]) ) { delete queryParams[k]; } } // Update the query params (preserving any existing query params not related to app state) const url = new URL(window.location.href); url.search = qs.stringify(queryParams); window.history.replaceState(null, "", url.toString()); // Remove query params no longer needed on unmount return () => { const queryParams = parseSearchString(window.location.search); for (const k of Object.keys(queryParams)) { if ( k in DEFAULT_APP_STATE && (!appStateKeysInUse[k] || queryParams[k] === DEFAULT_APP_STATE[k]) ) { delete queryParams[k]; } } const url = new URL(window.location.href); url.search = qs.stringify(queryParams); window.history.replaceState(null, "", url.toString()); }; }, [appState]); const result = {} as { [K in T[number]]: AppState[K] }; for (const k of keys) { result[k] = appState[k]; } return result; }; export const useSetAppState = <K extends keyof AppState>(): (( key: K, value: AppState[K] ) => void) => { const { appState: unstableAppState, setAppState } = useContext(AppStateContext); const appState = useStableValue(unstableAppState); const set = useCallback( (key, value) => { setAppState({ ...appState, [key]: value }); }, [appState, setAppState] ); return set; };