text
stringlengths
184
4.48M
const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const app = express(); const port = process.env.PORT || 3000; // Enable CORS for all routes app.use(cors()); // Express now includes built-in JSON parsing app.use(express.json()); // Connect to MongoDB mongoose.connect('mongodb+srv://mazeez:[email protected]/trans', { useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error:')); db.once('open', () => { console.log('Connected to MongoDB'); }); const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true } }); const User = mongoose.model('User', userSchema); module.exports = User; // Registration endpoint app.post('/register', async (req, res) => { const { name, email, password } = req.body; try { const existingUser = await User.findOne({ email: email.toLowerCase() }); if (existingUser) { return res.status(400).json({ error: "User already exists" }); } // Create a new user in the database with the hashed password const user = new User({ name, email: email.toLowerCase(), password: password }); await user.save(); res.setHeader('Content-Type', 'text/html'); res.json({ message: 'Registration successful, redirecting to login page...' }); } catch (error) { console.error('Registration error:', error); res.status(500).json({ error: 'Internal Server Error' }); } }); // Login endpoint app.post('/login', async (req, res) => { const { email, password } = req.body; console.log('Request Body:', req.body); try { // Check if the email exists in the database const user = await User.findOne({ email }); if (!user) { return res.status(401).json({ error: 'Invalid email or password. Please try again.' }); } // Compare the provided password with the password stored in the database if (password === user.password) { res.json({ message: 'Login successful' }); } else { res.status(401).json({ error: 'Invalid email or password. Please try again.' }); } } catch (error) { console.error('Login error:', error); res.status(500).json({ error: 'Internal Server Error' }); } }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
#include<iostream> using namespace std; class ListNode { public: int val; ListNode* next; ListNode(int val) { this->val = val; this->next = NULL; } }; void insertAtHead(ListNode*& head, int val) { ListNode* n = new ListNode(val); n->next = head; head = n; } void printLinkedList(ListNode* head) { while (head != NULL) { cout << head->val << " "; head = head->next; } cout << endl; } // ListNode* sumOfLinkedList(ListNode* head1, ListNode* head2) { // ListNode* head = NULL; // while (head1 != NULL and head2 != NULL) { // int d1 = head1->val; // int d2 = head2->val; // int sum = d1 + d2; // ListNode* n = new ListNode(sum); // n->next = head; // head = n; // head1 = head1->next; // head2 = head2->next; // } // return head; // } // ListNode* sumOfLinkedList(ListNode* head1, ListNode* head2) { // ListNode* head = NULL; // int carry = 0; // while (head1 != NULL and head2 != NULL) { // int d1 = head1->val; // int d2 = head2->val; // int sum = d1 + d2 + carry; // ListNode* n = new ListNode(sum % 10); // n->next = head; // head = n; // carry = sum / 10; // head1 = head1->next; // head2 = head2->next; // } // if (carry == 1) { // ListNode* n = new ListNode(1); // n->next = head; // head = n; // } // return head; // } // ListNode* sumOfLinkedList(ListNode* head1, ListNode* head2) { // ListNode* head = NULL; // int carry = 0; // while (head1 != NULL and head2 != NULL) { // int d1 = head1->val; // int d2 = head2->val; // int sum = d1 + d2 + carry; // ListNode* n = new ListNode(sum % 10); // n->next = head; // head = n; // carry = sum / 10; // head1 = head1->next; // head2 = head2->next; // } // while (head1 != NULL) { // int d1 = head1->val; // int sum = d1 + carry; // ListNode* n = new ListNode(sum % 10); // n->next = head; // head = n; // carry = sum / 10; // head1 = head1->next; // } // while (head2 != NULL) { // int d2 = head2->val; // int sum = d2 + carry; // ListNode* n = new ListNode(sum % 10); // n->next = head; // head = n; // carry = sum / 10; // head2 = head2->next; // } // if (carry == 1) { // ListNode* n = new ListNode(1); // n->next = head; // head = n; // } // return head; // } ListNode* sumOfLinkedList(ListNode* head1, ListNode* head2) { ListNode* head = NULL; int carry = 0; while (head1 != NULL || head2 != NULL || carry) { int d1 = head1 != NULL ? head1->val : 0; int d2 = head2 != NULL ? head2->val : 0; int sum = d1 + d2 + carry; ListNode* n = new ListNode(sum % 10); n->next = head; head = n; carry = sum / 10; head1 = head1 != NULL ? head1->next : NULL; head2 = head2 != NULL ? head2->next : NULL; } return head; } int main() { ListNode* head1 = NULL; insertAtHead(head1, 9); insertAtHead(head1, 9); insertAtHead(head1, 9); insertAtHead(head1, 9); insertAtHead(head1, 9); printLinkedList(head1); ListNode* head2 = NULL; insertAtHead(head2, 8); insertAtHead(head2, 8); insertAtHead(head2, 8); printLinkedList(head2); ListNode* head = sumOfLinkedList(head1, head2); printLinkedList(head); return 0; }
import { Image, Box, Center, Stack, Text, TableContainer, Table, Thead, Th, Tbody, Td, Button, Tr, } from "@chakra-ui/react"; import React, { useRef, useState, useEffect } from "react"; import StudentDashBoard from "./studentDashBoard"; import "../../App.css"; import { useReactToPrint } from "react-to-print"; import axios from "../../API/Api"; function RunningTS() { const [rtsData, setRtsData] = useState([]); useEffect(() => { const fetchRTS = async () => { try { const response = await axios.get( "/api/student/result/runningTranscript", { withCredentials: true } ); if (response) { setRtsData(response.data); console.log(response.data); console.log(rtsData); } else { alert("Student has not completed any course yet."); } } catch (err) { if (err.response) { // resposes is not in range of 200 console.log(err.response.data); console.log(err.response.status); console.log(err.response.headers); } else console.log(`Error: ${err.message}`); } }; fetchRTS(); }, []); const componentRef = useRef(); const handlePrint = useReactToPrint({ content: () => componentRef.current, }); return ( <Box> <StudentDashBoard /> <Center paddingTop={"9rem"} ref={componentRef}> <Box padding={20} maxW={800} justifyContent={"center"}> <Stack direction={"column"} mb={15}> <Center> <Image borderRadius="120px" boxSize="120px" src="./Images/tulogo.jpeg" alt="Dan Abramov" shape="" /> </Center> <Center color={"green"} fontSize={20}> R U N N I N G T R A N S C R I P T </Center> <Stack direction={"column"} padding={10} color={"#00C4FF"} width={"100%"} > <Text>Name: {rtsData.name}</Text> <Text>Roll Number: {rtsData.rollno}</Text> </Stack> <Stack direction={"row"} padding={"5"} color={"#00C4FF"} spacing={20} width={"100%"} > <Text>Previous Semester: {rtsData.prevSemNo} </Text> <Text paddingLeft={20}> CGPA(Comulative Point Grade Average): {rtsData.cgpa}{" "} </Text> </Stack> <Stack direction="row" padding={5} spacing={20} color={"#00C4FF"} width={"100%"} > <Text> SGPA(Semester's Grade Point Average):{rtsData.prevSemSgpa}{" "} </Text> <Text> Total Credit Completed: {rtsData.totalCreditCompleted} </Text> <Text color={"#B70404"}> Active Backlog: {rtsData.activeBackLog}{" "} </Text> </Stack> <Stack direction="row" padding={5} spacing={20} color={"#00C4FF"} width={"100%"} > <Text color={"#F79327"}> Withheld(W): {rtsData.withheld} </Text> <Text> InComplete(I): {rtsData.iGrade} </Text> <Text> Extension(X): {rtsData.xGrade} </Text> </Stack> <Center> <TableContainer width={"100%"}> <Table border={"2px solid"} className="running_table"> <Thead className="running_head"> <Th>Course Code</Th> <Th>Course Title</Th> <Th>Credit</Th> <Th>Grade</Th> </Thead> <Tbody className="running_body"> {rtsData.courses && rtsData.courses.map((e) => { return ( <Tr color={"#116D6E"}> <Td>{e.courseCode}</Td> <Td>{e.courseName}</Td> <Td>{e.credit}</Td> <Td>{e.gradeObt}</Td> </Tr> ); })} </Tbody> </Table> </TableContainer> </Center> </Stack> </Box> </Center> <Center> <Button color="white" backgroundColor={"#4942E4"} fontSize={20} width={110} padding={8} borderRadius={25} onClick={handlePrint} > Print </Button> </Center> </Box> ); } export default RunningTS;
import React from 'react'; import PropTypes from 'prop-types'; import { ButtonList, ButtonElement } from './FeedbackOptions.styled'; const FeedbackOptions = ({ options, onLeaveFeedback }) => { return ( <ButtonList> {options.map(el => ( <li key={el}> <ButtonElement type="button" name={el} onClick={onLeaveFeedback}> {el} </ButtonElement> </li> ))} </ButtonList> ); }; export default FeedbackOptions; FeedbackOptions.propTypes = { options: PropTypes.arrayOf(PropTypes.string).isRequired, onLeaveFeedback: PropTypes.func.isRequired, };
package com.zhugalcf.kameleoon.entity; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; import jakarta.persistence.Version; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import java.time.LocalDateTime; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "quotes") public class Quote { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "content", nullable = false, unique = true) private String content; @ManyToOne @JoinColumn(name = "user_id", nullable = false) private User user; @Column(name = "score") private long score; @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_at") private LocalDateTime createdAt; @OneToMany(mappedBy = "quote", cascade = CascadeType.ALL, orphanRemoval = true) private List<Vote> votes; @Version @Column(name = "version", nullable = false) private int version; public synchronized void voteIncrement() { score++; } public synchronized void voteDecrement() { score--; } }
import React, { useState, useRef } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faTimes } from '@fortawesome/free-solid-svg-icons'; import './note.css'; import { RiAddCircleLine ,RiDeleteBin3Line,RiImage2Line} from "react-icons/ri"; const EditNote = ({ note, onClose, onSubmit }) => { const [values, setValues] = useState({ note_title: note.title_note, note_desc: note.description, files: [], }); const fileInputRef = useRef(null); const handleFileChange = (e) => { setValues(prevValues => ({ ...prevValues, files: [...prevValues.files, ...e.target.files], })); }; const handleChange = (e) => { const { name, value } = e.target; setValues({ ...values, [name]: value }); }; const handleSubmit = () => { const updatedNote = { id: note.id_note, note_title: values.note_title, note_desc: values.note_desc, files: values.files, }; if (fileInputRef.current) fileInputRef.current.value = ''; // Reset the file input onSubmit(updatedNote); onClose(); }; return ( <div className="custom-modal"> <div className="modal-overlay" onClick={onClose}></div> <div className="modal-container"> <div className="modal-header"> <h2>Edit Note</h2> <button onClick={onClose} className="close-button"> <FontAwesomeIcon icon={faTimes} /> </button> </div> <div className="modal-body"> <input className='input-update' type="text" name="note_title" value={values.note_title} onChange={handleChange} placeholder="Title" /><br /> <input className='input-update' type='text' name="note_desc" value={values.note_desc} onChange={handleChange} placeholder="Description" /> <input className='file-input' type="file" id="fileInput" name="files" ref={fileInputRef} onChange={handleFileChange} multiple /> <div className="file-upload-container"> <label htmlFor="fileInput" style={{ fontSize: '25px' }}> <span title='add files'> <RiImage2Line /> </span> </label> <button className='btn_update' onClick={handleSubmit} type="button"> <span title='update'> Update </span> </button> </div> </div> </div> </div> ); }; export default EditNote; // import React from 'react'; // import { useState,useRef } from 'react'; // import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; // import { faTimes} from '@fortawesome/free-solid-svg-icons'; // import { Head, router } from '@inertiajs/react'; // import { Button, Modal, TextInput } from "flowbite-react"; // import './note.css' // import { faUpload } from '@fortawesome/free-solid-svg-icons'; // import { RiAddCircleLine ,RiDeleteBin3Line,RiImage2Line} from "react-icons/ri"; // const EditNote = ({ note, onClose,onSubmit }) => { // const [values, setValues] = useState({ // note_title: note.title_note, // note_desc: note.description, // files:[], // }); // const fileInputRef = useRef(null); // // const handleFileChange = (e) => { // // setValues(prevValues => ({ // // ...prevValues, // // file: e.target.files[0], // // })); // // }; // const handleFileChange = (e) => { // // Append new files to the existing files array // setValues(prevValues => ({ // ...prevValues, // files: [...prevValues.files, ...e.target.files], // })); // }; // const handleChange = (e) => { // const { name, value } = e.target; // setValues({ ...values, [name]: value }); // }; // const handleSubmit = () => { // const updatedNote = { // id: note.id_note, // note_title: values.note_title, // note_desc: values.note_desc, // files: values.files, // }; // if (fileInputRef.current) fileInputRef.current.value = ''; // Reset the file input // onSubmit(updatedNote); // onClose(); // }; // return ( // <Modal show={true} onClose={onClose} popup className='modal-view ' > // <div className='modal-container'> // <div className='modal-content'> // <Modal.Header /> // <Modal.Body> // <input className='input-update' type="text" name="note_title" value={values.note_title} onChange={handleChange} placeholder="Title" /><br/> // <input className='input-update' type='text' name="note_desc" value={values.note_desc} onChange={handleChange} placeholder="Description" /> // <input className='file-input' type="file" id="fileInput" name="files" ref={fileInputRef} onChange={handleFileChange} multiple /> // <div className="file-upload-container"> // <label htmlFor="fileInput" style={{ fontSize: '25px' }}> // <span title='add files'> // <RiImage2Line /> // </span> // </label> // <button className='btn_update' onClick={handleSubmit} type="button"> // <span title='update'> // Update // </span> // </button> // </div> // </Modal.Body> // </div> // </div> // </Modal> // ); // }; // export default EditNote // import React from 'react'; // import { useState,useRef } from 'react'; // import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; // import { faTimes} from '@fortawesome/free-solid-svg-icons'; // import { Head, router } from '@inertiajs/react'; // import { Button, Modal, TextInput } from "flowbite-react"; // const EditNote = ({ note, onClose,onSubmit }) => { // const [values, setValues] = useState({ // note_title: note.title_note, // note_desc: note.description, // files:[], // }); // const fileInputRef = useRef(null); // // const handleFileChange = (e) => { // // setValues(prevValues => ({ // // ...prevValues, // // file: e.target.files[0], // // })); // // }; // const handleFileChange = (e) => { // // Append new files to the existing files array // setValues(prevValues => ({ // ...prevValues, // files: [...prevValues.files, ...e.target.files], // })); // }; // const handleChange = (e) => { // const { name, value } = e.target; // setValues({ ...values, [name]: value }); // }; // const handleSubmit = () => { // const updatedNote = { // id: note.id_note, // note_title: values.note_title, // note_desc: values.note_desc, // files: values.files, // }; // if (fileInputRef.current) fileInputRef.current.value = ''; // Reset the file input // onSubmit(updatedNote); // onClose(); // }; // return ( // <Modal show={true} onClose={onClose} popup style={{ }}> // <Modal.Header /> // <Modal.Body> // <TextInput type="text" name="note_title" value={values.note_title} onChange={handleChange} placeholder="Title" /> // <TextInput type='text' name="note_desc" value={values.note_desc} onChange={handleChange} placeholder="Description" /> // <input type="file" name="files" ref={fileInputRef} onChange={handleFileChange} multiple/> // <Modal.Footer> // <button onClick={handleSubmit} type="button">Update</button> // </Modal.Footer> // </Modal.Body> // </Modal> // ); // }; // export default EditNote // import React from 'react'; // import { useState,useRef } from 'react'; // import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; // import { faTimes} from '@fortawesome/free-solid-svg-icons'; // import { Head, router } from '@inertiajs/react'; // import { Button, Checkbox, Label, Modal, TextInput } from "flowbite-react"; // const EditNote = ({ note, onClose,onSubmit }) => { // const [values, setValues] = useState({ // note_title: note.title_note, // note_desc: note.description, // }); // const fileInputRef = useRef(null); // const handleFileChange = (e) => { // setValues(prevValues => ({ // ...prevValues, // file: e.target.files[0], // })); // }; // const handleChange = (e) => { // const { name, value } = e.target; // setValues({ ...values, [name]: value }); // }; // const handleSubmit = () => { // const updatedNote = { // id: note.id_note, // note_title: values.note_title, // note_desc: values.note_desc, // file: values.file, // Ensure file is included // // Include any other fields you need to update // }; // if (fileInputRef.current) fileInputRef.current.value = ''; // Reset the file input // onSubmit(updatedNote); // onClose(); // }; // return ( // <div className="edit-note-modal"> // <div className="modal-content"> // <FontAwesomeIcon icon={faTimes} onClick={onClose} /> // <div > // <input type="text" name="note_title" value={values.note_title} onChange={handleChange} placeholder="Title" /> // <input type='text' name="note_desc" value={values.note_desc} onChange={handleChange} placeholder="Description" /> // <input type="file" name="file" ref={fileInputRef} onChange={handleFileChange} /> // <button onClick={handleSubmit} type="button">Update</button> // </div> // </div> // </div> // ); // }; // export default EditNote
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; /* https://learn.microsoft.com/en-us/dotnet/maui/xaml/fundamentals/data-binding-basics */ namespace Maui_in_Action; public class NamedColor { public string Name { get; private set; } public string FriendlyName { get; private set; } public Color Color { get; private set; } // Expose the Color fields as properties public float Red => Color.Red; public float Green => Color.Green; public float Blue => Color.Blue; public static IEnumerable<NamedColor> All { get; private set; } static NamedColor() { List<NamedColor> all = new List<NamedColor>(); StringBuilder stringBuilder = new StringBuilder(); // Loop through the public static fields of the Color structure. foreach (FieldInfo fieldInfo in typeof(Colors).GetRuntimeFields()) { if (fieldInfo.IsPublic && fieldInfo.IsStatic && fieldInfo.FieldType == typeof(Color)) { // Convert the name to a friendly name. string name = fieldInfo.Name; stringBuilder.Clear(); int index = 0; foreach (char ch in name) { if (index != 0 && Char.IsUpper(ch)) { stringBuilder.Append(' '); } stringBuilder.Append(ch); index++; } // Instantiate a NamedColor object. NamedColor namedColor = new NamedColor { Name = name, FriendlyName = stringBuilder.ToString(), Color = (Color)fieldInfo.GetValue(null) }; // Add it to the collection. all.Add(namedColor); } } all.TrimExcess(); All = all; } }
/* * Copyright © 2015 Integrated Knowledge Management ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.ikm.tinkar.entity.transfom; import dev.ikm.tinkar.common.id.PublicId; import dev.ikm.tinkar.common.id.PublicIds; import dev.ikm.tinkar.entity.ConceptEntity; import dev.ikm.tinkar.entity.ConceptVersionRecord; import dev.ikm.tinkar.entity.RecordListBuilder; import dev.ikm.tinkar.schema.ConceptVersion; import dev.ikm.tinkar.schema.StampChronology; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import java.util.List; import static dev.ikm.tinkar.entity.transfom.ProtobufToEntityTestHelper.openSession; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestEntityToProtobufConceptTransform { @Test @DisplayName("Transform a Entity Concept Chronology With Zero Versions/Values Present") public void conceptChronologyTransformWithZeroVersion() { openSession(this, (mockedEntityService, conceptMap) -> { // Given an Entity Concept Version // When we transform our Entity Concept Version into a PBConceptVersion // Then the resulting PBConceptVersion should match the original entity value assertThrows(Throwable.class, () -> EntityToTinkarSchemaTransformer.getInstance().createPBConceptVersions(RecordListBuilder.make().build()), "Not allowed to have an empty Concept Version."); }); } @Test @DisplayName("Transform a Entity Concept Chronology with all values") public void conceptChronologyTransformWithOneVersion() { openSession(this, (mockedEntityService, conceptMap) -> { ConceptEntity conceptPublic = mock(ConceptEntity.class); PublicId conceptPublicId = PublicIds.newRandom(); when(conceptPublic.publicId()).thenReturn(conceptPublic); ConceptVersionRecord mockConceptVersion = mock(ConceptVersionRecord.class); when(mockConceptVersion.publicId()).thenReturn(conceptPublic); EntityToTinkarSchemaTransformer entityTransformer = spy(EntityToTinkarSchemaTransformer.getInstance()); doReturn(StampChronology.getDefaultInstance()).when(entityTransformer).createPBStampChronology(any()); // When we transform our Entity Pattern Version into a PBPatternVersion List<ConceptVersion> actualPBConceptVersion = entityTransformer.createPBConceptVersions(RecordListBuilder.make().with(mockConceptVersion).build()); // Then the resulting PBConceptVersion should match the original entity value assertEquals(1, actualPBConceptVersion.size(), "The size of the Concept Chronology does not match the expected."); assertFalse(actualPBConceptVersion.isEmpty(), "The Concept Version is empty."); assertTrue(actualPBConceptVersion.get(0).hasStamp(), "The Concept Chronology is missing a STAMP."); }); } @Test @DisplayName("Transform a Entity Concept Version with two versions present") public void conceptVersionTransformWithTwoVersions() { openSession(this, (mockedEntityService, conceptMap) -> { ConceptEntity conceptPublic = mock(ConceptEntity.class); PublicId conceptPublicId = PublicIds.newRandom(); when(conceptPublic.publicId()).thenReturn(conceptPublic); ConceptVersionRecord mockConceptVersion = mock(ConceptVersionRecord.class); when(mockConceptVersion.publicId()).thenReturn(conceptPublic); EntityToTinkarSchemaTransformer entityTransformer = spy(EntityToTinkarSchemaTransformer.getInstance()); doReturn(StampChronology.getDefaultInstance()).when(entityTransformer).createPBStampChronology(any()); // When we transform our Entity Pattern Version into a PBPatternVersion List<ConceptVersion> actualPBConceptVersion = entityTransformer.createPBConceptVersions(RecordListBuilder.make().with(mockConceptVersion).addAndBuild(mockConceptVersion)); // Then the resulting PBConceptVersion should match the original entity value assertEquals(2, actualPBConceptVersion.size(), "The size of the Concept Chronology does not match the expected."); assertFalse(actualPBConceptVersion.isEmpty(), "The Concept Version is empty."); assertTrue(actualPBConceptVersion.get(0).hasStamp(), "The Concept Chronology is missing a STAMP."); assertTrue(actualPBConceptVersion.get(1).hasStamp(), "The Concept Chronology is missing a STAMP."); }); } }
package Regexp::Sudoku::Quadruple; use 5.028; use strict; use warnings; no warnings 'syntax'; use experimental 'signatures'; use experimental 'lexical_subs'; our $VERSION = '2022062001'; use Hash::Util::FieldHash qw [fieldhash]; use Regexp::Sudoku::Utils; fieldhash my %quadruple2cells; fieldhash my %cell2quadruples; fieldhash my %quadruple; ################################################################################ # # set_quadruples ($self, %quadruples) # # Set one or more quadruple constraints. For each constraint, we give # the top left as the key, and an arrayref of values as the value. # # TESTS: Quadruple/100-set_quadruples.t # ################################################################################ sub set_quadruples ($self, %quadruples) { foreach my $cell (keys %quadruples) { # # Calculate all the cells of the constraint # my $name = "Q-$cell"; my ($r, $c) = cell_row_column ($cell); my @cells = (cell_name ($r, $c), cell_name ($r, $c + 1), cell_name ($r + 1, $c), cell_name ($r + 1, $c + 1)); foreach my $cell (@cells) { $cell2quadruples {$self} {$cell} {$name} = 1; $quadruple2cells {$self} {$name} {$cell} = 1; } $quadruple {$self} {$name} = $quadruples {$cell}; } $self; } ################################################################################ # # cell2quadruples ($self, $cell) # # Return a list of quadruples a cell belongs to. # # TESTS: Quadruple/100-set_quadruples.t # ################################################################################ sub cell2quadruples ($self, $cell) { sort keys %{$cell2quadruples {$self} {$cell} || {}} } ################################################################################ # # quadruple2cells ($self, $name) # # Return a list of cells in a quadruple. # # TESTS: Quadruple/100-set_quadruples.t # ################################################################################ sub quadruple2cells ($self, $name) { sort keys %{$quadruple2cells {$self} {$name} || {}} } ################################################################################ # # quadruple_values ($name) # # Return the values for this quadruple # # TESTS: Quadruple/100-set_quadruples.t # ################################################################################ sub quadruple_values ($self, $name) { my @values = @{$quadruple {$self} {$name}}; wantarray ? @values : \@values; } ################################################################################ # # make_quadruple_statements ($self, $name) # # Return a set of statements which implements a quadruple constraint for # the set of cells belonging to the quadruple. # # TESTS: Quadruple/110-make_quadruple_statements.t # ################################################################################ sub make_quadruple_statements ($self, $name) { my ($subsub, $subpat) = ([], []); # # First, get the values, and count how often each of them # occurs (which will be once or twice) # my %value_count; $value_count {$_} ++ for $self -> quadruple_values ($name); # # Get the cells for this quadruple. # my @cells = $self -> quadruple2cells ($name); # # Now, we need a statement for each *different* value. # The patterns for each statement will be the same, the # subjects will differ. # my $pat = join "" => map {"\\g{$_}?"} @cells; foreach my $value (keys %value_count) { push @$subsub => ($value x $value_count {$value}) . $SENTINEL; push @$subpat => $pat . $SENTINEL; } ($subsub, $subpat); } __END__ =pod =head1 NAME Regexp::Sudoku::Quadruple -- Quadruple related methods =head1 DESCRIPTION This module is part of C<< Regexp::Sudoku >> and is not intended as a standalone module. See L<< Regexp::Sudoku >> for the documentation. =head1 DEVELOPMENT The current sources of this module are found on github, L<< git://github.com/Abigail/Regexp-Sudoku.git >>. =head1 AUTHOR Abigail, L<< mailto:[email protected] >>. =head1 COPYRIGHT and LICENSE Copyright (C) 2021-2022 by Abigail. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =cut
from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import loader from django.shortcuts import render from django.urls import reverse from django.views import generic from .models import Question, Choice # Create your views here. # def index(request): # latest_question_list = Question.objects.order_by('-pub_date')[:5] # template = loader.get_template("polls/index.html") # context = { # 'latest_question_list':latest_question_list # } #output = ', '. join([q.question_text for q in latest_question_list]) # return HttpResponse(template.render(context, request)) # def index(request): # latest_question_list = Question.objects.order_by('-pub_date')[:5] # context = { # 'latest_question_list':latest_question_list # } # return render(request, "polls/index.html", context) # # ##this is the normal way to use detail module # # def detail(request, question_id): # # try: # # question = Question.objects.get(pk = question_id) # # except Question.DoesNotExist: # # raise Http404("Question doesnot exist") # # context = {'question': question} # # return render(request, "polls/detail.html", context) # #this is the shortcut provided by django # def detail(request, question_id): # question = get_object_or_404(Question, pk=question_id) # return render(request, "polls/detail.html",{'question':question}) # def result(request, question_id): # question = get_object_or_404(Question, pk=question_id) # return render(request, "polls/results.html", {'question':question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, "polls/detail.html", { 'question': question, 'error_message' : "You didn't select a choice.", }) else: selected_choice.votes+=1 selected_choice.save() return HttpResponseRedirect(reverse('polls:result', args=(question.id,))) class IndexView(generic.ListView): template_name = "polls/index.html" context_object_name = "latest_question_list" def get_queryset(self): '''Return last 5 questions''' return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = "polls/detail.html" class ResultsView(generic.DetailView): model = Question template_name = "polls/results.html"
import React from 'react'; import { Query } from 'react-apollo'; import PropTypes from 'prop-types'; import GraphQLErrors from '@twigeducation/react-graphql-errors'; import { Loading } from '@twigeducation/ts-fe-components'; const QueryHandler = ({ children, ErrorComponent, LoadingComponent, NotFoundMessage, BadRequestMessage, query, variables, }) => ( <Query query={query} variables={{ ...variables }}> {({ data, loading, error }) => { if (loading) { return <LoadingComponent />; } if (error) { let errors; // This probably isn't scalable - eventually want to switch to a strategy of passing in an object/array // and using that i.e. [{ code: 400, message: 'custom 400 message' }] or similar if (error.message.includes('400:')) { errors = [BadRequestMessage]; } if (error.message.includes('404:')) { errors = [NotFoundMessage]; } if (error.message.includes('403:')) { errors = ['Sorry, you do not have permission to view this content']; } return <ErrorComponent errors={errors || [error]} />; } return children(data); }} </Query> ); QueryHandler.defaultProps = { ErrorComponent: GraphQLErrors, LoadingComponent: Loading, NotFoundMessage: '404: Not Found', BadRequestMessage: '400: Bad Request', variables: {}, }; QueryHandler.propTypes = { children: PropTypes.func.isRequired, ErrorComponent: PropTypes.oneOfType([PropTypes.element, PropTypes.func]), LoadingComponent: PropTypes.oneOfType([PropTypes.element, PropTypes.func]), NotFoundMessage: PropTypes.string, BadRequestMessage: PropTypes.string, query: PropTypes.shape({}).isRequired, variables: PropTypes.shape({}), }; export default QueryHandler;
import { formatarTexto } from 'common/animes' import Button from 'components/Button' import PopupRank from 'components/PopupRank' import Title from 'components/Title' import { useState } from 'react' import { Link } from 'react-router-dom' import { IAnimes } from 'types/anime' import styles from './Card.module.scss' interface Props { anime: IAnimes setMinhaLista?: React.Dispatch<React.SetStateAction<IAnimes[] | []>> minhaLista?: IAnimes[] | [] } export default function Card({ anime, setMinhaLista, minhaLista }: Props) { const { coverImage, title, description } = anime return ( <div className={styles.card} > <div className={styles.card__imgContainer}> <img src={coverImage.large} alt="Imagem do card" /> </div> <div className={styles.card__inner}> <div> <Title> <Link to={`/anime/${anime.id}`} className={styles.link}> <span>{title.romaji}</span> </Link> </Title> <p style={{ margin: 0 }}> {description && formatarTexto(description, 170)} </p> </div> <div className={styles.card__btnContainer}> <Button lista small setMinhaLista={setMinhaLista} anime={anime} minhaLista={minhaLista} /> <Button avaliar small anime={anime}/> </div> </div> </div> ) }
<?php declare(strict_types=1); namespace App\View\Cell; use App\Model\Entity\StudentStage; use App\Model\Field\AdscriptionStatus; use App\Model\Field\StageField; use Cake\View\Cell; /** * TrackingView cell */ class TrackingViewCell extends Cell { /** * List of valid options that can be passed into this * cell's constructor. * * @var array<string, mixed> */ protected $_validCellOptions = []; /** * Initialization logic run at the end of object construction. * * @return void */ public function initialize(): void { $this->Students = $this->fetchTable('Students'); $this->viewBuilder()->addHelpers([ 'Button', 'ModalForm', ]); } /** * @param int|string $student_id * @param array $urlList * @return void */ public function display(int|string $student_id, array $urlList = []) { $student = $this->Students ->find('withLapses') ->where(['Students.id' => $student_id]) ->first(); $trackingStage = $this->Students->StudentStages ->find() ->contain([ 'Students' => ['AppUsers'], ]) ->where([ 'StudentStages.student_id' => $student_id, 'StudentStages.stage' => StageField::TRACKING->value, ]) ->first(); $adscriptions = $this->Students->StudentAdscriptions ->find('withInstitution') ->find('withTracking') ->where([ 'StudentAdscriptions.student_id' => $student_id, 'StudentAdscriptions.status IN' => AdscriptionStatus::getTrackablesValues(), ]); $this->set(compact('student', 'adscriptions', 'urlList', 'trackingStage')); } /** * @param int|string $student_id * @return void */ public function info(int|string $student_id) { $trackingInfo = $this->Students->getStudentTrackingInfo($student_id) ?? []; $this->set(compact('trackingInfo')); } /** * @param int|string $student_id * @param \App\Model\Entity\StudentStage|null $trackingStage * @return void */ public function actions(int|string $student_id, ?StudentStage $trackingStage = null) { if (empty($trackingStage)) { $trackingStage = $this->Students->StudentStages ->find() ->contain([ 'Students' => ['AppUsers'], ]) ->where([ 'StudentStages.student_id' => $student_id, 'StudentStages.stage' => StageField::TRACKING->value, ]) ->first(); } $this->set(compact('trackingStage')); } }
'use strict' const Controller = require('egg').Controller const fs = require('fs') const path = require('path') class FileController extends Controller { // 上传 async upload() { const { ctx, app, service } = this const currentUser = ctx.authUser console.log(ctx.request.files) if (!ctx.request.files) { return ctx.apiFail('请先选择上传文件') } ctx.validate({ file_id: { required: true, type: 'int', defValue: 0, desc: '目录id', }, }) // 获取上传的文件 const file = ctx.request.files[0] const file_id = ctx.query.file_id console.log(file_id + '<<<<<<<<<<') // 处理传非根目录的情况 let prefixPath = '' // 根据file_id一直向上找到顶层目录 if(file_id > 0) { prefixPath = await service.file.searchDir(file_id) console.log(prefixPath) } // 处理传根目录的情况 if(file === 0) { prefixPath = '/' } // 拼接出最终文件上传目录 const name = prefixPath + ctx.genID(10) + path.extname(file.filename) // let f // // 目录id是否存在 // if (file_id > 0) { // // 目录是否存在,存在就返回目录对象,从而取得目录名字,不存在直接在service就出错返回了 // await service.file.isDirExist(file_id).then((res) => { // console.log(res + '>>>>>>>>>>') // f = res // }) // } // //取得上传的文件对象 // const file = ctx.request.files[0] // //动态将目录名称作为前缀和文件名拼接 // const name = f.name + '/' + ctx.genID(10) + path.extname(file.filename) // 判断用户网盘内存是否不足 let s = await new Promise((resolve, reject) => { fs.stat(file.filepath, (err, stats) => { resolve((stats.size / 1024).toFixed(1)) }) }) if (currentUser.total_size - currentUser.used_size < s) { return ctx.apiFail('你的可用内存不足') } // 上传到oss let result try { result = await ctx.oss.put(name, file.filepath) } catch (err) { console.log(err) } //得到文件url console.log(result.url) // 写入到数据表 if (result) { let addData = { name: file.filename, ext: file.mimeType, md: result.name, file_id, user_id: currentUser.id, size: parseInt(s), isdir: 0, url: result.url.replace('http','https'), } let res = await app.model.File.create(addData) // 更新用户的网盘内存使用情况 currentUser.used_size = currentUser.used_size + parseInt(s) currentUser.save() return ctx.apiSuccess(res) } ctx.apiFail('上传失败') } // 剩余容量 async getSize() { const { ctx, service } = this return ctx.apiSuccess({ total_size: ctx.authUser.total_size, used_size: ctx.authUser.used_size, }) } // 文件列表 async list() { const { xtx, app } = this; const user_id = this.ctx.authUser.id; this.ctx.validate({ file_id: { required: true, type: 'int', defValue: 0, desc: '目录id', }, orderby: { required: false, type: 'string', defValue: 'name', range: { in: ['name', 'created_time'], }, desc: '排序', }, type: { required: false, type: 'string', desc: '类型', }, }); const { file_id, orderby, type } = this.ctx.query; let where = { user_id, file_id, }; if (type && type !== 'all') { const Op = app.Sequelize.Op; where.ext = { [Op.like]: type + '%', }; } let rows = await app.model.File.findAll({ where, order: [ ['isdir', 'desc'], [orderby, 'desc'], ], }); this.ctx.apiSuccess({ rows, }); } // 创建文件夹 async createdir() { const { ctx, app } = this; const user_id = ctx.authUser.id; ctx.validate({ file_id: { required: true, type: 'int', defValue: 0, desc: '目录id', }, name: { required: true, type: 'string', desc: '文件夹名称', }, }); let { file_id, name } = ctx.request.body; // 验证目录id是否存在 if (file_id) { await this.service.file.isDirExist(file_id); } let res = await app.model.File.create({ name, file_id, user_id, isdir: 1, size: 0, }); ctx.apiSuccess(res); } // 重命名 async rename() { const { ctx, app } = this; const user_id = ctx.authUser.id; ctx.validate({ id: { required: true, type: 'int', desc: '记录', }, file_id: { required: true, type: 'int', defValue: 0, desc: '目录id', }, name: { required: true, type: 'string', desc: '文件名称', }, }); let { id, file_id, name } = ctx.request.body; // 验证目录id是否存在 if (file_id > 0) { await this.service.file.isDirExist(file_id); } // 文件是否存在 let f = await this.service.file.isExist(id); f.name = name; let res = await f.save(); ctx.apiSuccess(res); } // 批量删除 async deletel() { const { ctx, app } = this; const user_id = ctx.authUser.id; ctx.validate({ ids: { required: true, type: 'string', desc: '记录', }, }); let { ids } = ctx.request.body; ids = ids.split(','); // 计算删除文件内容 let files = await app.model.File.findAll({ where: { id: ids, user_id, }, }); let size = 0; files.forEach(item => { size = size + item.size; }); let res = await app.model.File.destroy({ where: { id: ids, user_id, }, }); if (res) { // 减去使用内存 size = ctx.authUser.used_size - size; ctx.authUser.used_size = size > 0 ? size : 0; ctx.authUser.save(); } ctx.apiSuccess(res); } // 搜索文件 async search() { const { ctx, app } = this; const user_id = ctx.authUser.id; ctx.validate({ keyword: { required: true, type: 'string', desc: '关键字', }, }); let { keyword } = ctx.query; const Op = app.Sequelize.Op; let rows = await app.model.File.findAll({ where: { name: { [Op.like]: `%${keyword}%`, }, isdir: 0, user_id, }, }); ctx.apiSuccess({ rows, }); } } module.exports = FileController
"""ModbusProtocol layer. Contains pure transport methods needed to - connect/listen, - send/receive - close/abort connections for unix socket, tcp, tls and serial communications as well as a special null modem option. Contains high level methods like reconnect. All transport differences are handled in transport, providing a unified interface to upper layers. Host/Port/SourceAddress explanation: - SourceAddress (host, port): - server (host, port): Listen on host:port - server serial (comm_port, _): comm_port is device string - client (host, port): Bind host:port to interface - client serial: not used - Host - server: not used - client: remote host to connect to (as host:port) - client serial: host is comm_port device string - Port - server: not used - client: remote port to connect to (as host:port) - client serial: no used Pyserial allow the comm_port to be a socket e.g. "socket://localhost:502", this allows serial clients to connect to a tcp server with RTU framer. Pymodbus allows this format for both server and client. For clients the string is passed to pyserial, but for servers it is used to start a modbus tcp server. This allows for serial testing, without a serial cable. Pymodbus offers nullmodem for clients/servers running in the same process if <host> is set to NULLMODEM_HOST it will be automatically invoked. This allows testing without actual network traffic and is a lot faster. Class NullModem is a asyncio transport class, that replaces the socket class or pyserial. The class is designed to take care of differences between the different transport mediums, and provide a neutral interface for the upper layers. It basically provides a pipe, without caring about the actual data content. """ from __future__ import annotations import asyncio import dataclasses import ssl from contextlib import suppress from enum import Enum from typing import Any, Callable, Coroutine from pymodbus.logging import Log from pymodbus.transport.serialtransport import create_serial_connection NULLMODEM_HOST = "__pymodbus_nullmodem" class CommType(Enum): """Type of transport.""" TCP = 1 TLS = 2 UDP = 3 SERIAL = 4 @dataclasses.dataclass class CommParams: """Parameter class.""" # generic comm_name: str | None = None comm_type: CommType | None = None reconnect_delay: float | None = None reconnect_delay_max: float = 0.0 timeout_connect: float | None = None host: str = "localhost" # On some machines this will now be ::1 port: int = 0 source_address: tuple[str, int] | None = None handle_local_echo: bool = False on_reconnect_callback: Callable[[], None] | None = None # tls sslctx: ssl.SSLContext | None = None # serial baudrate: int | None = None bytesize: int | None = None parity: str | None = None stopbits: int | None = None @classmethod def generate_ssl( cls, is_server: bool, certfile: str | None = None, keyfile: str | None = None, password: str | None = None, sslctx: ssl.SSLContext | None = None, ) -> ssl.SSLContext: """Generate sslctx from cert/key/passwor. MODBUS/TCP Security Protocol Specification demands TLSv2 at least """ if sslctx: return sslctx new_sslctx = ssl.SSLContext( ssl.PROTOCOL_TLS_SERVER if is_server else ssl.PROTOCOL_TLS_CLIENT ) new_sslctx.check_hostname = False new_sslctx.verify_mode = ssl.CERT_NONE new_sslctx.options |= ssl.OP_NO_TLSv1_1 new_sslctx.options |= ssl.OP_NO_TLSv1 new_sslctx.options |= ssl.OP_NO_SSLv3 new_sslctx.options |= ssl.OP_NO_SSLv2 if certfile: new_sslctx.load_cert_chain( certfile=certfile, keyfile=keyfile, password=password ) return new_sslctx def copy(self) -> CommParams: """Create a copy.""" return dataclasses.replace(self) class ModbusProtocol(asyncio.BaseProtocol): """Protocol layer including transport.""" def __init__( self, params: CommParams, is_server: bool, ) -> None: """Initialize a transport instance. :param params: parameter dataclass :param is_server: true if object act as a server (listen/connect) """ self.comm_params = params.copy() self.is_server = is_server self.is_closing = False self.transport: asyncio.BaseTransport = None # type: ignore[assignment] self.loop: asyncio.AbstractEventLoop = None # type: ignore[assignment] self.recv_buffer: bytes = b"" self.call_create: Callable[[], Coroutine[Any, Any, Any]] = lambda: None # type: ignore[assignment, return-value] if self.is_server: self.active_connections: dict[str, ModbusProtocol] = {} else: self.listener: ModbusProtocol | None = None self.unique_id: str = str(id(self)) self.reconnect_task: asyncio.Task | None = None self.reconnect_delay_current = 0.0 self.sent_buffer: bytes = b"" # ModbusProtocol specific setup if self.is_server: if self.comm_params.source_address is not None: host = self.comm_params.source_address[0] port = int(self.comm_params.source_address[1]) else: # This behaviour isn't quite right. # It listens on any IPv4 address rather than the more natural default of any address (v6 or v4). host = "0.0.0.0" # Any IPv4 host port = 0 # Server will select an ephemeral port for itself else: host = self.comm_params.host port = int(self.comm_params.port) if self.comm_params.comm_type == CommType.SERIAL and NULLMODEM_HOST in host: host, port = NULLMODEM_HOST, int(host[9:].split(":")[1]) if host == NULLMODEM_HOST: self.call_create = lambda: self.create_nullmodem(port) return if ( self.comm_params.comm_type == CommType.SERIAL and self.is_server and host.startswith("socket") ): # format is "socket://<host>:port" self.comm_params.comm_type = CommType.TCP parts = host.split(":") host, port = parts[1][2:], int(parts[2]) self.init_setup_connect_listen(host, port) def init_setup_connect_listen(self, host: str, port: int) -> None: """Handle connect/listen handler.""" if self.comm_params.comm_type == CommType.SERIAL: self.call_create = lambda: create_serial_connection( self.loop, self.handle_new_connection, host, baudrate=self.comm_params.baudrate, bytesize=self.comm_params.bytesize, parity=self.comm_params.parity, stopbits=self.comm_params.stopbits, timeout=self.comm_params.timeout_connect, exclusive=True, ) return if self.comm_params.comm_type == CommType.UDP: if self.is_server: self.call_create = lambda: self.loop.create_datagram_endpoint( self.handle_new_connection, local_addr=(host, port), ) else: self.call_create = lambda: self.loop.create_datagram_endpoint( self.handle_new_connection, remote_addr=(host, port), ) return # TLS and TCP if self.is_server: self.call_create = lambda: self.loop.create_server( self.handle_new_connection, host, port, ssl=self.comm_params.sslctx, reuse_address=True, start_serving=True, ) else: self.call_create = lambda: self.loop.create_connection( self.handle_new_connection, host, port, local_addr=self.comm_params.source_address, ssl=self.comm_params.sslctx, ) async def transport_connect(self) -> bool: """Handle generic connect and call on to specific transport connect.""" Log.debug("Connecting {}", self.comm_params.comm_name) if not self.loop: self.loop = asyncio.get_running_loop() self.is_closing = False try: self.transport, _protocol = await asyncio.wait_for( self.call_create(), timeout=self.comm_params.timeout_connect, ) except (asyncio.TimeoutError, OSError) as exc: # pylint: disable=overlapping-except Log.warning("Failed to connect {}", exc) return False return bool(self.transport) async def transport_listen(self) -> bool: """Handle generic listen and call on to specific transport listen.""" Log.debug("Awaiting connections {}", self.comm_params.comm_name) if not self.loop: self.loop = asyncio.get_running_loop() self.is_closing = False try: self.transport = await self.call_create() if isinstance(self.transport, tuple): self.transport = self.transport[0] except OSError as exc: Log.warning("Failed to start server {}", exc) # self.transport_close(intern=True) return False return True # ---------------------------------- # # ModbusProtocol asyncio standard methods # # ---------------------------------- # def connection_made(self, transport: asyncio.BaseTransport) -> None: """Call from asyncio, when a connection is made. :param transport: socket etc. representing the connection. """ Log.debug("Connected to {}", self.comm_params.comm_name) self.transport = transport self.reset_delay() self.callback_connected() def connection_lost(self, reason: Exception | None) -> None: """Call from asyncio, when the connection is lost or closed. :param reason: None or an exception object """ if not self.transport or self.is_closing: return Log.debug("Connection lost {} due to {}", self.comm_params.comm_name, reason) self.transport_close(intern=True) if ( not self.is_server and not self.listener and self.comm_params.reconnect_delay ): self.reconnect_task = asyncio.create_task(self.do_reconnect()) self.reconnect_task.set_name("transport reconnect") self.callback_disconnected(reason) def data_received(self, data: bytes) -> None: """Call when some data is received. :param data: non-empty bytes object with incoming data. """ self.datagram_received(data, None) def datagram_received(self, data: bytes, addr: tuple | None) -> None: """Receive datagram (UDP connections).""" if self.comm_params.handle_local_echo and self.sent_buffer: if data.startswith(self.sent_buffer): Log.debug( "recv skipping (local_echo): {} addr={}", self.sent_buffer, ":hex", addr, ) data = data[len(self.sent_buffer) :] self.sent_buffer = b"" elif self.sent_buffer.startswith(data): Log.debug( "recv skipping (partial local_echo): {} addr={}", data, ":hex", addr ) self.sent_buffer = self.sent_buffer[len(data) :] return else: Log.debug("did not receive local echo: {} addr={}", data, ":hex", addr) self.sent_buffer = b"" if not data: return Log.debug( "recv: {} old_data: {} addr={}", data, ":hex", self.recv_buffer, ":hex", addr, ) self.recv_buffer += data cut = self.callback_data(self.recv_buffer, addr=addr) self.recv_buffer = self.recv_buffer[cut:] if self.recv_buffer: Log.debug( "recv, unused data waiting for next packet: {}", self.recv_buffer, ":hex", ) def eof_received(self) -> None: """Accept other end terminates connection.""" Log.debug("-> transport: received eof") def error_received(self, exc): """Get error detected in UDP.""" Log.debug("-> error_received {}", exc) # --------- # # callbacks # # --------- # def callback_new_connection(self) -> ModbusProtocol: """Call when listener receive new connection request.""" Log.debug("callback_new_connection called") return ModbusProtocol(self.comm_params, False) def callback_connected(self) -> None: """Call when connection is succcesfull.""" Log.debug("callback_connected called") def callback_disconnected(self, exc: Exception | None) -> None: """Call when connection is lost.""" Log.debug("callback_disconnected called: {}", exc) def callback_data(self, data: bytes, addr: tuple | None = None) -> int: """Handle received data.""" Log.debug("callback_data called: {} addr={}", data, ":hex", addr) return 0 # ----------------------------------- # # Helper methods for external classes # # ----------------------------------- # def transport_send(self, data: bytes, addr: tuple | None = None) -> None: """Send request. :param data: non-empty bytes object with data to send. :param addr: optional addr, only used for UDP server. """ Log.debug("send: {}", data, ":hex") if self.comm_params.handle_local_echo: self.sent_buffer += data if self.comm_params.comm_type == CommType.UDP: if addr: self.transport.sendto(data, addr=addr) # type: ignore[attr-defined] else: self.transport.sendto(data) # type: ignore[attr-defined] else: self.transport.write(data) # type: ignore[attr-defined] def transport_close(self, intern: bool = False, reconnect: bool = False) -> None: """Close connection. :param intern: (default false), True if called internally (temporary close) :param reconnect: (default false), try to reconnect """ if self.is_closing: return if not intern: self.is_closing = True if self.transport: self.transport.close() self.transport = None # type: ignore[assignment] self.recv_buffer = b"" if self.is_server: for _key, value in self.active_connections.items(): value.listener = None value.callback_disconnected(None) value.transport_close() self.active_connections = {} return if not reconnect and self.reconnect_task: self.reconnect_task.cancel() self.reconnect_task = None self.reconnect_delay_current = 0.0 if self.listener: self.listener.active_connections.pop(self.unique_id) def reset_delay(self) -> None: """Reset wait time before next reconnect to minimal period.""" self.reconnect_delay_current = self.comm_params.reconnect_delay or 0.0 def is_active(self) -> bool: """Return true if connected/listening.""" return bool(self.transport) # ---------------- # # Internal methods # # ---------------- # async def create_nullmodem( self, port ) -> tuple[asyncio.Transport, asyncio.BaseProtocol]: """Bypass create_ and use null modem.""" if self.is_server: # Listener object self.transport = NullModem.set_listener(port, self) return self.transport, self # connect object return NullModem.set_connection(port, self) def handle_new_connection(self) -> ModbusProtocol: """Handle incoming connect.""" if not self.is_server: # Clients reuse the same object. return self new_protocol = self.callback_new_connection() self.active_connections[new_protocol.unique_id] = new_protocol new_protocol.listener = self return new_protocol async def do_reconnect(self) -> None: """Handle reconnect as a task.""" try: self.reconnect_delay_current = self.comm_params.reconnect_delay or 0.0 while True: Log.debug( "Wait {} {} ms before reconnecting.", self.comm_params.comm_name, self.reconnect_delay_current * 1000, ) await asyncio.sleep(self.reconnect_delay_current) if self.comm_params.on_reconnect_callback: self.comm_params.on_reconnect_callback() if await self.transport_connect(): break self.reconnect_delay_current = min( 2 * self.reconnect_delay_current, self.comm_params.reconnect_delay_max, ) except asyncio.CancelledError: pass self.reconnect_task = None # ----------------- # # The magic methods # # ----------------- # async def __aenter__(self) -> ModbusProtocol: """Implement the client with async enter block.""" return self async def __aexit__(self, _class, _value, _traceback) -> None: """Implement the client with async exit block.""" self.transport_close() def __str__(self) -> str: """Build a string representation of the connection.""" return f"{self.__class__.__name__}({self.comm_params.comm_name})" class NullModem(asyncio.DatagramTransport, asyncio.Transport): """ModbusProtocol layer. Contains methods to act as a null modem between 2 objects. (Allowing tests to be shortcut without actual network calls) """ listeners: dict[int, ModbusProtocol] = {} connections: dict[NullModem, int] = {} def __init__(self, protocol: ModbusProtocol, listen: int | None = None) -> None: """Create half part of null modem.""" asyncio.DatagramTransport.__init__(self) asyncio.Transport.__init__(self) self.protocol: ModbusProtocol = protocol self.other_modem: NullModem = None # type: ignore[assignment] self.listen = listen self.manipulator: Callable[[bytes], list[bytes]] | None = None self._is_closing = False # -------------------------- # # external nullmodem methods # # -------------------------- # @classmethod def set_listener(cls, port: int, parent: ModbusProtocol) -> NullModem: """Register listener.""" if port in cls.listeners: raise AssertionError(f"Port {port} already listening !") cls.listeners[port] = parent return NullModem(parent, listen=port) @classmethod def set_connection( cls, port: int, parent: ModbusProtocol ) -> tuple[NullModem, ModbusProtocol]: """Connect to listener.""" if port not in cls.listeners: raise asyncio.TimeoutError(f"Port {port} not being listened on !") client_protocol = parent.handle_new_connection() server_protocol = NullModem.listeners[port].handle_new_connection() client_transport = NullModem(client_protocol) server_transport = NullModem(server_protocol) cls.connections[client_transport] = port cls.connections[server_transport] = -port client_transport.other_modem = server_transport server_transport.other_modem = client_transport client_protocol.connection_made(client_transport) server_protocol.connection_made(server_transport) return client_transport, client_protocol def set_manipulator(self, function: Callable[[bytes], list[bytes]]) -> None: """Register a manipulator.""" self.manipulator = function @classmethod def is_dirty(cls): """Check if everything is closed.""" dirty = False if cls.connections: Log.error( "NullModem_FATAL missing close on port {} connect()", [str(key) for key in cls.connections.values()], ) dirty = True if cls.listeners: Log.error( "NullModem_FATAL missing close on port {} listen()", [str(value) for value in cls.listeners], ) dirty = True return dirty # ---------------- # # external methods # # ---------------- # def close(self) -> None: """Close null modem.""" if self._is_closing: return self._is_closing = True if self.listen: del self.listeners[self.listen] return if self.connections: with suppress(KeyError): del self.connections[self] if self.other_modem: self.other_modem.other_modem = None # type: ignore[assignment] self.other_modem.close() self.other_modem = None # type: ignore[assignment] if self.protocol: self.protocol.connection_lost(None) def sendto(self, data: bytes, _addr: Any = None) -> None: """Send datagrame.""" self.write(data) def write(self, data: bytes) -> None: """Send data.""" if not self.manipulator: self.other_modem.protocol.data_received(data) return data_manipulated = self.manipulator(data) for part in data_manipulated: self.other_modem.protocol.data_received(part) # ------------- # # Dummy methods # # ------------- # def abort(self) -> None: """Alias for closing the connection.""" self.close() def can_write_eof(self) -> bool: """Allow to write eof.""" return False def get_write_buffer_size(self) -> int: """Set write limit.""" return 1024 def get_write_buffer_limits(self) -> tuple[int, int]: """Set flush limits.""" return (1, 1024) def set_write_buffer_limits( self, high: int | None = None, low: int | None = None ) -> None: """Set flush limits.""" def write_eof(self) -> None: """Write eof.""" def get_protocol(self) -> ModbusProtocol | asyncio.BaseProtocol: """Return current protocol.""" return self.protocol def set_protocol(self, protocol: asyncio.BaseProtocol) -> None: """Set current protocol.""" def is_closing(self) -> bool: """Return true if closing.""" return self._is_closing def is_reading(self) -> bool: """Return true if read is active.""" return True def pause_reading(self): """Pause receiver.""" def resume_reading(self): """Resume receiver."""
import { useState, useContext } from 'react' import { TaskContext } from '../context/TaskContext' function TaskForm() { const [title, settitle] = useState('') const [description, setdescription] = useState('') const { createTask } = useContext(TaskContext) const handleSubmit = (e) => { e.preventDefault() createTask(title, description) settitle('') setdescription('') } return ( <div className='max-w-md mx-auto'> <form onSubmit={handleSubmit} className='bg-slate-800 p-10 mb-4 rounded-md' > <h1 className='text-2xl font-bold text-white mb-3'>Crea tu tarea</h1> <input placeholder="Ecribe tu tarea" onChange={(e) => settitle(e.target.value) } value={title} className='bg-slate-300 p-3 w-full mb-2 rounded-md' /> <textarea placeholder='Escribe la decripcion de la tarea' onChange={(e) => setdescription(e.target.value) } value={description} className='bg-slate-300 p-3 w-full mb-2 rounded-md'></textarea> <button className='bg-indigo-500 py-1 text-white rounded-md p-4 font-bold'> Guardar </button> </form> </div> ) } export default TaskForm
import { securityAPI } from "./../api/security-api"; import { ResultCodesEnum, ResultCodeForCaptchaEnum } from "./../api/api"; import { authAPI } from "./../api/auth-api"; import { BaseThunkType, InferActionsTypes } from "./redux-store"; const SET_USER_DATA = "social-network/auth/SET_USER_DATA"; const GET_CAPTCHA_URL_SUCCESS = "social-network/auth/SET_CAPTCHA_URL"; let initialState = { userId: null as number | null, email: null as string | null, login: null as string | null, isAuth: false as boolean, captchaUrl: null as string | null, }; export type InitialStateType = typeof initialState; type ActionsTypes = InferActionsTypes<typeof actions>; type ThunkType= BaseThunkType<ActionsTypes > const authReducer = (state = initialState, action: any): InitialStateType => { switch (action.type) { case SET_USER_DATA: return { ...state, ...action.payload, }; case GET_CAPTCHA_URL_SUCCESS: return { ...state, captchaUrl: action.payload.captchaUrl, }; default: return state; } }; export const actions = { setAuthUserData: ( userId: number | null, email: string | null, login: string | null, isAuth: boolean ) => ({ type: SET_USER_DATA, payload: { userId, email, login, isAuth }, } as const), getCaptchaUrlSuccess: (captchaUrl: string) => ({ type: GET_CAPTCHA_URL_SUCCESS, payload: { captchaUrl }, } as const), }; export const getAuthUserData = ():ThunkType => async (dispatch) => { let data = await authAPI.me(); if (data.resultCode === ResultCodesEnum.Success) { let { id, email, login } = data.data; dispatch(actions.setAuthUserData(id, email, login, true)); } }; export const login = (email: string, password: string, rememberMe: boolean, captcha: string):ThunkType => async (dispatch) => { let data = await authAPI.login(email, password, rememberMe, captcha); if (data.resultCode === ResultCodesEnum.Success) { dispatch(getAuthUserData()); } else { if (data.resultCode === ResultCodeForCaptchaEnum.CaptchaIsRequired) { dispatch(getCaptchaUrl()); } let message = data.messages.length > 0 ? data.messages[0] : "Some error"; alert(message); } }; export const getCaptchaUrl = ():ThunkType => async (dispatch) => { const data = await securityAPI.getCaptchaUrl(); const captchaUrl = data.url; dispatch(actions.getCaptchaUrlSuccess(captchaUrl)); }; export const logout = ():ThunkType => async (dispatch) => { let response = await authAPI.logout(); if (response.data.resultCode === 0) { dispatch(actions.setAuthUserData(null, null, null, false)); } }; export default authReducer;
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="lib/vue.js"></script> <link rel="stylesheet" href="https://unpkg.com/[email protected]/animate.min.css"> <!-- 入场 bounceIn 离场 bounceOut --> </head> <body> <div id="app"> <input type="button" value="toggle" @click="flag=!flag"> <!-- 需求:点击按钮,让h3显示,再点击,让h3隐藏 --> <!-- <transition enter-active-class="animated bounceIn" leave-active-class="animated bounceOut"> <h3 v-if="flag">这是一个h3</h3> </transition> --> <!-- 或者 --> <!-- 使用 :duration="毫秒值" 来统一设置 入场 和 离场 时候的动画时长 --> <!-- <transition enter-active-class="bounceIn" leave-active-class="bounceOut" :duration="200"> <h3 v-if="flag" class="animated">这是一个h3</h3> </transition> --> <!-- 使用 :duration="{ enter:200,leave:400 }" 来分别设置 入场的时长 和 离场的时长 --> <transition enter-active-class="bounceIn" leave-active-class="bounceOut" :duration="{ enter:200,leave:400 }"> <h3 v-if="flag" class="animated">这是一个h3</h3> </transition> </div> <script> var vm = new Vue({ el: '#app', data: { flag:false }, methods: {} }); </script> </body> </html>
/********************************************************************* * Copyright (c) Intel Corporation 2023 * SPDX-License-Identifier: Apache-2.0 **********************************************************************/ package ethernetport import ( "encoding/xml" "testing" "github.com/stretchr/testify/assert" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/internal/message" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/common" "github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/wsman/wsmantesting" ) func TestJson(t *testing.T) { response := Response{ Body: Body{ GetAndPutResponse: SettingsResponse{}, }, } expectedResult := "{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"GetAndPutResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"ElementName\":\"\",\"InstanceID\":\"\",\"VLANTag\":0,\"SharedMAC\":false,\"MACAddress\":\"\",\"LinkIsUp\":false,\"LinkPolicy\":null,\"LinkPreference\":0,\"LinkControl\":0,\"SharedStaticIp\":false,\"SharedDynamicIP\":false,\"IpSyncEnabled\":false,\"DHCPEnabled\":false,\"IPAddress\":\"\",\"SubnetMask\":\"\",\"DefaultGateway\":\"\",\"PrimaryDNS\":\"\",\"SecondaryDNS\":\"\",\"ConsoleTcpMaxRetransmissions\":0,\"WLANLinkProtectionLevel\":0,\"PhysicalConnectionType\":0,\"PhysicalNicMedium\":0},\"EnumerateResponse\":{\"EnumerationContext\":\"\"},\"PullResponse\":{\"XMLName\":{\"Space\":\"\",\"Local\":\"\"},\"EthernetPortItems\":null}}" result := response.JSON() assert.Equal(t, expectedResult, result) } func TestYaml(t *testing.T) { response := Response{ Body: Body{ GetAndPutResponse: SettingsResponse{}, }, } expectedResult := "xmlname:\n space: \"\"\n local: \"\"\ngetandputresponse:\n xmlname:\n space: \"\"\n local: \"\"\n elementname: \"\"\n instanceid: \"\"\n vlantag: 0\n sharedmac: false\n macaddress: \"\"\n linkisup: false\n linkpolicy: []\n linkpreference: 0\n linkcontrol: 0\n sharedstaticip: false\n shareddynamicip: false\n ipsyncenabled: false\n dhcpenabled: false\n ipaddress: \"\"\n subnetmask: \"\"\n defaultgateway: \"\"\n primarydns: \"\"\n secondarydns: \"\"\n consoletcpmaxretransmissions: 0\n wlanlinkprotectionlevel: 0\n physicalconnectiontype: 0\n physicalnicmedium: 0\nenumerateresponse:\n enumerationcontext: \"\"\npullresponse:\n xmlname:\n space: \"\"\n local: \"\"\n ethernetportitems: []\n" result := response.YAML() assert.Equal(t, expectedResult, result) } func TestPositiveAMT_EthernetPortSettings(t *testing.T) { messageID := 0 resourceURIBase := wsmantesting.AMTResourceURIBase wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/ethernetport", } elementUnderTest := NewEthernetPortSettingsWithClient(wsmanMessageCreator, &client) t.Run("amt_EthernetPortSettings Tests", func(t *testing.T) { tests := []struct { name string method string action string body string extraHeader string responseFunc func() (Response, error) expectedResponse interface{} }{ // GETS { "should create a valid AMT_EthernetPortSettings Get wsman message", AMTEthernetPortSettings, wsmantesting.Get, "", "<w:SelectorSet><w:Selector Name=\"InstanceID\">Intel(r) AMT Ethernet Port Settings 0</w:Selector></w:SelectorSet>", func() (Response, error) { client.CurrentMessage = wsmantesting.CurrentMessageGet return elementUnderTest.Get("Intel(r) AMT Ethernet Port Settings 0") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: SettingsResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", Local: "AMT_EthernetPortSettings"}, ElementName: "Intel(r) AMT Ethernet Port Settings", InstanceID: "Intel(r) AMT Ethernet Port Settings 0", SharedMAC: true, MACAddress: "c8-d9-d2-7a-1e-33", LinkIsUp: true, LinkPolicy: []LinkPolicy{1, 14}, SharedStaticIp: false, SharedDynamicIP: true, IpSyncEnabled: true, DHCPEnabled: true, SubnetMask: "255.255.255.0", DefaultGateway: "192.168.0.1", PrimaryDNS: "68.105.28.11", SecondaryDNS: "68.105.29.11", PhysicalConnectionType: 0, }, }, }, // ENUMERATES { "should create a valid AMT_EthernetPortSettings Enumerate wsman message", AMTEthernetPortSettings, wsmantesting.Enumerate, wsmantesting.EnumerateBody, "", func() (Response, error) { client.CurrentMessage = wsmantesting.CurrentMessageEnumerate return elementUnderTest.Enumerate() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "7700000-0000-0000-0000-000000000000", }, }, }, // PULLS { "should create a valid AMT_EthernetPortSettings Pull wsman message", AMTEthernetPortSettings, wsmantesting.Pull, wsmantesting.PullBody, "", func() (Response, error) { client.CurrentMessage = wsmantesting.CurrentMessagePull return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PullResponse: PullResponse{ XMLName: xml.Name{Space: "http://schemas.xmlsoap.org/ws/2004/09/enumeration", Local: "PullResponse"}, EthernetPortItems: []SettingsResponse{ { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", Local: "AMT_EthernetPortSettings"}, ElementName: "Intel(r) AMT Ethernet Port Settings", InstanceID: "Intel(r) AMT Ethernet Port Settings 0", VLANTag: 0, SharedMAC: true, MACAddress: "00-be-43-d8-22-a4", LinkIsUp: true, LinkPolicy: []LinkPolicy{1, 14}, SharedStaticIp: false, SharedDynamicIP: true, IpSyncEnabled: true, DHCPEnabled: true, SubnetMask: "255.255.255.0", DefaultGateway: "192.168.6.1", PrimaryDNS: "192.168.6.1", PhysicalConnectionType: 0, }, { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", Local: "AMT_EthernetPortSettings"}, ElementName: "Intel(r) AMT Ethernet Port Settings", InstanceID: "Intel(r) AMT Ethernet Port Settings 1", SharedMAC: true, MACAddress: "00-00-00-00-00-00", LinkIsUp: false, LinkPreference: 2, LinkControl: 2, DHCPEnabled: true, ConsoleTcpMaxRetransmissions: 5, WLANLinkProtectionLevel: 1, PhysicalConnectionType: 3, }, }, }, }, }, // PUTS { "should create a valid AMT_EthernetPortSettings Put wsman message", AMTEthernetPortSettings, wsmantesting.Put, "<h:AMT_EthernetPortSettings xmlns:h=\"http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings\"><h:ElementName>Intel(r) AMT Ethernet Port Settings</h:ElementName><h:InstanceID>Intel(r) AMT Ethernet Port Settings 0</h:InstanceID><h:SharedMAC>true</h:SharedMAC><h:LinkIsUp>false</h:LinkIsUp><h:SharedStaticIp>true</h:SharedStaticIp><h:IpSyncEnabled>true</h:IpSyncEnabled><h:DHCPEnabled>true</h:DHCPEnabled></h:AMT_EthernetPortSettings>", "<w:SelectorSet><w:Selector Name=\"InstanceID\">Intel(r) AMT Ethernet Port Settings 0</w:Selector></w:SelectorSet>", func() (Response, error) { ethernetPortSettings := SettingsRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", DHCPEnabled: true, ElementName: "Intel(r) AMT Ethernet Port Settings", InstanceID: "Intel(r) AMT Ethernet Port Settings 0", IpSyncEnabled: true, SharedMAC: true, SharedStaticIp: true, } client.CurrentMessage = wsmantesting.CurrentMessagePut return elementUnderTest.Put(ethernetPortSettings.InstanceID, ethernetPortSettings) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: SettingsResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", Local: "AMT_EthernetPortSettings"}, DHCPEnabled: true, DefaultGateway: "192.168.0.1", ElementName: "Intel(r) AMT Ethernet Port Settings", IPAddress: "192.168.0.24", InstanceID: "Intel(r) AMT Ethernet Port Settings 0", IpSyncEnabled: true, LinkIsUp: true, LinkPolicy: []LinkPolicy{1, 14, 16}, MACAddress: "a4-ae-11-1e-46-53", PhysicalConnectionType: 0, PrimaryDNS: "68.105.28.11", SecondaryDNS: "68.105.29.11", SharedDynamicIP: true, SharedMAC: true, SharedStaticIp: true, SubnetMask: "255.255.255.0", }, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.NoError(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.Equal(t, test.expectedResponse, response.Body) }) } }) } func TestNegativeAMT_EthernetPortSettings(t *testing.T) { messageID := 0 resourceURIBase := wsmantesting.AMTResourceURIBase wsmanMessageCreator := message.NewWSManMessageCreator(resourceURIBase) client := wsmantesting.MockClient{ PackageUnderTest: "amt/ethernetport", } elementUnderTest := NewEthernetPortSettingsWithClient(wsmanMessageCreator, &client) t.Run("amt_EthernetPortSettings Tests", func(t *testing.T) { tests := []struct { name string method string action string body string extraHeader string responseFunc func() (Response, error) expectedResponse interface{} }{ // GETS { "should create a valid AMT_EthernetPortSettings Get wsman message", AMTEthernetPortSettings, wsmantesting.Get, "", "<w:SelectorSet><w:Selector Name=\"InstanceID\">Intel(r) AMT Ethernet Port Settings 0</w:Selector></w:SelectorSet>", func() (Response, error) { client.CurrentMessage = wsmantesting.CurrentMessageError return elementUnderTest.Get("Intel(r) AMT Ethernet Port Settings 0") }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: SettingsResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", Local: "AMT_EthernetPortSettings"}, ElementName: "Intel(r) AMT Ethernet Port Settings", InstanceID: "Intel(r) AMT Ethernet Port Settings 0", SharedMAC: true, MACAddress: "c8-d9-d2-7a-1e-33", LinkIsUp: true, LinkPolicy: []LinkPolicy{1, 14}, SharedStaticIp: false, SharedDynamicIP: true, IpSyncEnabled: true, DHCPEnabled: true, SubnetMask: "255.255.255.0", DefaultGateway: "192.168.0.1", PrimaryDNS: "68.105.28.11", SecondaryDNS: "68.105.29.11", PhysicalConnectionType: 0, }, }, }, // ENUMERATES { "should create a valid AMT_EthernetPortSettings Enumerate wsman message", AMTEthernetPortSettings, wsmantesting.Enumerate, wsmantesting.EnumerateBody, "", func() (Response, error) { client.CurrentMessage = wsmantesting.CurrentMessageError return elementUnderTest.Enumerate() }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, EnumerateResponse: common.EnumerateResponse{ EnumerationContext: "7700000-0000-0000-0000-000000000000", }, }, }, // PULLS { "should create a valid AMT_EthernetPortSettings Pull wsman message", AMTEthernetPortSettings, wsmantesting.Pull, wsmantesting.PullBody, "", func() (Response, error) { client.CurrentMessage = wsmantesting.CurrentMessageError return elementUnderTest.Pull(wsmantesting.EnumerationContext) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, PullResponse: PullResponse{ XMLName: xml.Name{Space: "http://schemas.xmlsoap.org/ws/2004/09/enumeration", Local: "PullResponse"}, EthernetPortItems: []SettingsResponse{ { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", Local: "AMT_EthernetPortSettings"}, ElementName: "Intel(r) AMT Ethernet Port Settings", InstanceID: "Intel(r) AMT Ethernet Port Settings 0", VLANTag: 0, SharedMAC: true, MACAddress: "00-be-43-d8-22-a4", LinkIsUp: true, LinkPolicy: []LinkPolicy{1, 14}, SharedStaticIp: false, SharedDynamicIP: true, IpSyncEnabled: true, DHCPEnabled: true, SubnetMask: "255.255.255.0", DefaultGateway: "192.168.6.1", PrimaryDNS: "192.168.6.1", PhysicalConnectionType: 0, }, { XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", Local: "AMT_EthernetPortSettings"}, ElementName: "Intel(r) AMT Ethernet Port Settings", InstanceID: "Intel(r) AMT Ethernet Port Settings 1", SharedMAC: true, MACAddress: "00-00-00-00-00-00", LinkIsUp: false, LinkPreference: 2, LinkControl: 2, DHCPEnabled: true, ConsoleTcpMaxRetransmissions: 5, WLANLinkProtectionLevel: 1, PhysicalConnectionType: 3, }, }, }, }, }, // PUTS { "should create a valid AMT_EthernetPortSettings Put wsman message", AMTEthernetPortSettings, wsmantesting.Put, "<h:AMT_EthernetPortSettings xmlns:h=\"http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings\"><h:ElementName>Intel(r) AMT Ethernet Port Settings</h:ElementName><h:InstanceID>Intel(r) AMT Ethernet Port Settings 0</h:InstanceID><h:SharedMAC>true</h:SharedMAC><h:LinkIsUp>false</h:LinkIsUp><h:SharedStaticIp>true</h:SharedStaticIp><h:IpSyncEnabled>true</h:IpSyncEnabled><h:DHCPEnabled>true</h:DHCPEnabled></h:AMT_EthernetPortSettings>", "<w:SelectorSet><w:Selector Name=\"InstanceID\">Intel(r) AMT Ethernet Port Settings 0</w:Selector></w:SelectorSet>", func() (Response, error) { ethernetPortSettings := SettingsRequest{ H: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", DHCPEnabled: true, ElementName: "Intel(r) AMT Ethernet Port Settings", InstanceID: "Intel(r) AMT Ethernet Port Settings 0", IpSyncEnabled: true, SharedMAC: true, SharedStaticIp: true, } client.CurrentMessage = wsmantesting.CurrentMessageError return elementUnderTest.Put(ethernetPortSettings.InstanceID, ethernetPortSettings) }, Body{ XMLName: xml.Name{Space: message.XMLBodySpace, Local: "Body"}, GetAndPutResponse: SettingsResponse{ XMLName: xml.Name{Space: "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_EthernetPortSettings", Local: "AMT_EthernetPortSettings"}, DHCPEnabled: true, DefaultGateway: "192.168.0.1", ElementName: "Intel(r) AMT Ethernet Port Settings", IPAddress: "192.168.0.24", InstanceID: "Intel(r) AMT Ethernet Port Settings 0", IpSyncEnabled: true, LinkIsUp: true, LinkPolicy: []LinkPolicy{1, 14, 16}, MACAddress: "a4-ae-11-1e-46-53", PhysicalConnectionType: 0, PrimaryDNS: "68.105.28.11", SecondaryDNS: "68.105.29.11", SharedDynamicIP: true, SharedMAC: true, SharedStaticIp: true, SubnetMask: "255.255.255.0", }, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { expectedXMLInput := wsmantesting.ExpectedResponse(messageID, resourceURIBase, test.method, test.action, test.extraHeader, test.body) messageID++ response, err := test.responseFunc() assert.Error(t, err) assert.Equal(t, expectedXMLInput, response.XMLInput) assert.NotEqual(t, test.expectedResponse, response.Body) }) } }) }
/* * Copyright (c) 2023 Airbyte, Inc., all rights reserved. */ package io.airbyte.integrations.source.singlestore; import io.airbyte.cdk.db.factory.DatabaseDriver; import io.airbyte.cdk.testutils.ContainerFactory.NamedContainerModifier; import io.airbyte.cdk.testutils.TestDatabase; import io.airbyte.integrations.source.singlestore.SingleStoreTestDatabase.SingleStoreConfigBuilder; import java.io.IOException; import java.io.UncheckedIOException; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jooq.SQLDialect; public class SingleStoreTestDatabase extends TestDatabase<AirbyteSingleStoreTestContainer, SingleStoreTestDatabase, SingleStoreConfigBuilder> { public enum BaseImage { SINGLESTORE_DEV("ghcr.io/singlestore-labs/singlestoredb-dev:latest"); public final String reference; BaseImage(String reference) { this.reference = reference; } } public enum ContainerModifier implements NamedContainerModifier<AirbyteSingleStoreTestContainer> { CERT(SingleStoreContainerFactory::withCert); private Consumer<AirbyteSingleStoreTestContainer> modifer; ContainerModifier(final Consumer<AirbyteSingleStoreTestContainer> modifer) { this.modifer = modifer; } @Override public Consumer<AirbyteSingleStoreTestContainer> modifier() { return modifer; } } static public SingleStoreTestDatabase in(BaseImage baseImage, ContainerModifier... modifiers) { final var container = new SingleStoreContainerFactory().shared(baseImage.reference, modifiers); return new SingleStoreTestDatabase(container).initialized(); } public SingleStoreTestDatabase(AirbyteSingleStoreTestContainer container) { super(container); } @Override protected Stream<Stream<String>> inContainerBootstrapCmd() { final var sql = Stream.of(String.format("CREATE DATABASE %s", getDatabaseName()), String.format("CREATE USER %s IDENTIFIED BY '%s'", getUserName(), getPassword()), String.format("GRANT ALL ON %s.* TO %s", getDatabaseName(), getUserName())); getContainer().withUsername(getUserName()).withPassword(getPassword()).withDatabaseName(getDatabaseName()); return Stream.of(singlestoreCmd(sql)); } @Override protected Stream<String> inContainerUndoBootstrapCmd() { return singlestoreCmd(Stream.of(String.format("DROP USER %s", getUserName()), String.format("DROP DATABASE \\`%s\\`", getDatabaseName()))); } @Override public DatabaseDriver getDatabaseDriver() { return DatabaseDriver.SINGLESTORE; } @Override public SQLDialect getSqlDialect() { return SQLDialect.DEFAULT; } @Override public SingleStoreConfigBuilder configBuilder() { return new SingleStoreConfigBuilder(this); } public Stream<String> singlestoreCmd(Stream<String> sql) { return Stream.of("/bin/bash", "-c", String.format("set -o errexit -o pipefail; echo \"%s\" | singlestore -v -v -v --user=root --password=root", sql.collect(Collectors.joining("; ")))); } private Certificates cachedCerts; public synchronized Certificates getCertificates() { if (cachedCerts == null) { final String caCert, serverKey, serverCert; try { caCert = getContainer().execInContainer("/bin/bash", "-c", "cat /certs/ca-cert.pem").getStdout().trim(); serverKey = getContainer().execInContainer("/bin/bash", "-c", "cat /certs/server-key.pem").getStdout().trim(); serverCert = getContainer().execInContainer("/bin/bash", "-c", "cat /certs/server-cert.pem").getStdout().trim(); } catch (IOException e) { throw new UncheckedIOException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } cachedCerts = new Certificates(caCert, serverKey, serverCert); } return cachedCerts; } public record Certificates(String caCertificate, String serverKey, String serverCert) { } static public class SingleStoreConfigBuilder extends ConfigBuilder<SingleStoreTestDatabase, SingleStoreConfigBuilder> { protected SingleStoreConfigBuilder(SingleStoreTestDatabase testDatabase) { super(testDatabase); } public SingleStoreConfigBuilder withStandardReplication() { return with("replication_method", "STANDARD"); } } }
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class CreateUser extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ "username"=>"required|min:8|max:40|unique:users,username", "avatar"=>"required", "role"=>"required|in:normal,admin,author", "email"=>"required|email|unique:users,email", "password"=>"required|min:8|max:225" ]; } }
import * as path from 'path'; import * as vscode from 'vscode'; import * as logger from './lib/logger'; import { Device, Simulator, Target, TargetType } from './lib/commonTypes'; import { randomString } from './lib/utils'; import * as targetCommand from './targetCommand'; import { getTargetFromUDID, pickTarget, getOrPickTarget } from './targetPicker'; import * as simulatorFocus from './simulatorFocus'; let context: vscode.ExtensionContext; const lldbPlatform: {[T in TargetType]: string} = { // eslint-disable-next-line @typescript-eslint/naming-convention "Simulator": "ios-simulator", // eslint-disable-next-line @typescript-eslint/naming-convention "Device": "remote-ios" }; function getOutputBasename() { return path.join('/tmp', `ios-${randomString(16)}`); } export class DebugConfigurationProvider implements vscode.DebugConfigurationProvider { private async getTarget(iosTarget: string): Promise<Target|undefined> { if (iosTarget === "select") { return await pickTarget(); } else if (iosTarget === "last-selected") { return await getOrPickTarget(); } else if (typeof iosTarget === "string") { return await getTargetFromUDID(iosTarget); } return undefined; } ensureBundleId(dbgConfig: vscode.DebugConfiguration): string { if (!dbgConfig.iosBundleId) { throw new Error("Could not determine bundle id for the app"); } return dbgConfig.iosBundleId; } async resolveDebugConfiguration(folder: vscode.WorkspaceFolder|undefined, dbgConfig: vscode.DebugConfiguration, token: vscode.CancellationToken) { logger.log("resolveDebugConfiguration", dbgConfig); if (!dbgConfig.iosTarget) { return dbgConfig; } let target: Target|undefined = await this.getTarget(dbgConfig.iosTarget); if (!target) { return null; } dbgConfig.iosTarget = target; dbgConfig.iosRequest = dbgConfig.request; dbgConfig.request = target.type === "Simulator" ? "attach" : dbgConfig.request; dbgConfig.initCommands = (dbgConfig.initCommands instanceof Array) ? dbgConfig.initCommands : []; dbgConfig.initCommands.unshift(`command script import '${context.asAbsolutePath("lldb/logs.py")}'`); dbgConfig.initCommands.unshift(`command script import '${context.asAbsolutePath("lldb/simulator_focus.py")}'`); dbgConfig.initCommands.unshift(`platform select ${lldbPlatform[target.type]}`); return dbgConfig; } async resolveDebugConfigurationWithSubstitutedVariables(folder: vscode.WorkspaceFolder|undefined, dbgConfig: vscode.DebugConfiguration, token: vscode.CancellationToken) { logger.log("resolveDebugConfigurationWithSubstitutedVariables", dbgConfig); if (!dbgConfig.iosTarget) { return dbgConfig; } if (dbgConfig.sessionName) { dbgConfig.name = dbgConfig.sessionName; } // Enable OS_ACTIVITY_DT_MODE by default unless disabled for both Simulator and Device // This is required for logging to work properly dbgConfig.env = { // eslint-disable-next-line @typescript-eslint/naming-convention "OS_ACTIVITY_DT_MODE": "YES", ...dbgConfig.env }; if (typeof dbgConfig.iosInstallApp === "undefined") { dbgConfig.iosInstallApp = true; } let target: Target = dbgConfig.iosTarget; if (target.type === "Simulator") { let pid: string|void; // Check if we have enough permissions for the simulator focus monitor. let enableSimulatorFocusMonitor = vscode.workspace.getConfiguration().get('ios-debug.focusSimulator') && await simulatorFocus.tryEnsurePermissions(); if (dbgConfig.iosRequest === "launch") { let outputBasename = getOutputBasename(); let stdout = `${outputBasename}-stdout`; let stderr = `${outputBasename}-stderr`; if (dbgConfig.iosInstallApp) { pid = await targetCommand.simulatorInstallAndLaunch({ target: target as Simulator, path: dbgConfig.program, bundleId: this.ensureBundleId(dbgConfig), env: dbgConfig.env, args: dbgConfig.args, stdio: {stdout, stderr}, waitForDebugger: true, }); } else { pid = await targetCommand.simulatorLaunch({ target: target as Simulator, bundleId: this.ensureBundleId(dbgConfig), env: dbgConfig.env, args: dbgConfig.args, stdio: {stdout, stderr}, waitForDebugger: true, }); } dbgConfig.initCommands.push(`follow ${stdout}`); dbgConfig.initCommands.push(`follow ${stderr}`); } else { pid = await targetCommand.simulatorGetPidFor({ target: target as Simulator, bundleId: this.ensureBundleId(dbgConfig), }); } if (!pid) { return null; } dbgConfig.pid = pid; if (enableSimulatorFocusMonitor) { dbgConfig.postRunCommands = (dbgConfig.postRunCommands instanceof Array) ? dbgConfig.postRunCommands : []; dbgConfig.postRunCommands.push(`simulator-focus-monitor ${target.name} – ${target.runtime}`); } delete dbgConfig.env; delete dbgConfig.args; } else if (target.type === "Device") { let platformPath: string|void; if (dbgConfig.iosRequest === "launch") { if (dbgConfig.iosInstallApp) { platformPath = await targetCommand.deviceInstall({ target: target as Device, path: dbgConfig.program, }); } else { platformPath = await targetCommand.deviceAppPath({ target: target as Device, bundleId: this.ensureBundleId(dbgConfig), }); } } else { platformPath = await targetCommand.deviceAppPath({ target: target as Device, bundleId: this.ensureBundleId(dbgConfig), }); let pid = await targetCommand.deviceGetPidFor({ target: target as Device, bundleId: this.ensureBundleId(dbgConfig), }); if (!pid) { return null; } dbgConfig.pid = pid; } if (!platformPath) { return null; } let debugserverPort = await targetCommand.deviceDebugserver({ target: target as Device, }); if (!debugserverPort) { return null; } dbgConfig.iosDebugserverPort = debugserverPort; dbgConfig.preRunCommands = (dbgConfig.preRunCommands instanceof Array) ? dbgConfig.preRunCommands : []; dbgConfig.preRunCommands.push(`script lldb.target.module[0].SetPlatformFileSpec(lldb.SBFileSpec('${platformPath}'))`); dbgConfig.preRunCommands.push(`process connect connect://127.0.0.1:${debugserverPort}`); } logger.log("resolved debug configuration", dbgConfig); return dbgConfig; } } export function activate(c: vscode.ExtensionContext) { context = c; }
package GDT_JAVA_Train.Assignment7.src.com.infosys.dao; import java.util.ArrayList; import GDT_JAVA_Train.Assignment7.src.com.infosys.exceptions.UserNotFoundException; import GDT_JAVA_Train.Assignment7.src.com.infosys.pojo.User; public class UserDAO { private ArrayList<User> userList = new ArrayList<User>(); private int count = 0; private int id = 0; public void addUser(String name, String password, String role){ User user = new User(id, name,password, role); userList.add(user); id++; count++; } public User getUserByName(String name) throws UserNotFoundException { User user = null; for(User u : userList){ if(u.getName().equals(name)){ user = u; } } if(user == null){ throw new UserNotFoundException("User not found"); } return user; } public void deleteUser(int userId) throws UserNotFoundException { User user = null; try{ user = getUserById(userId); } catch (UserNotFoundException e) { throw e; } userList.remove(user); } public void updateUserById(int userId, String name, String password, String role) throws UserNotFoundException { User user = null; try { user = getUserById(userId); } catch (UserNotFoundException e){ throw e; } user.setName(name); user.setPassword(password); user.setRole(role); } public User getUserById(int userId) throws UserNotFoundException { User user = null; for ( User u : userList){ if (u.getUserId() == userId){ user = u; } } if(user == null){ throw new UserNotFoundException("User not found"); } return user; } public int getUserCount(){ return count; } }
Nome do Componente Curricular: Tópicos em Ressonância Magnética Nuclear Pré-requisitos: Fenômenos Eletromagnéticos Carga Horária Total: 72h Carga Horária Prática: 0h Carga Horária Teórica: 72h Objetivos Gerais: Propiciar amplo conhecimento sobre os conceitos físicos e a instrumentação em equipamentos de Ressonância Magnética Nuclear (RMN) para aplicações em imagens, espectroscopia e técnicas de relaxometria. Específicos: Fornecer ao aluno conhecimento amplo sobre os conceitos físicos de RMN, incluindo sequências de pulso, formação de imagens e obtenção de técnicas uni e bidimensionais. Fornecer ao aluno o conceito básico de um equipamento de RMN, incluindo o espectrômetro, o magneto e as sondas utilizadas para as medidas. Propiciar ao aluno uma visão geral sobre uma gama de aplicações de RMN nas mais diversas áreas de conhecimento (biológicas e materiais). Desenvolver a capacidade do aluno em relacionar os conceitos de RMN em suas áreas de trabalho. Ementa: Introdução à Ressonância Magnética Nuclear; O equipamento de RMN; Sequências de pulso; Formação de imagens; Instrumentação em RMN; Técnicas espectroscópicas de RMN; Relaxometria; Técnicas avançadas de imagens em RMN. Conteúdo Programático: 1. Introdução à teoria de RMN: propriedades dos núcleos atômicos, magnetização, excitação da magnetização por radiofrequência (RF), FID, mecanismos de relaxação, equações de Bloch, ecos de spin. 2. Equipamento de RMN: Magneto, espectrômetro, sondas e bobinas de gradientes; 3. Sequências de pulso: Spin Eco e Gradiente Eco; 4. Formação de imagens: princípio de formação de imagem, resolução e contraste - efeito de T1, T2 e DP; 5. Técnicas avançadas de imagens “in vivo” por RM: Relaxometria; Perfusão; Difusão; BOLD; Transferência de magnetização; Angiografia. 6. Instrumentação em RMN: sondas, linha de transmissão e filtros; 7. Técnicas de espectroscopia em RMN – interações nucleares, RMN multidimensional, ciclagem de fase; 8. Técnicas uni e bidimensionais, medidas de distribuição de tempos de relaxação e difusão; 9. Aplicações em materiais e biologia – estudo de dinâmica molecular em sólidos, determinação de estruturas moleculares, materiais porosos, polímeros sólidos. Metodologia de Ensino Utilizada: Aulas expositivas e seminários. Recursos Instrucionais Necessários: Lousa e projetor multimídia. Critérios de Avaliação: O sistema de avaliação será definido pelo docente responsável pela unidade curricular no início das atividades letivas e divulgado aos alunos. O sistema adotado deve contemplar o processo de ensino e aprendizagem estabelecido neste Projeto Pedagógico, com o objetivo de favorecer o progresso do aluno ao longo do semestre. Para isto, as avaliações deverão ser ponderadas de maneira crescente ou, ainda, propiciar alternativas de recuperação, como provas substitutivas ou aplicação de trabalhos adicionais. A promoção do aluno na unidade curricular obedecerá aos critérios estabelecidos pela Pró-Reitoria de Graduação, tal como discutido no Projeto Pedagógico do Curso. Bibliografia Básica: 1. WEBB, S. (Ed.). The physics of medical imaging. Bristol: Institute of Physics, 2003. 2. HAACKE, E.M. Magnetic resonance imaging: physical principles and sequence design. New York, Wiley. 3. HOBBIE, R.K. Intermediate Physics for Medicine and Biology, AIP Press, New York, 1997. Complementar: 1. TOFTS, P. Quantitative MRI of the brain: measuring changes caused by disease. Chichester, John Wiley & Sons Ltd, 2003. 2. DUER, M. J. Solid State NMR Spectroscopy – Principles and applications, Blackwell Science, 2002. 3. SPRAWLS, JR. P., Physical Principles of Medical Imaging. Second edition. Medical Physics Publishing Company, ed. Aspen Publishers, 1995. 4. BUSHONG, S.C. Magnetic resonance imaging : physical and biological principles. St Louis, CV. Mosby, 1989. 5. BUSHBERG, J. T.; SEIBERT, J. A.; LEIDHOLFT JUNIOR, E. M.; BOONE, J. M. The essential physics of medical imaging. 2. ed. Philadelphia, PA: Lippincott Willians & Wilkins, 2002.
import { UserProps } from './User'; export class Attributes<T> { constructor(private data: T) {} // this will bind this to context get = <K extends keyof T>(key: K): T[K] => { return this.data[key]; } set(update: T): void { Object.assign(this.data, update); } getAll(): T { return this.data; } } // if you hover over these variable names, you'll see different type set due to get<K extends keyof T>(key: K): T[K] setup on get // const attrs = new Attributes<UserProps>({ // id: 5, // age: 20, // name: 'hello', // }) // const name = attrs.get('name'); // const age = attrs.get('age'); // const id = attrs.get('age');
import { useContext } from "react"; //import { getRooms } from "../../api/rooms"; import { AuthContext } from "../../providers/AuthProvider"; import RoomDataRow from "../../components/Dashboard/RoomDataRow"; import EmptyState from "../../components/Shared/Navbar/EmptyState"; import useAxiosSecure from "../../Hooks/useAxiosSecure"; import { useQuery } from "@tanstack/react-query"; const MyListings = () => { const [axiosSecure] = useAxiosSecure(); const { user, loading } = useContext(AuthContext); const { refetch, data: rooms = [] } = useQuery({ queryKey: ["rooms", user?.email], enabled: !loading, queryFn: async () => { const res = await axiosSecure( `${import.meta.env.VITE_API_URL}/rooms/${user?.email}` ); console.log("res from axios", res.data); return res.data; }, }); // const [rooms, setRooms] = useState([]) // const fetchRooms = () => getRooms(user?.email).then(data => setRooms(data)) // useEffect(() => { // fetchRooms() // }, [user]) return ( <> {rooms && Array.isArray(rooms) && rooms.length > 0 ? ( <div className="container mx-auto px-4 sm:px-8"> <div className="py-8"> <div className="-mx-4 sm:-mx-8 px-4 sm:px-8 py-4 overflow-x-auto"> <div className="inline-block min-w-full shadow rounded-lg overflow-hidden"> <table className="min-w-full leading-normal"> <thead> <tr> <th scope="col" className="px-5 py-3 bg-white border-b border-gray-200 text-gray-800 text-left text-sm uppercase font-normal" > Title </th> <th scope="col" className="px-12 sm:px-14 py-3 bg-white border-b border-gray-200 text-gray-800 text-left text-sm uppercase font-normal" > Location </th> <th scope="col" className="px-5 py-3 bg-white border-b border-gray-200 text-gray-800 text-left text-sm uppercase font-normal" > Price </th> <th scope="col" className="px-5 py-3 bg-white border-b border-gray-200 text-gray-800 text-left text-sm uppercase font-normal" > From </th> <th scope="col" className="px-5 py-3 bg-white border-b border-gray-200 text-gray-800 text-left text-sm uppercase font-normal" > To </th> <th scope="col" className="px-5 py-3 bg-white border-b border-gray-200 text-gray-800 text-left text-sm uppercase font-normal" > Delete </th> <th scope="col" className="px-5 py-3 bg-white border-b border-gray-200 text-gray-800 text-left text-sm uppercase font-normal" > Update </th> </tr> </thead> <tbody> {rooms && rooms.map((room) => ( <RoomDataRow key={room?._id} room={room} refetch={refetch} //fetchRooms={fetchRooms} /> ))} </tbody> </table> </div> </div> </div> </div> ) : ( <EmptyState message="No Room data available." address="/dashboard/add-room" label="Add Rooms" /> )} </> ); }; export default MyListings;
package org.springframework.boot.ioc.demo.annotations; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.ioc.demo.annotations.goods.FruitTea; import org.springframework.boot.ioc.demo.annotations.goods.PureTea; import org.springframework.boot.ioc.demo.common.imports.Menu; import org.springframework.boot.ioc.demo.common.scans.AliPay; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class BinaryTeaTest { /** * 基于注解 */ @Test public void annotationDemo() { try { // 说明@Bean标注的方法生效 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class); Boss boss = context.getBean(Boss.class); // 说明@ComponentScan生效 AliPay aliPay = context.getBean(AliPay.class); System.out.println(aliPay); Customer bean = context.getBean(Customer.class); System.out.println(bean); // 说明@Import生效 Menu menu = context.getBean(Menu.class); System.out.println(menu); } catch (Exception e) { System.out.println(e); } } /** * 基于spi + BeanDefinitonRegistryPostProcessor完成编程式添加 */ @Test public void programAddBeanDef() { try { // 说明我们动态注册生效 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class); FruitTea fruitTea = context.getBean(FruitTea.class); System.out.println(fruitTea); } catch (Exception e) { System.out.println(e); } } /** * 基于BeanFactoryPostProcessor */ @Test public void programModifyBeanDef() { try { // 说明我们动态注册生效 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class); PureTea pureTea = context.getBean(PureTea.class); System.out.println(pureTea); } catch (Exception e) { System.out.println(e); } } }
interface CaptureConf { is_var:boolean; is_array:boolean; aliases: string[]; } const AliasFormat = /(^[-]{1,2}[^-]+$)/u; const OptionFormat = /^(-[^-=]+)$|^((--[^-=]+)(=.*)?)$/u; const _Captures:WeakMap<CliPArgs, { alias_map:{[alias:string]:string}, var_map:{[name:string]:CaptureConf} }> = new WeakMap(); interface NamedArgs { [key:string|number|symbol]:string[]|string|boolean; } interface ParsedArgs extends NamedArgs { _:string[]; } class CliPArgs { constructor() { _Captures.set(this, {alias_map:{}, var_map:{}}); } variable(name:string, ...aliases:string[]):this { const {var_map} = _Captures.get(this)!; name = name.trim(); if ( name === '_' ) { throw new RangeError("Option \`_\` is a reserved word!"); } if ( !var_map[name] ) { var_map[name] = {is_var:true, is_array:false, aliases:[]}; } if ( !var_map[name].is_var ) { throw new SyntaxError(`Option \"${name}\" has been declared as flag already!`); } RegisterAlias.call(this, name, aliases); return this; } array(name:string, ...aliases:string[]):this { this.variable(name, ...aliases); _Captures.get(this)!.var_map[name].is_array = true; return this; } flag(name:string, ...aliases:string[]):this { const {var_map:capture_map} = _Captures.get(this)!; name = name.trim(); if ( name === '_' ) { throw new RangeError("Option \`_\` is a reserved word!"); } if ( !capture_map[name] ) { capture_map[name] = {is_var:false, is_array:false, aliases:[]}; } if ( capture_map[name].is_var ) { throw new SyntaxError(`Option \"${name}\" has been declared as variable already!`); } RegisterAlias.call(this, name, aliases); return this; } clear(name:string):this { name = name.trim(); if ( name !== "_" ) { const {var_map, alias_map} = _Captures.get(this)!; const {aliases} = var_map[name]; delete var_map[name]; for(const alias of aliases) { delete alias_map[alias]; } } return this; } reset():this { _Captures.set(this, {alias_map:{}, var_map:{}}); return this; } parse<ReturnType extends NamedArgs = any>(args:string[]):ParsedArgs&ReturnType { const {var_map:capture_map, alias_map} = _Captures.get(this)!; const return_value:ParsedArgs = { _:[] }; const _args = args.slice(0).reverse(); while(_args.length > 0) { const arg = _args.pop()!.trim(); const matches = arg.match(OptionFormat); // Not an option if ( !matches ) { return_value._.push(arg); continue; } const [,short,, long, long_val] = matches; const alias = short||long; const var_name = alias_map[alias]; if ( var_name === undefined ) { return_value._.push(arg); continue; } const {is_var, is_array} = capture_map[var_name]; if ( !is_var ) { return_value[var_name] = true; continue; } const value = short ? (_args.pop()?.trim()||null) : (long_val ? long_val.substring(1) : null); if ( value === null ) continue; const registered_value = return_value[var_name]; if ( registered_value === undefined ) { return_value[var_name] = is_array ? [value] : value; } else if ( Array.isArray(registered_value) ) { registered_value.push(value); } else { return_value[var_name] = value; } } return return_value as ParsedArgs&ReturnType; } } function RegisterAlias(this:CliPArgs, name:string, aliases:string[]) { const {var_map:capture_map, alias_map} = _Captures.get(this)!; const {aliases:alias_registry} = capture_map[name]; for(let alias of aliases) { alias = (''+alias).trim(); if ( !AliasFormat.test(alias) ) { console.error(`Alias should only be started with \"-\" or \"--\"! Skipping \"${alias}\" for option \"${name}\"...`); continue; } if ( alias_map[alias] && alias_map[alias] !== name ) { console.error(`Alias \`${alias}\` has been used by option \`${alias_map[alias]}\`! Skipping...`); continue; } alias_registry.push(alias); alias_map[alias] = name; } } export = new CliPArgs();
import React, { useState, useEffect } from "react"; import PropTypes from "prop-types"; import InfiniteScroll from "react-infinite-scroll-component"; import Post from "./post"; export default function Index({ url }) { /* Display image and post owner of a single post */ const [results, setResults] = useState([]) const [nextUrl, setNextUrl] = useState("/api/v1/posts/"); // const [postid, setPostid] = useState(); useEffect(() => { // Declare a boolean flag that we can use to cancel the API request. let ignoreStaleRequest = false; // Call REST API to get the post's information fetch(url, { credentials: "same-origin" }) .then((response) => { if (!response.ok) throw Error(response.statusText); return response.json(); }) .then((data) => { // If ignoreStaleRequest was set to true, we want to ignore the results of the // the request. Otherwise, update the state to trigger a new render. if (!ignoreStaleRequest) { setResults(data.results) if (data.next) { setNextUrl(data.next); } else { setNextUrl(null); } } }) .catch((error) => console.log(error)); return () => { // This is a cleanup function that runs whenever the Post component // unmounts or re-renders. If a Post is about to unmount or re-render, we // should avoid updating state. ignoreStaleRequest = true; }; }, [url]); const fetchMoreData = () => { if (nextUrl) { fetch(nextUrl, { credentials: "same-origin" }) .then(response => response.json()) .then(data => { setResults(prevResults => [...prevResults, ...data.results]); if (data.next) { setNextUrl(data.next); } else { setNextUrl(null); // No more posts to load } }) .catch(error => console.log(error)); } }; const listPosts = results.map(post => <li key={post.postid}> <Post url = {post.url}/> </li> ); // Render post image and post owner return ( <InfiniteScroll dataLength={results.length} next={fetchMoreData} hasMore={nextUrl !== null} loader={<h4>Loading...</h4>} endMessage={ <p style={{textAlign: 'center'}}> <b>No more posts to display</b> </p> } > <ul>{listPosts}</ul> </InfiniteScroll> ); } Index.propTypes = { url: PropTypes.string.isRequired, };
package com.chenlisa.springbootmall.controller; import com.chenlisa.springbootmall.constant.ProductCategory; import com.chenlisa.springbootmall.dto.ProductQueryParams; import com.chenlisa.springbootmall.dto.ProductRequest; import com.chenlisa.springbootmall.model.Product; import com.chenlisa.springbootmall.service.ProductService; import com.chenlisa.springbootmall.util.Page; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import java.util.List; @RestController @Validated public class ProductController { @Autowired private ProductService productService; @GetMapping("/products") public ResponseEntity<Page<Product>> getProducts( // 查詢條件 Filtering @RequestParam(required = false) ProductCategory category, @RequestParam(required = false) String search, // 排序 Sorting @RequestParam(defaultValue = "created_date") String orderBy, @RequestParam(defaultValue = "DESC") String sort, // 分頁 pagination @RequestParam(defaultValue = "10") @Max(1000) @Min(0) Integer limit, @RequestParam(defaultValue = "0") @Min(0) Integer offset ) { ProductQueryParams productQueryParams = new ProductQueryParams(); productQueryParams.setCategory(category); productQueryParams.setSearch(search); productQueryParams.setOrderBy(orderBy); productQueryParams.setSort(sort); productQueryParams.setLimit(limit); productQueryParams.setOffset(offset); // 取得商品列表 List<Product> productList = productService.getProducts(productQueryParams); // 取得商品總數 Integer total = productService.countProduct(productQueryParams); // 分頁 Page<Product> page = new Page<>(); page.setLimit(limit); page.setOffset(offset); page.setTotal(total); page.setResults(productList); return ResponseEntity.status(HttpStatus.OK).body(page); } @GetMapping("/products/{pid}") public ResponseEntity<Product> getProduct(@PathVariable Integer pid) { Product product = productService.getById(pid); if (product != null) { return ResponseEntity.status(HttpStatus.OK).body(product); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } } @PostMapping("/products") public ResponseEntity<Product> createProduct(@RequestBody @Valid ProductRequest productRequest) { Integer productId = productService.create(productRequest); Product product = productService.getById(productId); if (product != null) { return ResponseEntity.status(HttpStatus.CREATED).body(product); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } } @PutMapping("/products/{pid}") public ResponseEntity<Product> createProduct(@PathVariable Integer pid, @RequestBody @Valid ProductRequest productRequest) { // 檢查商品是否存在 Product product = productService.getById(pid); if (product == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } productService.update(pid, productRequest); Product updatedProduct = productService.getById(pid); return ResponseEntity.status(HttpStatus.OK).body(updatedProduct); } @DeleteMapping("/products/{pid}") public ResponseEntity<?> deleteProduct(@PathVariable Integer pid) { productService.delete(pid); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } }
import { DEFAULT_ERROR_CODES } from "./defaultErrorCodes.js"; import { HandlerName } from "../types.js"; import { SessionMiddlewareError } from "./SessionMiddlewareError.js"; export class SessionHandlerError extends SessionMiddlewareError { public get status(): number { if (this._status) { return this._status; } const defaultCode = DEFAULT_ERROR_CODES.get(this._sessionErrorCode)?.status || 500; return defaultCode; } public override get message(): string { if (super.message === undefined) { return super.message; } const defaultMessage = DEFAULT_ERROR_CODES.get(this._sessionErrorCode)?.message || 'Unknown error'; return defaultMessage; } public set handlerChain(chain: HandlerName[]) { this._handlerChain = chain; } public get handlerChain(): HandlerName[]|undefined { return this._handlerChain; } public get clientMessage(): string { if (this._clientMessage) { return this._clientMessage; } return this.message; } public set clientMessage(message: string) { this._clientMessage = message; } private _handlerChain?: HandlerName[]; private readonly _status?: number; private readonly _sessionErrorCode: number; private _clientMessage?: string; // TODO: Make this constructor protected. constructor ( sesisonErrorCode: number, status?: number, message?: string, cause?: unknown ) { super(message); this.name = (this.constructor.name != 'SessionHandlerError' ? (this.constructor.name + ':') : '') + 'SessionHandlerError'; this._sessionErrorCode = sesisonErrorCode; if (status) { this._status = status; } if (message) { super.message = message; } if (cause) { this.cause = cause; } }; static override isType(error: Error): boolean { return error.name?.endsWith('SessionHandlerError'); } }
using System.Text.Json; using HackerNews.Application.Interfaces; using HackerNews.Application.Models; using HackerNews.Application.Models.Paging; using Microsoft.Extensions.Caching.Memory; namespace HackerNews.Application.Services; public class HackerNewsService : IHackerNewsService { private IHttpClientFactory _httpClientFactory; private IMemoryCache _memoryCache; private IConfiguration _configuration; private ILogger<HackerNewsService> _logger; private static string _baseUrl = null; public HackerNewsService(IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, IConfiguration configuration, ILogger<HackerNewsService> logger) { _httpClientFactory = httpClientFactory; _memoryCache = memoryCache; _configuration = configuration; _baseUrl = _configuration.GetValue<string>("ConnectionSettings:BaseUrl")!; _logger = logger; } private static readonly JsonSerializerOptions? jsonSerializerOptions; static HackerNewsService() { jsonSerializerOptions = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, }; } public async Task<PaginatedList<Story>> GetNewStoriesAsync(int page, int pageSize, string searchFilter) { const string cacheKey = "new-stories"; var client = _httpClientFactory.CreateClient(); var jsonResponse = await client.GetStringAsync($"{_baseUrl}newstories.json"); var currentStoryIds = JsonSerializer.Deserialize<List<int>>(jsonResponse); List<Story> allStories; var isCacheUpdated = false; if (_memoryCache.TryGetValue(cacheKey, out List<Story> cachedStories)) { var cachedStoryIds = cachedStories.Select(s => s.Id).ToHashSet(); var newStoryIds = currentStoryIds.Except(cachedStoryIds).ToList(); var obsoleteStoryIds = cachedStoryIds.Except(currentStoryIds).ToHashSet(); // Fetch new stories var newStoriesTasks = newStoryIds.Select(GetStoryDetailsAsync); var newStories = await Task.WhenAll(newStoriesTasks); if (newStories.Any()) { // Update cache by adding new stories and removing obsolete ones cachedStories.AddRange(newStories.Where(story => story != null)); cachedStories.RemoveAll(story => obsoleteStoryIds.Contains(story.Id)); isCacheUpdated = true; } allStories = cachedStories; } else { // First time fetch var storyDetailsTasks = currentStoryIds.Select(GetStoryDetailsAsync); var stories = await Task.WhenAll(storyDetailsTasks); allStories = stories.Where(story => story != null).ToList(); isCacheUpdated = true; } if (isCacheUpdated) { _memoryCache.Set(cacheKey, allStories); } IEnumerable<Story> filteredStories = allStories; if (!string.IsNullOrWhiteSpace(searchFilter)) { filteredStories = filteredStories.Where(s => s.Title != null && s.Title.Contains(searchFilter, StringComparison.OrdinalIgnoreCase)); } var paginatedList = filteredStories .Skip((page - 1) * pageSize) .Take(pageSize) .ToList(); return new PaginatedList<Story>(paginatedList, filteredStories.Count(), page, pageSize); } public async Task<List<Story>> GetNewStoriesAsync() { const string cacheKey = "new-stories"; var client = _httpClientFactory.CreateClient(); var jsonResponse = await client.GetStringAsync($"{_baseUrl}newstories.json"); var currentStoryIds = JsonSerializer.Deserialize<List<int>>(jsonResponse); List<Story> allStories; var isCacheUpdated = false; if (_memoryCache.TryGetValue(cacheKey, out List<Story> cachedStories)) { var cachedStoryIds = cachedStories.Select(s => s.Id).ToHashSet(); var newStoryIds = currentStoryIds.Except(cachedStoryIds).ToList(); var obsoleteStoryIds = cachedStoryIds.Except(currentStoryIds).ToHashSet(); // Fetch new stories var newStoriesTasks = newStoryIds.Select(GetStoryDetailsAsync); var newStories = await Task.WhenAll(newStoriesTasks); if (newStories.Any()) { // Update cache by adding new stories and removing obsolete ones cachedStories.AddRange(newStories.Where(story => story != null)); cachedStories.RemoveAll(story => obsoleteStoryIds.Contains(story.Id)); isCacheUpdated = true; } allStories = cachedStories; } else { // First time fetch var storyDetailsTasks = currentStoryIds.Select(GetStoryDetailsAsync); var stories = await Task.WhenAll(storyDetailsTasks); allStories = stories.Where(story => story != null).ToList(); isCacheUpdated = true; } if (isCacheUpdated) { _memoryCache.Set(cacheKey, allStories); } return allStories; } private async Task<Story?> GetStoryDetailsAsync(int id) { var client = _httpClientFactory.CreateClient(); try { var response = await client.GetAsync($"{_baseUrl}/item/{id}.json"); response.EnsureSuccessStatusCode(); var jsonResponse = await response.Content.ReadAsStringAsync(); Story? storyDetails = JsonSerializer.Deserialize<Story>(jsonResponse, jsonSerializerOptions); return storyDetails; } catch (HttpRequestException e) { throw new Exception($"Could not retrieve story details for Id {id} from Hacker News", e); } } public async Task RefreshCacheAsync() { var stories = await GetNewStoriesAsync(); _memoryCache.Set("new-stories", stories); _logger.LogInformation("Cache updated with new stories at: {time}", DateTimeOffset.Now); } }
import { Box, Button, IconButton, InputAdornment, OutlinedInput, Stack, Typography, } from '@mui/material'; import React from 'react'; import { useEffect, useState } from 'react'; import { Visibility, VisibilityOff } from '@mui/icons-material'; import PersonIcon from '@mui/icons-material/Person'; import { authApi } from '@/api/auth-api'; import { useRouter } from 'next/router'; import { enqueueSnackbar } from 'notistack'; import { useDispatch } from 'react-redux'; import { setLoading } from '@/redux/loading'; export interface ILoginComponentProps { setSignUp2: any; } export default function LoginComponent({ setSignUp2 }: ILoginComponentProps) { const [nameSignIn, setNameSignIn] = useState(''); const router = useRouter(); const [passwordSignIn, setPasswordSignIn] = useState(''); const [showPassword, setShowPassword] = useState(false); const dispatch = useDispatch(); const [type, setType] = useState('password'); const handleClickShowPassword = () => { setShowPassword((show) => !show); setType(showPassword ? 'password' : 'text'); }; const handleSingUp2 = () => { setSignUp2('sign-up-mode2'); }; const handleLogin = async () => { if (nameSignIn === '') { enqueueSnackbar('Email không được để trống', { variant: 'error' }); return; } if (passwordSignIn === '') { enqueueSnackbar('Password không được để trống', { variant: 'error' }); return; } const payload = { email: nameSignIn, password: passwordSignIn, }; try { dispatch(setLoading(true)); const { data } = await authApi.login(payload); enqueueSnackbar(data.message, { variant: 'success' }); router.push( { pathname: '/home', query: { data: data, }, }, '/home' ); } catch (error: any) { enqueueSnackbar('Login faill !', { variant: 'error' }); } finally { dispatch(setLoading(false)); } }; return ( <Box component="form"> <Typography variant="h2">Đăng Nhập</Typography> <OutlinedInput onChange={(e: any) => setNameSignIn(e.target.value)} value={nameSignIn} endAdornment={<PersonIcon sx={{ color: '#fff' }} />} placeholder="Email" /> <OutlinedInput onChange={(e: any) => setPasswordSignIn(e.target.value)} value={passwordSignIn} endAdornment={ showPassword ? ( <VisibilityOff onClick={handleClickShowPassword} sx={{ color: '#fff', '&:hover': { color: '#6e6b6b', cursor: 'pointer', }, }} /> ) : ( <Visibility onClick={handleClickShowPassword} sx={{ color: '#fff', '&:hover': { color: '#6e6b6b', cursor: 'pointer', }, }} /> ) } placeholder="Password" type={type} /> <Button sx={{ color: '#fff', background: '#000' }} variant="outlined" onClick={handleLogin} > Đăng Nhập </Button> <Stack flexDirection="row" className="account-text"> Chưa có tài khoản ?{' '} <Typography onClick={handleSingUp2} sx={{ color: '#002dff', cursor: 'pointer', '&:hover': { color: '#ff0000' }, }} > Đăng ký </Typography> </Stack> </Box> ); }
extends Node # Declare member variables here. Examples: # var a = 2 # var b = "text" signal avgStatsChanged var rng = RandomNumberGenerator.new() var spotScene = preload("res://Spot.tscn") var unitScene = preload("res://units/Unit.tscn") var player var game var stagesPerBiome = 2 var timer = Timer.new() var tieredLibrary = [] var maxTier = 4 var avgStats = {'power':1, 'hp': 1} var onScreenUnits = [] var biomeOrder = [] var possibleStats = [] var allUnitsUsedStage const keywords = { 'hp':{ 'desc':"HP represents how much damage a unit can withstand before fainting", 'color':'#32e691' #'type':'stat' }, 'power':{ 'desc':"Power represents damage done when attacking", 'color':'#f04d4d', 'type':'stat' }, 'heal':{ 'type': 'buff', 'desc':"increase HP. any healing above max HP will still increase HP at half effectiveness, and return to max after the battle", 'color':'#96ffae' }, 'poison':{ 'desc':"ROUND-END: take damage equal to poison stacks remove 1 stack", 'color':'#cf6eff', 'type':'stat' }, 'triumph':{ 'type': 'trigger', 'desc':"Triggers an effect when an enemy is killed", 'color':'#e85e47' }, 'armor':{ 'desc': "Reduce all damage taken by 1 per armor", #'color':'#a2a568' # snail colored 'color':'#c3d5dd', 'type':'stat' }, 'regeneration':{ 'desc': "round-end: heal 1 per regeneration", 'color':'#27e496', 'type':'stat', 'abrev':'regen' }, 'taunt':{ 'desc': "50% increased chance of being targeted by enemy attacks, per stack of taunt", 'color':'#f19220', 'type':'stat' }, 'weaken':{ 'desc': "reduce power. if power would go below 1, take damage instead", 'color':'#ffe552', 'type':'stat' }, 'slow':{ 'desc': "If a unit recieves enough stacks of slow, they are stunned. The amount of stacks needed to stun an enemy increases every time they are stunned", 'color':'#c2f2ff', 'type':'stat' }, 'stun':{ 'type':'debuff', 'desc': "Stunned units miss their next attack. Getting stunned again will take an extra stack of slow", 'color':'#29d0ff' }, 'on-attack':{ 'desc': "Triggers an effect when this unit attacks", }, 'on-guard':{ 'desc': "Triggers an effect when this is attacked", }, 'round-end':{ 'desc': "Triggers an effect each time all units have attacked", }, } const elementLibrary = { 'aquatic':{ 'desc':'if you have unitsNeeded unique aquatic units, reduce all enemies attack by effectPerStack', 'unitsNeeded': [2,4,6], 'effectPerStack':[-1,-2,-3], 'color':'#638bff' }, 'earthen':{ 'desc':'if you have unitsNeeded unique earthen units, grant all allies + effectPerStack armor', 'unitsNeeded': [2,4,6], 'effectPerStack':[1,2,3], 'color':'#c09b7b' }, 'floral':{ 'desc':'if you have unitsNeeded unique floral units, grant all allies + effectPerStack regeneration', 'unitsNeeded': [2,4,6], 'effectPerStack':[1,2,3], 'color':'#5dfd82' }, 'glacial':{ 'desc':'if you have unitsNeeded unique glacial units, chill a random enemy effectPerStack times at the start of battle', 'unitsNeeded': [2,4,6], 'effectPerStack':[2,5,9], 'effectedTeam':'enemies', 'color':'#c2f2ff' }, 'toxic':{ 'desc':'if you have unitsNeeded unique toxic units, whenever an enemy recieves damage they also gain effectPerStack stacks of poison', 'unitsNeeded': [3,6], 'effectPerStack':[1,2], 'effectedTeam':'enemies', 'color':'#cf6eff' }, 'lunar':{ 'desc':'if you have unitsNeeded unique lunar units, all allies gain effectPerStack power at the end of each round', 'unitsNeeded': [2,4,6], 'effectPerStack':[2,4,6], 'effectedTeam':'allies', 'color':'#000000' }, 'solar':{ 'desc':'if you have unitsNeeded unique solar units, your first effectPerStack units attack before the battle starts', 'unitsNeeded': [2,4,7], 'effectPerStack':[1,2,4], 'effectedTeam':'allies', 'color':'#ffe552' }, } #ABILITY KEYWORDS # stat: what stat is being changed ( poison, armor, hp, power) # target: what unit is being affected ( guarding, attacking, randomEnemy, randomAlly) # scaling: what is the value at each level ( [1,2,4] ) # scalingType: how does scaling effect the ability (amount, triggers) # # const unitLibrary = { ##################### Tier 1 ########################### 'skunk':{ 'tier':1, 'baseStats' : {'power':3, 'maxHp':8}, 'types':['toxic','floral'], 'desc':'round-end: apply 1 poison to a random enemy scaling times', 'abilities': { 'round-end':[ {'desc':'apply 1 poison to a random enemy','stat':'poison', 'triggers': [1,2,4], 'amount':1,'target':'randomEnemy'} ]} }, 'skorpion':{ 'tier':1, 'baseStats' : {'power':2, 'maxHp':6, 'armor':1}, 'types':['toxic', 'earthen'], 'desc':"", 'abilities': { 'on-attack':[ {'desc':'apply 1 poison to target','stat':'poison', 'triggers': [1,2,4], 'amount':1, 'target':'guarding'} ]} }, 'snail':{ 'tier':1, 'baseStats' : {'power':2, 'maxHp':8, 'armor':1, 'taunt':1}, 'armor':1, 'types':['earthen', 'aquatic'], 'desc':"armor: 1", 'abilities': {} }, 'rat':{ 'baseStats' : {'power':4, 'maxHp':7}, 'tier':1, 'types':['floral', 'solar'], 'desc':"on-attack: gain 1 power. triumph: heal 1", 'abilities': {} }, ##################### Tier 2 ########################### 'eagle':{ 'baseStats' : {'power':5, 'maxHp':9}, 'tier':1, 'types':['solar','lunar'], 'desc':'', 'abilities': { 'round-end':[ {'desc':'round-end: weaken by 1','stat':'power', 'triggers': [1,2,4], 'amount':-1, 'target':'self'} ]} }, 'penguin':{ 'tier':2, 'baseStats' : {'power':2, 'maxHp':8}, 'types':['glacial','aquatic'], 'desc':'round-start: apply slow to a random enemy', 'abilities': {} }, 'octopus':{ 'baseStats' : {'power':2, 'maxHp':8}, 'tier':2, 'types':['aquatic', 'lunar'], 'desc':'round-end: deal damage equal to my power to [1/2/4] random enemies', 'abilities': {} }, 'snake':{ 'baseStats' : {'power':3, 'maxHp':8}, 'tier':2, 'types':['solar', 'toxic'], 'desc':'on-attack: apply 2 poison to target', 'abilities': {} }, ##################### Tier 3 ########################### 'crocodile':{ 'tier':3, 'baseStats' : {'armor':1, 'power':4, 'maxHp':11}, 'types':['aquatic','solar'], 'desc':"triumph: gain +[1,2,3] power and heal by [2,4,8]' ", 'abilities': {} }, 'tiger':{ 'baseStats' : {'power':3, 'maxHp':14}, 'tier':3, 'power':3, 'hp': 14, 'types':['floral','lunar'], 'desc':"round-end: gain multistrike +1", 'abilities': {} }, ##################### Tier 4 ########################### 'elephant':{ 'baseStats' : {'power':5, 'maxHp':12}, 'tier': 4, 'power':5, 'hp': 12, 'types':['earthen','solar'], 'desc':'on-attack: gain 1 armor', 'abilities': {} }, 'polarbear':{ 'baseStats' : {'power':4, 'maxHp':15}, 'tier': 4, 'power':5, 'hp': 14, 'types':['glacial','solar'], 'desc':'on-attack: apply [1, 2, 4] slow to target', 'abilities': {} } } # Called when the node enters the scene tree for the first time. func _ready(): add_child(timer) timer.one_shot = true rng.randomize() randomize() generateBiomeOrder() for keyword in keywords: if keywords[keyword].has('type'): if keywords[keyword]['type'] == 'stat': possibleStats.append(keyword) for i in range(maxTier): var curTierArray = [] for unitName in unitLibrary: if unitLibrary[unitName]['tier']== i+1: curTierArray.append(unitName) tieredLibrary.append(curTierArray) allUnitsUsedStage = stagesPerBiome*(biomeOrder.size()-1) print('ALL UNITS USED AT STAGE: '+str(allUnitsUsedStage)) for i in range(allUnitsUsedStage): var pu = getPossibleUnitsBasedOnStage(i+1) print(pu.size(), ' possible units at stage ',i+1,':',pu) pass pass # Replace with function body. func generateBiomeOrder(): var possibleBiomes = [] biomeOrder = [] for element in elementLibrary: possibleBiomes.append(element) biomeOrder = shuffleArray(possibleBiomes) biomeOrder.insert(0,'neutral') print('BIOME ORDER: '+str(biomeOrder)) func addSpot(parentNode): var newSpot = spotScene.instance() parentNode.add_child(newSpot) func randomUnitBasedOn(stage): var possibleUnits = getPossibleUnitsBasedOnStage(stage) var rand = rng.randi_range(0,possibleUnits.size()-1) return possibleUnits[rand] func instanceUnit(unitName): var unit = load('res://units/Unit.tscn').instance() #var file2Check = File.new() #var scriptName = str('res://units/scripts/', unitName, '.gd') #var doesScriptExist = file2Check.file_exists(scriptName) #if doesScriptExist: #unit.set_script( load(scriptName )) unit.render(unitName) connect('avgStatsChanged', unit, 'updateInfo') return unit func updateAverageStats(array2d): var powerSum = 0 var hpSum = 0 var divisor = 0 for unitArray in array2d: for unit in unitArray: powerSum += unit.curStats['power'] hpSum += unit.baseStats['maxHp'] divisor+=1 if divisor > 0: avgStats['power'] = float(powerSum) / float(divisor) avgStats['hp'] = float(hpSum) / float(divisor) print('AVG stats: '+ str(avgStats)) emit_signal("avgStatsChanged") func getPossibleUnitsBasedOnStage(stage): #print('GETTING UNIT BASED ON STAGE: ',stage) var minPercentUsed = float(tieredLibrary[0].size()) / float(unitLibrary.size()) #print('minPercentUsed: '+str(minPercentUsed)) var prop = min(float(stage-1) / float(allUnitsUsedStage-1),1)#subtract 1 because we want prop at 0 when stage is 1 var percentOfTotalLibToUse = CustomFormulas.proportion(minPercentUsed, 1, prop) #print('percentOfTotalLibToUse = ', percentOfTotalLibToUse) var libsFullyUsed = 0 var percentOfPartialTier for i in range(4): var curTier = i+1 #print(' curTier: ',i+1) #print(' percentIsAtLeastTier: ',percentIsAtLeastTier(curTier),' vs ',percentOfTotalLibToUse) if percentIsAtLeastTier(curTier) <= percentOfTotalLibToUse: #print(' using all of tier ',curTier) libsFullyUsed+=1 else: #print(' percent of tier ',curTier) var percentOfTotalLibraryMissingFromPartialLib = percentOfTotalLibToUse - percentIsAtLeastTier(curTier) #print(' percent of total lib missing from partial lib: ', percentOfTotalLibraryMissingFromPartialLib) var numberFromPartialLib = unitLibrary.size() * percentOfTotalLibraryMissingFromPartialLib percentOfPartialTier = float(1+float(numberFromPartialLib)/ float(tieredLibrary[i].size())) #print(' using ',percentOfPartialTier*100,'% of tier ',curTier) break var possibleUnits = [] for i in range(libsFullyUsed): possibleUnits.append_array(tieredLibrary[i]) #print(' percentOfPartialTier: '+str(percentOfPartialTier)) if libsFullyUsed == 4 || percentOfPartialTier <= 0.05: #print(' stage ',stage,' using ',possibleUnits.size(),' / ', unitLibrary.size()) return possibleUnits var partialLib = shuffleArray(tieredLibrary[libsFullyUsed]) var percentCovered = 0 for barelyUnlockedUnit in partialLib: if percentCovered <= percentOfPartialTier: possibleUnits.append(barelyUnlockedUnit) percentCovered += 1.0 / float(partialLib.size()) #print(' stage ',stage,' using ',possibleUnits.size(),' / ', unitLibrary.size()) return possibleUnits func shuffleArray(array): var shuffled = [] var indexList = range(array.size()) for i in range(array.size()): rng.randomize() var x = rng.randi_range(0,indexList.size()-1) shuffled.append(array[indexList[x]]) indexList.remove(x) return shuffled func percentIsAtLeastTier(tier): var percentSum = 0 var totalSum = 0 var i = 0 while i < 4: totalSum += tieredLibrary[i].size() if i < tier: percentSum += tieredLibrary[i].size() i+=1 return float(percentSum) / float(totalSum) func playAudio(filepath, volume = 0, delay = 0): if delay > 0: timer.connect("timeout", self, 'playAudio', [filepath, volume]) timer.start(delay) return var aud = AudioStreamPlayer.new() add_child(aud) if !ResourceLoader.exists(filepath): filepath = 'res://resources/audio/'+filepath+'.ogg' aud.stream = load(filepath) aud.play()
<!DOCTYPE html> <html> <head> <title>Flappy Educational Recreation</title> <meta charset="UTF-8"> <script type="text/javascript" src="processing-1.4.1.js"></script> <!-- This is a source-file-less sketch, loaded from inline source code in the html header. This only works if the script specifies a data-processing-target --> <script type="text/processing" data-processing-target="targetcanvas"> /* Hot Balloon Date: 02-28-14 Credit: Images from Clumsy Bird open-source project https://github.com/ellisonleao/clumsy-bird It works! This version includes pipes and points. It could be considered first release version. Problems: It lags!!! Future adds: - Real gravity using physic laws - Improve space between pipes - Improve lag (try calculating fps with delta_millis()) - Add a menu at the beginning to set up game */ /* @pjs preload="bg.png,clumsyOne.png,pipe.png,pipeBottom.png,ground.png"; */ PImage bg; PImage bird; PImage[] pipeTop = new PImage[3]; PImage[] pipeBottom = new PImage[3]; PImage tempP; PImage ground; PFont font; //change this values to set up the game int windowX=640, windowY=480, gravity=3, setGameSpeed=7, setJump=5,floor=100,points=0; int gameSpeed=setGameSpeed,jump=setJump; boolean gameStart = false, gameOver = false; int birdX,birdY,birdSizeX=48,birdSizeY=36; int[][] pipe = {{0,0,50,500}, {0,0,50,500}, {0,0,50,500}, {0,0,50,500}, {0,0,50,500}, {0,0,50,500}}; int pipeNumber=3,pipeDistance=windowX/3,pipeMin=80,pipeMax=240,gap=180; int clickIn=0,clickOut=0; long time=0; int groundX=0; void setup() { size(640,480); bg = loadImage("bg.png"); bird = loadImage("clumsyOne.png"); for(int i=0;i<pipeNumber;i++) { pipeTop[i] = loadImage("pipe.png"); pipeBottom[i] = loadImage("pipeBottom.png"); } tempP=loadImage("pipe.png"); ground = loadImage("ground.png"); font = createFont("Arial",48,true); background(255,255,255); initiation(); } void draw() { if(gameSpeed != 0 && gameStart == true) { game(); pipes(); movingGround(); refreshImages(); } else { if(gameOver == true) { gameOverF(); if(mousePressed == true) { initiation(); } } } } void mousePressed() { gameStart = true; } void initiation() { birdX = 200; birdY = height/2; gameOver = false; gameStart = false; gameSpeed = 7; jump = 5; points = 0; //pipes for(int i = 0; i<pipeNumber; i++) { time = second() + clickIn + clickOut + i; randomSeed(time); pipe[2*i][0] = windowX+(i*pipeDistance); pipe[2*i][1] = (int)(random(pipeMin-pipe[2*i][3],pipeMax-pipe[2*i][3])); pipe[2*i+1][0] = pipe[2*i][0]; pipe[2*i+1][1] = pipe[2*i][1]+pipe[2*i][3]+gap; } image(bg,0,0,windowX,windowY); refreshImages(); //Instructions textFont(font,48); stroke(0); fill(0); text("Click to Start",windowX/2-120,windowY/4); } void game() { if(mousePressed == true && mouseButton == LEFT && (millis()-clickIn)<100) { clickOut = millis(); birdY = ((birdY-=jump) <= 0) ? 0 : birdY - jump; } else if(mousePressed == false) { clickIn = millis(); birdY = ((birdY+(gravity)) >= windowY-floor) ? windowY-floor : birdY + (gravity); } else birdY = ((birdY+(gravity)) >= windowY-floor) ? windowY-floor : birdY + (gravity); } void pipes() { if(millis()>1000) { for(int i = 0; i<pipeNumber; i++) { if(pipe[2*i][0]>= -gameSpeed-pipe[2*i][2]) { pipe[2*i][0] -= gameSpeed; pipe[2*i+1][0] -= gameSpeed; if(((birdX+birdSizeX) > pipe[2*i][0]) && (birdX < (pipe[2*i][0]+pipe[2*i][2]))) { if((birdY <= (pipe[2*i][1]+pipe[2*i][3])) || (birdY+birdSizeY) >= (pipe[2*i+1][1])) gameOverF(); else if(birdX+gameSpeed >= (pipe[2*i][0]+pipe[2*i][2])) points++; } } else { time = second() + clickIn + clickOut; randomSeed(time); pipe[2*i][0] = windowX; pipe[2*i+1][0] = pipe[2*i][0]; pipe[2*i][1] = (int)(random(pipeMin-pipe[2*i][3],pipeMax-pipe[2*i][3])); pipe[2*i+1][1] = pipe[2*i][1]+pipe[2*i][3]+gap; } } } } void movingGround() { if(groundX <= (-windowX + gameSpeed)) groundX = 0; else groundX -= gameSpeed; } void gameOverF() { textFont(font,48); stroke(0); fill(0); text("Game Over",windowX/2-120,windowY/2); textFont(font,24); text("Click to start again",windowX/2-90,windowY/2+30); //println("Game Over"); gameSpeed = 0; jump = 0; gameOver = true; } void refreshImages() { image(bg,0,0,windowX,windowY); image(bird,birdX,birdY,birdSizeX,birdSizeY); image(ground,groundX,windowY-floor+birdSizeY,windowX*2,floor+birdSizeY); for(int i = 0;i < pipeNumber; i++) { image(pipeTop[i],pipe[2*i][0],pipe[2*i][1],pipe[2*i][2],pipe[2*i][3]); image(pipeBottom[i],pipe[2*i+1][0],pipe[2*i+1][1],pipe[2*i+1][2],pipe[2*i+1][3]); } textFont(font,24); stroke(0); fill(0); text("Points: "+points,windowX/2-80,windowY-20); } </script> </head> <body> <h3>Flappy Game!</h3> <canvas id="targetcanvas" style="border: 1px solid black;"></canvas> <p>This is an early release, but I hope you enjoy the game.</p> </body> </html>
// // RewardItemCell.swift // MapleStoryGuide // // Created by brad on 2023/04/20. // import UIKit class RewardItemCell: UICollectionViewCell { static let id = "RewardItemCell" private let horizontalStackView = UIStackView().then { stackView in stackView.axis = .horizontal stackView.distribution = .equalSpacing stackView.translatesAutoresizingMaskIntoConstraints = false } private let imageView = UIImageView().then { imageView in imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false } private let nameLabel = UILabel().then { label in label.textAlignment = .left label.numberOfLines = 2 label.font = .MapleLightFont() label.translatesAutoresizingMaskIntoConstraints = false } override init(frame: CGRect) { super.init(frame: frame) setLayout() self.contentView.layer.addBorder([.bottom], color: .systemGray4, width: 1.5) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setLayout() { // imageView Scale 맞추기 self.contentView.addSubview(horizontalStackView) self.horizontalStackView.addArrangedSubview(imageView) self.horizontalStackView.addArrangedSubview(nameLabel) self.horizontalStackView.snp.makeConstraints { make in make.top.leading.trailing.equalTo(self.contentView) make.bottom.equalTo(self.contentView).offset(-10) } self.imageView.snp.makeConstraints { make in make.height.equalTo(self.horizontalStackView) make.width.equalTo(self.horizontalStackView).multipliedBy(0.2) } self.nameLabel.snp.makeConstraints { make in make.leading.equalTo(self.imageView.snp.trailing).offset(20) } } func configureCell(imageURL: String, name: String) { self.nameLabel.text = name guard let url = URL(string: imageURL) else { return } let request = URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad) Task { await self.imageView.fetchImage(request) } } }
import java.util.Scanner; //강사님 문제풀이 public class Array04_01 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); boolean[] ar = new boolean[5]; // 5개 방을 만들었고, ar[0] ar[1] ~ar[4] 0부터 시작 int num; while(true) { System.out.println(); //줄바꿈용 System.out.println("주차관리 시스템"); System.out.println("**********"); System.out.println("1. 입차"); System.out.println("2. 출차"); System.out.println("3. 리스트"); System.out.println("4. 종료"); System.out.println("**********"); System.out.print("메뉴 : "); num = scan.nextInt(); if(num == 4) break; //4번을 찍으면 종료 if(num<1 || num>4) { // 1234 제외 하고 나머지 찍었을경우 System.out.println("1 ~ 4번 까지만 입력하세요"); continue; } if(num == 1) { // 1번 찍으면 System.out.print("위치 입력 : "); int position = scan.nextInt(); //3번 위치로 들어갈거면 ar[2], 0부터 시작하닌까 1이 작아야함 if(ar[position-1]) // 차가 있으면 System.out.println("이미 주차되어 있습니다"); else { //차가 없으면 ar[position-1] = true; System.out.println(position + "위치에 입차"); } }else if(num == 2) { //2번 찍으면 System.out.print("위치 입력 : "); int position = scan.nextInt(); if(ar[position-1]) { //if 가 true 일때 ar[position-1] = false; // 2번에 System.out.println(position + "위치에 출차"); }else System.out.println("주차되어 있지 않습니다."); }else if(num == 3) { //3번 찍으면 for(int i=0; i<ar.length; i++) { System.out.println((i+1) + "위치 : " + ar[i]); }//for } }//while System.out.println("프로그램을 종료합니다."); } } /* 주차장 관리 프로그램 ************** 1. 입차 input() 2. 출차 output() 3. 리스트 list() 4. 종료 // 무한 루프가 도는걸 끝내야함 (while, if) ************** 메뉴 : 1번인 경우 위치 입력 : 3 3위치에 입차 / 이미 주차되어있습니다 2번인 경우 위치 입력 : 4 4위치에 출차 / 주차되어 있지않습니다 3번인 경우 1위치 : true 2위치 : false 3위치 : true 4위치 : false 5위치 : false */
<template> <div> <splide class="riseup-slider" :options="splideOptions" @splide:move="_onMove" ref="sliderRef"> <splide-slide v-for="slide in slidesData" :key="slide.key" class="riseup-slider-slide" :style="{ '--pagination-padding': `${paginationPadding}px` }"> <slot v-bind:slideData="slide"/> </splide-slide> </splide> <slider-pagination v-if="useCustomPagination" :pages="customPaginationPages" :current-page="currentPage" :on-pagination-click="_onPaginationClick" :direction="direction" :max-dots="maxDots"/> </div> </template> <script> import _ from 'lodash'; import { Splide, SplideSlide } from '@splidejs/vue-splide'; import SliderPagination from './SliderPagination.vue'; export default { name: 'Slider', components: { SliderPagination, Splide, SplideSlide, }, data() { return { currentPage: this.firstSlideIndex, }; }, props: { infinite: { type: Boolean, required: false, default: false, }, autoWidth: { type: Boolean, required: false, default: false, }, direction: { type: String, required: false, default: 'rtl', validator: direction => ['ltr', 'rtl'].includes(direction), }, padding: { type: Number, required: false, default: 24, }, paginationPadding: { type: Number, required: false, default: 16, }, gap: { type: Number, required: false, default: 10, }, firstSlideIndex: { type: Number, required: false, }, slidesData: { type: Array, required: true, validator: data => data.length > 0 && data.every(slide => slide.key), }, maxDots: { type: Number, required: false, }, minDots: { type: Number, required: false, }, disableDrag: { type: Boolean, default: false, }, }, computed: { splideOptions() { return { type: this.infinite ? 'loop' : 'slide', padding: this.padding, arrows: false, autoWidth: this.autoWidth, trimSpace: this.autoWidth, direction: this.direction, gap: this.gap, start: this.firstSlideIndex ?? 0, drag: !this.disableDrag, pagination: !this.useCustomPagination && !this.hidePagination, classes: { pagination: 'splide__pagination riseup-slider-pagination' }, }; }, hidePagination() { return this.slidesData.length <= this.minDots; }, useCustomPagination() { return _.isNumber(this.maxDots) && !this.hidePagination; }, customPaginationPages() { return this.slidesData.map((_, index) => index); }, }, methods: { _onMove(_, newIndex, prevIndex) { this.currentPage = newIndex; this.$emit('on-slide', newIndex, prevIndex); }, _onPaginationClick(page) { this.$refs.sliderRef.go(page); }, }, }; </script> <style lang="scss"> @import '~@splidejs/splide/dist/css/themes/splide-default.min.css'; @import '../scss/riseup-colors'; .riseup-slider { .riseup-slider-slide { padding-top: 2px; padding-bottom: var(--pagination-padding); } .riseup-slider-pagination { padding: 0 24px; bottom: unset; position: relative; box-sizing: border-box; width: 100%; li > button { margin: 0 6px; width: 8px; height: 8px; background-color: $riseup_gray_0; transition: background-color 0.2s; cursor: pointer; &.is-active { transform: unset; background-color: var(--dot-color, $riseup_blue); } } } } </style>
package org.l3e.Boulanger.block.entity; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.Containers; import net.minecraft.world.MenuProvider; import net.minecraft.world.SimpleContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerData; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemStackHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.l3e.Boulanger.recipe.DiscSeparatorRecipe; import org.l3e.Boulanger.screen.DiscSeparatorMenu; import java.util.Optional; public class DiscSeparatorBlockEntity extends BlockEntity implements MenuProvider { private final ItemStackHandler itemHandler = new ItemStackHandler(2) { @Override protected void onContentsChanged(int slot) { setChanged(); } }; private LazyOptional<IItemHandler> lazyItemHandler = LazyOptional.empty(); protected final ContainerData data; private int progress = 0; private int maxProgress = 78; public DiscSeparatorBlockEntity(BlockPos blockPos, BlockState blockState) { super(ModBlockEntities.DISC_SEPARATOR.get(), blockPos, blockState); this.data = new ContainerData() { @Override public int get(int index) { return switch (index) { case 0 -> DiscSeparatorBlockEntity.this.progress; case 1 -> DiscSeparatorBlockEntity.this.maxProgress; default -> 0; }; } @Override public void set(int index, int value) { switch (index) { case 0 -> DiscSeparatorBlockEntity.this.progress = value; case 1 -> DiscSeparatorBlockEntity.this.maxProgress = value; } } @Override public int getCount() { return 2; } }; } @Override public Component getDisplayName() { //can this be localized? return Component.literal("Disc-Separator"); } @Nullable @Override public AbstractContainerMenu createMenu(int i, Inventory inventory, Player player) { return new DiscSeparatorMenu(i, inventory, this, this.data); } @Override public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, Direction side) { if(cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { return lazyItemHandler.cast(); } return super.getCapability(cap, side); } @Override public void onLoad() { super.onLoad(); lazyItemHandler = LazyOptional.of(() -> itemHandler); } @Override public void invalidateCaps() { super.invalidateCaps(); lazyItemHandler.invalidate(); } @Override protected void saveAdditional(CompoundTag nbt) { nbt.put("inventory", itemHandler.serializeNBT()); super.saveAdditional(nbt); } @Override public void load(CompoundTag nbt) { itemHandler.deserializeNBT(nbt.getCompound("inventory")); super.load(nbt); } public void drops() { SimpleContainer inventory = new SimpleContainer(itemHandler.getSlots()); for (int i = 0; i < itemHandler.getSlots(); i++) { inventory.setItem(i, itemHandler.getStackInSlot(i)); } Containers.dropContents(this.level, this.worldPosition, inventory); } public static void tick(Level level, BlockPos blockPos, BlockState state, DiscSeparatorBlockEntity e) { if(level.isClientSide()) { return; } if(hasRecipe(e)) { e.progress++; setChanged(level, blockPos, state); if(e.progress >= e.maxProgress) { craftItem(e); } } else { e.resetProgress(); setChanged(level, blockPos, state); } } private void resetProgress() { this.progress = 0; } private static void craftItem(DiscSeparatorBlockEntity pEntity) { Level level = pEntity.level; SimpleContainer inventory = new SimpleContainer(pEntity.itemHandler.getSlots()); for (int i = 0; i < pEntity.itemHandler.getSlots(); i++) { inventory.setItem(i, pEntity.itemHandler.getStackInSlot(i)); } Optional<DiscSeparatorRecipe> recipe = level.getRecipeManager() .getRecipeFor(DiscSeparatorRecipe.Type.INSTANCE, inventory, level); if(hasRecipe(pEntity)) { pEntity.itemHandler.extractItem(0, 1, false); ItemStack output1 = new ItemStack((recipe.get().getResultItem(level.registryAccess()).getItem()), pEntity.itemHandler.getStackInSlot(1).getCount() + 1); CompoundTag nbtData = new CompoundTag(); nbtData.putString("boulanger:test", "disc-separated wheat berries"); output1.setTag(nbtData); pEntity.itemHandler.setStackInSlot(1, output1); pEntity.resetProgress(); } } private static boolean hasRecipe(DiscSeparatorBlockEntity e) { Level level = e.level; SimpleContainer inventory = new SimpleContainer(e.itemHandler.getSlots()); for (int i = 0; i < e.itemHandler.getSlots(); i ++) { inventory.setItem(i, e.itemHandler.getStackInSlot(i)); } Optional<DiscSeparatorRecipe> recipe = level.getRecipeManager() .getRecipeFor(DiscSeparatorRecipe.Type.INSTANCE, inventory, level); ItemStack is = e.itemHandler.getStackInSlot(0); CompoundTag nbt = is.getOrCreateTag(); return recipe.isPresent() && canInsertAmountIntoOutputSlot(inventory) && canInsertItemIntoOutputSlot(inventory, recipe.get().getResultItem(level.registryAccess())) && nbt.getString("boulanger:test").equals("destoned wheat berries"); } private static boolean canInsertItemIntoOutputSlot(SimpleContainer inventory, ItemStack itemStack) { return inventory.getItem(1).getItem() == itemStack.getItem() || inventory.getItem(1).isEmpty(); } private static boolean canInsertAmountIntoOutputSlot(SimpleContainer inventory) { return inventory.getItem(1).getMaxStackSize() > inventory.getItem(1).getCount(); } }
<template> <header class="app-header navbar"> <button class="navbar-toggler mobile-sidebar-toggler d-lg-none" type="button" @click="mobileSidebarToggle"> <span class="navbar-toggler-icon"></span> </button> <b-link class="navbar-brand" to="#"></b-link> <button class="navbar-toggler sidebar-toggler d-md-down-none mr-auto" type="button" @click="sidebarToggle"> <span class="navbar-toggler-icon"></span> </button> <b-dropdown id="userDropdown" right class="customDropdown"> <b-dropdown-item href="#" @click="goToMainPage()"> SuperAdmin Main Page </b-dropdown-item> <b-dropdown-item href="#" @click="logout"> Logout </b-dropdown-item> </b-dropdown> </header> </template> <script> import vSelect from 'vue-select' import store from '../vuex/store' import router from '../router' export default { name: 'headersuper', components: { vSelect }, router: router, data() { return { hasComponentMounted: false, selected: {}, } }, computed: { options() { return [{label: 'Turkçe', value: 'tr'}, {label: 'English', value: 'en'}] }, language () { return store.getters.getLanguage }, user () { return store.getters.getUser }, }, created() { /* console.log('language from header') console.log(this.language) */ for (let i = 0; i < this.options.length; i++) { if (this.language === this.options[i].value) { this.selected = {...this.options[i]} } } }, methods: { sidebarToggle (e) { e.preventDefault() document.body.classList.toggle('sidebar-hidden') }, sidebarMinimize (e) { e.preventDefault() document.body.classList.toggle('sidebar-minimized') }, mobileSidebarToggle (e) { e.preventDefault() document.body.classList.toggle('sidebar-mobile-show') }, asideToggle (e) { e.preventDefault() document.body.classList.toggle('aside-menu-hidden') }, selectLang() { if (this.selected !== null) { this.$language = this.selected.value store.dispatch({ type: 'setAppLanguage', language: this.selected.value }) this.updateLabels() this.$localStorage.set('appLanguage', this.selected.value) } }, updateLabels() { let labelsObject = {} if (this.$language === 'en') { labelsObject.totalBookings = 'Total Bookings' store.dispatch({ type: 'setAppLabels', labels: labelsObject }) } else if (this.$language === 'tr') { labelsObject.totalBookings = 'Toplam rezervasyonlar' store.dispatch({ type: 'setAppLabels', labels: labelsObject }) } }, logout() { // Update user data in store with authenticated = false let userData = {...this.user} userData.authenticated = false store.dispatch({ type: 'setAppUser', user: userData }) this.$localStorage.remove('user') // Redirect to login router.push({name: 'Login'}) }, goToMainPage() { router.push({name: 'superadminDashboard'}) }, } } </script> <style lang="scss"> .customDropdown { border: 1px solid rgba(60,60,60,.26)!important; border-radius: 4px; margin-right: 46px; .btn { /*border: none;*/ background-color: transparent; } .btn:hover { background-color: white!important; } .btn.btn-default:hover, .btn.btn-default.active, .btn.btn-default:active, .btn.btn-default:focus, .show > .btn.btn-default.dropdown-toggle, .btn.btn-secondary:hover, .btn.btn-secondary.active, .btn.btn-secondary:active, .btn.btn-secondary:focus, .show > .btn.btn-secondary.dropdown-toggle, .btn.btn-default:hover, .btn.btn-default.active, .btn.btn-default:active, .btn.btn-default:focus, .show > .btn.btn-default.dropdown-toggle, .btn.btn-secondary:hover, .btn.btn-secondary.active, .btn.btn-secondary:active, .btn.btn-secondary:focus { background-color: white!important; } .profileImage { width: 43px; margin-top: -10px!important; } .nav-link.dropdown-toggle:after, .btn.dropdown-toggle:after { content: ""; } .dropdown-toggle.btn-secondary { border: none; height: 38px; } .fa-caret-down { color: #999; } } .langSelect { display: inline-block; width:64px; margin-right: 7px; .dropdown-menu { width: 60px!important; min-width: 0px !important; } } .customUserIcon { font-size: 1.8rem; vertical-align: middle; margin-top: -2px; margin-left: -4px; color: #999; } .app-header.navbar .navbar-brand { background-image: url("../assets/img/logo.png"); } </style>
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Domain.Interfaces.Services; using Domain.Interfaces.Repositories; using Data.Repositories; using Logic; namespace WebApi.Configuration.Extensions { public static class RegisterDependencyInjectionExtension { public static WebApplicationBuilder ConfigureDI(this WebApplicationBuilder builder) { builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); builder.Services.AddScoped<ICardRepository, CardRepository>(); builder.Services.AddScoped<ICardService, CardService>(); builder.Services.AddSingleton<IUniversalFeesExchange>(UniversalFeesExchange.Instance); return builder; } } }
\ifndef{langchainAgent} \define{langchainAgent} \include{_software/includes/langchain-software.md} \editme \subsection{Langchain agent} \notes{Now we should configure a Langchain `agent`. This agent is the interface between our code and the LLM. The `agent` receives our questions in natural language and will provide, hopefully, the answer we are looking for.} \notes{First let's import the required libraries.} \setupcode{import os import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from getpass import getpass import openai from langchain.agents import create_pandas_dataframe_agent from langchain.llms import OpenAI} \notes{We need to create an agent using our OpenAI API key now. The agent receives the data we want to analyse as a parameter. In this case, it is the data frame. The verbosity is set to True to track the workflow the agent follows to get the required answer.} \code{openai_api_key = [INSERT_YOUR_OPENAI_API_HERE] os.environ["OPENAI_API_KEY"] = openai_api_key openai.api_key = openai_api_key} \code{agent = create_pandas_dataframe_agent(OpenAI(temperature=0, openai_api_key=openai_api_key), data, verbose=True)} \notes{Once the agent is configured we can start by asking questions about our data. For example, we can ask the agent for the names of the columns of the dataframe.} \code{results = agent("What are Column names?")} \notes{If you look at the output closer, you will see in green the "thoughts" and "actions" the agent performs. It is of particular interest the second "action" of this agent execution chain. This "action" corresponds to the execution ot the `df.columns` command, where `df` is the dataframe the agent received as a parameter during its configuration (i.e., the `data` dataframe). You should get a similar output to the `Observation` in blue if you execute the `data.columns` Python command.} \code{data.columns} \notes{Let's go a bit deeper in our analysis. We want to know which columns in our data frame are categorical and which columns store numeric values. Let's see what the agent says ...} \code{results = agent("Which columns are categorical and which are numeric?")} \codeassignment{What is the main command the agent executes to get the answer according to its "actions" and "observations"? Write and execute the Python command using the `data` data frame in the next box. Compare the output of this execution with the output of the agent "observation".}{}{10} \notes{In a final example to describe our data, we want to know if there are any missing values in our data frame.} \code{results = agent("Are there any missing values in columns")} \codeassignment{Again, please identify the main command the agend executed and compare the output you get.} \notes{The last steps were useful to know the data better. It looks like the integration of LLMs in the process was useful. But, what about data visualisation?} \notes{Well, there are already specific libraries designed to this end. That is the case of [`autoplotlib`](https://github.com/rdnfn/autoplotlib), which generates plots of your data from text descriptions.} \installcode{autoplotlib} \notes{Now we can use the library. Let's ask for a plot of the Nigerian health facilities. The autoplotlib plot function receives the figure description and the data we want to visualise as parameters. The function returns the code of the plot, the figure, and the response from the LLM. These outputs are then prompted to you for checking.} \setupplotcode{import autoplotlib as aplt} \plotcode{figure_description = "Plot a map with the nigerian health facilities." code, fig, llm_response = aplt.plot(figure_description, data=data)} \codeassignment{One nice property of `autoplotlib` is that it prompts the code before execution. So, you can inspect the code the LLM generates. What do you think of the plotted map? Is it similar to the one we created before?}{}{10} \notes{Certainly, it is similar, but there are some differences. You can add more details to the figure description to make it more similar or change the plot's appearance. For example, we can change the value of the parameter `alpha` for the figure. This parameter changes the transparency of the graph, so we can see the places with more density of healthcare facilities.} \setupplotcode{import autoplotlib as aplt} \plotcode{figure_description = "Plot a map with the nigerian health facilities with alpha=0.01." code, fig, llm_response = aplt.plot(figure_description, data=data)} \notes{Now, you have initial ideas about integrating LLMs into the data science process. We will come back to this later in this lab and we expect you to continue thinking of and exploring its potential. For now, let's save our data frame in a more self-descriptive variable for later. In our next section, we will start learning about Databases.} \endif
<!DOCTYPE html> <html> <head> <title>JS_DOM_개요</title> <script> /* 1 DOM 객체 (DOM, Document Object Model) 1.1 문서 객체 모델(DOM)이란? 웹 브라우저는 서버로부터 전달받는 Resource를 읽고 HTML 태그들을 분석하고 화면에 표시합니다. 이때 웹 브라우저가 HTML을 분석하고 표시하는 방식을 문서 객체 모델( DOM : Document Object Model ) 이라고 합니다. 1.2 DOM으로 할수 있는 작업 - HTML 요소나 속성 추가, 변경, 제거 - CSS 스타일을 변경 - HTML 이벤트를 추가 1.3 사용법 개요 DOM 객체 선택 -> 추가, 변경, 삭제 1.3.1 DOM 객체 선택 1.3.1.1 개별 선택 1. document.getElementById() DOM에서 특정 id값을 가진 엘리먼트를 반환합니다. 값이 없을 경우 null을 반환합니다. 만약 id값이 여러개일 경우 첫 번째 id값을 반환합니다. let div_1 = document.getElementById("div_1"); 2. document.querySelector() HTML5 부터 사용가능 css 선택자를 기준으로 제일 첫 번째 엘리먼트를 반환합니다. let div_li = document.querySelector(".div_li"); 1.3.1.2 다중선택 1. document.getElementsByClassName() 특정 클래스명을 가진 엘리먼트들을 NodeList로 반환합니다. let board_div = document.getElementsByClassName(".board_div"); 2. document.getElementsByName() name에 명시된 조건에 맞는 모든 값들을 live NodeList로 반환합니다. index로 접근이 가능하며 length속성을 가집니다. let board_title = document.getElementsByName("board_title"); 3. document.getElementsByTagName() 특정 태그명을 가진 엘리먼트들을 HTMLCollection을 반환합니다. let input_tags = document.getElementsByTagName("input"); 4. document.querySelectorAll() css 선택자에 맞는 모든 엘리먼트를 NodeList로 반환합니다. let div_li = document.querySelectorAll(".div_li"); 1.3.1.3 HTML 객체 집합(object collection)을 이용한 선택 HTML DOM에서 제공하는 객체 집합(object collection)을 이용하여 HTML 요소를 선택할 수 있습니다. 예제 let title = document.title; // <title> 요소를 선택함. 종류 document.anchors name 속성을 가지는 <a>요소를 모두 반환함. document.applets applet 요소를 모두 반환함. (HTML5에서 제외됨) document.body <body>요소를 반환함. document.cookie HTML 문서의 쿠키(cookie)를 반환함. document.domain HTML 문서가 위치한 서버의 도메인 네임(domain name)을 반환함. document.forms <form>요소를 모두 반환함. document.images <img>요소를 모두 반환함. document.links href 속성을 가지는 <area>요소와 <a>요소를 모두 반환함. document.referrer 링크(linking)되어 있는 문서의 URI를 반환함. document.title <title>요소를 반환함. document.URL HTML 문서의 완전한 URL 주소를 반환함. document.baseURI HTML 문서의 절대 URI(absolute base URI)를 반환함. document.doctype HTML 문서의 문서 타입(doctype)을 반환함. document.documentElement <html>요소를 반환함. document.documentMode 웹 브라우저가 사용하고 있는 모드를 반환함. document.documentURI HTML 문서의 URI를 반환함. document.domConfig HTML DOM 설정을 반환함. (더는 사용하지 않음) document.embeds <embed>요소를 모두 반환함. document.head <head>요소를 반환함. document.implementation HTML DOM 구현(implementation)을 반환함. document.inputEncoding HTML 문서의 문자 인코딩(character set) 형식을 반환함. document.lastModified HTML 문서의 마지막 갱신 날짜 및 시간을 반환함 document.readyState HTML 문서의 로딩 상태(loading status)를 반환함. document.scripts <script>요소를 모두 반환함. document.strictErrorChecking 오류의 강제 검사 여부를 반환함. 1.3.2 DOM 객체 생성, 추가, 수정 및 출력, 삭제 1. DOM 객체 생성, document.createElement(HTML요소) 2. DOM 객체 추가 appendChild() insertBefore() 3. DOM 객체 출력 및 수정 3.1 write 3.2 innerHTML XSS 취약점 존재 3.3 insertAdjacentHTML innerHTML의 대안 참고 (https://developer.mozilla.org/ko/docs/Web/API/Element/insertAdjacentHTML) 3.4 innerText 3.5 textContent 권장 참고(https://developer.mozilla.org/ko/docs/Web/API/Node/textContent) 4. 속성 변경 4.1 CSS 스타일 변경 요소.style.color 요소.style.fontSize font-size 처럼 글자 사이에 "-"이 있는경우 "-"뒤 첫글자를 대문자로 치환 4.2 속성값 변경 1 일반 속성 변경 getAttribute() - 어트리뷰트 값을 가져온다. hasAttribute() - 어트리뷰트 값을 가지고 있는지 검사한다. setAttribute() - 어트리뷰트에 값을 대입한다. removeAttribute() - 어트리뷰트를 제거한다. 2 class 속성 변경 className class 네임 지정 classList add class 추가 remove class 제거 item 여려개 class 순번 선택 toggle class toggle(반복) 5. DOM 객체 삭제 removeChild() 1.3.3 HTML 이벤트 핸들러 03_JS_10_02_DOM_이벤트_개요.html */ </script> </head> <body> <h3>JS_DOM_개요</h3> <hr> <p id="test01" class="test01_class" name="test01">test01test01</p> <script> /*nodelist, htmlcollection 차이 https://www.w3schools.com/js/js_htmldom_nodelist.asp A NodeList object is almost the same as an HTMLCollection object. NodeList와 HTMLCollection 모두 DOM인터페이스로 엘리먼트의 집합을 말합니다. 둘다 배열 메소드를 지원하지는 않습니다. 차이점이 있다면 HTMLCollection은 노드의 집합이며 DOM의 변화를 반영합니다. NodeList로 반환된 것은 배열로 전환할 수 있습니다. let nodesArray = Array.prototype.slice.call(document.querySelectorAll(".div_li")); nodelist 노드 메서드 getElementsByName (live) querySelectorAll (static) (참고 https://im-developer.tistory.com/110) 유사배열(length 사용 가능) foreach 사용 가능 htmlcollection 노드하위 메서드 getElementsByTagName (live) getElementsByClassName (live) 유사배열(length 사용 가능) foreach 사용 못함 */ let test02 = document.getElementsByName("test01"); let test03 = document.getElementsByTagName("p"); let test04 = document.getElementsByClassName("test01_class"); let test05 = document.querySelectorAll(".test01_class"); console.log(test02); //nodelist console.log(test03); //htmlcollection console.log(test04); //htmlcollection console.log(test05); //nodelist //nodelist forEach사용가능 test02.forEach(function(element, index){ console.log("test02_index::::"+index+" , test02_textContent::::"+element.textContent ); }); console.log("test03.length::::"+test03.length); // (htmlcollection으로 foreEach 사용 못함) 주석 풀고 실행 하면 에러발생 // test03.forEach(function(element, index){ // console.log(index+" "+element.textContent ); // }); // 따라서 기본 for문 사용 for(let i=0; i<test03.length; i++){ console.log("test03_index::::"+i+" , test03_textContent::::"+test03[i].textContent ); } //nodelist 일때 속성 취득 console.log("nodelist_test02::::::"+test02[0].getAttribute("name")); console.log("nodelist_test02::::::"+test02[0].textContent); //htmlcollection 일때 속성 취득 (nodelist와 같음) console.log("htmlcollection_test03::::::"+test03[0].getAttribute("name")); console.log("htmlcollection_test03::::::"+test03[0].textContent); </script> </body> </html> </body> </html>
import 'package:absoftexamination/model/user.dart'; import 'package:absoftexamination/util/shared_preferences_util.dart'; import 'package:flutter/material.dart'; class UserProvider extends ChangeNotifier { User? _user; // String? _token; // User? get user => _user; // String? get token => _token; UserProvider() { _loadUser(); } Map<String, dynamic>? _userData; String? _token; Map<String, dynamic>? get userData => _userData; String? get token => _token; void setUserData(Map<String, dynamic> data) { _userData = data; print(_userData); notifyListeners(); } void setToken(String token) { _token = token; print('token isnnnnnnnnn: ${_token}'); notifyListeners(); } Future<void> _loadUser() async { _user = await UserPreferences.getUser(); _token = await UserPreferences.getToken(); notifyListeners(); } Future<void> loginUser(User user, String token) async { _user = user; _token = token; await UserPreferences.saveUser(user); await UserPreferences.saveToken(token); notifyListeners(); } Future<void> logoutUser() async { _user = null; _token = null; await UserPreferences.removeToken(); notifyListeners(); } }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule } from '@angular/router'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CustomerProfileComponent, DialogElementsDialog } from './components/customer-profile/customer-profile.component'; import { MakerProfileComponent } from './components/maker-profile/maker-profile.component'; import { MatDialogModule } from '@angular/material/dialog'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatRadioModule } from '@angular/material/radio'; import { LoginComponent } from './components/login/login.component'; import { HeaderProfileComponent } from './components/header-profile/header-profile.component'; import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { HttpClientModule } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTabsModule } from '@angular/material/tabs'; import { DetailsServiceComponent } from './components/maker-profile/details-service/details-service.component'; @NgModule({ declarations: [ AppComponent, CustomerProfileComponent, MakerProfileComponent, LoginComponent, HeaderProfileComponent, DetailsServiceComponent, DialogElementsDialog ], imports: [ BrowserModule, AppRoutingModule, FormsModule, MatFormFieldModule, MatRadioModule, ReactiveFormsModule, RouterModule, MatAutocompleteModule, MatDialogModule, HttpClientModule, BrowserAnimationsModule, MatIconModule, MatTooltipModule, MatTabsModule ], exports: [ MatFormFieldModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
import { Prisma } from "@prisma/client"; import DatabaseLib from "../libs/database.lib"; import { TFetchAllParams } from "../types/indexType"; export type TCreateWriterBody = { name: string; }; export type TGetWritersParams = { term?: string; }; class WriterRepository { static writerSelect: Prisma.WriterSelect = { id: true, name: true, }; static async createWriterIfNotExist(data: TCreateWriterBody) { try { const writer = await DatabaseLib.models.writer.findFirst({ where: { name: data.name }, }); if (!!writer) { return { writer, isNew: false }; } const resp = await DatabaseLib.models.writer.create({ data, }); return { writer: resp, isNew: true }; } catch (error) { console.error("Error on service: ", error); throw error; } } static async createWriter(data: TCreateWriterBody) { try { const resp = await DatabaseLib.models.writer.create({ data, }); return resp; } catch (error) { console.error("Error on service: ", error); throw error; } } static async updateWriter(id: number, data: TCreateWriterBody) { try { const resp = await DatabaseLib.models.writer.update({ where: { id }, data, }); return resp; } catch (error) { console.error("Error on service: ", error); throw error; } } static async deleteWriterById(id: number) { try { const resp = await DatabaseLib.models.writer.delete({ where: { id }, }); return resp; } catch (error) { console.error("Error on service: ", error); throw error; } } static async getWriters({ limit, offset, term }: TGetWritersParams & TFetchAllParams) { try { const resp = await DatabaseLib.models.writer.findMany({ skip: offset, take: limit, select: this.writerSelect, where: { name: { contains: term?.toLowerCase() }, }, }); return resp; } catch (error) { console.error("Error on service: ", error); throw error; } } static async getWriterById(id: number) { try { const resp = await DatabaseLib.models.writer.findFirst({ where: { id, }, }); if (!resp) throw `404|WRITER_NOT_FOUND`; return resp; } catch (error) { console.error("Error on service: ", error); throw error; } } } export default WriterRepository;
package com.security.config; import com.security.service.UserInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.NegatedRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; @EnableWebSecurity @Configuration public class SecurityConfig { @Lazy @Autowired private JwtAuthFilter authFilter; @Bean public UserDetailsService userDetailsService(){ return new UserInfoService(); } @Bean public RequestMatcher publicUrls() { return new OrRequestMatcher( new AntPathRequestMatcher("/auth/welcome"), new AntPathRequestMatcher("/auth/addNewUser"), new AntPathRequestMatcher("/auth/generateToken") ); } @Bean public RequestMatcher authenticatedUrls() { return new OrRequestMatcher( new AntPathRequestMatcher("/auth/user/**"), new AntPathRequestMatcher("/auth/admin/**") ); } @Bean public RequestMatcher protectedUrls() { return new NegatedRequestMatcher(publicUrls()); } @Bean public SecurityFilterChain configure(HttpSecurity http) throws Exception{ return http.csrf().disable() .authorizeHttpRequests().requestMatchers(publicUrls()).permitAll() .and() .authorizeHttpRequests().requestMatchers(authenticatedUrls()).authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authenticationProvider(authenticationProvider()) .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class) .build(); } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean public AuthenticationProvider authenticationProvider(){ DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService()); authenticationProvider.setPasswordEncoder(passwordEncoder()); return authenticationProvider; } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)throws Exception{ return authenticationConfiguration.getAuthenticationManager(); } }
package me.grgamer2626.service.users.registration; import jakarta.servlet.http.HttpServletRequest; import me.grgamer2626.model.users.User; import me.grgamer2626.model.users.roles.Role; import me.grgamer2626.model.users.roles.RoleRepository; import me.grgamer2626.model.users.roles.RoleType; import me.grgamer2626.model.users.token.VerificationToken; import me.grgamer2626.service.users.UserService; import me.grgamer2626.service.users.exceptions.emailValidation.EmailAlreadyConfirmedException; import me.grgamer2626.service.users.exceptions.emailValidation.EmailVerificationException; import me.grgamer2626.service.users.exceptions.emailValidation.InvalidTokenException; import me.grgamer2626.service.users.exceptions.emailValidation.TokenExpiredException; import me.grgamer2626.service.users.exceptions.registration.EmailAlreadyExistsException; import me.grgamer2626.service.users.exceptions.registration.RegistrationException; import me.grgamer2626.service.users.exceptions.registration.UserNameAlreadyExistsException; import me.grgamer2626.utils.dto.UserRegistrationDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.validation.BindingResult; import java.util.List; @Service public class UserRegistrationManager implements UserRegistrationService { private final UserService userService; private final RoleRepository roleRepository; private final PasswordEncoder passwordEncoder; @Autowired public UserRegistrationManager(UserService userService, RoleRepository roleRepository, PasswordEncoder passwordEncoder) { this.userService = userService; this.roleRepository = roleRepository; this.passwordEncoder = passwordEncoder; } @Override public User registerUser(UserRegistrationDto dto) throws RegistrationException { String email = dto.getEmail(); if(userService.isEmailRegistered(email)) throw new EmailAlreadyExistsException("User with email " + email + " already exists!"); String nickName = dto.getNickName(); if(userService.isNameTaken(nickName)) throw new UserNameAlreadyExistsException("User with nick name " + nickName + " already exists!"); String encodedPassword = passwordEncoder.encode(dto.getPassword()); Role userRole = roleRepository.findByName(RoleType.USER); if(userRole == null) userRole = new Role(RoleType.USER); User user = new User(nickName, email, encodedPassword, List.of(userRole)); return userService.save(user); } @Override public void validateUser(UserRegistrationDto dto, BindingResult bindingResult) { if(userService.isNameTaken(dto.getNickName())) bindingResult.rejectValue("nickName", "error.nickNameTaken", "This name is already taken!"); if(userService.isEmailRegistered(dto.getEmail())) bindingResult.rejectValue("email", "error.emailTaken", "This email is already registered!"); } @Override public User validateEmail(VerificationToken token) throws EmailVerificationException { if(token == null) throw new InvalidTokenException("Invalid token!"); User user = token.getUser(); if(user.isEnabled()) throw new EmailAlreadyConfirmedException("This Email is already confirmed!"); if(token.isExpired()) throw new TokenExpiredException("The token has been expired!"); user.setEnabled(true); return userService.save(user); } @Override public String createApplicationUrl(HttpServletRequest request) { return "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); } }
import axios from 'axios'; import React, { useState, useEffect } from 'react'; import ChatBot from 'react-simple-chatbot'; import { ThemeProvider } from 'styled-components'; const Chatbot = () => { // const [userInput, setUserInput] = useState(''); // const [response, setResponse] = useState(''); // const [isLoading, setIsLoading] = useState(false); // useEffect(() => { // if (userInput) { // setIsLoading(true) // axios.post('https://lms-with-chatbot.onrender.com/chat', { userInput: userInput }) // .then((res) => { // console.log(res); // setResponse(res.data.response); // }) // .catch((error) => { // console.error('Error fetching response:', error); // }) // .finally(() => { // setIsLoading(false) // }); // } // }, [userInput]) const theme = { background: 'rgb(201, 255, 143)', headerBgColor: '#197B22', headerFontSize: '18px', botBubbleColor: '#0F3789', headerFontColor: 'white', botFontColor: 'white', userBubbleColor: '#FF5733', userFontColor: 'white', }; return ( <div> <ThemeProvider theme={theme}> <ChatBot steps={[ { id: '1', message: 'Hey there! Im Nichole, here to assist you with everything at Edu Junction. To get started, please enter your name. Thanks!', trigger: '2', }, { id: '2', user: true, validator: (value) => { if (!value) { return 'Please Enter Your Name'; } return true; }, trigger: '3', }, { id: '3', message: 'Hi {previousValue}, nice to meet you! What can I help you with ?', trigger: '4', }, { id: '4', options: [ { value: 1, label: 'Courses', trigger: '5' }, { value: 2, label: 'About Edu Junction', trigger: '6' }, ], }, { id: '5', message: 'Currently we are offering upto 5 courses but many courses are comming up very soon.', }, { id: '6', message: 'Edu Junction is a learning management system where user can enroll in variety of courses and level up their skills.', end: true, } ]} floating = {true} botAvatar = 'https://cdn-icons-png.flaticon.com/512/8649/8649595.png' headerTitle='Edu_Junction Support' /> </ThemeProvider> </div> ); }; export default Chatbot;
package leetcode.editor.cn; //给定两个由一些 闭区间 组成的列表,firstList 和 secondList ,其中 firstList[i] = [starti, endi] 而 //secondList[j] = [startj, endj] 。每个区间列表都是成对 不相交 的,并且 已经排序 。 // // 返回这 两个区间列表的交集 。 // // 形式上,闭区间 [a, b](其中 a <= b)表示实数 x 的集合,而 a <= x <= b 。 // // 两个闭区间的 交集 是一组实数,要么为空集,要么为闭区间。例如,[1, 3] 和 [2, 4] 的交集为 [2, 3] 。 // // // // 示例 1: // // //输入:firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15, //24],[25,26]] //输出:[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] // // // 示例 2: // // //输入:firstList = [[1,3],[5,9]], secondList = [] //输出:[] // // // 示例 3: // // //输入:firstList = [], secondList = [[4,8],[10,12]] //输出:[] // // // 示例 4: // // //输入:firstList = [[1,7]], secondList = [[3,10]] //输出:[[3,7]] // // // // // 提示: // // // 0 <= firstList.length, secondList.length <= 1000 // firstList.length + secondList.length >= 1 // 0 <= starti < endi <= 10⁹ // endi < starti+1 // 0 <= startj < endj <= 10⁹ // endj < startj+1 // // 👍 301 👎 0 import java.util.*; /** * 区间列表的交集 * * @author IronSid * @version 1.0 * @since 2022-06-29 17:05:28 */ public class IntervalListIntersectionsSolution { //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int[][] intervalIntersection(int[][] firstList, int[][] secondList) { int n1 = firstList.length, n2 = secondList.length; int p1 = 0, p2 = 0; List<int[]> list = new ArrayList<>(); while (p1 < n1 && p2 < n2) { int x1 = firstList[p1][0], y1 = firstList[p1][1]; int x2 = secondList[p2][0], y2 = secondList[p2][1]; if (y1 < x2) { p1++; } else if (y2 < x1) { p2++; } else { list.add(new int[]{Math.max(x1, x2), Math.min(y1, y2)}); if (y1 <= y2) p1++; else p2++; } } int[][] res = new int[list.size()][]; for (int i = 0; i < list.size(); i++) { res[i] = list.get(i); } return res; } } //leetcode submit region end(Prohibit modification and deletion) }
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/metrics/structured/key_data_provider_ash.h" #include "components/metrics/structured/key_data_provider_file.h" #include "components/metrics/structured/structured_metrics_validator.h" namespace metrics::structured { namespace { // Default delay period for the PersistentProto. This is the delay before a file // write is triggered after a change has been made. constexpr base::TimeDelta kSaveDelay = base::Milliseconds(1000); // The path used to store per-profile keys. Relative to the user's // cryptohome. This file is created by chromium. constexpr char kProfileKeyPath[] = "structured_metrics/keys"; // The path used to store per-device keys. This file is created by tmpfiles.d // on start and has its permissions and ownership set such that it is writable // by chronos. constexpr char kDeviceKeyPath[] = "/var/lib/metrics/structured/chromium/keys"; } // namespace KeyDataProviderAsh::KeyDataProviderAsh() : KeyDataProviderAsh(base::FilePath(kDeviceKeyPath), kSaveDelay) {} KeyDataProviderAsh::KeyDataProviderAsh(const base::FilePath& device_key_path, base::TimeDelta write_delay) : device_key_path_(device_key_path), write_delay_(write_delay) { device_key_ = std::make_unique<KeyDataProviderFile>(device_key_path_, write_delay_); device_key_->AddObserver(this); } KeyDataProviderAsh::~KeyDataProviderAsh() { device_key_->RemoveObserver(this); if (profile_key_) { profile_key_->RemoveObserver(this); } } bool KeyDataProviderAsh::IsReady() { DCHECK(device_key_); return device_key_->IsReady(); } void KeyDataProviderAsh::OnKeyReady() { NotifyKeyReady(); } KeyData* KeyDataProviderAsh::GetKeyData(const std::string& project_name) { auto* key_data_provider = GetKeyDataProvider(project_name); if (!key_data_provider || !key_data_provider->IsReady()) { return nullptr; } return key_data_provider->GetKeyData(project_name); } std::optional<uint64_t> KeyDataProviderAsh::GetId( const std::string& project_name) { KeyDataProvider* key_data_provider = GetKeyDataProvider(project_name); if (!key_data_provider) { return std::nullopt; } return key_data_provider->GetId(project_name); } std::optional<uint64_t> KeyDataProviderAsh::GetSecondaryId( const std::string& project_name) { auto maybe_project_validator = validator::Validators::Get()->GetProjectValidator(project_name); if (!maybe_project_validator.has_value()) { return std::nullopt; } // If |project_name| is not of type sequence, return std::nullopt as it // should not have a corresponding secondary ID. const auto* project_validator = maybe_project_validator.value(); if (project_validator->event_type() != StructuredEventProto_EventType_SEQUENCE) { return std::nullopt; } DCHECK(device_key_); if (device_key_->IsReady()) { return device_key_->GetId(project_name); } return std::nullopt; } void KeyDataProviderAsh::OnProfileAdded(const base::FilePath& profile_path) { // Only the primary user's keys should be loaded. If there is already is a // profile key, no-op. if (profile_key_) { return; } profile_key_ = std::make_unique<KeyDataProviderFile>( profile_path.Append(kProfileKeyPath), write_delay_); profile_key_->AddObserver(this); } void KeyDataProviderAsh::Purge() { if (device_key_) { device_key_->Purge(); } if (profile_key_) { profile_key_->Purge(); } } KeyDataProvider* KeyDataProviderAsh::GetKeyDataProvider( const std::string& project_name) { auto maybe_project_validator = validator::Validators::Get()->GetProjectValidator(project_name); if (!maybe_project_validator.has_value()) { return nullptr; } const auto* project_validator = maybe_project_validator.value(); switch (project_validator->id_scope()) { case IdScope::kPerProfile: { if (profile_key_) { return profile_key_.get(); } break; } case IdScope::kPerDevice: { // Retrieve the profile key if the type is a sequence. if (project_validator->event_type() == StructuredEventProto_EventType_SEQUENCE) { return profile_key_ ? profile_key_.get() : nullptr; } if (device_key_) { return device_key_.get(); } break; } default: NOTREACHED(); break; } return nullptr; } } // namespace metrics::structured
#pragma once #include <boost/asio.hpp> #include <functional> namespace Sim::Common { struct ITimer { virtual ~ITimer() = default; virtual void start(std::function<void()> const& callback) = 0; virtual void stop() = 0; }; class SimulantTimer : public ITimer { public: SimulantTimer(int repeatCount); void start(std::function<void()> const& callback); void stop(); private: int mRepeatCount; std::function<void()> mCallback; }; class Timer : ITimer { public: Timer(boost::asio::io_context& io_context, boost::posix_time::millisec interval); void start(std::function<void()> const& callback); void stop(); private: void tick(const boost::system::error_code&); std::optional<std::function<void()>> mCallback; boost::posix_time::millisec mInterval; boost::asio::deadline_timer mTimer; bool mIsRunning = false; }; } // namespace Sim::Common
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; import { LoginComponent } from './login/login.component'; import { LayoutComponent } from './layout/layout.component'; import { importType, importExpr } from '@angular/compiler/src/output/output_ast'; @NgModule({ declarations: [ // 引入的component AppComponent, HomeComponent, AboutComponent, LoginComponent, LayoutComponent ], imports: [ // 引入的模組 BrowserModule, AppRoutingModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
<!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>TechNews</title> <!--FontAwesome--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <!--Font Oswald --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Oswald:wght@200;300;400&display=swap" rel="stylesheet"> <!--Custom CSS--> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="menu-btn"> <i class="fas fa-bars"></i> </div> <div class="container"> <nav class="nav-main"> <img src="img/logo.png" alt="TechNews Logo" class="nav-brand"> <ul class="nav-menu"> <li> <a href="#">Web Development</a> </li> <li> <a href="#">Pokemon</a> </li> <li> <a href="#">Dragon Ball</a> </li> <li> <a href="#">Cod Mobile</a> </li> <li> <a href="#">Clash</a> </li> </ul> <ul class="nav-menu-right"> <li> <a href="#"> <i class="fas fa-search"></i> </a> </li> </ul> </nav> <hr> <!--Show Case--> <header class="showcase"> <h2>Big News Today</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum quos molestias, sit repudiandae iure iste adipisci temporibus esse cupiditate hic voluptate perferendis consequatur soluta consequuntur! Maxime, quaerat voluptatum. Velit, molestiae!</p> <a href="#" class="btn">Read More <i class="fas fa-angle-double-right"></i></a> </header> <!--News Cards--> <div class="news-cards"> <div> <img src="./img/img1.jpg" alt="News 1"> <h3>Lorem, ipsum dolor.</h3> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum laudantium minima rem ducimus iure corrupti vel aspernatur numquam iste sint.</p> <a href="#">Learn More <i class="fas fa-angle-double-right"></i></a> </div> <div> <img src="./img/img2.png" alt="News 2"> <h3>Lorem, ipsum dolor.</h3> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum laudantium minima rem ducimus iure corrupti vel aspernatur numquam iste sint.</p> <a href="#">Learn More <i class="fas fa-angle-double-right"></i></a> </div> <div> <img src="./img/img3.png" alt="News 3"> <h3>Lorem, ipsum dolor.</h3> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum laudantium minima rem ducimus iure corrupti vel aspernatur numquam iste sint.</p> <a href="#">Learn More <i class="fas fa-angle-double-right"></i></a> </div> <div> <img src="./img/img4.png" alt="News 4"> <h3>Lorem, ipsum dolor.</h3> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum laudantium minima rem ducimus iure corrupti vel aspernatur numquam iste sint.</p> <a href="#">Learn More <i class="fas fa-angle-double-right"></i></a> </div> </div> <section class="cards-banner-one"> <div class="content"> <h2>Lorem, ipsum dolor.</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit ipsum nobis nemo accusamus adipisci minima. Placeat quam optio alias ab!</p> <a href="#" class="btn">Learn More <i class="fas fa-angle-double-right"></i></a> </div> </section> <!--News Cards--> <div class="news-cards"> <div> <img src="./img/img1.jpg" alt="News 1"> <h3>Lorem, ipsum dolor.</h3> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum laudantium minima rem ducimus iure corrupti vel aspernatur numquam iste sint.</p> <a href="#">Learn More <i class="fas fa-angle-double-right"></i></a> </div> <div> <img src="./img/img2.png" alt="News 2"> <h3>Lorem, ipsum dolor.</h3> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum laudantium minima rem ducimus iure corrupti vel aspernatur numquam iste sint.</p> <a href="#">Learn More <i class="fas fa-angle-double-right"></i></a> </div> <div> <img src="./img/img3.png" alt="News 3"> <h3>Lorem, ipsum dolor.</h3> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum laudantium minima rem ducimus iure corrupti vel aspernatur numquam iste sint.</p> <a href="#">Learn More <i class="fas fa-angle-double-right"></i></a> </div> <div> <img src="./img/img4.png" alt="News 4"> <h3>Lorem, ipsum dolor.</h3> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum laudantium minima rem ducimus iure corrupti vel aspernatur numquam iste sint.</p> <a href="#">Learn More <i class="fas fa-angle-double-right"></i></a> </div> </div> <section class="cards-banner-two"> <div class="content"> <h2>Lorem, ipsum dolor.</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Sit voluptatibus rerum nisi aliquid aspernatur. Enim earum necessitatibus et, voluptatem tempora accusantium debitis non dolore iusto fugit. Explicabo perferendis dicta fugiat!</p> <a href="#" class="btn">Learn More <i class="fas fa-angle-double-right"></i></a> </div> </section> <section class="social"> <p>Follow Black</p> <div class="links"> <a href="#"> <i class="fab fa-facebook-f"></i> </a> <a href="#"> <i class="fab fa-twitter"></i> </a> <a href="#"> <i class="fab fa-linkedin"></i> </a> </div> </section> </div> <footer class="footer"> <h3>Black Ferruzo Copyright</h3> </footer> <!--ScrollReveal--> <script src="https://unpkg.com/scrollreveal"></script> <!--Custom JS--> <script src="main.js"></script> </body> </html>
# 功能整理 # 基础 ## 1、版本错误,版本很多是老的 ## 2、路径问题(一定要英文路径) ## 3、包下载、启动 ``` flutter packages get ``` ``` flutter run ``` ## 4、flutter创建 ``` flutter create weixin ``` ## 5、命名规范问题 ![image-20240322072638152](C:/Users/lingzipeng/AppData/Roaming/Typora/typora-user-images/image-20240322072638152.png) ## 6、图片自适应问题 ``` fit: BoxFit.cover, ``` ## 7、StatefulWidget和StatelessWidget的区别 `StatelessWidget` 是一个无状态的 Widget 类型,意味着它的 UI 在创建后就不会再发生变化。无状态的小部件,即在其生命周期内不会发生状态变化 - 如果你的 UI 不需要根据数据变化而更新,或者是静态的展示内容,可以使用 `StatelessWidget`。 - 如果你的 UI 需要根据数据变化或用户交互而更新,需要包含可变状态,就应该使用 `StatefulWidget`。 ## 8、返回键 appbar自动生成 ## 9、格式化代码快捷键 Android Ctrl+ALT+L vs Shift+Alt+F ## 10、Widget状态管理 setState() 11、 ## 100、其他 ``` - images/img.jpg - images/lebron.jpg - images/xk.jpg - images/a001.jpg - images/a002.jpg - images/a003.jpg - images/a004.jpg - images/a005.jpg - assets/[email protected] - assets/[email protected] - assets/[email protected] - assets/[email protected] - assets/[email protected] - assets/[email protected] - assets/[email protected] - assets/[email protected] - assets/haugnbo.png - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/[email protected] - images/刘备.png - images/曹操.png - images/孙权.png - images/关羽.png - images/张飞.png - images/吕布.png - images/赵云.png - images/诸葛亮.png - images/周瑜.png - images/鲁肃.png - images/司马懿.png - images/袁绍.png - images/华佗.png - images/华雄.png - images/公孙瓒.png - images/刘表.png - images/典韦.png - images/黄忠.png - images/刘禅.png - images/徐庶.png - images/郭嘉.png - images/荀攸.png - images/xiaoheizi.jpg ``` ``` import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'test/a.dart'; class XKTabBar extends StatefulWidget { final String title; const XKTabBar({required this.title, Key? key}) : super(key: key); @override _XKTabBar createState() => _XKTabBar(); } class _XKTabBar extends State<XKTabBar> { Dio dio = Dio(); TextEditingController textController = TextEditingController(); String responseData = ''; void sendPostRequest() async { try { // 构建请求体 Map<String, dynamic> data = { 'username': "lihua", 'password': '1234567', }; Uri uri = Uri( scheme: 'http', host: 'localhost', port: 8080, path: '/user/login', queryParameters: data, ); String url = uri.toString(); // 发送POST请求 Response response = await dio.post(url); // 处理服务器响应 responseData = response.data.toString(); print('成功: $responseData'); } catch (e) { print('失败: $e'); } } void sendGetRequest() async { try { // 发送GET请求 Response response = await dio.get('http://127.0.0.1:4523/m1/3535579-0-default/test/a'); responseData = response.data.toString(); print('成功: $responseData'); } catch (e) { print('失败: $e'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: const Color.fromARGB(255, 234, 230, 230), ), body: Container( alignment: const Alignment(0.0, 0.0), height: 100.0, child: ElevatedButton( onPressed: () { sendPostRequest(); }, child: const Text("老铁666"), ))); } } ```
import { useNavigate } from 'react-router-dom'; import useSnackBar from '@/hooks/common/useSnackBar'; import useDeleteRefreshToken from '@/hooks/login/useDeleteRefreshToken'; function WithHooksHOC<F>(Component: React.ComponentType<F>) { return function Hoc(props: F) { const { showSnackBar } = useSnackBar(); const navigate = useNavigate(); const { mutate: mutateDeleteRefreshToken } = useDeleteRefreshToken(); return ( <Component {...props} showSnackBar={showSnackBar} navigate={navigate} mutateDeleteRefreshToken={mutateDeleteRefreshToken} /> ); }; } export default WithHooksHOC;
/* * This file is part of AndroidIDE. * * AndroidIDE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroidIDE 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 AndroidIDE. If not, see <https://www.gnu.org/licenses/>. */ package com.itsaky.androidide.actions.build import android.content.Context import androidx.core.content.ContextCompat import com.itsaky.androidide.resources.R import com.itsaky.androidide.actions.ActionData import com.itsaky.androidide.actions.EditorActivityAction import com.itsaky.androidide.actions.markInvisible import com.itsaky.androidide.lookup.Lookup import com.itsaky.androidide.projects.builder.BuildService import com.itsaky.androidide.utils.ILogger /** @author Akash Yadav */ class CancelBuildAction() : EditorActivityAction() { private val log = ILogger.newInstance(javaClass.simpleName) constructor(context: Context) : this() { label = context.getString(R.string.title_cancel_build) icon = ContextCompat.getDrawable(context, R.drawable.ic_stop_daemons) } override val id: String = "editor_stopGradleDaemons" override fun prepare(data: ActionData) { super.prepare(data) if (!visible) { return } val context = getActivity(data) val buildService = Lookup.DEFAULT.lookup(BuildService.KEY_BUILD_SERVICE) if (context == null || buildService == null) { markInvisible() return } visible = true enabled = buildService.isBuildInProgress } override fun execAction(data: ActionData): Boolean { log.info("Sending build cancellation request...") Lookup.DEFAULT.lookup(BuildService.KEY_BUILD_SERVICE)?.cancelCurrentBuild()?.whenComplete { result, error -> if (error != null) { log.error("Failed to send build cancellation request", error) return@whenComplete } if (!result.wasEnqueued) { log.warn( "Unable to enqueue cancellation request", result.failureReason, result.failureReason!!.message ) return@whenComplete } log.info("Build cancellation request was successfully enqueued...") } return true } }
package util; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import util.HttpRequestUtils.Pair; import java.util.Map; public class HttpRequestUtilsTest { @Test public void parseQueryString() { String queryString = "userId=javajigi"; Map<String, String> parameters = HttpRequestUtils.parseQueryString(queryString); Assertions.assertThat(parameters.get("userId")).isEqualTo("javajigi"); Assertions.assertThat(parameters.get("password")).isNull(); queryString = "userId=javajigi&password=password2"; parameters = HttpRequestUtils.parseQueryString(queryString); Assertions.assertThat(parameters.get("userId")).isEqualTo("javajigi"); Assertions.assertThat(parameters.get("password")).isEqualTo("password2"); } @Test public void parseQueryString_null() { Map<String, String> parameters = HttpRequestUtils.parseQueryString(null); Assertions.assertThat(parameters.isEmpty()).isTrue(); parameters = HttpRequestUtils.parseQueryString(""); Assertions.assertThat(parameters.isEmpty()).isTrue(); parameters = HttpRequestUtils.parseQueryString(" "); Assertions.assertThat(parameters.isEmpty()).isTrue(); } @Test public void parseQueryString_invalid() { String queryString = "userId=javajigi&password"; Map<String, String> parameters = HttpRequestUtils.parseQueryString(queryString); Assertions.assertThat(parameters.get("userId")).isEqualTo( "javajigi"); Assertions.assertThat(parameters.get("password")).isNull(); } @Test public void parseCookies() { String cookies = "logined=true; JSessionId=1234"; Map<String, String> parameters = HttpRequestUtils.parseCookies(cookies); Assertions.assertThat(parameters.get("logined")).isEqualTo("true"); Assertions.assertThat(parameters.get("JSessionId")).isEqualTo("1234"); Assertions.assertThat(parameters.get("session")).isNull(); } @Test public void getKeyValue() throws Exception { Pair pair = HttpRequestUtils.getKeyValue("userId=javajigi", "="); Assertions.assertThat(pair).isEqualTo(new Pair("userId", "javajigi")); } @Test public void getKeyValue_invalid() throws Exception { Pair pair = HttpRequestUtils.getKeyValue("userId", "="); Assertions.assertThat(pair).isNull(); } @Test public void parseHeader() throws Exception { String header = "Content-Length: 59"; Pair pair = HttpRequestUtils.parseHeader(header); Assertions.assertThat(pair).isEqualTo(new Pair("Content-Length", "59")); } }
package com.procex.procexapp.presentation.screens.client.resumen import androidx.compose.runtime.getValue import androidx.compose.runtime.* import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.procex.procexapp.domain.model.Formulario import com.procex.procexapp.domain.useCase.formulario.FormularioUseCase import com.procex.procexapp.domain.util.Resource import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ClientFormularioResumenViewModel @Inject constructor(private val formularioUseCase: FormularioUseCase): ViewModel() { var formularioRespone by mutableStateOf<Resource<List<Formulario>>?>(null) private set var countFormulariosM1 by mutableStateOf(0) private set var countFormulariosM2 by mutableStateOf(0) private set var countFormulariosF by mutableStateOf(0) private set var countFormulariosM by mutableStateOf(0) private set var countFormulariosE by mutableStateOf(0) private set var countFormulariosNE by mutableStateOf(0) private set var countFormulariosPendientes by mutableStateOf(0) private set var countFormulariosListos by mutableStateOf(0) private set init { getVisitas() getFormularioMes1() getFormularioMes2() findBySexoF() findBySexoM() findVisitasEfectivas() findVisitasNoEfectivas() getFormulariosListos() getFormulariosPendientes() } fun getVisitas() = viewModelScope.launch { formularioRespone = Resource.Loading formularioUseCase.getFormulario().collect { data -> formularioRespone = data } } fun getFormulariosListos() = viewModelScope.launch { formularioRespone = Resource.Loading formularioUseCase.findReady(estado = String()).collect { data -> formularioRespone = data if (data is Resource.Success) { countFormulariosListos = data.data.size } else { countFormulariosListos = 0 } } } fun getFormulariosPendientes() = viewModelScope.launch { formularioRespone = Resource.Loading formularioUseCase.findNotReady(estado = String()).collect { data -> formularioRespone = data if (data is Resource.Success) { countFormulariosPendientes = data.data.size } else { countFormulariosPendientes = 0 } } } fun getFormularioMes1() = viewModelScope.launch { formularioRespone = Resource.Loading formularioUseCase.findByMes1(created_at = String()).collect { data -> formularioRespone = data if (data is Resource.Success) { countFormulariosM1 = data.data.size } else { countFormulariosM1 = 0 } } } fun getFormularioMes2() = viewModelScope.launch { formularioRespone = Resource.Loading formularioUseCase.findByMes2(created_at = String()).collect { data -> formularioRespone = data if (data is Resource.Success) { countFormulariosM2 = data.data.size } else { countFormulariosM2 = 0 } } } fun findBySexoF() = viewModelScope.launch { formularioRespone = Resource.Loading formularioUseCase.findBySexoF(sexo = String()).collect { data -> formularioRespone = data if (data is Resource.Success) { countFormulariosF = data.data.size } else { countFormulariosF = 0 } } } fun findBySexoM() = viewModelScope.launch { formularioRespone = Resource.Loading formularioUseCase.findBySexoM(sexo = String()).collect { data -> formularioRespone = data if (data is Resource.Success) { countFormulariosM = data.data.size } else { countFormulariosM = 0 } } } fun findVisitasEfectivas() = viewModelScope.launch { formularioRespone = Resource.Loading formularioUseCase.findVisitasEfectivas(cl_visita = String()).collect { data -> formularioRespone = data if (data is Resource.Success) { countFormulariosE = data.data.size } else { countFormulariosE = 0 } } } fun findVisitasNoEfectivas() = viewModelScope.launch { formularioRespone = Resource.Loading formularioUseCase.findVisitasNoEfectivas(cl_visita = String()).collect { data -> formularioRespone = data if (data is Resource.Success) { countFormulariosNE = data.data.size } else { countFormulariosNE = 0 } } } }
package com.diplom.creo.ui.kit.input import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.diplom.creo.ui.theme.CreoGray import com.diplom.creo.ui.theme.CreoPurple import com.diplom.creo.ui.theme.Typography import com.diplom.creo.ui.theme.montserrat @OptIn(ExperimentalMaterial3Api::class) @Composable fun CreoInput( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, keyboardType: KeyboardType, maxLines: Int = 1, singleLine: Boolean = true, hintText: String = "", underlined: Boolean = false, label: String, rounded: Boolean = true, color: Color = Color.White, error: String? = "", withCheckBox: Boolean = false, isChecked: Boolean = false, onCheckChange: (Boolean) -> Unit = { } ) { if (label.isNotEmpty()) { Text( text = label, fontSize = 16.sp, fontWeight = FontWeight.W500, modifier = Modifier .fillMaxWidth() .padding(bottom = 4.dp), textAlign = TextAlign.Start, color = CreoPurple, fontFamily = montserrat, ) } TextField( shape = if (rounded) RoundedCornerShape(24.dp) else RoundedCornerShape(0.dp), modifier = modifier .border( BorderStroke(if (error != "" && error != null) { 1.dp } else { 0.dp }, if (error != "" && error != null && rounded) { Color.Red } else if (error == "" && error == null && rounded) { Color.Black } else { Color.Transparent }), shape = if (rounded) { RoundedCornerShape(24.dp) } else { RoundedCornerShape(0.dp) }, ), textStyle = Typography.bodyMedium, value = value, onValueChange = onValueChange, singleLine = singleLine, keyboardOptions = KeyboardOptions( keyboardType = keyboardType ), placeholder = { Text( text = hintText, fontFamily = montserrat, color = CreoGray, fontSize = 16.sp ) }, maxLines = maxLines, colors = TextFieldDefaults.textFieldColors( containerColor = color, focusedIndicatorColor = if (!underlined) Color.Transparent else CreoGray, unfocusedIndicatorColor = if (!underlined) Color.Transparent else CreoGray, disabledIndicatorColor = if (!underlined) Color.Transparent else CreoGray ), ) }
import Title from 'components/texts/Title' import TimeLineItem from './TimeLineItem' import {timeLineItem} from 'utility/listItems' import styled from 'styled-components' import {useEffect, useRef, useState} from 'react' const AboutTimeLine = () => { const top = useRef<HTMLDivElement>(null) const bottom = useRef<HTMLDivElement>(null) const [isTopRef, setIsTopRef] = useState(false) const [isBottomRef, setIsBottomRef] = useState(false) const [shadow, setShadow] = useState('') useEffect(() => { const observer = new IntersectionObserver( entries => { entries.forEach(entry => { if (entry.target.id === 'top') { setIsTopRef(entry.isIntersecting) } else if (entry.target.id === 'bottom') { setIsBottomRef(entry.isIntersecting) } }) }, { root: null, threshold: 0.1, }, ) if (top.current) observer.observe(top.current) if (bottom.current) observer.observe(bottom.current) return () => { if (top.current) observer.unobserve(top.current) if (bottom.current) observer.unobserve(bottom.current) } }, []) useEffect(() => { if (isTopRef && !isBottomRef) { setShadow('shadow-boxBottom') } else if (!isTopRef && !isBottomRef) { setShadow('shadow-boxYAll') } else if (!isTopRef && isBottomRef) { setShadow('shadow-boxTop') } else if (isTopRef && isBottomRef) { setShadow('') } }, [isTopRef, isBottomRef]) return ( <div className={'w-full h-full flex flex-col items-center justify-center'}> <div className={'text-left w-full '}> <Title title={'History'} color={'#eee'} /> </div> <div className={'px-4'}> <div className={`w-full px-4 py-4 max-h-[800px] overflow-scroll scrollbar-hide ${shadow} rounded-default bg-itemBg max-w-[70%] md:max-w-[85%] sm:max-w-[100%]`} > <ol className={'relative flex flex-col text-text hover:will-change-scroll max-w-[70%] sm:max-w-[100%]'}> <ScrollLine ref={top} className={' top-[10px]'} id={'top'} /> {timeLineItem.map((v, i) => ( <TimeLineItem item={v} key={i} /> ))} <ScrollLine ref={bottom} className={'bottom-[10px]'} id={'bottom'} /> </ol> </div> </div> </div> ) } export default AboutTimeLine const ScrollLine = styled.div` padding-top: 1px; width: 100%; position: absolute; `
const mocha = require("mocha") const chai = require("chai") const utils = require("../utils") const expect = chai.expect // NOTE: https://mochajs.org/#arrow-functions // Passing arrow functions (“lambdas”) to Mocha is discouraged. // Lambdas lexically bind this and cannot access the Mocha context. it("should say hello", function() { const hello = utils.sayHello() expect(hello).to.be.a("string") expect(hello).to.equal("Hello") expect(hello).with.lengthOf(5) }) // Level 1 Challenges // 1. Write the pending tests check that they are pending, like this: // it("should do something that you want done") // 2. Next, write the test and see that it fails. // 3. Write the code in the utils.js file to make the test pass. // 4. Finally see if you would like to refactor your code at all. // This is called "Red-Green-Refactor" it("should return the area", function() { const w = 10 const h = 10 const area = utils.area(w, h) expect(area).to.be.a('number') expect(area).to.equal(100) }) it("should return the perimeter", function() { const w = 10 const h = 10 const perimeter = utils.perimeter(w, h) expect(perimeter).to.be.a('number') expect(perimeter).to.equal(40) }) // Level 2 Challenges // NOTE: The following unimplemented test cases are examples // of "Pending Tests" in Chai. Someone should write these // tests eventually. beforeEach((done) => { utils.clearCart() done() }) it("Should create a new (object) Item with name and price", function() { const item = utils.createItem("apple", 0.99) expect(item).to.be.a("object") expect(item).to.have.property("name", "apple") expect(item).to.have.property("price", 0.99) expect(item).to.have.property("quantity", 1) }) it("Should return an array containing all items in cart", function() { const cart = utils.getShoppingCart() expect(cart).to.be.a("array") }) it("Should add a new item to the shopping cart", function() { const item = utils.createItem("apple", 0.99) const item2 = utils.createItem("orange", 0.99) const cart = utils.getShoppingCart() utils.addItemToCart(item) utils.addItemToCart(item2) // expect([1, 2, 3]).to.have.members([2, 1, 3]); expect(cart).to.have.members([item, item2]); expect(cart).to.have.members([item, item2]); // expect(cart).to.have.members([item2]) }) it("Should return the number of items in the cart", function() { // should be similar to adding to a cart but we just check the length const item = utils.createItem("apple", 0.99) const cart = utils.getShoppingCart() utils.addItemToCart(item) expect(cart).to.have.lengthOf(1) }) // it("Should remove items from cart", function() { // // use splice property to remove // }) // Stretch Challenges it("Should update the count of items in the cart") it("Should validate that an empty cart has 0 items") it("Should return the total cost of all items in the cart")
import { expect, test } from "@playwright/test"; import { describe } from "node:test"; import { AUTH_MOCK_USER, AUTH_MOCK_USER_UPDATE } from "utils/mockData"; import { loginUser, signupUser } from "./utils/authentication"; describe("User Signup Tests", () => { test("Signup with valid data: to Dashboard", async ({ page }) => { await signupUser(page); await expect( page.getByRole("heading", { name: "User Dashboard" }), ).toBeVisible(); await expect( page.getByRole("heading", { name: "Your Events" }), ).toBeVisible(); }); test("Signup with registered email: email error", async ({ page }) => { await signupUser(page); await expect( page.getByText("Email address already registered"), ).toBeVisible(); }); }); describe("User Login Tests", () => { test("Login with valid data: to Dashboard", async ({ page }) => { await loginUser(page); await expect( page.getByRole("heading", { name: "User Dashboard" }), ).toBeVisible(); await expect( page.getByRole("heading", { name: "Your Events" }), ).toBeVisible(); }); test("Login with invalid email: email error", async ({ page }) => { await page.goto("/login"); await page.getByLabel("Email Address").fill("[email protected]"); await page.getByLabel("Password").fill(AUTH_MOCK_USER.password); await page.getByRole("button", { name: "Login" }).click(); await expect(page.getByText("E-mail address not found")).toBeVisible(); }); test("Login with invalid password: password error", async ({ page }) => { await page.goto("/login"); await page.getByLabel("Email Address").fill(AUTH_MOCK_USER.email); await page.getByLabel("Password").fill("invalidpassword"); await page.getByRole("button", { name: "Login" }).click(); await expect(page.getByText("Invalid password")).toBeVisible(); }); }); describe("User Update Tests", () => { test("Update w/ valid data: to Dashboard", async ({ page }) => { await loginUser(page); await page.getByRole("button", { name: "Update Personal Info" }).click(); await expect( page.getByRole("heading", { name: "Update Personal Info" }), ).toBeVisible(); await page.getByLabel("First Name").fill(AUTH_MOCK_USER_UPDATE.firstName); await page.getByLabel("Last Name").fill(AUTH_MOCK_USER_UPDATE.lastName); await page.getByLabel("Email Address").fill(AUTH_MOCK_USER_UPDATE.email); await page.getByLabel("Phone").fill(AUTH_MOCK_USER_UPDATE.phone); await page .getByLabel("Address", { exact: true }) .fill(AUTH_MOCK_USER_UPDATE.address); await page.getByLabel("City").fill(AUTH_MOCK_USER_UPDATE.city); await page.getByLabel("State").fill(AUTH_MOCK_USER_UPDATE.state); await page.getByLabel("Zip").fill(AUTH_MOCK_USER_UPDATE.zip); await page .getByRole("button", { name: "Update Personal Information" }) .click(); await expect( page.getByRole("heading", { name: "User Dashboard" }), ).toBeVisible(); await expect( page.getByRole("heading", { name: "Your Events" }), ).toBeVisible(); await expect( page.getByText( `${AUTH_MOCK_USER_UPDATE.firstName} ${AUTH_MOCK_USER_UPDATE.lastName}`, ), ).toBeVisible(); await expect(page.getByText(AUTH_MOCK_USER_UPDATE.email)).toBeVisible(); await expect(page.getByText(AUTH_MOCK_USER_UPDATE.address)).toBeVisible(); await expect(page.getByText(AUTH_MOCK_USER_UPDATE.city)).toBeVisible(); await expect(page.getByText(AUTH_MOCK_USER_UPDATE.zip)).toBeVisible(); }); test("Update w/ invalid phone: phone error", async ({ page }) => { await loginUser(page); await page.getByRole("button", { name: "Update Personal Info" }).click(); await expect( page.getByRole("heading", { name: "Update Personal Info" }), ).toBeVisible(); await page.getByLabel("First Name").fill(AUTH_MOCK_USER_UPDATE.firstName); await page.getByLabel("Last Name").fill(AUTH_MOCK_USER_UPDATE.lastName); await page.getByLabel("Email Address").fill(AUTH_MOCK_USER_UPDATE.email); await page.getByLabel("Phone").fill("(123) 333-33333"); await page .getByLabel("Address", { exact: true }) .fill(AUTH_MOCK_USER_UPDATE.address); await page.getByLabel("City").fill(AUTH_MOCK_USER_UPDATE.city); await page.getByLabel("State").fill(AUTH_MOCK_USER_UPDATE.state); await page.getByLabel("Zip").fill(AUTH_MOCK_USER_UPDATE.zip); await page .getByRole("button", { name: "Update Personal Information" }) .click(); await expect( page.getByText("A valid phone number is required"), ).toBeVisible(); }); }); test("User Logout to Home", async ({ page }) => { await loginUser(page); await page.getByRole("button", { name: "Logout" }).click(); await expect( page.getByRole("heading", { name: "Elevate Your Events With" }), ).toBeVisible(); }); test("Delete User to Home", async ({ page }) => { await loginUser(page); await page.getByRole("button", { name: "Update Personal Info" }).click(); await page.getByRole("button", { name: "Delete Account" }).click(); await expect( page.getByRole("heading", { name: "Delete Your Account?" }), ).toBeVisible(); await page.getByRole("button", { name: "Delete Account" }).nth(1).click(); });
<?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); class Persona { protected $dni; protected $nombre; protected $correo; protected $celular; public function __construct($dni, $nombre, $correo, $celular) { $this->dni = $dni; $this->nombre = $nombre; $this->correo = $correo; $this->celular = $celular; } public function imprimir(){ echo "DNI:" . $this->dni . "<br>"; echo "Nombre:" . $this->nombre . "<br>"; echo "Correo:" . $this->correo . "<br>"; echo "Celular:" . $this->celular . "<br>"; } } class Entrenador extends Persona{ private $aClases; public function __construct($dni, $nombre, $correo, $celular) { parent::__construct($dni, $nombre, $correo, $celular); //Parent:: Hereda el constructor de la clase persona $this->aClases = array(); } public function __get($propiedad) { return $this->$propiedad; } public function __set($propiedad, $valor) { $this->$propiedad = $valor; } public function imprimir(){ } } class Alumno extends Persona { private $fechaNac; private $peso; private $altura; private $bAptoFisico; private $presentismo; public function __construct($dni, $nombre, $correo, $celular, $fechaNac) { parent::__construct($dni, $nombre, $correo, $celular); $this->fechaNac = $fechaNac; $this->peso = 0.0; $this->altura = 0.0; $this->bAptoFisico = false; $this->presentismo = 0.0; } public function __get($propiedad) { return $this->$propiedad; } public function __set($propiedad, $valor) { $this->$propiedad = $valor; } public function setFichaMedica($peso, $altura, $bAptoFisico){ $this->peso = $peso; $this->altura = $altura; $this->bAptoFisico = $bAptoFisico; } public function imprimir(){ } } class Clase{ private $nombre; //es un string private $entrenador; //es un objeto private $aAlumnos; //es un array de objetos public function __construct() { $this->aAlumnos = array(); } public function __get($propiedad) { return $this->$propiedad; } public function __set($propiedad, $valor) { $this->$propiedad = $valor; } public function asignarEntrenador($entrenador){ $this->entrenador = $entrenador; } public function inscribirAlumno($alumno){ $this->aAlumnos[] = $alumno; } public function imprimirListado(){ echo "<table class='table table-warning table-bordered table-hover'>"; echo "<tr><th class='table-dark text-center' colspan='4'>Clase: " . $this->nombre . "</th></tr>"; echo "<tr><th colspan='4'>Entrenador: " . $this->entrenador->nombre . "</th></tr>"; echo "<tr><th colspan='4'>Alumnos:</th></tr>"; echo "<tr><th>DNI</th><th>Nombre</th><th>Correo</th><th>Celular</th>"; foreach($this->aAlumnos as $alumno){ echo "<tr><td>" . $alumno->dni . "</td><td>" . $alumno->nombre . "</td><td>" . $alumno->correo . "</td><td>" . $alumno->celular . "</td></tr>"; } echo "</table>"; } } //Programa $entrenador1 = new Entrenador("34987789", "Miguel Ocampo", "[email protected]", "11678634"); $entrenador2 = new Entrenador("28987589", "Andrea Zarate", "[email protected]", "11768654"); $alumno1 = new Alumno("40787657", "Dante Montera", "[email protected]", "1145632457", "1997-08-28"); $alumno1->setFichaMedica(90, 178, true); $alumno1->presentismo = 78; $alumno2 = new Alumno("46766547", "Darío Turchi", "[email protected]", "1145632457", "1986-11-21"); $alumno2->setFichaMedica(73, 1.68, false); $alumno2->presentismo = 68; $alumno3 = new Alumno("39765454", "Facundo Fagnano", "[email protected]", "1145632457", "1993-02-06"); $alumno3->setFichaMedica(90, 1.87, true); $alumno3->presentismo = 88; $alumno4 = new Alumno("41687536", "Gastón Aguilar", "[email protected]", "1145632457", "1999-11-02"); $alumno4->setFichaMedica(70, 1.69, false); $alumno4->presentismo = 98; $clase1 = new Clase(); $clase1->nombre = "Funcional"; $clase1->asignarEntrenador($entrenador1); $clase1->inscribirAlumno($alumno1); $clase1->inscribirAlumno($alumno3); $clase1->inscribirAlumno($alumno4); $clase1->imprimirListado(); $clase2 = new Clase(); $clase2->nombre = "Zumba"; $clase2->asignarEntrenador($entrenador2); $clase2->inscribirAlumno($alumno1); $clase2->inscribirAlumno($alumno2); $clase2->inscribirAlumno($alumno3); $clase2->imprimirListado(); ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <title>Gimnasio</title> </head> <body> </body> </html>
<?php /** * CommentTest class file. * * @package HCaptcha\Tests */ namespace HCaptcha\Tests\Integration\WPDiscuz; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; use HCaptcha\WPDiscuz\Comment; use Mockery; use tad\FunctionMocker\FunctionMocker; /** * Test Comment class. * * @group wpdiscuz */ class CommentTest extends HCaptchaWPTestCase { /** * Tear down test. * * @return void * @noinspection PhpLanguageLevelInspection * @noinspection PhpUndefinedClassInspection */ public function tearDown(): void { // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.voidFound unset( $_POST['h-captcha-response'], $_POST['g-recaptcha-response'] ); } /** * Test init_hooks(). * * @return void */ public function test_init_hooks() { $subject = new Comment(); self::assertTrue( has_filter( 'wpdiscuz_recaptcha_site_key' ) ); self::assertSame( 11, has_action( 'wp_enqueue_scripts', [ $subject, 'enqueue_scripts' ] ) ); self::assertSame( 10, has_filter( 'wpdiscuz_form_render', [ $subject, 'add_hcaptcha' ] ) ); self::assertSame( 9, has_filter( 'preprocess_comment', [ $subject, 'verify' ] ) ); self::assertSame( 20, has_action( 'wp_head', [ $subject, 'print_inline_styles' ] ) ); self::assertSame( '', apply_filters( 'wpdiscuz_recaptcha_site_key', 'some site key' ) ); } /** * Test enqueue_scripts(). * * @return void */ public function test_enqueue_scripts() { self::assertFalse( wp_script_is( 'wpdiscuz-google-recaptcha', 'registered' ) ); self::assertFalse( wp_script_is( 'wpdiscuz-google-recaptcha' ) ); wp_enqueue_script( 'wpdiscuz-google-recaptcha', 'https://domain.tld/api.js', [], '1.0', true ); self::assertTrue( wp_script_is( 'wpdiscuz-google-recaptcha', 'registered' ) ); self::assertTrue( wp_script_is( 'wpdiscuz-google-recaptcha' ) ); $subject = new Comment(); $subject->enqueue_scripts(); self::assertFalse( wp_script_is( 'wpdiscuz-google-recaptcha', 'registered' ) ); self::assertFalse( wp_script_is( 'wpdiscuz-google-recaptcha' ) ); } /** * Test add_captcha(). * * @return void */ public function test_add_captcha() { $args = [ 'id' => [ 'source' => [ 'wpdiscuz/class.WpdiscuzCore.php' ], 'form_id' => 0, ], ]; $hcap_form = $this->get_hcap_form( $args ); $output = 'Some comment output<div class="wc-field-submit">Submit</div>'; $expected = 'Some comment output' . ' <div class="wpd-field-hcaptcha wpdiscuz-item"> <div class="wpdiscuz-hcaptcha" id="wpdiscuz-hcaptcha"></div> ' . $hcap_form . ' <div class="clearfix"></div> </div> ' . '<div class="wc-field-submit">Submit</div>'; $subject = new Comment(); self::assertSame( $expected, $subject->add_hcaptcha( $output, 0, false ) ); } /** * Test verify(). * * @return void */ public function test_verify() { $comment_data = [ 'some comment data' ]; $hcaptcha_response = 'some response'; $wp_discuz = Mockery::mock( 'WpdiscuzCore' ); FunctionMocker::replace( 'wpDiscuz', $wp_discuz ); add_filter( 'preprocess_comment', [ $wp_discuz, 'validateRecaptcha' ] ); $this->prepare_hcaptcha_request_verify( $hcaptcha_response ); $subject = new Comment(); self::assertSame( $comment_data, $subject->verify( $comment_data ) ); self::assertFalse( has_filter( 'preprocess_comment', [ $wp_discuz, 'validateRecaptcha' ] ) ); } /** * Test verify() when not verified. * * @return void */ public function test_verify_NOT_verified() { $comment_data = [ 'some comment data' ]; $hcaptcha_response = 'some response'; $die_arr = []; $expected = [ 'Please complete the hCaptcha.', '', [], ]; $wp_discuz = Mockery::mock( 'WpdiscuzCore' ); FunctionMocker::replace( 'wpDiscuz', $wp_discuz ); add_filter( 'preprocess_comment', [ $wp_discuz, 'validateRecaptcha' ] ); $this->prepare_hcaptcha_request_verify( $hcaptcha_response, false ); unset( $_POST['h-captcha-response'], $_POST['g-recaptcha-response'] ); add_filter( 'wp_die_handler', static function ( $name ) use ( &$die_arr ) { return static function ( $message, $title, $args ) use ( &$die_arr ) { $die_arr = [ $message, $title, $args ]; }; } ); $subject = new Comment(); $subject->verify( $comment_data ); // phpcs:ignore WordPress.Security.NonceVerification.Missing self::assertFalse( isset( $_POST['h-captcha-response'], $_POST['g-recaptcha-response'] ) ); self::assertSame( $expected, $die_arr ); self::assertFalse( has_filter( 'preprocess_comment', [ $wp_discuz, 'validateRecaptcha' ] ) ); } /** * Test print_inline_styles(). * * @return void */ public function test_print_inline_styles() { $expected = '.wpd-field-hcaptcha .h-captcha{margin-left:auto}'; $expected = "<style>\n$expected\n</style>\n"; $subject = new Comment(); ob_start(); $subject->print_inline_styles(); self::assertSame( $expected, ob_get_clean() ); } }
@extends('layouts.main') @section('title', $title) @section('container') <main id="main" class="main"> <div class="pagetitle"> <h1>Ubah Data Siswa</h1> <nav> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li> <li class="breadcrumb-item"><a href="{{ route('siswa.index') }}">Kelola Siswa</a></li> <li class="breadcrumb-item active">Ubah Siswa</li> </ol> </nav> </div> <section class="section dashboard"> <div class="row"> <!-- Left side columns --> <div class="col-lg-12"> <div class="row"> <!-- Default Card --> <div class="card"> <div class="card-body p-3 overflow-auto"> <form action="{{ route('siswa.update', $siswa->id) }}" method="POST" enctype="multipart/form-data"> @csrf @method('PUT') <div class="row mb-5"> <label for="jenjang_kelas" class="col-sm-2 col-form-label">Jenjang Kelas</label> <div class="col-sm-10"> <select id="jenjang_kelas" name="jenjang_kelas" class="form-select @error('jenjang_kelas') is-invalid @enderror" aria-label="Default select example"> <option disabled>Pilih Jenjang Kelas</option> @foreach (['X', 'XI', 'XII'] as $jenjang_kelas) <option value="{{ $jenjang_kelas }}" {{ $siswa->jenjang_kelas == $jenjang_kelas ? 'selected' : '' }}> {{ $jenjang_kelas }}</option> @endforeach </select> @error('jenjang_kelas') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> </div> <div class="row mb-3"> <label for="kategori_kelas" class="col-sm-2 col-form-label">Kategori Kelas</label> <div class="col-sm-10"> <input id="kategori_kelas" name="kategori_kelas" type="text" class="form-control @error('kategori_kelas') is-invalid @enderror" value="{{ old('kategori_kelas', $siswa->kategori_kelas) }}"> @error('kategori_kelas') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> </div> <div class="row mb-5"> <label for="nisn" class="col-sm-2 col-form-label">Nama Siswa</label> <div class="col-sm-10"> <select id="nisn" name="nisn" class="form-select @error('nisn') is-invalid @enderror" aria-label="Default select example"> <option disabled>Pilih Nama Siswa</option> @foreach ($siswas as $siswa) <option value="{{ $siswa->nip }}" {{ $siswa->nisn == $siswa->nip ? 'selected' : '' }}> {{ $siswa->name }}</option> @endforeach </select> @error('nisn') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> </div> <div class="d-flex justify-content-end gap-2"> <button type="submit" class="btn btn-success">Simpan</button> <a href="{{ route('siswa.index') }}"> <button type="button" class="btn btn-secondary">Kembali</button> </a> </div> </form> </div> </div><!-- End Default Card --> </div> </div><!-- End Left side columns --> </div> </section> </main> @endsection
package iotgin import ( "bytes" "encoding/json" "strings" "time" "cloud_platform/iot_common/iotconst" "cloud_platform/iot_common/iotlogger" "cloud_platform/iot_common/iotnats/jetstream" "cloud_platform/iot_common/iotutil" "github.com/gin-gonic/gin" ) type AppLog struct { Id int64 `json:"id"` Account string `json:"account"` AppKey string `json:"appKey"` TenantId string `json:"tenantId"` RegionServerId int64 `json:"regionServerId"` LogType string `json:"logType"` EventName string `json:"eventName"` Details map[string]string `json:"details"` CreatedAt time.Time `json:"createdAt"` } type ResponseWriterWrapper struct { gin.ResponseWriter Body *bytes.Buffer // 缓存 } func (w ResponseWriterWrapper) Write(b []byte) (int, error) { w.Body.Write(b) return w.ResponseWriter.Write(b) } func (w ResponseWriterWrapper) WriteString(s string) (int, error) { w.Body.WriteString(s) return w.ResponseWriter.WriteString(s) } func AppLogger(jspub *jetstream.JsPublisherMgr) gin.HandlerFunc { return func(c *gin.Context) { // 处理请求 blw := &ResponseWriterWrapper{Body: bytes.NewBufferString(""), ResponseWriter: c.Writer} c.Writer = blw c.Next() ip := c.ClientIP() sys := c.GetHeader("x-sys-info") appKey := c.GetHeader("appKey") tenantId := c.GetHeader("tenantId") regionServerId := c.GetHeader("region") account, ok := c.Get("Account") if !ok { iotlogger.LogHelper.Helper.Errorf("get account: %v", account) return } resp := struct { Code int Msg string }{} if err := json.Unmarshal([]byte(blw.Body.String()), &resp); err != nil { iotlogger.LogHelper.Helper.Errorf("json unmarshal response error: %v", err) return } if resp.Msg == "ok" { resp.Msg = "success" } var logType string if resp.Code == 0 { logType = iotconst.APP_OPERATE_LOG } else { logType = iotconst.APP_ERROR_LOG } if event, ok := iotconst.LogEventMap[c.Request.RequestURI]; ok { resp.Msg = event if err := newAppLog(jspub, account.(string), logType, event, ip, sys, resp.Msg, appKey, tenantId, regionServerId); err != nil { iotlogger.LogHelper.Helper.Errorf("new app register log error: %v", err) return } } else { // 以下针对uri+请求参数的情况,需要再做一次判断 for k, v := range iotconst.LogEventMap { if strings.Contains(c.Request.RequestURI, k) { resp.Msg = v if err := newAppLog(jspub, account.(string), logType, v, ip, sys, resp.Msg, appKey, tenantId, regionServerId); err != nil { iotlogger.LogHelper.Helper.Errorf("new app register log error: %v", err) return } } } } } } func newAppLog(jspub *jetstream.JsPublisherMgr, account, logType, eventName, ip, sys, msg, appKey, tenanntId, regionServerId string) error { var regionId int64 = 0 regionId, _ = iotutil.ToInt64AndErr(regionServerId) appLog := AppLog{ Id: iotutil.GetNextSeqInt64(), Account: account, AppKey: appKey, TenantId: tenanntId, RegionServerId: regionId, LogType: logType, EventName: eventName, Details: map[string]string{ "ip": ip, "system": sys, "msg": msg, }, CreatedAt: time.Now(), } data, err := json.Marshal(appLog) if err != nil { return err } pd := &jetstream.NatsPubData{ Subject: iotconst.NATS_SUBJECT_RECORDS, Data: string(data), } jspub.PushData(pd) iotlogger.LogHelper.Helper.Debugf("subject: %s data: %s", pd.Subject, pd.Data) return nil }
import CreateProductDto from '@/core/products/dtos/CreateProduct.dto' import { UpdateProductDto } from '@/core/products/dtos/UpdateProduct.dto' import Products from '@/core/products/model/Products' import { ProductsRepository } from '@/core/products/services/repository' import ProductsModel, { ProductModelProps } from '../../model/products/Products' export class RepositoryProductsMongo implements ProductsRepository { private productsModel: ProductModelProps constructor() { this.productsModel = ProductsModel } /** * Creates a new product. * @param {CreateProductDto} productData - The data of the product to be created. * @returns {Promise<Products>} - The created product. * @throws {Error} - If an error occurs during creation. */ async createProduct(productData: CreateProductDto): Promise<Products> { try { // eslint-disable-next-line new-cap const newProduct = new this.productsModel(productData) await newProduct.save() return newProduct } catch (error) { throw new Error('Error creating the product: ' + error) } } /** * Gets a product by ID. * @param {string} id - The ID of the product. * @returns {Promise<Products | null>} - The corresponding product or null if not found. * @throws {Error} - If an error occurs during retrieval. */ async getProductById(id: string): Promise<Products | null> { try { return (await this.productsModel.findOne({ id })) ?? null } catch (error) { throw new Error('Error fetching the product by ID: ' + error) } } /** * Gets a product by name. * @param {string} productName - The name of the product. * @returns {Promise<Products | null>} - The corresponding product or null if not found. * @throws {Error} - If an error occurs during retrieval. */ async getProductByName(productName: string): Promise<Products | null> { try { return (await this.productsModel.findOne({ productName })) ?? null } catch (error) { throw new Error('Error fetching the product by name: ' + error) } } /** * Gets all products. * @returns {Promise<Products[]>} - A list of all products. * @throws {Error} - If an error occurs during retrieval. */ async getAllProducts(): Promise<Products[]> { try { return await this.productsModel.find() } catch (error) { throw new Error('Error fetching all products: ' + error) } } /** * Updates a product by ID. * @param {string} id - The ID of the product to be updated. * @param {UpdateProductDto} updates - The update data. * @returns {Promise<Products | null>} - The updated product or null if not found. * @throws {Error} - If an error occurs during the update. */ async updateProduct(id: string, updates: UpdateProductDto): Promise<Products | null> { try { return (await this.productsModel.findByIdAndUpdate(id, updates, { new: true })) ?? null } catch (error) { throw new Error('Error updating the product: ' + error) } } }
// React import { useEffect, useState } from "react"; //React Router Dom import { Outlet, Navigate, useNavigate, useRouteLoaderData, } from "react-router-dom"; //Bootstrap import Container from "react-bootstrap/Container"; const Home = (props) => { // let flip = useRef(true); // Controls between creating a new exercise and displaying all exercises const [flip, setFlip] = useState(true); const token = useRouteLoaderData("main"); const navigate = useNavigate(); useEffect(() => { if (!token) navigate("/login"); }, [token, flip]); return ( <Container className="p-3"> <div className="p-5 mb-4 bg-dark rounded-3"> <h1 className="header text-center text-success">Workouts</h1> <div className="row my-5 d-flex justify-content-center"> <button onClick={() => { setFlip(!flip); }} className="btn w-50 btn-success" > {(!flip && <p>Add New Exercise</p>) || <p>Exercise Journal</p>} </button> </div> <Outlet context={flip}></Outlet> {flip && <Navigate to="/home/newExercise" />} {!flip && <Navigate to="/home/list" />} </div> </Container> ); }; export default Home;
module Byebug module Helpers # # Utilities to assist command parsing # module ParseHelper # # Parses +str+ of command +cmd+ as an integer between +min+ and +max+. # # If either +min+ or +max+ is nil, that value has no bound. # # @todo Remove the `cmd` parameter. It has nothing to do with the method's # purpose. # def get_int(str, cmd, min = nil, max = nil) if str !~ /\A-?[0-9]+\z/ return nil, pr('parse.errors.int.not_number', cmd: cmd, str: str) end int = str.to_i if min && int < min err = pr('parse.errors.int.too_low', cmd: cmd, str: str, min: min) return nil, err elsif max && int > max err = pr('parse.errors.int.too_high', cmd: cmd, str: str, max: max) return nil, err end int end # # @return true if code is syntactically correct for Ruby, false otherwise # def syntax_valid?(code) return true unless code without_stderr do begin RubyVM::InstructionSequence.compile(code) true rescue SyntaxError false end end end # # @return +str+ as an integer or 1 if +str+ is empty. # def parse_steps(str, cmd) return 1 unless str steps, err = get_int(str, cmd, 1) return nil, err unless steps steps end private # # Temporarily disable output to $stderr # def without_stderr old_stderr = $stderr $stderr = StringIO.new yield ensure $stderr = old_stderr end end end end
/* eslint-disable quotes */ import { MigrationInterface, QueryRunner } from 'typeorm'; export class Default1685407876661 implements MigrationInterface { name = 'Default1685407876661'; public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query( `CREATE TABLE \`employee\` (\`idEmployee\` int NOT NULL AUTO_INCREMENT, \`nameEmployee\` varchar(255) NOT NULL, \`salaryEmployee\` decimal(5,2) NOT NULL, PRIMARY KEY (\`idEmployee\`)) ENGINE=InnoDB` ); await queryRunner.query( `CREATE TABLE \`order\` (\`idOrder\` int NOT NULL AUTO_INCREMENT, \`datePurchase\` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, \`clientIdClient\` int NULL, \`employeeIdEmployee\` int NULL, UNIQUE INDEX \`REL_2936682a6f483cffcd6edbae8a\` (\`clientIdClient\`), UNIQUE INDEX \`REL_2047bac56abbc37da219b9b283\` (\`employeeIdEmployee\`), PRIMARY KEY (\`idOrder\`)) ENGINE=InnoDB` ); await queryRunner.query( `CREATE TABLE \`client\` (\`idClient\` int NOT NULL AUTO_INCREMENT, \`nameClient\` varchar(255) NOT NULL, \`cpfClient\` varchar(255) NOT NULL, PRIMARY KEY (\`idClient\`)) ENGINE=InnoDB` ); await queryRunner.query( `CREATE TABLE \`product\` (\`idProduct\` int NOT NULL AUTO_INCREMENT, \`nameProduct\` varchar(255) NOT NULL, \`descProduct\` varchar(255) NULL, \`valueUnitProduct\` decimal(5,2) NOT NULL, \`countProduct\` int NOT NULL, PRIMARY KEY (\`idProduct\`)) ENGINE=InnoDB` ); await queryRunner.query( `ALTER TABLE \`order\` ADD CONSTRAINT \`FK_2936682a6f483cffcd6edbae8a7\` FOREIGN KEY (\`clientIdClient\`) REFERENCES \`client\`(\`idClient\`) ON DELETE NO ACTION ON UPDATE NO ACTION` ); await queryRunner.query( `ALTER TABLE \`order\` ADD CONSTRAINT \`FK_2047bac56abbc37da219b9b2838\` FOREIGN KEY (\`employeeIdEmployee\`) REFERENCES \`employee\`(\`idEmployee\`) ON DELETE NO ACTION ON UPDATE NO ACTION` ); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query( `ALTER TABLE \`order\` DROP FOREIGN KEY \`FK_2047bac56abbc37da219b9b2838\`` ); await queryRunner.query( `ALTER TABLE \`order\` DROP FOREIGN KEY \`FK_2936682a6f483cffcd6edbae8a7\`` ); await queryRunner.query(`DROP TABLE \`product\``); await queryRunner.query(`DROP TABLE \`client\``); await queryRunner.query( `DROP INDEX \`REL_2047bac56abbc37da219b9b283\` ON \`order\`` ); await queryRunner.query( `DROP INDEX \`REL_2936682a6f483cffcd6edbae8a\` ON \`order\`` ); await queryRunner.query(`DROP TABLE \`order\``); await queryRunner.query(`DROP TABLE \`employee\``); } }
/* * Copyright (c) 2006-2007, AIOTrade Computing Co. and Contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of AIOTrade Computing Co. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.aiotrade.platform.core.ui.netbeans.explorer; import java.awt.Image; import java.beans.IntrospectionException; import java.util.HashSet; import java.util.Set; import javax.swing.Action; import org.aiotrade.math.timeseries.Frequency; import org.aiotrade.util.swing.action.AddAction; import org.aiotrade.util.swing.action.RefreshAction; import org.aiotrade.math.timeseries.descriptor.AnalysisDescriptor; import org.aiotrade.math.timeseries.descriptor.AnalysisContents; import org.aiotrade.platform.core.netbeans.GroupDescriptor; import org.aiotrade.util.swing.action.UpdateAction; import org.openide.ErrorManager; import org.openide.nodes.AbstractNode; import org.openide.nodes.BeanNode; import org.openide.nodes.Children; import org.openide.nodes.FilterNode; import org.openide.nodes.Node; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.InstanceContent; /** * * * * @author Caoyuan Deng * * This node is just a virtul node without any physical object in file system * * The tree view of Stock and others * + Stocks (config/Stocks) * +- sunw (sunw.ser) * +- Indicators (DescriptorGroupNode) * | +- MACD (DescriptorNode) * | | +-opt1 * | | +-opt2 * | +- ROC * | +-opt1 * | +-opt2 * +- Drawings (DescriptorGroupNode) * +- layer1 * | +- line * | +- parallel * | +- gann period * +- layer2 */ public class GroupNode extends FilterNode { private GroupDescriptor<AnalysisDescriptor> group; private Frequency freq = Frequency.DAILY; public GroupNode(GroupDescriptor<AnalysisDescriptor> group, AnalysisContents contents) throws IntrospectionException { this(group, contents, new InstanceContent()); this.group = group; setName(group.getDisplayName()); } private GroupNode(GroupDescriptor<AnalysisDescriptor> group, AnalysisContents contents, InstanceContent content) throws IntrospectionException { super(new BeanNode<GroupDescriptor>(group), new GroupChildren(contents, group.getBindClass()), new AbstractLookup(content)); /* add this node to our own lookup */ content.add(this); /* add aditional items to the lookup */ content.add(contents); content.add(new GroupRefreshAction(this)); content.add(new GroupUpdateAction(this)); /** * add actions carried with nodeInfo */ for (Action action : group.createActions(contents)) { /** * as content only do flat lookup, should add actions one by one, * instead of adding an array, otherwise this.getLookup().loopup * can only search an array. */ content.add(action); } } /** * Providing the Open action on a each descriptor groupClass */ public Action[] getActions(boolean popup) { /** * Use SystemAction to find instance of those actions registered in layer.xml * * The following code works for any kind of group node witch implemented * AddAction and has been added into the lookup content in construction. */ return new Action[] { getLookup().lookup(AddAction.class), }; } public Action getPreferredAction() { return getActions(false) [0]; } public Image getOpenedIcon(int type) { return getIcon(0); } public String getDisplayName() { return group.getDisplayName(); } /** * Making a tooltip out of the descriptor's description */ public String getShortDescription() { return group.getTooltip(); } public Image getIcon(int type) { return group.getIcon(type); } public void setTimeFrequency(Frequency freq) { this.freq = freq.clone(); getLookup().lookup(UpdateAction.class).execute(); } private Frequency getFreq() { return freq; } /** * The children wrap class * ------------------------------------------------------------------------ */ private static class GroupChildren extends Children.Keys<AnalysisDescriptor> { private AnalysisContents contents; private Class<AnalysisDescriptor> groupClass; public GroupChildren(AnalysisContents contents, Class<AnalysisDescriptor> groupClass) { this.contents = contents; this.groupClass = groupClass; } /** * since setKeys(childrenKeys) will copy the elements of childrenKeys, it's safe to * use a repeatly used bufChildrenKeys here. * And, to sort them in letter order, we can use a SortedSet to copy from collection.(TODO) */ private Set<AnalysisDescriptor> bufChildrenKeys = new HashSet<AnalysisDescriptor>(); protected void addNotify() { GroupNode node = (GroupNode)getNode(); bufChildrenKeys.clear(); bufChildrenKeys.addAll(contents.lookupDescriptors(groupClass, node.getFreq())); setKeys(bufChildrenKeys); } public Node[] createNodes(AnalysisDescriptor key) { try { return new Node[] { new DescriptorNode(key, contents) }; } catch (final IntrospectionException ex) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); /** Should never happen - no reason for it to fail above */ return new Node[] { new AbstractNode(Children.LEAF) { public String getHtmlDisplayName() { return "<font color='red'>" + ex.getMessage() + "</font>"; } }}; } } } private static class GroupRefreshAction extends RefreshAction { private final GroupNode node; GroupRefreshAction(GroupNode node) { this.node = node; } public void execute() { GroupChildren children = ((GroupChildren)node.getChildren()); /** if new descriptor is added, this will add it to children */ children.addNotify(); for (Node child : children.getNodes()) { ((DescriptorNode)child).refreshIcon(); ((DescriptorNode)child).refreshDisplayName(); } } } private static class GroupUpdateAction extends UpdateAction { private final GroupNode node; GroupUpdateAction(GroupNode node) { this.node = node; } public void execute() { GroupChildren children = ((GroupChildren)node.getChildren()); /** * by calling children.addNotify(), the children will re setKeys() * according to the current time unit and nUnits. * @see GroupChildren.addNotify() */ children.addNotify(); } } }
package fpoly.namdhph34455.duanmau.fragment; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.Spinner; import android.widget.Toast; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import fpoly.namdhph34455.duanmau.Adapter.PhieuMuonAdapter; import fpoly.namdhph34455.duanmau.Adapter.SachSpinner; import fpoly.namdhph34455.duanmau.Adapter.ThanhVienSpinner; import fpoly.namdhph34455.duanmau.DAO.PhieuMuonDao; import fpoly.namdhph34455.duanmau.DAO.SachDao; import fpoly.namdhph34455.duanmau.DAO.ThanhVienDao; import fpoly.namdhph34455.duanmau.Database.DBHelper; import fpoly.namdhph34455.duanmau.Model.PhieuMuon; import fpoly.namdhph34455.duanmau.Model.Sach; import fpoly.namdhph34455.duanmau.Model.ThanhVien; import fpoly.namdhph34455.duanmau.R; public class fragmentPM extends Fragment { FloatingActionButton btn_add; PhieuMuonDao dao; ArrayList<PhieuMuon> list = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); ArrayList<ThanhVien> thanhViens = new ArrayList<>(); ArrayList<Sach> saches = new ArrayList<>(); ThanhVienDao thanhVienDao; SachDao sachDao; int maThanhVien, maSach; Spinner sp_sach, sp_thanhVien; CheckBox chk_trangThai; int position; PhieuMuonAdapter adapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_phieu_muon, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); btn_add = view.findViewById(R.id.btn_add); RecyclerView recyclerView = view.findViewById(R.id.recycler); dao = new PhieuMuonDao(new DBHelper(getContext()), getContext()); list = dao.getAll(); adapter = new PhieuMuonAdapter(list, getContext()); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setAdapter(adapter); btn_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialogAdd(); } }); } private void showDialogAdd(){ View view1 = LayoutInflater.from(getContext()).inflate(R.layout.item_pm_add_update, null, false); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setView(view1); AlertDialog alertDialog = builder.create(); alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); alertDialog.show(); thanhVienDao = new ThanhVienDao(new DBHelper(getContext()), getContext()); thanhViens = thanhVienDao.getAll(); ThanhVienSpinner adapterTV = new ThanhVienSpinner(thanhViens, getContext()); sp_thanhVien = view1.findViewById(R.id.sp_thanhVien); sp_thanhVien.setAdapter(adapterTV); sp_thanhVien.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { maThanhVien = thanhViens.get(position).getMaTV(); Toast.makeText(getContext(), "Chọn: " + thanhViens.get(position).getHoTen(), Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); sachDao = new SachDao(new DBHelper(getContext()), getContext()); saches = sachDao.getAll(); SachSpinner sachAdapter = new SachSpinner(saches, getContext()); sp_sach = view1.findViewById(R.id.sp_tenSach); sp_sach.setAdapter(sachAdapter); sp_sach.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { maSach = saches.get(position).getMaSach(); Toast.makeText(getContext(), "Chọn: " + saches.get(position).getTenSach(), Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); Button btn_them = view1.findViewById(R.id.btn_pm); btn_them.setText("ADD"); btn_them.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Sach sach = sachDao.getID(maSach); Date date = new Date(); String ngay = sdf.format(date); PhieuMuon phieuMuon = new PhieuMuon(); int trangThai; chk_trangThai = view1.findViewById(R.id.chk_trangThai); if (chk_trangThai.isChecked()){ trangThai = 0; }else { trangThai=1; } SharedPreferences sharedPreferences = getContext().getSharedPreferences("File_User", Context.MODE_PRIVATE); String maTT = sharedPreferences.getString("USERNAME",""); PhieuMuon phieuMuon1 = new PhieuMuon(getId(), maTT, maThanhVien, maSach, sach.getGiaThue(), ngay, trangThai); boolean check = dao.insertPM(phieuMuon1); if (check) { list.add(phieuMuon1); adapter.notifyDataSetChanged(); alertDialog.dismiss(); Toast.makeText(getContext(), "Thêm thành công", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(getContext(), "Thêm thất bại", Toast.LENGTH_SHORT).show(); alertDialog.dismiss(); } } }); Button btn_huy = view1.findViewById(R.id.btn_huy); btn_huy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); } }
# Python program to create a simple GUI # Simple Quiz using Tkinter import pandas as pd import numpy as np import random import json #import everything from tkinter from tkinter import * # and import messagebox as mb from tkinter from tkinter import messagebox as mb #import json to use json file for data import json from PIL import Image, ImageTk #class to define the components of the GUI class Quiz: # This is the first method which is called when a # new object of the class is initialized. This method # sets the question count to 0. and initialize all the # other methoods to display the content and make all the # functionalities available def __init__(self): # set question number to 0 self.q_no= 0 #bird image self.bird_image = Image.open(image[str(self.q_no)]) self.final_bird_image = ImageTk.PhotoImage(self.bird_image) # assigns ques to the display_question function to update later. self.display_title() self.display_question() # opt_selected holds an integer value which is used for # selected option in a question. self.opt_selected=IntVar() # displaying radio button for the current question and used to # display options for the current question self.opts=self.radio_buttons() # display options for the current question self.display_options() # displays the button for next and exit. self.buttons() #entry = Entry(gui, width= 40) #entry.focus_set() #entry.pack() # no of questions self.data_size=len(question) #self.data_size = entry.get() # keep a counter of correct answers self.correct=0 # This method is used to display the result # It counts the number of correct and wrong answers # and then display them at the end as a message Box def display_result(self): # calculates the wrong count wrong_count = self.data_size - self.correct correct = f"Correct: {self.correct}" wrong = f"Wrong: {wrong_count}" # calcultaes the percentage of correct answers score = int(self.correct / self.data_size * 100) result = f"Score: {score}%" # Shows a message box to display the result mb.showinfo("Result", f"{result}\n{correct}\n{wrong}") # This method checks the Answer after we click on Next. def check_ans(self, q_no): # checks for if the selected option is correct if self.opt_selected.get() == answer[str(q_no)]: # if the option is correct it return true return True else: mb.showinfo("INCORRECT", "Incorrect! That was a " + species[str(q_no)]) return False # This method is used to check the answer of the # current question by calling the check_ans and question no. # if the question is correct it increases the count by 1 # and then increase the question number by 1. If it is last # question then it calls display result to show the message box. # otherwise shows next question. def next_btn(self): # Check if the answer is correct if self.check_ans(self.q_no): # if the answer is correct it increments the correct by 1 self.correct += 1 # Moves to next Question by incrementing the q_no counter self.q_no += 1 # checks if the q_no size is equal to the data size if self.q_no==self.data_size: # if it is correct then it displays the score self.display_result() # destroys the GUI gui.destroy() else: # shows the next question self.display_question() self.display_options() # This method shows the two buttons on the screen. # The first one is the next_button which moves to next question # It has properties like what text it shows the functionality, # size, color, and property of text displayed on button. Then it # mentions where to place the button on the screen. The second # button is the exit button which is used to close the GUI without # completing the quiz. def buttons(self): # The first button is the Next button to move to the # next Question next_button = Button(gui, text="Next",command=self.next_btn, width=10,bg="blue",fg="white",font=("ariel",16,"bold")) # placing the button on the screen next_button.place(x=350,y=380) # This is the second button which is used to Quit the GUI quit_button = Button(gui, text="Quit", command=gui.destroy, width=5,bg="black", fg="white",font=("ariel",16," bold")) # placing the Quit button on the screen quit_button.place(x=700,y=50) # This method deselect the radio button on the screen # Then it is used to display the options available for the current # question which we obtain through the question number and Updates # each of the options for the current question of the radio button. def display_options(self): val=0 # deselecting the options self.opt_selected.set(0) # looping over the options to be displayed for the # text of the radio buttons. for option in options[str(self.q_no)]: self.opts[val]['text']=option val+=1 # This method shows the current Question on the screen def display_question(self): filename = image[str(self.q_no)] self.bird_image = Image.open(filename) self.final_bird_image = ImageTk.PhotoImage(self.bird_image) # image_label = Label(gui, image = self.final_bird_image) # setting the Question properties q_no = Label(gui, text=question[str(self.q_no)], width=60, font=( 'ariel' ,16, 'bold' ), anchor= 'w') #placing the option on the screen q_no.place(x=70, y=100) canvas = Canvas(gui, width=300, height=300) canvas.place(relx=0.65, rely=0.5, anchor=CENTER) bimg = canvas.create_image((100,100), image=self.final_bird_image) # This method is used to Display Title def display_title(self): # The title to be shown title = Label(gui, text="Kenyan Bird Quiz", width=50, bg="green",fg="white", font=("ariel", 20, "bold")) # place of the title title.place(x=0, y=2) # This method shows the radio buttons to select the Question # on the screen at the specified position. It also returns a # list of radio button which are later used to add the options to # them. def radio_buttons(self): # initialize the list with an empty list of options q_list = [] # position of the first option y_pos = 150 # adding the options to the list while len(q_list) < 4: # setting the radio button properties radio_btn = Radiobutton(gui,text=" ",variable=self.opt_selected, value = len(q_list)+1,font = ("ariel",14)) # adding the button to the list q_list.append(radio_btn) # placing the button radio_btn.place(x = 100, y = y_pos) # incrementing the y-axis position by 40 y_pos += 40 # return the radio buttons return q_list # Create a GUI Window gui = Tk() # set the size of the GUI Window gui.geometry("800x450") # set the title of the Window gui.title("Kenyan Bird Quiz") # load bird data, shuffle it, add option and question columns. df = pd.read_csv('bird_data_clean.csv') df = df[df["image_url"].str.contains("www.inaturalist")==False] df.reset_index(inplace=True, drop=True) options = [] for i in range(len(df)): temp = list(df['species']) if i < (len(df)-1): ans = temp.pop(i) else: ans = temp.pop() choices = random.choices( temp, k=3 ) choices.append(ans) random.shuffle(choices) options.append(choices) df['options'] = options df['answer'] = [ (df['options'][i].index(df['species'][i])) + 1 for i in range(len(df)) ] df['question'] = ['What bird is this?' for i in range(len(df))] df['image_filename'] = 'bird_pics\\full\\' + df['image_filename'].astype(str) df2 = df.sample(frac=0.03) df2.reset_index(inplace=True, drop=True) df2.to_json('json_questions.json', orient='columns') # get the data from the json file with open('json_questions.json') as f: data = json.load(f) # set the question, options, and answer question = (data['question']) image = (data['image_filename']) options = (data['options']) answer = (data[ 'answer']) species = (data['species']) # create an object of the Quiz Class. quiz = Quiz() # Start the GUI gui.mainloop() # END OF THE PROGRAM
<!DOCTYPE html> <html lang="en" class="no-js"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Meo So</title> <link rel="shortcut icon" href="favicon.ico" /> <link rel="stylesheet" href="https://use.typekit.net/dec4mzz.css" /> <link rel="stylesheet" type="text/css" href="./css/style.css" /> <script> document.documentElement.className = "js"; var supportsCssVars = function() { var e, t = document.createElement("style"); return ( (t.innerHTML = "root: { --tmp-var: bold; }"), document.head.appendChild(t), (e = !!( window.CSS && window.CSS.supports && window.CSS.supports("font-weight", "var(--tmp-var)") )), t.parentNode.removeChild(t), e ); }; supportsCssVars() || alert( "Please view this demo in a modern browser that supports CSS Variables." ); </script> </head> <body class="container loading"> <div class="projectBackground"></div> <main> <video muted loop id="myVideo"> <source src="./img/van_gogh_vid.mp4" type="video/mp4" /> </video> <div data-scroll class="page page--layout-2"> <h1 class="page__title">Meo So - Junior Software Developer</h1> <p id="introduction"> Former chef, creative problem solver. Passionate about coding. Scroll down to find out more </p> <div class="content content--center"> <div class="content__item" id="aboutMe"> <div class="content__item-imgwrap"> <div class="content__item-img" style="background-image: url(./img/panda_back.jpg);" ></div> </div> <h2 class="content__item-title">Hello World</h2> <p class="content__item-description"> I have just finished an amazing bootcamp at General Assembly. I enjoy the creativity and possibilities that coding brings. Currently looking for opportunities to kickstart my career in front-end development. </p> <div class="content__item-decobar"></div> </div> <div class="content__item"> <div class="content__item-imgwrap"> <div class="content__item-img" style="background-image: url(./img/skills.jpg);" ></div> </div> <h2 class="content__item-title">Skills</h2> <p class="content__item-description"> Full-stack ready. In 3 months, I learned front-end skills like HTML/CSS, JavaScript, jQuery, React. Also back-end skills like Ruby on Rails, Node.js. </p> <div class="content__item-decobar"></div> </div> <div class="content__item" id="projects"> <div class="content__item-imgwrap projectPage" id="p0"> <div class="content__item-img" style="background-image: url(img/robot_run.png);" ></div> <a href="https://github.com/meowsoso/Robot_run" target="_blank" class="codePage" >Code</a > <a href="https://meowsoso.github.io/Robot_run/" target="_blank" class="demoPage" >Demo</a > </div> <h2 class="content__item-title">Project#0</h2> <p class="content__item-description"> First project in GA. Robot escape page with interactive puzzles. Made with JavaScript and jQuery. Hover image to find out more. </p> <div class="content__item-decobar"></div> </div> <div class="content__item"> <div class="content__item-imgwrap projectPage" id="p1"> <div class="content__item-img" style="background-image: url(./img/the_great_wave.jpg);" ></div> <a href="https://github.com/meowsoso/Bonsai" target="_blank" class="codePage" >Code</a > <a href="https://meo-bonsai.herokuapp.com/" target="_blank" class="demoPage" >Demo</a > </div> <h2 class="content__item-title">Bonsai</h2> <p class="content__item-description"> Team communication tool. Express feelings in form of a bonsai. Made with Ruby on Rails, JavaScript and Anime.js. </p> <div class="content__item-decobar"></div> </div> <div class="content__item"> <div class="content__item-imgwrap projectPage" id="p2"> <div class="content__item-img" style="background-image: url(./img/ripplebg.jpg);" ></div> <a href="https://github.com/meowsoso/Dripple_server" target="_blank" class="codePage" >Code</a > <a href="https://herdmangct.github.io/dripple-client/#/" target="_blank" class="demoPage" >Demo</a > </div> <h2 class="content__item-title">Dripple</h2> <p class="content__item-description"> Share ideas with like-minded people in close locations and chat with them. Made with Ruby on Rails and React.js. </p> <div class="content__item-decobar"></div> </div> <div class="content__item"> <div class="content__item-imgwrap projectPage" id="p3"> <div class="content__item-img" style="background-image: url(./img/sound_canvas.jpg);" ></div> <a href="https://github.com/meowsoso/Sound-Canvas" target="_blank" class="codePage" >Code</a > <a href="https://meowsoso.github.io/Sound-Canvas/" target="_blank" class="demoPage" >Demo</a > </div> <h2 class="content__item-title">Sound Canvas</h2> <p class="content__item-description"> Art, music and audio visualisation. Made with JavaScript, P5.js and P5.sound. </p> <div class="content__item-decobar"></div> </div> <div class="content__item" id="contact"> <div class="content__item-imgwrap"> <div class="content__item-img" style="background-image: url(./img/panda_video_game.gif);" ></div> </div> <h2 class="content__item-title">Contact Me</h2> <p class="content__item-description contactInfo"> <a target="_blank" href="https://www.linkedin.com/in/meo-so" >LinkedIn<img src="./img/linkin.png" /></a> <a target="_blank" href="https://www.github.com/meowsoso/" >Github<img src="./img/github.png" /></a> <a href="mailto:[email protected]" >Email<img src="./img/email.png" /></a> </p> <div class="content__item-decobar"></div> </div> </div> </div> <p class="credits credits--fixed"> <a class="nav" href="#aboutMe">About Me</a> <a class="nav" href="#projects">Projects</a> <a class="nav" href="#contact">Contact Me</a> </p> </main> <script src="js/jquery.min.js"></script> <script src="js/imagesloaded.pkgd.min.js"></script> <script src="js/TweenMax.min.js"></script> <script src="js/main.js"></script> </body> </html>
package mycompiler.yufa; import java.util.*; import mycompiler.cifa.*; class TokenType /****Token序列的定义*******/ { int lineshow; String Lex; String Sem; } /********************************************************************/ /* 类 名 Recursion */ /* 功 能 总程序的处理 */ /* 说 明 建立一个类,处理总程序 */ /********************************************************************/ public class Recursion { TokenType token=new TokenType();//当前处理token int lineno=0;//当前处理行数 public String serror;//错误信息 boolean Error=false;//是否出现错误 StringTokenizer fenxi;//分割token public boolean ans; public Recursion(String s) { ans=Program(s); } /********************************************************************/ /********************************************************************/ /* 函数名 match */ /* 功 能 终极符匹配处理函数 */ /* 说 明 函数参数expected给定期望单词符号与当前单词符号token相匹配 */ /* 如果不匹配,则报非期望单词语法错误 */ /********************************************************************/ boolean match(String expected) { if (token.Lex.equals(expected)) { ReadNextToken(); return true; } else { syntaxError("not match error "); ReadNextToken(); return false; } } /************************************************************/ /* 函数名 syntaxError */ /* 功 能 语法错误处理函数 */ /* 说 明 将函数参数message指定的错误信息输出 */ /************************************************************/ void syntaxError(String s) /*向错误信息.txt中写入字符串*/ { serror=serror+"\n>>> ERROR :"+"Syntax error at "+String.valueOf(token.lineshow)+": "+s; /* 设置错误追踪标志Error为TRUE,防止错误进一步传递 */ Error = true; } /********************************************************************/ /* 函数名 ReadNextToken */ /* 功 能 从Token序列中取出一个Token */ /* 说 明 从文件中存的Token序列中依次取一个单词,作为当前单词 */ /********************************************************************/ void ReadNextToken() { //token.lineshow:token.Lex,token.Sem\n if (fenxi.hasMoreTokens()) { int i=1; String stok=fenxi.nextToken(); StringTokenizer fenxi1=new StringTokenizer(stok,":,"); while (fenxi1.hasMoreTokens()) { String fstok=fenxi1.nextToken(); if (i==1) { token.lineshow=Integer.parseInt(fstok); lineno=token.lineshow; } if (i==2) token.Lex=fstok; if (i==3) token.Sem=fstok; i++; } } } /********************************************************************/ /********************************************************************/ /********************************************************************/ /* 函数名 Program */ /* 功 能 总程序的处理函数 */ /* 产生式 < Program > ::= ProgramHead DeclarePart ProgramBody . */ /********************************************************************/ boolean Program(String ss) { fenxi=new StringTokenizer(ss,"\n"); ReadNextToken(); boolean ans=true; if(ProgramHead()==false){ syntaxError("a program head is expected!"); ans=false; } if(DeclarePart()==false) {ans=false;} if (ProgramBody()==false){ syntaxError("a program body is expected!"); ans=false; } if(match("DOT")==false);{ans=false;} if (!(token.Lex.equals("ENDFILE"))){ ans=false; syntaxError("Code ends before file\n"); } if (Error==true&&ans==false) return false; else return true; } /**************************函数头部分********************************/ /********************************************************************/ /********************************************************************/ /* 函数名 ProgramHead */ /* 功 能 程序头的处理函数 */ /* 产生式 < ProgramHead > ::= PROGRAM ProgramName */ /********************************************************************/ boolean ProgramHead() { return match("PROGRAM")&&match("ID"); } /**************************声明部分**********************************/ /********************************************************************/ /********************************************************************/ /* 函数名 DeclarePart */ /* 功 能 声明部分的处理 */ /* 产生式 < DeclarePart > ::= TypeDec VarDec ProcDec */ /********************************************************************/ boolean DeclarePart() { /*类型*/ boolean tp1 = TypeDec(); /*变量*/ boolean tp2 = VarDec(); /*函数*/ boolean procP = ProcDec(); return tp1&&tp2&&procP; } /**************************类型声明部分******************************/ /********************************************************************/ /* 函数名 TypeDec */ /* 功 能 类型声明部分的处理 */ /* 产生式 < TypeDec > ::= ε | TypeDeclaration */ /********************************************************************/ boolean TypeDec() { if (token.Lex.equals("TYPE")) return TypeDeclaration(); else if ((token.Lex.equals("VAR"))||(token.Lex.equals("PROCEDURE")) ||(token.Lex.equals("BEGIN"))) {} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 TypeDeclaration */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < TypeDeclaration > ::= TYPE TypeDecList */ /********************************************************************/ boolean TypeDeclaration() { if(match("TYPE")) { if (TypeDecList()==false) { syntaxError("a type declaration is expected!"); return false; } else return true; } else return false; } /********************************************************************/ /* 函数名 TypeDecList */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < TypeDecList > ::= TypeId = TypeName ; TypeDecMore */ /********************************************************************/ boolean TypeDecList() { return TypeId()&&match("EQ")&&TypeName()&& match("SEMI")&&TypeDecMore(); } /********************************************************************/ /* 函数名 TypeDecMore */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < TypeDecMore > ::= ε | TypeDecList */ /* 说 明 函数根据文法产生式,调用相应的递归处理函数,生成语法树节点 */ /********************************************************************/ boolean TypeDecMore() { if (token.Lex.equals("ID")) return TypeDecList(); else if ((token.Lex.equals("VAR"))||(token.Lex.equals("PROCEDURE"))||(token.Lex.equals("BEGIN"))) {} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 TypeId */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < TypeId > ::= id */ /********************************************************************/ boolean TypeId() { return match("ID"); } /********************************************************************/ /* 函数名 TypeName */ /* 功 能 类型声明部分的处理 */ /* 产生式 < TypeName > ::= BaseType | StructureType | id */ /********************************************************************/ boolean TypeName() { if ((token.Lex.equals("INTEGER"))||(token.Lex.equals("CHAR"))) return BaseType(); else if ((token.Lex.equals("ARRAY"))||(token.Lex.equals("RECORD"))) return StructureType(); else if (token.Lex.equals("ID")) { return match("ID"); } else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 BaseType */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < BaseType > ::= INTEGER | CHAR */ /********************************************************************/ boolean BaseType() { if (token.Lex.equals("INTEGER")) { return match("INTEGER"); } else if (token.Lex.equals("CHAR")) { return match("CHAR"); } else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 StructureType */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < StructureType > ::= ArrayType | RecType */ /********************************************************************/ boolean StructureType() { if (token.Lex.equals("ARRAY")) { return ArrayType(); } else if (token.Lex.equals("RECORD")) { return RecType(); } else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 ArrayType */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < ArrayType > ::= ARRAY [low..top] OF BaseType */ /********************************************************************/ boolean ArrayType() { return match("ARRAY") &&match("LMIDPAREN") &&match("INTC") &&match("UNDERANGE") &&match("INTC") &&match("RMIDPAREN") &&match("OF") &&BaseType(); } /********************************************************************/ /* 函数名 RecType */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < RecType > ::= RECORD FieldDecList END */ /********************************************************************/ boolean RecType() { boolean ans=true; if(!match("RECORD")){ans=false;} if (!FieldDecList()) { syntaxError("a record body is requested!"); ans=false; } if(!match("END")){ans=false;} return ans; } /********************************************************************/ /* 函数名 FieldDecList */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < FieldDecList > ::= BaseType IdList ; FieldDecMore */ /* | ArrayType IdList; FieldDecMore */ /********************************************************************/ boolean FieldDecList() { if ((token.Lex.equals("INTEGER"))||(token.Lex.equals("CHAR"))) { return BaseType()&& IdList()&&match("SEMI")&&FieldDecMore(); } else if (token.Lex.equals("ARRAY")) { return ArrayType() &&IdList() &&match("SEMI") &&FieldDecMore(); } else { ReadNextToken(); syntaxError("type name is expected"); return false; } } /********************************************************************/ /* 函数名 FieldDecMore */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < FieldDecMore > ::= ε | FieldDecList */ /********************************************************************/ boolean FieldDecMore() { if (token.Lex.equals("INTEGER")||token.Lex.equals("CHAR")||token.Lex.equals("ARRAY")) return FieldDecList(); else if (token.Lex.equals("END")) {} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 IdList */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < IdList > ::= id IdMore */ /********************************************************************/ boolean IdList() { return match("ID") &&IdMore(); } /********************************************************************/ /* 函数名 IdMore */ /* 功 能 类型声明部分的处理函数 */ /* 产生式 < IdMore > ::= ε | , IdList */ /********************************************************************/ boolean IdMore() { if (token.Lex.equals("COMMA")) { return match("COMMA")&&IdList(); } else if (token.Lex.equals("SEMI")) {} else ReadNextToken(); return true; } /**************************变量声明部分******************************/ /********************************************************************/ /* 函数名 VarDec */ /* 功 能 变量声明部分的处理 */ /* 产生式 < VarDec > ::= ε | VarDeclaration */ /********************************************************************/ boolean VarDec() { if (token.Lex.equals("VAR")) return VarDeclaration(); else if ((token.Lex.equals("PROCEDURE"))||(token.Lex.equals("BEGIN"))){} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 VarDeclaration */ /* 功 能 变量声明部分的处理函数 */ /* 产生式 < VarDeclaration > ::= VAR VarDecList */ /********************************************************************/ boolean VarDeclaration() { boolean ans=true; if(!match("VAR")){ans=false;} if (!VarDecList()) { syntaxError("a var declaration is expected!"); ans=false; } return ans; } /********************************************************************/ /* 函数名 VarDecList */ /* 功 能 变量声明部分的处理函数 */ /* 产生式 < VarDecList > ::= TypeName VarIdList; VarDecMore */ /********************************************************************/ boolean VarDecList() { return TypeName()&&VarIdList()&&match("SEMI")&&VarDecMore(); } /********************************************************************/ /* 函数名 VarDecMore */ /* 功 能 变量声明部分的处理函数 */ /* 产生式 < VarDecMore > ::= ε | VarDecList */ /********************************************************************/ boolean VarDecMore() { if ((token.Lex.equals("INTEGER"))||(token.Lex.equals("CHAR"))||(token.Lex.equals("ARRAY"))||(token.Lex.equals("RECORD")||(token.Lex.equals("ID")))) return VarDecList(); else if ((token.Lex.equals("PROCEDURE"))||(token.Lex.equals("BEGIN"))) {} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 VarIdList */ /* 功 能 变量声明部分的处理函数 */ /* 产生式 < VarIdList > ::= id VarIdMore */ /********************************************************************/ boolean VarIdList() { boolean ans=true; if (!match("ID")) { ans=false; syntaxError("a varid is expected here!"); ReadNextToken(); } return ans&&VarIdMore(); } /********************************************************************/ /* 函数名 VarIdMore */ /* 功 能 变量声明部分的处理函数 */ /* 产生式 < VarIdMore > ::= ε | , VarIdList */ /********************************************************************/ boolean VarIdMore() { if (token.Lex.equals("COMMA")) { return match("COMMA")&&VarIdList(); } else if (token.Lex.equals("SEMI")) {} else ReadNextToken(); return true; } /****************************过程声明部分****************************/ /********************************************************************/ /* 函数名 ProcDec */ /* 功 能 函数声明部分的处理 */ /* 产生式 < ProcDec > ::= ε | ProcDeclaration */ /********************************************************************/ boolean ProcDec() { if (token.Lex.equals("PROCEDURE")) return ProcDeclaration(); else if (token.Lex.equals("BEGIN")) {} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 ProcDeclaration */ /* 功 能 函数声明部分的处理函数 */ /* 产生式 < ProcDeclaration > ::= PROCEDURE ProcName(ParamList); */ /* ProcDecPart */ /* ProcBody */ /* ProcDecMore * /********************************************************************/ boolean ProcDeclaration() { return match("PROCEDURE")&&match("ID") && match("LPAREN") &&ParamList() && match("RPAREN") && match("SEMI") &&ProcDecPart() &&ProcBody() &&ProcDecMore(); } /********************************************************************/ /* 函数名 ProcDecMore */ /* 功 能 更多函数声明中处理函数 */ /* 产生式 < ProcDecMore > ::= ε | ProcDeclaration */ /********************************************************************/ boolean ProcDecMore() { if (token.Lex.equals("PROCEDURE")) return ProcDeclaration(); else if (token.Lex.equals("BEGIN")) {} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 ParamList */ /* 功 能 函数声明中参数声明部分的处理函数 */ /* 产生式 < ParamList > ::= ε | ParamDecList */ /********************************************************************/ boolean ParamList() { if ((token.Lex.equals("INTEGER")) ||(token.Lex.equals("CHAR")) ||(token.Lex.equals("ARRAY")) ||(token.Lex.equals("RECORD")) ||(token.Lex.equals("ID")) ||(token.Lex.equals("VAR"))) { boolean b= ParamDecList(); if(!b) syntaxError("paramter error!"); return b; } else if (token.Lex.equals("RPAREN")) {} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 ParamDecList */ /* 功 能 函数声明中参数声明部分的处理函数 */ /* 产生式 < ParamDecList > ::= Param ParamMore */ /********************************************************************/ boolean ParamDecList() { return Param()&&ParamMore(); } /********************************************************************/ /* 函数名 ParamMore */ /* 功 能 函数声明中参数声明部分的处理函数 */ /* 产生式 < ParamMore > ::= ε | ; ParamDecList */ /********************************************************************/ boolean ParamMore() { boolean ans=true; if (token.Lex.equals("SEMI")) { if(!match("SEMI")) { ans=false; } if (!ParamDecList()) { syntaxError("a param declaration is request!"); ans=false; } return ans; } else if (token.Lex.equals("RPAREN")){} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 Param */ /* 功 能 函数声明中参数声明部分的处理函数 */ /* 产生式 < Param > ::= TypeName FormList | VAR TypeName FormList */ /********************************************************************/ boolean Param() { if ((token.Lex.equals("INTEGER")) ||(token.Lex.equals("CHAR")) ||(token.Lex.equals("ARRAY")) ||(token.Lex.equals("RECORD")) || (token.Lex.equals("ID"))) { return TypeName()&&FormList(); } else if (token.Lex.equals("VAR")) { return match("VAR")&&TypeName()&&FormList(); } else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 FormList */ /* 功 能 函数声明中参数声明部分的处理函数 */ /* 产生式 < FormList > ::= id FidMore */ /********************************************************************/ boolean FormList() { return match("ID")&&FidMore(); } /********************************************************************/ /* 函数名 FidMore */ /* 功 能 函数声明中参数声明部分的处理函数 */ /* 产生式 < FidMore > ::= ε | , FormList */ /********************************************************************/ boolean FidMore() { if (token.Lex.equals("COMMA")) { return match("COMMA")&&FormList(); } else if ((token.Lex.equals("SEMI"))||(token.Lex.equals("RPAREN"))){} else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 ProcDecPart */ /* 功 能 函数中的声明部分的处理函数 */ /* 产生式 < ProcDecPart > ::= DeclarePart */ /********************************************************************/ boolean ProcDecPart() { return DeclarePart(); } /********************************************************************/ /* 函数名 ProcBody */ /* 功 能 函数体部分的处理函数 */ /* 产生式 < ProcBody > ::= ProgramBody */ /********************************************************************/ boolean ProcBody() { if (!ProgramBody()) { syntaxError("a program body is requested!"); return false; } else return true; } /****************************函数体部分******************************/ /********************************************************************/ /********************************************************************/ /* 函数名 ProgramBody */ /* 功 能 程序体部分的处理 */ /* 产生式 < ProgramBody > ::= BEGIN StmList END */ /********************************************************************/ boolean ProgramBody() { return match("BEGIN")&&StmList()&&match("END"); } /********************************************************************/ /* 函数名 StmList */ /* 功 能 语句部分的处理函数 */ /* 产生式 < StmList > ::= Stm StmMore */ /********************************************************************/ boolean StmList() { return Stm()&&StmMore(); } /********************************************************************/ /* 函数名 StmMore */ /* 功 能 语句部分的处理函数 */ /* 产生式 < StmMore > ::= ε | ; StmList */ /********************************************************************/ boolean StmMore() { if ((token.Lex.equals("ELSE"))||(token.Lex.equals("FI"))||(token.Lex.equals("END"))||(token.Lex.equals("ENDWH"))) {} else if (token.Lex.equals("SEMI")) { return match("SEMI")&&StmList(); } else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 Stm */ /* 功 能 语句部分的处理函数 */ /* 产生式 < Stm > ::= ConditionalStm {IF} */ /* | LoopStm {WHILE} */ /* | InputStm {READ} */ /* | OutputStm {WRITE} */ /* | ReturnStm {RETURN} */ /* | id AssCall {id} */ /********************************************************************/ boolean Stm() { if (token.Lex.equals("IF")) return ConditionalStm(); else if (token.Lex.equals("WHILE")) return LoopStm(); else if (token.Lex.equals("READ")) return InputStm(); else if (token.Lex.equals("WRITE")) return OutputStm(); else if (token.Lex.equals("RETURN")) return ReturnStm(); else if (token.Lex.equals("ID")) { return match("ID")&&AssCall(); } else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 AssCall */ /* 功 能 语句部分的处理函数 */ /* 产生式 < AssCall > ::= AssignmentRest {:=,LMIDPAREN,DOT} */ /* | CallStmRest {(} */ /********************************************************************/ boolean AssCall() { if ((token.Lex.equals("ASSIGN"))||(token.Lex.equals("LMIDPAREN"))||(token.Lex.equals("DOT"))) return AssignmentRest(); else if (token.Lex.equals("LPAREN")) return CallStmRest(); else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 AssignmentRest */ /* 功 能 赋值语句部分的处理函数 */ /* 产生式 < AssignmentRest > ::= VariMore : = Exp */ /********************************************************************/ boolean AssignmentRest() { return VariMore()&& match("ASSIGN")&&Exp(); } /********************************************************************/ /* 函数名 ConditionalStm */ /* 功 能 条件语句部分的处理函数 */ /* 产生式 <ConditionalStm>::=IF RelExp THEN StmList ELSE StmList FI */ /********************************************************************/ boolean ConditionalStm() { boolean ans=match("IF")&&Exp()&&match("THEN")&&StmList(); if(token.Lex.equals("ELSE")) { if(match("ELSE")) ans=ans&&StmList(); else ans=false; } ans=ans&&match("FI"); return ans; } /********************************************************************/ /* 函数名 LoopStm */ /* 功 能 循环语句部分的处理函数 */ /* 产生式 < LoopStm > ::= WHILE RelExp DO StmList ENDWH */ /********************************************************************/ boolean LoopStm() { return match("WHILE")&& Exp()&&match("DO")&&StmList()&&match("ENDWH"); } /********************************************************************/ /* 函数名 InputStm */ /* 功 能 输入语句部分的处理函数 */ /* 产生式 < InputStm > ::= READ(id) */ /********************************************************************/ boolean InputStm() { boolean ans=true; if(!match("READ")){ans=false;} if(!match("LPAREN")){ans=false;} if (token.Lex.equals("ID")) { if(!match("ID")) ans=false; } if(!match("RPAREN")){ans=false;} return ans; } /********************************************************************/ /* 函数名 OutputStm */ /* 功 能 输出语句部分的处理函数 */ /* 产生式 < OutputStm > ::= WRITE(Exp) */ /********************************************************************/ boolean OutputStm() { return match("WRITE")&&match("LPAREN")&&Exp()&&match("RPAREN"); } /********************************************************************/ /* 函数名 ReturnStm */ /* 功 能 返回语句部分的处理函数 */ /* 产生式 < ReturnStm > ::= RETURN(Exp) */ /********************************************************************/ boolean ReturnStm() { return match("RETURN"); } /********************************************************************/ /* 函数名 CallStmRest */ /* 功 能 函数调用语句部分的处理函数 */ /* 产生式 < CallStmRest > ::= (ActParamList) */ /********************************************************************/ boolean CallStmRest() { return match("LPAREN")&&ActParamList()&&match("RPAREN"); } /********************************************************************/ /* 函数名 ActParamList */ /* 功 能 函数调用实参部分的处理函数 */ /* 产生式 < ActParamList > ::= ε | Exp ActParamMore */ /********************************************************************/ boolean ActParamList() { if (token.Lex.equals("RPAREN")) {} else if ((token.Lex.equals("ID"))||(token.Lex.equals("INTC"))) { return Exp()&&ActParamMore(); } else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 ActParamMore */ /* 功 能 函数调用实参部分的处理函数 */ /* 产生式 < ActParamMore > ::= ε | , ActParamList */ /********************************************************************/ boolean ActParamMore() { if (token.Lex.equals("RPAREN")) {} else if (token.Lex.equals("COMMA")) { return match("COMMA")&&ActParamList(); } else ReadNextToken(); return true; } /*************************表达式部分********************************/ /*******************************************************************/ /* 函数名 Exp */ /* 功 能 表达式处理函数 */ /* 产生式 Exp ::= simple_exp | 关系运算符 simple_exp */ /* 说 明 函数根据文法产生式,调用相应的递归处理函数,生成语法树节点 */ /*******************************************************************/ boolean Exp() { boolean ans=simple_exp(); /* 当前单词token为逻辑运算单词LT或者EQ */ if ((token.Lex.equals("LT"))||(token.Lex.equals("EQ"))) { return ans&&match(token.Lex)&&simple_exp(); } return ans; } /*******************************************************************/ /* 函数名 simple_exp */ /* 功 能 表达式处理 */ /* 产生式 simple_exp ::= term | 加法运算符 term */ /*******************************************************************/ boolean simple_exp() { boolean ans= term(); boolean b=true; /* 当前单词token为加法运算符单词PLUS或MINUS */ while ((token.Lex.equals("PLUS"))||(token.Lex.equals("MINUS"))) { b=match(token.Lex)&&term(); } return b&&ans; } /********************************************************************/ /* 函数名 term */ /* 功 能 项处理函数 */ /* 产生式 < 项 > ::= factor | 乘法运算符 factor */ /********************************************************************/ boolean term() { boolean ans=factor(); /* 当前单词token为乘法运算符单词TIMES或OVER */ while ((token.Lex.equals("TIMES"))||(token.Lex.equals("OVER"))) { return match(token.Lex)&&factor(); } return ans; } /*********************************************************************/ /* 函数名 factor */ /* 功 能 因子处理函数 */ /* 产生式 factor ::= INTC | Variable | ( Exp ) */ /*********************************************************************/ boolean factor() { if (token.Lex.equals("INTC")) { return match("INTC"); } else if (token.Lex.equals("ID")) return Variable(); else if (token.Lex.equals("LPAREN")) { return match("LPAREN")&&Exp()&&match("RPAREN"); } else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 Variable */ /* 功 能 变量处理函数 */ /* 产生式 Variable ::= id VariMore */ /********************************************************************/ boolean Variable() { return match("ID")&&VariMore(); } /********************************************************************/ /* 函数名 VariMore */ /* 功 能 变量处理 */ /* 产生式 VariMore ::= ε */ /* | [Exp] {[} */ /* | . FieldVar {DOT} */ /********************************************************************/ boolean VariMore() { if ((token.Lex.equals("EQ")) ||(token.Lex.equals("LT")) ||(token.Lex.equals("PLUS")) ||(token.Lex.equals("MINUS")) ||(token.Lex.equals("RPAREN")) ||(token.Lex.equals("RMIDPAREN")) ||(token.Lex.equals("SEMI")) ||(token.Lex.equals("COMMA")) || (token.Lex.equals("THEN")) ||(token.Lex.equals("ELSE")) ||(token.Lex.equals("FI")) ||(token.Lex.equals("DO")) ||(token.Lex.equals("ENDWH")) ||(token.Lex.equals("END")) ||(token.Lex.equals("ASSIGN")) ||(token.Lex.equals("TIMES")) ||(token.Lex.equals("OVER"))){} else if (token.Lex.equals("LMIDPAREN")) { return match("LMIDPAREN")&&Exp()&&match("RMIDPAREN"); } else if (token.Lex.equals("DOT")) { return match("DOT")&&FieldVar(); } else ReadNextToken(); return true; } /********************************************************************/ /* 函数名 FieldVar */ /* 功 能 变量处理函数 */ /* 产生式 FieldVar ::= id FieldVarMore */ /********************************************************************/ boolean FieldVar() { return match("ID")&&FieldVarMore(); } /********************************************************************/ /* 函数名 FieldVarMore */ /* 功 能 变量处理函数 */ /* 产生式 FieldVarMore ::= ε| [Exp] {[} */ /********************************************************************/ boolean FieldVarMore() { if ((token.Lex.equals("ASSIGN")) ||(token.Lex.equals("TIMES")) ||(token.Lex.equals("EQ"))||(token.Lex.equals("LT")) ||(token.Lex.equals("PLUS"))||(token.Lex.equals("MINUS")) || (token.Lex.equals("OVER"))||(token.Lex.equals("RPAREN")) || (token.Lex.equals("SEMI"))||(token.Lex.equals("COMMA")) ||(token.Lex.equals("THEN"))||(token.Lex.equals("ELSE")) ||(token.Lex.equals("FI"))||(token.Lex.equals("DO")) || (token.Lex.equals("ENDWH"))||(token.Lex.equals("END"))) {} else if (token.Lex.equals("LMIDPAREN")) { return match("LMIDPAREN")&&Exp()&&match("RMIDPAREN"); } else ReadNextToken(); return true; } }
import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs'; // *------- Model -------*/ import { recipeModel } from './../models/recipe.model'; import { ingredient } from '../models/ingredient.model'; // *------- Services -------*/ import { ShoppingListService } from './shopping-list.service'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class RecipeService { initiateDetailDrawer = new Subject<boolean>(); /** * * ? Recipe Database * * @type {recipeModel[]} * @memberof RecipeService */ recipes: recipeModel[]; constructor( private shoppingListService: ShoppingListService, private http: HttpClient ) {} fetchRecipes() { const data = []; this.http .get( 'https://tasty.p.rapidapi.com/recipes/list?from=0&size=20&tags=under_30_minutes', { headers: { 'x-rapidapi-key': 'a5a7981f86msh016f80f350e57edp1f3646jsn0ea0ecd6b9ea', 'x-rapidapi-host': 'tasty.p.rapidapi.com', }, } ) .subscribe((Data: any) => { for (const recipeData of Data.results) { const ingredients: ingredient[] = []; let instructions = ''; for (const component of recipeData.sections[0].components) { let componentA: string; for (const componentAmount of component.measurements) { componentA = componentAmount.quantity; } ingredients.push(new ingredient(component.raw_text, componentA)); } for (const inst of recipeData.instructions) { instructions += inst.display_text; } data.push( new recipeModel( recipeData.name, recipeData.description, instructions, recipeData.thumbnail_url, ingredients, recipeData.id ) ); } }); return data; } fetchRecipeById(id: number): Observable<any> { let data: recipeModel; return this.http.get( `https://tasty.p.rapidapi.com/recipes/detail?id=${id}`, { headers: { 'x-rapidapi-key': 'a5a7981f86msh016f80f350e57edp1f3646jsn0ea0ecd6b9ea', 'x-rapidapi-host': 'tasty.p.rapidapi.com', }, } ); } /** * * ? it adds an ingredient into the shopping list * * @param ings * @memberof RecipeService */ addRecipeIng(ings: ingredient[]): void { this.shoppingListService.addRecipeIng(ings); } /** * * ? it used to add a recipe to Database * * @param recipe * @memberof RecipeService */ addRecipe(recipe: recipeModel): void { this.recipes.push(recipe); } /** * * ? it used to edit the information of a recipe in the database * * @param recipe * @param index * @memberof RecipeService */ editRecipe(recipe: recipeModel, index: number): void { this.recipes[index] = recipe; } /** * * ? used to delete a recipe from database * * @param index * @memberof RecipeService */ deleteRecipe(index: number): void { this.recipes.splice(index, 1); } }
package multiThreading.master.ch02.matrix; /** * 从start行到第end行 * * @author chenyuqun * @date 2021/1/12 2:33 下午 */ public class GroupMultiplierTask implements Runnable { private final double[][] result; private final double[][] matrix1; private final double[][] matrix2; private int startIndex; private int endIndex; public GroupMultiplierTask(double[][] result, double[][] matrix1, double[][] matrix2, int startIndex, int endIndex) { this.result = result; this.matrix1 = matrix1; this.matrix2 = matrix2; this.startIndex = startIndex; this.endIndex = endIndex; } /** * 计算 [start, end) 行的值 */ @Override public void run() { for (int i = startIndex; i < endIndex; i++) { for (int j = 0; j < matrix2[0].length; j++) { result[i][j] = 0; for (int k = 0; k < matrix1[i].length; k++) { result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } } }
import { BadRequestException, Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { InjectRepository } from '@nestjs/typeorm'; import axios from 'axios'; import { BaseService } from 'src/base/nestjsx.service'; import { InternalServerEvent } from 'src/constance/event'; import { getCustomRepository, getRepository, Repository } from 'typeorm'; import { Role } from '../role/entities/role.entity'; import { Team } from '../team/entities/team.entity'; import { TeamRepository } from '../team/team.repository'; import { CreateAccountDto, JoinTeamDto } from './dto/create-account.dto'; import { Account } from './entities/account.entity'; @Injectable() export class AccountService extends BaseService<Account> { constructor( @InjectRepository(Account) repository: Repository<Account>, private eventEmitter: EventEmitter2, private config: ConfigService, ) { super(repository); } async joinTeam({ accountId, teamId }: JoinTeamDto) { const teamRepository = getCustomRepository(TeamRepository); const [account, team] = await Promise.all([ this.findOneItem({ where: { id: accountId } }), teamRepository.findOneItem({ where: { id: teamId }, relations: ['accounts'], }), ]); if (team.accounts == undefined) { team.accounts = [account]; return team.save(); } for (const { id } of team.accounts) { if (id === accountId) throw new BadRequestException('already join this team'); } team.accounts.push(account); this.eventEmitter.emit(InternalServerEvent.NEW_MEMBER_JOIN_TEAM, { account, teamId, }); return team.save(); } async createAccount({ roleId, teamId, ...dto }: CreateAccountDto) { try { const roleRepository = getRepository(Role); const teamRepository = getRepository(Team); const [role, team] = await Promise.all([ roleRepository.findOne({ where: { id: roleId } }), teamRepository.findOne({ where: { id: teamId } }), ]); const createResult = await this.repository .create({ ...dto, role, team, }) .save(); await this.createAccountOnEmailServer( dto.username, dto.email, dto.password, createResult.id, ); return createResult; } catch (error) { throw new BadRequestException(error); } } async createAccountOnEmailServer( username: string, email: string, password: string, id: string, ) { try { const { data } = await axios.post( `${this.config.get<string>('email.serverUrl')}/account`, { username, password, email, id, }, ); return data; } catch (error) { throw new BadRequestException('cannot create account'); } } async makeLeader(id: string, teamId: string) { const teamRepository = getCustomRepository(TeamRepository); const [team] = await Promise.all([ teamRepository.findOneItem({ where: { id: teamId }, relations: ['accounts'], }), ]); team.accounts.forEach((account) => { if (account.isLeader) account.isLeader = false; }); team.accounts.forEach((account) => { if (account.id === id) { account.isLeader = true; } }); return team.save(); } }
import React from 'react'; import { Switch,Route } from 'react-router-dom'; import './App.css'; import HomePage from './pages/homepage/homepage.component' import ShopPage from './pages/shop/shop.component' import Header from './components/header/header.component' import SignInAndSignUpPage from './pages/sign-in-and-sign-up/sign-in-and-sign-up.component'; import {auth,createUserProfileDocument} from './firebase/firebase.utils' class App extends React.Component { constructor() { super(); this.state={ currentUser:null } } unsubscribeFromAuth=null; componentDidMount(){ this.unsubscribeFromAuth=auth.onAuthStateChanged(async userAuth=>{ if(userAuth){ const userRef=await createUserProfileDocument(userAuth); userRef.onSnapshot(snapShot=>{ this.setState({ currentUser:{ id:snapShot.id, ...snapShot.data() } }) }) } this.setState({currentUser:userAuth}) }) } componentWillUnmount(){ this.unsubscribeFromAuth(); } render() { return ( <div> <Header currentUser={this.state.currentUser}></Header> <Switch> <Route exact path="/" component={HomePage}/> <Route exact path="/shop" component={ShopPage}/> <Route exact path="/signin" component={SignInAndSignUpPage}/> </Switch> </div> );} } export default App;
import React, { useEffect } from 'react'; import Box from '@mui/material/Box'; import Chip from '@mui/material/Chip'; import Grid from '@mui/material/Grid'; import Stack from '@mui/material/Stack'; import Typography from '@mui/material/Typography'; import Contributors from './contributors'; import ProfilePicture from './profile'; import StockImage from '../../assets/images/stock-image.jpg'; import PublicIcon from '@mui/icons-material/Public'; import LockIcon from '@mui/icons-material/Lock'; import instance from '../api/api_instance.js' import { useState } from 'react'; import { Link } from 'react-router-dom'; import Tags from './tags'; import '../../assets/styles/global.css'; export default function IndividualPost(props) { const [title, setTitle] = useState('') const [banner, setBanner] = useState('') const [summary, setSummary] = useState('') const [publicity, setPublicity] = useState('') const [description, setDescription] = useState('') const [date, setDate] = useState('') const [post_id, setPostID] = useState('') const [tags, setTags] = useState([]) const [collaborators, setCollaborators] = useState([]) useEffect(() => { async function GetPostInformation() { try{ await instance ({ url: "/post/get_by_id", method: "GET", params: {post_id: props.post_id} }).then((res) => { setTitle(res.data.title) setSummary(res.data.summary) setPublicity(res.data.publicity) setDescription(res.data.description) setDate(new Date(res.data.post_time).toLocaleDateString()) setPostID("/post/"+props.post_id) setTags(res.data.tags) setCollaborators(res.data.collaborators) setBanner(res.data.post_pic) }); } catch(e) { console.error(e) } } GetPostInformation(); } , // <- function that will run on every dependency update [] // <-- empty dependency array ) return ( <Link to={post_id} style={{ textDecoration: "none", color: 'black' }}> <Box sx={{ width: '100%', bgcolor: '#D9D9D9', borderRadius: '10px', padding: "10px 0px 10px 0px" }}> <Box sx={{ my: 3, mx: 2, margin: "0px" }}> <Grid container alignItems="center" > {/* Profile picture will need to be reviewed when the backend is linked */} <Grid item sx={{margin: "0px 0px 0px 20px"}}> <ProfilePicture /> </Grid> <Grid item xs sx={{padding: '0px 0px 0px 10px'}}> <Typography gutterBottom variant="h6" component="div" sx={{marginBottom: "0px"}}> Group name <br></br>{date} { publicity ? <PublicIcon /> : <LockIcon /> } </Typography> </Grid> {/* Contributors pictures will also need to be reviewed when the backend is linked */} <Grid item sx={{margin: "0px 20px 0px 0px"}}> <Contributors collaborators = {collaborators} /> </Grid> </Grid> <Typography gutterBottom variant="h4" component="div" sx={{margin: "0px 20px 0px 20px"}}> { title } </Typography> <Typography color="text.secondary" variant="body2" sx={{margin: "0px 20px 0px 20px"}}> { description.slice(0,250) }... </Typography> <img src={instance.defaults.baseURL.replace("/api", "") + banner} className="Post-image" alt="logo" style={{padding: '10px 0px 10px 0px'}}/> <Tags tagArray={tags}/> </Box> </Box> </Link> ); }
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <link rel="stylesheet" href="viewRooms.css"> </head> <body> <div class="sidemenu"> <a href="AdminDashboard.jsp">Home</a> <a class="active" href="showRoom">View Rooms</a> <a href="roomInsert.jsp">Create Room</a> <a href="#profile">profile</a> </div> <a href="showRoom"> view</a> <div class="rooms-list-div"> <table> <tr> <th class="room-det">Room No</th> <th class="room-det">Room Name</th> <th class="room-det">Room Description</th> <th class="room-det">Maximum Occupants</th> <th class="room-det">Price per Night</th> <th class="room-det">Image location</th> </tr> <c:forEach var="rm" items="${roomsdet}"> <tr> <div class="room-div"> <c:set var="roomid" value="${rm.rID}"/> <c:set var="rname" value="${rm.roomName}"/> <c:set var="rdesc" value="${rm.descript}"/> <c:set var="maxoccupants" value="${rm.maxOccupants}" /> <c:set var="rprice" value="${rm.price}"/> <c:set var="imgloc" value="${rm.imageLocation}"/> <td><div class="room-det">${rm.rID}</div></td> <td><div class="room-det">${rm.roomName}</div></td> <td><div class="room-det">${rm.descript}</div></td> <td><div class="room-det">${rm.maxOccupants}</div></td> <td><div class="room-det">${rm.price}</div></td> <td><div class="room-det">${rm.imageLocation}</div></td> <td> <div> <c:url value="updateRoom.jsp" var="updateroom"> <c:param name="roomid" value="${roomid}"/> <c:param name="rname" value="${rname}"/> <c:param name="rdesc" value="${rdesc}"/> <c:param name="maxoccupants" value="${maxoccupants}"/> <c:param name="rprice" value="${rprice}"/> <c:param name="imgloc" value="${imgloc}"/> </c:url> <a href="${updateroom}"> <button>Update Room</button> </a> </div> </td> <td> <div> <c:url value="deleteRoom.jsp" var="deleteroom"> <c:param name="roomid" value="${roomid}"/> <c:param name="rname" value="${rname}"/> <c:param name="rdesc" value="${rdesc}"/> <c:param name="maxoccupants" value="${maxoccupants}"/> <c:param name="rprice" value="${rprice}"/> <c:param name="imgloc" value="${imgloc}"/> </c:url> <a href="${deleteroom}"> <button>Delete Room</button> </a> </div> </td> </div> </tr> </c:forEach> </table> </div> </body> </html>
# frozen_string_literal: true require "rails_helper" describe ContactDetailsForm, type: :model do let(:params) { {} } let(:trainee) { build(:trainee) } let(:form_store) { class_double(FormStore) } subject { described_class.new(trainee, params: params, store: form_store) } before do allow(form_store).to receive(:get).and_return(nil) end describe "validations" do it { is_expected.to validate_presence_of(:email) } it "validates length of email" do subject.email = "a" * 256 expect(subject).not_to be_valid expect(subject.errors[:email]).to include("is too long (maximum is 255 characters)") end context "empty form data" do let(:params) do { "email" => "", } end before do subject.valid? end it "returns 1 error about email" do expect(subject.errors.attribute_names).to match(%i[email]) end end end describe "#stash" do let(:trainee) { create(:trainee) } it "uses FormStore to temporarily save the fields under a key combination of trainee ID and contact_details" do expect(form_store).to receive(:set).with(trainee.id, :contact_details, subject.fields) subject.stash end end describe "#save!" do let(:params) { {} } let(:trainee) { create(:trainee) } before do allow(form_store).to receive(:get).and_return({ "email" => "test @example.com", }) allow(form_store).to receive(:set).with(trainee.id, :contact_details, nil) end it "strips all whitespace from emails" do expect { subject.save! }.to change(trainee, :email).to("[email protected]") end end end
<!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="style.css" /> <title>Document</title> </head> <body> <main> <header> <h2 id="head-logo">Header Logo</h2> <nav> <ul> <li>header link one</li> <li>header link two</li> <li>header link three</li> </ul> </nav> </header> <div id="hero"> <div id="hero-headline"> <h1>This website is awesome!</h1> <p> This website has some subtext that goes under the main title. It's a smaller font and the color is lower contrast. </p> <h2 class="sign-up">Sign up</h2> </div> <div id="hero-image"><img src="" alt="Main website image" aria-placeholder="this is placeholder text"></div> </div> </main> <section id="content-highlights"> <h1>Content Highlights</h1> <ul> <li> <div></div> <p>this is some subtext under an illustration of an image</p> </li> <li> <div></div> <p>this is some subtext under an illustration of an image</p> </li> <li> <div></div> <p>this is some subtext under an illustration of an image</p> </li> <li> <div></div> <p>this is some subtext under an illustration of an image</p> </li> </ul> </section> <section id="big-quote"> <blockquote> <p> This is an inspiring quote, or a testimonial from a customer. Maybe it's just filling up space, or maybe people will actually read it. Who knows? All I know is that it looks nice. </p> <footer>-Someone, <cite>Pulled from Anus</cite></footer> </blockquote> </section> <section id="call-to-action"> <div> <div> <h3>Call to action! It's time!</h3> <p>Sign up for our products by clicking the button over there!</p> </div> <div> <h3 class="sign-up">Sign up</h3> </div> </div> </section> <footer><p>Copyright &copy; The Odin Project</p></footer> </body> </html>
Master Data Management (MDM) is a method for defining and managing the critical data of an organization (also known as master data). Master data covers core business entities such as customers, products, employees, suppliers, and these often reside in siloed data repositories even within the same organization. MDM seeks to ensure this data is consistently defined and interconnected. ## Components of MDM 1. **Data Collection**: Gathering data from various sources. 2. **Data Transformation**: Converting data into a common format. 3. **Error Detection & Correction**: Identifying and correcting data errors. 4. **Data Governance**: Implementing management policies, procedures, and governance to ensure data quality. 5. **Data Maintenance/Quality Assurance**: Ongoing processes to keep data up to date and of high quality. ## Key Objectives 1. **Data Quality & Business Process Management Efforts**: Ensures that data is accurate, consistent, actionable, and pertinent. 2. **Business Intelligence**: Drives analytics and data mining, empowering business decisions. 3. **Compliance**: Aids in compliance with various laws and regulations related to data. ## Types of Master Data A typical entreprise / organisation will have the following data that are relevant to MDM: 1. **Customer Data**: Information about customers and prospects. 2. **Product Data**: Information about products that a company makes or sells. 3. **Employee Data**: Information about employees in an organization. 4. **Supplier Data**: Information about suppliers and supply chain logistics. 5. **Asset Data**: Information about physical and virtual assets and their attributes. ### MDM Processes 1. **Data Collection**: Aggregating data from disparate sources. 2. **Data Transformation**: Standardizing and enriching data. 3. **Data Governance**: Applying rules, policies, and governance. 4. **Data Maintenance**: Ongoing quality assurance processes to keep data accurate, timely, and relevant. ### Benefits of MDM 1. **Enhanced Compliance**: Better data handling and records for compliance with legal and business policies. 2. **Improved Efficiency**: Reduces redundancy and eliminates the expense of having to reconcile data inconsistencies. 3. **Better Decision-making**: Provides a 'single version of the truth,' making data more reliable. 4. **Customer Satisfaction**: Improved data quality provides more accurate insights into customer behavior, enabling better service. ### Challenges in Implementing MDM 1. **Organizational Silos**: Data residing in disparate parts of the organization, in different formats, and maintained by different units. 2. **Data Quality**: Ensuring data is clean, accurate, and up-to-date. 3. **Data Governance**: Establishing the roles, responsibilities, and procedures for data quality, consistency, and usage. 4. **Technology & Tools**: Implementing the right MDM solutions that fit the organization's needs and scale. ### MDM and Open Source Open-source solutions for MDM enable organizations to implement these processes without the burden of licensing fees and with greater flexibility to customize the system to their specific needs. ### Solutions - Pimcore: Open Source Data & Experience Management Platform (PIM, MDM, CDP, DAM, DXP/CMS & Digital Commerce) → https://github.com/pimcore/pimcore - Talend Open Studio for MDM → https://github.com/Talend/tmdm-server-se
package com.project.foodtracker.domain.use_case import com.project.foodtracker.domain.repository.IFavoritesRepository import javax.inject.Inject /** * Use case for adding a product to favorites. * * @property repository The repository to interact with favorites data. */ class AddToFavoritesUseCase @Inject constructor( private val repository: IFavoritesRepository ) { /** * Invokes the use case to add a product to favorites. * * @param productId The ID of the product to be added to favorites. */ suspend operator fun invoke(productId: String) { repository.addProductToFavorites(productId) } }
import 'package:flutter/material.dart'; import 'package:flutter_phone_number_field/flutter_phone_number_field.dart'; import 'package:get/get.dart'; import 'package:lhw/Login_SignUp/Login.dart'; import 'package:pin_code_fields/pin_code_fields.dart'; import '../controllers/signup_controller.dart'; class ForgotPasswordScreen extends StatefulWidget { const ForgotPasswordScreen({super.key}); @override State<ForgotPasswordScreen> createState() => _ForgotPasswordScreenState(); } class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> { bool showVerificationCode = false; final _formkey = GlobalKey<FormState>(); final controller = Get.put(SignUpController()); @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.only(left: 15, right: 15, top: 60), child: Form( key: _formkey, child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ const Center( child: Text( "پاسورڈ بھول گے", style: TextStyle(fontFamily: "UrduType", fontSize: 30), )), const Directionality( textDirection: TextDirection.rtl, child: Center( child: Text( "وہ نمبر درج کریں جس میں آپ ری سیٹ لنک وصول کرنا چاہتے ہیں۔", style: TextStyle( fontFamily: "UrduType", fontSize: 20, color: Color(0xff878787)), ), ), ), const SizedBox( height: 30, ), Container( alignment: Alignment.centerRight, child: RichText( text: const TextSpan( text: '*', style: TextStyle( color: Color(0xffEC5A53), // This makes the asterisk red fontSize: 16, ), children: <TextSpan>[ TextSpan( text: 'فون نمبر', style: TextStyle( fontFamily: "UrduType", color: Colors.black, // Change the color as you want fontSize: 16, ), ), ], ), ), ), const SizedBox( height: 5, ), FlutterPhoneNumberField( controller: controller.phoneNo, showCountryFlag: true, showDropdownIcon: false, textAlign: TextAlign.right, initialCountryCode: "PK", pickerDialogStyle: PickerDialogStyle( countryFlagStyle: const TextStyle(fontSize: 17), ), decoration: const InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 10.0), hintText: 'اپنا موبائل نمبر درج کیجئے', hintStyle: TextStyle( fontFamily: "UrduType", color: Color(0xff7A7D84), ), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10)), borderSide: BorderSide( color: Color( 0xffCDD1E0)), // You can set it to transparent here. ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10)), borderSide: BorderSide( color: Color(0xffCDD1E0)), // Grey border when enabled ), ), languageCode: "ar", onChanged: (phone) {}, onCountryChanged: (country) {}, ), const SizedBox( height: 20, ), if (showVerificationCode) ...[ const SizedBox(height: 20), Padding( padding: const EdgeInsets.only(left: 40, right: 40, bottom: 30), child: PinCodeTextField( obscureText: false, length: 6, animationDuration: const Duration(milliseconds: 300), keyboardType: TextInputType.number, animationType: AnimationType.fade, appContext: context, ), ), ], Center( child: RoundedButton( title: 'لنک بھیجیں۔', onTap: () { setState(() { showVerificationCode = true; }); }), ), const SizedBox( height: 15, ), ], ), ), ), ); } }
// IMPORTS ATOMS import Link from "@/atoms/link/jsx/index.jsx" import PrimaryButton from "@/atoms/button/primary/jsx/index.jsx" // IMPORTS REACT import { useState } from "react" // IMPORTS FRAMER MOTION import { motion, AnimatePresence } from "framer-motion" const Accordion = ( props ) => { // GET PROPS const { expand, index, updateExpand, value } = props const isOpen = index === expand return ( <div className="py-4 md:py-8 px-8 md:px-12 bg-white z-30 my-8 rounded-[42px]"> <motion.section initial={ false } onClick={() => updateExpand( isOpen ? false : index )} className="cursor-pointer flex items-center justify-between gap-4 event" un9n-event={ "service-" + index } > <div className="flex-wrap"> <h4 className="text-lg md:text-3xl font-bold md:font-black text-[#071641]">{ value.title }</h4> </div> <div className="w-6 aspect-square"> <motion.img alt="add icon" className={`${ isOpen ? "rotate-45": "rotate-0" } w-6 h-6 transition-all duration-300`} src="/icons/add.svg" /> </div> </motion.section> <div> <AnimatePresence initial={ false }> { isOpen && <motion.div key="content" initial="collapsed" animate="open" exit="collapsed" variants={{ open: { opacity: 1, height: "auto" }, collapsed: { opacity: 0, height: 0 } }} transition={{ duration: 0.2 }} > <div className="md:w-[50%] pt-4 md:pt-6 space-y-4 md:space-y-6"> <p className="font-proxima_nova text-base md:text-2xl text-ms_dark_blue md:leading-normal">{ value.description }</p> <Link href={ value.button_link } aria_label={ value.button_text }> <PrimaryButton>{ value.button_text }</PrimaryButton> </Link> </div> </motion.div> } </AnimatePresence> </div> </div> ) } const Service = ( props ) => { // GET PROPS const { data } = props const [ expand, updateExpand ] = useState("") return ( <section> { data.map( ( value, index ) => { return ( <Accordion expand={ expand } index={ index } key={ "service" + index } updateExpand={ updateExpand } value={ value } /> ) }) } </section> ) } export default Service
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.ejb.gen; import com.caucho.config.gen.*; import com.caucho.config.*; import com.caucho.inject.Module; import com.caucho.java.JavaWriter; import com.caucho.util.L10N; import java.io.IOException; import java.util.*; import java.lang.reflect.Method; import javax.enterprise.inject.spi.AnnotatedMethod; import javax.enterprise.inject.spi.AnnotatedType; /** * Represents a public interface to a stateful bean, e.g. a stateful view */ @Module public class MessageView<X,T> extends View<X,T> { private static final L10N L = new L10N(MessageView.class); private MessageGenerator<X> _messageBean; private ArrayList<BusinessMethodGenerator<X,T>> _businessMethods = new ArrayList<BusinessMethodGenerator<X,T>>(); public MessageView(MessageGenerator<X> bean, AnnotatedType<T> api) { super(bean, api); _messageBean = bean; } public MessageGenerator<X> getMessageBean() { return _messageBean; } public String getContextClassName() { return getMessageBean().getClassName(); } @Override public String getViewClassName() { return getMessageBean().getClassName(); } /** * Returns the introspected methods */ @Override public ArrayList<? extends BusinessMethodGenerator<X,T>> getMethods() { return _businessMethods; } /** * Introspects the APIs methods, producing a business method for * each. */ @Override public void introspect() { AnnotatedType<T> apiClass = getViewClass(); for (AnnotatedMethod<? super T> apiMethod : apiClass.getMethods()) { Method javaMethod = apiMethod.getJavaMember(); if (javaMethod.getDeclaringClass().equals(Object.class)) continue; if (javaMethod.getDeclaringClass().getName().startsWith("javax.ejb.") && ! javaMethod.getName().equals("remove")) continue; int index = _businessMethods.size(); BusinessMethodGenerator<X,T> bizMethod = createMethod(apiMethod, index); if (bizMethod != null) { bizMethod.introspect(bizMethod.getApiMethod(), bizMethod.getImplMethod()); _businessMethods.add(bizMethod); } } } /** * Generates the view code. */ @Override public void generate(JavaWriter out) throws IOException { HashMap<String,Object> map = new HashMap<String,Object>(); map.put("caucho.ejb.xa", "done"); out.println(); out.println("private static final com.caucho.ejb.util.XAManager _xa"); out.println(" = new com.caucho.ejb.util.XAManager();"); /* ejb/0fbm for (BusinessMethodGenerator bizMethod : _businessMethods) { bizMethod.generatePrologueTop(out, map); } */ for (BusinessMethodGenerator<X,T> bizMethod : _businessMethods) { bizMethod.generate(out, map); } } protected BusinessMethodGenerator<X,T> createMethod(AnnotatedMethod<? super T> apiMethod, int index) { AnnotatedMethod<? super X> implMethod = findImplMethod(apiMethod); if (implMethod == null) return null; BusinessMethodGenerator<X,T> bizMethod = new MessageMethod<X,T>(this, apiMethod, implMethod, index); return bizMethod; } protected AnnotatedMethod<? super X> findImplMethod(AnnotatedMethod<? super T> apiMethod) { AnnotatedMethod<? super X> implMethod = getMethod(getBeanClass(), apiMethod.getJavaMember()); if (implMethod != null) return implMethod; throw ConfigException.create(apiMethod.getJavaMember(), L.l("api method has no corresponding implementation in '{0}'", getBeanClass().getJavaClass().getName())); } protected AnnotatedMethod<? super X> getImplMethod(String name, Class<?> []param) { return getMethod(getBeanClass(), name, param); } }
-- Assume you are given the table containing measurement values obtained from a Google sensor over several days. Measurements are taken several times within a given day. -- Write a query to obtain the sum of the odd-numbered and even-numbered measurements on a particular day, in two different columns. Refer to the Example Output below for the output format. WITH window_measurements AS (SELECT CAST(measurement_time AS DATE) AS measurement_day, measurement_value, ROW_NUMBER() OVER ( PARTITION BY CAST(measurement_time AS DATE) ORDER BY measurement_time) AS measurement_num FROM measurements), even_measurements AS ( SELECT measurement_day, sum(measurement_value) AS even_sum FROM window_measurements WHERE measurement_num%2 = 0 GROUP BY measurement_day ), odd_measurements AS ( SELECT measurement_day, sum(measurement_value) AS odd_sum FROM window_measurements WHERE measurement_num%2 <> 0 GROUP BY measurement_day ) SELECT odd_measurements.measurement_day, odd_sum, even_sum from even_measurements inner JOIN odd_measurements using(measurement_day) ORDER BY odd_measurements.measurement_day; WITH ranked_measurements AS ( SELECT CAST(measurement_time AS DATE) AS measurement_day, measurement_value, ROW_NUMBER() OVER ( PARTITION BY CAST(measurement_time AS DATE) ORDER BY measurement_time) AS measurement_num FROM measurements ) SELECT measurement_day, SUM( CASE WHEN measurement_num % 2 != 0 THEN measurement_value ELSE 0 END) AS odd_sum, SUM( CASE WHEN measurement_num % 2 = 0 THEN measurement_value ELSE 0 END) AS even_sum FROM ranked_measurements GROUP BY measurement_day;
## [1663 具有给定数值的最小字符串](https://leetcode.cn/problems/smallest-string-with-a-given-numeric-value/description/) + `贪心` + Python3 ```python class Solution: def getSmallestString(self, n: int, k: int) -> str: ans = ['a'] * n k -= n idx = n-1 for i in range(k//25): ans[idx] = 'z' idx -= 1 k %= 25 if k > 0: ans[idx] = chr(ord('a') + k) idx -= 1 return "".join(ans) ``` + Golang ```go func getSmallestString(n int, k int) string { ans := make([]byte, n) k -= n idx := n - 1 for i := 0; i < k/25; i++ { ans[idx] = 'z' idx-- } k %= 25 if k > 0 { ans[idx] = byte(k) + 'a' idx-- } for idx >= 0 { ans[idx] = 'a' idx-- } return string(ans) } ```
from django.db import models # from .models import Product # Create your models here. from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator STATE_CHOICE = ( ('Andaman & Nicobar Islands', 'Andaman & Nicobar Islands'), ('Andhra Pradesh', 'Andhra Pradesh'), ('Arunachal Pradesh', 'Arunachal Pradesh'), ('Assam', 'Assam'), ('Bihar', 'Bihar'), ('Chandigarh', 'Chandigarh'), ('Chhattisgarh', 'Chhattisgarh'), ('Dadra & Nagar Haveli', 'Dadra & Nagar Haveli'), ('Daman and Diu', 'Daman and Diu'), ('Delhi', 'Delhi'), ('Goa', 'Goa'), ('Gujarat', 'Gujarat'), ('Haryana', 'Haryana'), ('Himachal Pradesh', 'Himachal Pradesh'), ('Jammu & Kashmir', 'Jammu & Kashmir'), ('Jharkhand', 'Jharkhand'), ('Karnataka', 'Karnataka'), ('Kerala', 'Kerala'), ('Lakshadweep', 'Lakshadweep'), ('Madhya Pradesh', 'Madhya Pradesh'), ('Maharashtra', 'Maharashtra'), ('Manipur', 'Manipur'), ('Meghalaya', 'Meghalaya'), ('Mizoram','Mizoram'), ('Nagaland','Nagaland'), ('Odisha', 'Odisha'), ('Puducherry', 'Puducherry'), ('Punjab', 'Punjab'), ('Rajasthan', 'Rajasthan'), ('Sikkim', 'Sikkim'), ('Tamil Nadu', 'Tamil Nadu'), ('Telangana', 'Telangana'), ('Tripura', 'Tripura'), ('Uttarakhand', 'Uttarakhand'), ('Uttar Pradesh','Uttar Pradesh'), ('West Bengal','West Bengal'), ) class Customer (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) locality = models.CharField (max_length=200) city = models.CharField(max_length=50) zipcode = models.IntegerField() state = models.CharField (choices=STATE_CHOICE, max_length=50) phone = models.BigIntegerField(default='') def __str__(self): return str(self.id) CATEGORY_CHOICES = ( ('M','Mobile'), ('L','Laptops'), ('MF','Men'), ('FF','Women'), ('ND','Networking Devices'), ('TV','TVs'), ('FU','Furnitures'), ('AP','Appliances'), # ('All','all'), ) class Product (models.Model): title = models.CharField(max_length=100) selling_price = models.FloatField() discounted_price = models.FloatField() description= models.TextField() brand = models.CharField (max_length=100) category =models.CharField(choices=CATEGORY_CHOICES,max_length=3) product_image = models.ImageField(upload_to = "productimg") def __str__(self): return str(self.id) CATEG_CHOICES = ( ('E','Electronics'), ('F','Fashion'), ) class catcart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # brands = models.CharField (max_length=100) categ =models.CharField(choices=CATEG_CHOICES,max_length=3) def __str__(self): return str(self.id) class Cart (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product= models.ForeignKey(Product, on_delete=models.CASCADE) quantity= models.PositiveIntegerField(default=1) catego =models.CharField(choices=CATEG_CHOICES,max_length=3,default='') @property def total_cost(self): return self.quantity * self.product.discounted_price def __str__(self): return str(self.id) STATUS_CHOICES =( ('Accepted', 'Accepted'), ('Packed', 'Packed'), ('On The Way', 'On The Way'), ('Delivered', 'Delivered'), ('Cancel', 'Cancel') ) class OrderPlaced (models.Model): user = models. ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models. ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) ordered_date = models.DateTimeField (auto_now_add=True) status = models. CharField (max_length=50, choices=STATUS_CHOICES, default='Pending')
// Copyright (C) 2023, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. package builder import ( "context" "sync/atomic" "time" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer" "go.uber.org/zap" ) // minBuildGap ensures we don't build blocks too quickly (can fail // if we build empty blocks too soon) // // TODO: consider replacing this with AvalancheGo block build metering const minBuildGap int64 = 25 // ms var _ Builder = (*Time)(nil) // Time tells the engine when to build blocks and gossip transactions type Time struct { vm VM doneBuild chan struct{} timer *timer.Timer lastQueue int64 waiting atomic.Bool } func NewTime(vm VM) *Time { b := &Time{ vm: vm, doneBuild: make(chan struct{}), } b.timer = timer.NewTimer(b.handleTimerNotify) return b } func (b *Time) Run() { b.Queue(context.TODO()) // start building loop (may not be an initial trigger) b.timer.Dispatch() // this blocks } func (b *Time) handleTimerNotify() { if err := b.Force(context.TODO()); err != nil { b.vm.Logger().Warn("unable to build", zap.Error(err)) } else { txs := b.vm.Mempool().Len(context.TODO()) b.vm.Logger().Debug("trigger to notify", zap.Int("txs", txs)) } b.waiting.Store(false) } func (b *Time) nextTime(now int64, preferred int64) int64 { gap := b.vm.Rules(now).GetMinBlockGap() next := math.Max(b.lastQueue+minBuildGap, preferred+gap) if next < now { return -1 } return next } func (b *Time) Queue(ctx context.Context) { if !b.waiting.CompareAndSwap(false, true) { b.vm.Logger().Debug("unable to acquire waiting lock") return } preferredBlk, err := b.vm.PreferredBlock(context.TODO()) if err != nil { b.waiting.Store(false) b.vm.Logger().Warn("unable to load preferred block", zap.Error(err)) return } now := time.Now().UnixMilli() next := b.nextTime(now, preferredBlk.Tmstmp) if next < 0 { if err := b.Force(ctx); err != nil { b.vm.Logger().Warn("unable to build", zap.Error(err)) } else { txs := b.vm.Mempool().Len(context.TODO()) b.vm.Logger().Debug("notifying to build without waiting", zap.Int("txs", txs)) } b.waiting.Store(false) return } sleep := next - now sleepDur := time.Duration(sleep * int64(time.Millisecond)) b.timer.SetTimeoutIn(sleepDur) b.vm.Logger().Debug("waiting to notify to build", zap.Duration("t", sleepDur)) } func (b *Time) Force(context.Context) error { select { case b.vm.EngineChan() <- common.PendingTxs: b.lastQueue = time.Now().UnixMilli() default: b.vm.Logger().Debug("dropping message to consensus engine") } return nil } func (b *Time) Done() { b.timer.Stop() }
import { StyleSheet, Text, View, ImageProps, Image, ImageBackground, } from "react-native"; import React from "react"; const Card = (props: { avatar: ImageProps; title: string; body: string; imageBackground: ImageProps; }) => { const { avatar, title, body, imageBackground } = props; return ( <View style={styles.cardContainer}> <ImageBackground source={imageBackground} style={styles.BackImage} resizeMode="cover" > <View style={styles.cardContent}> <Image style={styles.avatar} source={avatar} /> <Text style={styles.cardTitle}>{title}</Text> </View> <Text style={styles.bodyText}>{body}</Text> </ImageBackground> </View> ); }; export default Card; const styles = StyleSheet.create({ cardContainer: { flexDirection: "row", alignItems: "center", width: "100%", marginTop: -9, }, cardContent: { margin: 8, padding: 10, justifyContent: "center", borderRadius: 10, width: "70%", flexDirection: "row", }, cardTitle: { fontWeight: "900", textAlign: "center", paddingBottom: 1, fontSize: 30, fontStyle: "italic", color: "yellow", paddingTop: 20, paddingLeft: 25, textShadowColor: "black", textShadowRadius: 30, textShadowOffset: { width: 2, height: 2, }, }, avatar: { height: 90, width: 90, borderRadius: 100, borderColor: "yellow", borderWidth: 2, }, BackImage: { padding: 15, width: 400, }, bodyText: { color: "white", fontWeight: "700", textAlign: "center", paddingLeft: 30, paddingRight: 30, textShadowColor: "black", textShadowRadius: 5, textShadowOffset: { width: 2, height: 2, }, }, });
// // Copyright Aliaksei Levin ([email protected]), Arseny Smirnov ([email protected]) 2014-2024 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include "td/utils/common.h" #include "td/utils/format.h" #include "td/utils/HashTableUtils.h" #include "td/utils/StringBuilder.h" #include <type_traits> namespace td { namespace mtproto { class MessageId { uint64 message_id_ = 0; public: MessageId() = default; explicit constexpr MessageId(uint64 message_id) : message_id_(message_id) { } template <class T, typename = std::enable_if_t<std::is_convertible<T, int64>::value>> MessageId(T message_id) = delete; uint64 get() const { return message_id_; } bool operator==(const MessageId &other) const { return message_id_ == other.message_id_; } bool operator!=(const MessageId &other) const { return message_id_ != other.message_id_; } friend bool operator<(const MessageId &lhs, const MessageId &rhs) { return lhs.get() < rhs.get(); } friend bool operator>(const MessageId &lhs, const MessageId &rhs) { return lhs.get() > rhs.get(); } friend bool operator<=(const MessageId &lhs, const MessageId &rhs) { return lhs.get() <= rhs.get(); } friend bool operator>=(const MessageId &lhs, const MessageId &rhs) { return lhs.get() >= rhs.get(); } }; struct MessageIdHash { uint32 operator()(MessageId message_id) const { return Hash<uint64>()(message_id.get()); } }; inline StringBuilder &operator<<(StringBuilder &string_builder, MessageId message_id) { return string_builder << "message " << format::as_hex(message_id.get()); } } // namespace mtproto } // namespace td
<?php namespace App\Http\Controllers\CMS; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Auth; use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use Session; class PermissionController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']); // isAdmin 中介軟體讓具備指定許可權的用戶才能訪問該資源 } /** * 顯示許可權清單 * * @return \Illuminate\Http\Response */ public function index() { $permissions = Permission::where('name', '<>', 'Administer roles & permissions')->get();// 獲取所有權限 $page_title = '權限管理'; return view('cms.permissions.index', compact('page_title', 'permissions')); } /** * 顯示創建許可權表單 * * @return \Illuminate\Http\Response */ public function create() { $roles = Role::get(); // 獲取所有角色 $page_title = '新增權限資料'; return view('cms.permissions.create', compact('page_title', 'roles')); } /** * 保存新創建的許可權 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'name'=>'required|max:40', ]); $name = $request['name']; $permission = new Permission(); $permission->name = $name; $roles = $request['roles']; $permission->save(); if (!empty($request['roles'])) { // 如果選擇了角色 foreach ($roles as $role) { $r = Role::where('id', '=', $role)->firstOrFail(); // 將輸入角色和資料庫記錄進行匹配 $permission = Permission::where('name', '=', $name)->first(); // 將輸入許可權與資料庫記錄進行匹配 $r->givePermissionTo($permission); } } return redirect()->route('cms.permissions.index') ->with('flash_message', 'Permission'. $permission->name.' added!'); } /** * 顯示給定許可權 * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return redirect('permissions'); } /** * 顯示編輯許可權表單 * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $permission = Permission::findOrFail($id); $page_title = '編輯權限資料'; return view('cms.permissions.edit', compact('page_title', 'permission')); } /** * 更新指定許可權 * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $permission = Permission::findOrFail($id); $this->validate($request, [ 'name'=>'required|max:40', ]); $input = $request->all(); $permission->fill($input)->save(); return redirect()->route('cms.permissions.index') ->with('flash_message', 'Permission'. $permission->name.' updated!'); } /** * 刪除給定許可權 * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $permission = Permission::findOrFail($id); // 讓特定許可權無法刪除 if ($permission->name == "Administer roles & permissions") { return redirect()->route('cms.permissions.index') ->with('flash_message', 'Cannot delete this Permission!'); } $permission->delete(); if ($permission) { return json_encode(['result' => '01', 'message' => 'success']); } else { return json_encode(['result' => '00', 'message' => 'fail']); } // return redirect()->route('cms.permissions.index') // ->with('flash_message', // 'Permission deleted!'); } }
import React from "react"; import Snackbar from "@mui/material/Snackbar"; import MuiAlert from "@mui/material/Alert"; import Slide from "@mui/material/Slide"; import { useDispatch, useSelector } from "react-redux"; import { snackbarNotificationClose } from "../../redux/snackbar.action"; // import { snackbarNotificationClose } from ""; // CONSTANT VALUES: severity: "success" | "info" | "warning" | "error" only const Alert = React.forwardRef(function Alert(props, ref) { return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />; }); function TransitionUp(props) { return <Slide {...props} direction="up" />; } /** * @description: This function is used show some information in the UI to inform something to the user. * @returns: JSX Component to show to the user */ export const SnackbarNotification = () => { const snackbarNotificationDetails = useSelector( (state) => state.snackbarNotification ); const { isOpen, notificationType, notificationMessage } = snackbarNotificationDetails; const dispatch = useDispatch(); const handleClose = () => { dispatch(snackbarNotificationClose()); }; return isOpen ? ( <Snackbar open={isOpen} autoHideDuration={3000} TransitionComponent={TransitionUp} onClose={handleClose} > <Alert onClose={handleClose} severity={notificationType} sx={{ width: "100%" }} > {notificationMessage} </Alert> </Snackbar> ) : null; };
<template> <div class="container text-center"> <h1 class="text-center">Buy a top-level domain</h1> <div class="row mt-3"> <div class="col-md-8 offset-md-2"> <p class="text-center"> Punk Domains protocol allows anyone to create and own a top-level domain. As a TLD holder you have complete control over it and you earn revenue from selling domains. </p> <div class="d-flex justify-content-center domain-input-container mt-5"> <div class="input-group mb-3 domain-input input-group-lg"> <input v-model="chosenTldName" placeholder="enter top-level domain to buy" type="text" class="form-control text-center" > </div> </div> <p class="mt-3 text-center"> Domain price: {{this.parseValue(this.selectedPrice)}} {{getNetworkCurrency}} </p> <button class="btn btn-primary btn-lg mt-1 buy-button" @click="buyDomain" :disabled="waiting || tldBuyNotValid(chosenTldName).invalid"> <span v-if="waiting" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> <span v-if="!chosenTldName">Buy TLD</span> <span v-if="chosenTldName">Buy {{chosenTldName}}!</span> </button> <p class="error text-center mt-2" v-if="tldBuyNotValid(chosenTldName).invalid"> <small> <em>{{ tldBuyNotValid(chosenTldName).message }}</em> </small> </p> </div> </div> </div> </template> <script lang="ts"> import { ethers } from 'ethers'; import { displayEther, useEthers } from 'vue-dapp'; import { mapActions, mapGetters, mapMutations } from 'vuex'; import { useToast, TYPE } from "vue-toastification"; import WaitingToast from "../components/toasts/WaitingToast.vue"; import useDomainHelpers from "../hooks/useDomainHelpers"; export default { name: "TldBuy", data() { return { chosenTldName: null } }, methods: { parseValue(someVal) { if (someVal) { return ethers.utils.formatEther(someVal); } } }, setup() { const { address, isActivated, signer } = useEthers() const toast = useToast(); const { tldBuyNotValid } = useDomainHelpers(); return { address, isActivated, displayEther, signer, tldBuyNotValid, toast } }, } </script> <style scoped> p { text-align: justify; font-size: 1.1em; } h3 { margin-top: 35px; } </style>
/* * Copyright (c) 2022 Contour Labs, Inc. * SPDX-License-Identifier: AGPL-3.0-only */ import { ApiProperty } from "@nestjs/swagger"; import { IsEmail, IsNotEmpty, Matches, MaxLength, MinLength, } from "class-validator"; export class CreateForgotPasswordResetTokenDto { @ApiProperty({ description: "Email address" }) @IsNotEmpty() @IsEmail() email: string; } export class ValidateForgotPasswordResetTokenDto { @ApiProperty({ description: "Password reset token" }) @IsNotEmpty() token: string; @ApiProperty({ description: "New password for the user" }) @IsNotEmpty() @MinLength(8) @MaxLength(150) @Matches(/^(?=.*[A-Za-z])(?=.*\d)[a-zA-Z\d\w\W]{8,}$/, { message: "Password must contain at least one letter and one number", }) newPassword: string; }
{% extends 'base/base_jp.html' %} {% load static %} {% load humanize %} {% block main_area %} <script src="{% static 'libs/js/jquery-3.6.3.min.js' %}"></script> <div class="card mb-4"> <div class="card-body text-center"> <h4><i class="fa fa-shopping-cart mr-2"></i>ショッピングカート</h4> </div> </div> {% include 'base/error.html' %} <div class="row cart_data"> <div class="col-md-8 mt-4 mb-4"> {% if cart_list %} {% for my_cart in cart_list %} <div class="media product_data"> {% csrf_token %} <input type="hidden" value="{{my_cart.product.id}}" class="prod_id"> <a href="/shop/{{my_cart.product.id}}/"> <img src="{{ my_cart.product.signature_img.url }}" class="align-self-center mr-3" style="width:200px; height:200px"> <div class="media-body"> <h5 class="mt-0">{{my_cart.product.title}}</h5> <p>{{my_cart.product.brand}}</p> </a> <br /> <div class="mt-5"> <br /> <button class="btn btn-secondary btn-minus" id="decrease"> <i class="fa fa-minus"></i> </button> <input type="text" style="width: 3rem; border: none;" name="quantity" class="qty-input text-center" value="{{my_cart.product_qty}}"> <button class="btn btn-secondary btn-plus" id="increase"> <i class="fa fa-plus"></i> </button> <button class="btn btn-dark ml-3 btn-remove" style="float: right; color:#fff;"><i class="fa fa-trash"></i></button> <span class="sub_total-{{my_cart.product.id}}" style="float: right; margin-top: 7px; color: black;">¥{{my_cart.sub_total | intcomma}}</span> </div> </div> </div> <hr /> {% endfor %} <!-- 페이징 --> <ul class="pagination justify-content-center mt-5"> <!-- 이전 페이지 --> {% if cart_list.has_previous %}<!-- 이전 페이지 있음 --> <li class="page-item"> <a class="page-link" href="?page={{ cart_list.previous_page_number }}">前のページ </a> </li> {% else %}<!-- 이전 페이지 없음 --> <li class="page-item disabled"> <a class="page-link" tabindex="-1" aria-disabled="true" href="#">前のページ </a> </li> {% endif %} <!-- 페이지 리스트 --> {% for page_number in cart_list.paginator.page_range %} <!-- 현재 페이지를 기준으로 좌우 5개씩 보이도록 처리 --> {% if page_number >= cart_list.number|add:-5 and page_number <= cart_list.number|add:5 %} {% if page_number == cart_list.number %}<!-- 현재 페이지 번호와 같음 --> <li class="page-item active" aria-current="page"> <a class="page-link" href="/shop/cart_list?page={{ page_number }}">{{ page_number }}</a> </li> {% else %}<!-- 현재 페이지 번호와 다름 --> <li class="page-item"> <a class="page-link" href="/shop/cart_list?page={{ page_number }}">{{ page_number }}</a> </li> {% endif %} {% endif %} {% endfor %} <!-- 다음 페이지 --> {% if cart_list.has_next %}<!-- 다음 페이지 있음 --> <li class="page-item"> <a class="page-link" href="/shop/cart_list?page={{ cart_list.next_page_number }}">次のページ</a> </li> {% else %}<!-- 다음 페이지 없음 --> <li class="page-item disabled"> <a class="page-link" tabindex="-1" aria-disabled="true" href="#">次のページ</a> </li> {% endif %} </ul> <!--// 페이징 --> </div> <div class="col-md-4"> {% if cart_list %} <div class="card text-center"> <div class="card-header font-weight-bold"> 決済商品 <small class="text-muted">合計 {{cart_count}}けん</small> </div> <div class="card-body"> <p class="card-text text-left">小計<span class="total-price" style="float: right;">¥{{ total_cart | intcomma}}</span></p> <p class="card-text text-left">割引 <span class="sale-price" style="color: #37B6FF; float: right; margin-left: 10px;">-¥{{sale_price | intcomma}}</span> <span style="color: red; float: right;">15% SAVE</span> </p> <hr /> <p class="card-text text-left font-weight-bold">商品合計<span class="calculate" style="float: right;">¥{{ cart_sum | intcomma}}</span></p> </div> <div class="card-footer text-dark"> <a href="#" class="btn btn-primary" style="width: 320px;">ご注文手続きへ</a> </div> </div> {% endif %} </div> {% else %} <div class="card mb-5" style="width: 70rem;"> <div class="card-body"> <h5 class="card-title">ショッピングカート</h5> <h6 class="card-subtitle mb-2 text-muted"></h6> <br /> <p class="card-text">カートに商品は入っていません。</p> <a href="{% url 'shop:shop_list' %}" class="btn btn-primary">ショッピングを続ける。</a> </div> </div> {% endif %} </div> </div> <script> $(document).ready(function() { $('.btn-minus').click(function(e) { e.preventDefault(); var inc_value = $(this).closest('.product_data').find('.qty-input').val(); var value = parseInt(inc_value, 10); value = isNaN(value) ? 0: value; if(value > 1) { value--; $(this).closest('.product_data').find('.qty-input').val(value); } }); $('.btn-plus').click(function(e) { e.preventDefault(); var inc_value = $(this).closest('.product_data').find('.qty-input').val(); var value = parseInt(inc_value, 10); value = isNaN(value) ? 0: value; if(value < 10) { value++; $(this).closest('.product_data').find('.qty-input').val(value); } }); }); //숫자 가격 표시 함수 function priceToString(price) { return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } //plusBtn $('.btn-plus').click(function (e) { e.preventDefault(); var product_id = $(this).closest('.product_data').find('.prod_id').val(); var product_qty = $(this).closest('.product_data').find('.qty-input').val(); var token = $('input[name=csrfmiddlewaretoken]').val() $.ajax({ method: "POST", url: '{% url 'shop:plus_cart' %}', dataType: 'JSON', data: { 'product_id':product_id, 'product_qty':product_qty, csrfmiddlewaretoken: token }, success: function(response) { var sub_total = priceToString(response.prod_price); var total_price = priceToString(response.total_price); var sale_price = priceToString(response.sale_price); var calculate_price = priceToString(response.calculate); $('.sub_total-' + product_id).text('¥' + sub_total) $('.total-price').text('¥' + total_price) $('.sale-price').text( '-' + '¥' + sale_price) $('.calculate').text('¥' + calculate_price) } }) }) //minusBtn $('.btn-minus').click(function (e) { e.preventDefault(); var product_id = $(this).closest('.product_data').find('.prod_id').val(); var product_qty = $(this).closest('.product_data').find('.qty-input').val(); var token = $('input[name=csrfmiddlewaretoken]').val() $.ajax({ method: "POST", url: '{% url 'shop:minus_cart' %}', dataType: 'JSON', data: { 'product_id':product_id, 'product_qty':product_qty, csrfmiddlewaretoken: token }, success: function(response) { var sub_total = priceToString(response.prod_price); var total_price = priceToString(response.total_price); var sale_price = priceToString(response.sale_price); var calculate_price = priceToString(response.calculate); $('.sub_total-' + product_id).text('¥' + sub_total) $('.total-price').text('¥' + total_price) $('.sale-price').text( '-' + '¥' + sale_price) $('.calculate').text('¥' + calculate_price) } }) }) //removeBtn $('.btn-remove').click(function (e) { e.preventDefault(); var product_id = $(this).closest('.product_data').find('.prod_id').val(); var token = $('input[name=csrfmiddlewaretoken]').val() $.ajax({ method: "POST", url: '{% url 'shop:delete_cart' %}', dataType: 'JSON', data: { 'product_id':product_id, csrfmiddlewaretoken: token }, success: function(response) { location.reload(); } }) }) </script> {% endblock %}