text
stringlengths
184
4.48M
// function without parameter and return // function print(){ // console.log("hello world"); // } // print() // // function with return value // function passMessage(){ // return "I am happy to learn web dev" // } // const message = passMessage() // console.log(message); // console.log(message.toUpperCase()); // const newMessage = message + " Enroll Today" // console.log(newMessage); // function with parameter function passMessage(coursename,EnrollMessage = "enroll karo harami"){ return "I am happy to learn "+ coursename + "from Pw Skills by Chirag Goyal" + EnrollMessage } // console.log(passMessage('full stack development',"enroll today")); // console.log(passMessage('web development',"enroll tomorrow")); // console.log(passMessage('front development')); // console.log(passMessage('Backend development')); // function with multiple parameter // function sum(a,b){ // return a+b; // } // let total = sum(2,2) // console.log(total); // function with unlimited parameter function sumOfAllparameter(){ let sum = 0 for (let i = 0; i < arguments.length; i++) { sum = sum + arguments[i]; } return sum } const total = sumOfAllparameter(1,2,3,4,5,6,7) console.log(total); // Arrow function // const square1 = (x)=> x*x // console.log(square1(2)); // console.log(square1(3)); // let square2 = (x,y) => x+y // console.log(square2(2,3)); // let square3 = (x) => { // console.log("input value :-",x); // return x*x // } // console.log(square3(3)); // Anonymous function // const getFullName = function (firstname,lastname) { // return firstname+" "+lastname // } // console.log(getFullName("hassan","ashraf")); // immediately invoked function (function(x) { console.log(x*x); })(5); // // function expressions let sum = function (x,y){ return x+y } const total1 = sum; // sum ko call nhi kiya , sum reference total ko dediya console.log(total1(3,9));
<template> <div class="wrapper"> <form> <div class="containerr"> <h2 id="error">{{ message }}</h2> <h1>Register</h1> <p>Please fill in this form to create an account.</p> <label for="fstname"><b>First Name</b></label ><br /> <input type="text" id="fstname" v-model="firstName" name="fstname" placeholder="Enter First Name" required /><br /> <label for="lstname"><b>Last Name</b></label ><br /> <input type="text" v-model="lastName" id="lstname" placeholder="Enter Last Name" required /><br /> <label for="uname"><b>Username</b></label ><br /> <input type="text" v-model="username" id="uname" placeholder="Enter Username" required /><br /> <label for="email"><b>Email</b></label ><br /> <input type="text" v-model="email" placeholder="Enter Email" name="email" id="email" required /><br /> <label for="psw"><b>Password</b></label ><br /> <input type="password" v-model="password" placeholder="Enter Password" name="psw" id="psw" required /><br /> <br /> <p> By creating an account you agree to our <a href="#">Terms & Privacy</a>. </p> <h2 id="success"></h2> <button @click.prevent="register()" class="registerbtn"> Register </button> <div class="container signin"> <p> Already have an account? <router-link to="/login">Sign in</router-link>. </p> </div> </div> </form> </div> </template> <script> export default { name: "RegisterPage", data() { return { firstName: "", lastName: "", username: "", email: "", password: "", message: "", }; }, methods: { register() { let h2 = document.getElementById("error"); if ( this.firstName === "" || this.lastName === "" || this.username === "" || this.email === "" || this.password === "" ) { this.message = "Please fill out all the fields"; h2.style.color = "red"; } else { h2.style.color = "green"; this.message = "Registration was successful. Redirecting to login page now."; localStorage.setItem(this.username, this.password); let user = { loginStatus: false, firstname: this.firstName, lastname: this.lastName, username: this.username, email: this.email, password: this.password, }; this.$store.commit("addUser", user); setTimeout(() => this.$router.push({ name: "login" }), 2500); } }, }, }; </script> <style scoped> * { box-sizing: border-box; } /* Add padding to containers */ .containerr { padding: 16px; color: black; background-color: rgba(180, 180, 180, 0.6); border-radius: 10px; margin-left: 20%; margin-right: 20%; } label { color: black; } /* Full-width input fields */ input[type="text"], input[type="password"] { padding: 15px; margin: 5px 0 22px 0; display: inline-block; border: none; background: #f1f1f1; } input[type="text"]:focus, input[type="password"]:focus { background-color: #ddd; outline: none; } /* Overwrite default styles of hr */ hr { border: 1px solid #f1f1f1; margin-bottom: 25px; } /* Set a style for the submit/register button */ .registerbtn { background-color: #04aa6d; color: white; padding: 16px 20px; margin: 8px 0; border: none; cursor: pointer; opacity: 0.9; border-radius: 15px; } .registerbtn:hover { opacity: 1; } /* Add a blue text color to links */ a { color: blue; } /* Set a grey background color and center the text of the "sign in" section */ .signin { text-align: center; } </style>
package work.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Consumer; /** * @author 30391 */ public class StreamTest { public static void main(String[] args) { List<String> name = new ArrayList<>(); Collections.addAll(name, "张三丰", "王思聪", "张飞", "刘晓敏", "张靓颖"); System.out.println("-------1------"); name.forEach(new Consumer<String>() { @Override public void accept(String s) { System.out.println(s); } }); name.forEach(System.out::println); System.out.println("name = " + name); System.out.println("-------2------"); //2.2 name.stream().filter(s -> s.startsWith("张")) .forEach(System.out::println); System.out.println("-------3------"); //2.3 long count = name.stream() .filter(s -> s.startsWith("张")) .count(); System.out.println(count); } }
<!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" /> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" /> <title>Carousel Component</title> <style> /* SPACING SYSTEM (px) 2 / 4 / 8 / 12 / 16 / 24 / 32 / 48 / 64 / 80 / 96 / 128 FONT SIZE SYSTEM (px) 10 / 12 / 14 / 16 / 18 / 20 / 24 / 30 / 36 / 44 / 52 / 62 / 74 / 86 / 98 */ * { margin: 0; padding: 0; box-sizing: border-box; } /* MAIN COLOR: #087f5b GREY COLOR - Text: #343a40 */ /* ------------------------ */ /* GENERAL STYLES - SAME AS SAYING REUSABLE ONES */ /* ------------------------ */ body { font-family: "Inter", sans-serif; color: #343a40; line-height: 1; } /* Pagination component */ .buttons { /* background-color: #087f5b; */ width: 600px; height: 100px; display: flex; justify-content: center; align-items: center; margin: 200px auto; gap: 24px; } .page-link { border: 1px solid #087f5b; /* border: none; */ color: #343a40; background-color: #fff; text-decoration: none; font-size: 18px; display: flex; width: 40px; height: 40px; /* padding:px; 16 */ justify-content: center; align-items: center; border-radius: 50%; cursor: pointer; } .btn-box { border: 1px solid #087f5b; background-color: #fff; width: 48px; height: 48px; border-radius: 50%; /* display: flex; justify-content: center; align-items: center; */ cursor: pointer; } .btn-icon { stroke: #087f5b; width: 24px; height: 24px; } .active-link { background-color: #087f5b; color: #fff; } .page-link:hover { background-color: #087f5b; color: #fff; } .btn-box:hover { background-color: #087f5b; } .btn-icon:hover { stroke: #fff; } </style> </head> <body> <div class="buttons"> <button class="btn-box"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="btn-icon" > <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" /> </svg> </button> <a href="#" class="page-link">1</a> <a href="#" class="page-link">2</a> <a href="#" class="page-link active-link">3</a> <a href="#" class="page-link">4</a> <a href="#" class="page-link">5</a> <a href="#" class="page-link">6</a> <span class="dots">...</span> <a href="#" class="page-link">23</a> <button class="btn-box"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="btn-icon" > <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /> </svg> </button> </div> </body> </html>
# My first postmortem ## __Outage Postmoterm: Database Replication Failure__ ### Issue Summary: - __Duration:__ July 29, 2023, 09:00 AM - Aug 04, 2023, 04:30 AM (UTC) - __Impact:__ Unavailability of critical services leading to a complete downtime of our application. 74% of users were unable to access the platform. - __Root Cause:__ Configuration mismatch and communication breakdown between primary and replica databases. ### Timeline: - __Issue Detected:__ July 29, 09:00 AM (UTC) - __Detection Method:__ Monitoring alert triggered due to a spike in latency on the database server. - __Actions Taken:__ Initial investigation focused on the application servers due to latency reports. Assumed potential application code bottlenecks. - __Misleading Investigation:__ Believed the issue was related to an ongoing server maintenance task. Invested time in assessing recent changes to application code. - __Escalation:__ Incident escalated to the database team when no code or server-related issues were found. - __Resolution:__ Aug 04, 04:30 AM (UTC). Identified configuration mismatch between primary and replica databases. Applied correct configurations and performed a manual synchronization. ### Root Cause and Resolution - __Root Cause:__ The issue was caused by a configuration mismatch between the primary and replica databases. The mismatch led to failed replication attempts and data divergence between the two databases. - __Resolution:__ To address the issue, we reconfigured the replica database to match the primary's configuration settings. After ensuring the settings were consistent, we manually synchronized the data from the primary database to the replica. This resolved the replication failure and brought the replica up-to-date. ## Corrective and Preventative Measures: ### Improvements/Fixes: - Strengthen monitoring: Enhance monitoring to detect configuration inconsistencies between critical components. - Documentation: Maintain up-to-date documentation for database configuration and replication processes. - Regular Testing: Implement regular testing of database failover and replication scenarios to identify issues beforehand. ### Tasks to Address the Issue: - Update Monitoring: Configure alerts for detecting database configuration inconsistencies and replication failures. - Automation: Develop scripts to automate the synchronization process between primary and replica databases. - Documentation: Revise and improve documentation for database configuration and replication procedures. - Training: Conduct training sessions for the operations team on identifying and addressing database replication issues. ## Conclusion The outage exposed the vulnerability of our database replication setup to configuration discrepancies. Prompt identification and collaboration across teams were crucial in restoring service and minimizing user impact. Going forward, we are committed to improving our monitoring capabilities, automation processes, and documentation practices to prevent such incidents. By addressing these corrective measures, we aim to enhance our system's resilience and provide a more stable experience for our users.
import { CommonModule } from '@angular/common'; import { Component, inject } from '@angular/core'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { Observable, catchError, debounceTime, distinctUntilChanged, filter, of, switchMap, tap } from 'rxjs'; import { FlightService } from '../../../booking/flight/logic/data-access/flight.service'; import { Flight } from '../../../booking/flight/logic/model/flight'; @Component({ selector: 'app-flight-typeahead', standalone: true, imports: [ CommonModule, ReactiveFormsModule ], templateUrl: './departure.component.html' }) export class FlightTypeaheadComponent { private flightService = inject(FlightService); control = new FormControl('', { nonNullable: true }); flights$ = this.initFlightsStream(); loading = false; initFlightsStream(): Observable<Flight[]> { return this.control.valueChanges.pipe( filter(airport => airport.length > 2), debounceTime(300), distinctUntilChanged(), tap(() => this.loading = true), switchMap(airport => this.load(airport)), tap(() => this.loading = false) ) } load(airport: string): Observable<Flight[]> { return this.flightService.find(airport, '').pipe( catchError(() => of([])) ); } }
<template> <div class="submit-form"> <div v-if="!submitted"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" required v-model="link.title" name="title" /> </div> <div class="form-group"> <label for="source">Source</label> <input class="form-control" id="source" required v-model="link.source" name="source" /> </div> <button @click="saveLink" class="btn btn-success">Submit</button> </div> <div v-else> <h4>You submitted successfully!</h4> <button class="btn btn-success" @click="newLink">Add</button> </div> </div> </template> <script> import LinkDataService from "../services/LinkService"; export default { name: "add-link", data() { return { link: { id: null, title: "", source: "" }, submitted: false }; }, methods: { saveLink() { var data = { title: this.link.title, source: this.link.source }; LinkDataService.create(data) .then(response => { this.link.id = response.data.id; console.log(response.data); this.submitted = true; }) .catch(e => { console.log(e); }); }, newLink() { this.submitted = false; this.link = {}; } } }; </script> <style> .submit-form { max-width: 300px; margin: auto; } </style>
import React, { useState } from 'react'; import { useDispatch } from 'react-redux'; import { useNavigate } from 'react-router-dom'; import { GoogleLogin } from 'react-google-login'; import { Form, Input, Button } from 'antd'; import 'antd/dist/antd.css'; import { signup, googleSignup } from '../actions/auth'; import { GoogleOutlined } from '@ant-design/icons'; const initialState = { firstName: '', lastName: '', email: '', password: '' }; const SignUp = () => { const [form, setForm] = useState(initialState); const dispatch = useDispatch(); const navigate = useNavigate(); const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { dispatch(signup(form, navigate)); }; const googleSuccess = async (res: any) => { const result = res?.profileObj; try { dispatch(googleSignup(result,navigate)); } catch (error) { console.log(error); } }; const googleError = () => alert('Google Sign In was unsuccessful. Try again later'); const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => setForm({ ...form, [e.target.name]: e.target.value }); return ( <Form name="basic" labelCol={{ span: 8, }} wrapperCol={{ span: 16, }} initialValues={{ remember: true, }} onFinish={handleSubmit} autoComplete="off" > <Form.Item label="Email" name="email" rules={[ { required: true, message: 'Please input your first name!', }, ]} > <Input name="email" onChange={handleChange} /> </Form.Item> <Form.Item label="First name" name="firstName" rules={[ { required: true, message: 'Please input your first name!', }, ]} > <Input name="firstName" onChange={handleChange} /> </Form.Item> <Form.Item label="Last name" name="lastName" rules={[ { required: true, message: 'Please input your last name!', }, ]} > <Input name="lastName" onChange={handleChange} /> </Form.Item> <Form.Item label="Password" name="password" rules={[ { required: true, message: 'Please input your password!', }, ]} > <Input.Password name={"password"} onChange={handleChange} /> </Form.Item> <Form.Item wrapperCol={{ offset: 8, span: 16, }} > <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> <GoogleLogin clientId="998866258630-a7gvc4kb657bh86gujbrr9domlquh4h4.apps.googleusercontent.com" render={(renderProps) => ( <Button color="primary" style={{marginLeft:155}} onClick={renderProps.onClick} disabled={renderProps.disabled} icon={<GoogleOutlined />} > Sign up with Google </Button> )} onSuccess={googleSuccess} onFailure={googleError} cookiePolicy="single_host_origin" /> </Form> ); }; export default SignUp;
<template> <jet-action-section> <template #content> <jet-dialog-modal :show="isModalActive" @close="closeModal"> <template #title> <div class="flex justify-between"> {{title}} <slot name="title"> </slot> </div> </template> <template #content> <slot name="content"/> </template> <template #footer> <jet-secondary-button @click="closeModal"> Cancel </jet-secondary-button> <jet-button class="ml-3" :class="{ 'opacity-25': processing }" :disabled="processing" @click="method"> Save </jet-button> </template> </jet-dialog-modal> </template> </jet-action-section> </template> <script> import JetButton from '@/Jetstream/Button.vue' import JetActionSection from '@/Jetstream/ActionSection.vue' import JetDialogModal from '@/Jetstream/DialogModal.vue' import JetDangerButton from '@/Jetstream/DangerButton.vue' import JetSecondaryButton from '@/Jetstream/SecondaryButton.vue' export default { emits: ["closeModal", "store", "update"], props:{ isModalActive:Boolean, processing: Boolean, title: String, method: Function }, components: { JetDialogModal, JetActionSection, JetSecondaryButton, JetDangerButton, JetButton }, methods:{ closeModal(){ this.$emit('closeModal'); }, store(){ this.$emit('store'); }, update(){ this.$emit('update'); } } } </script>
package Controller; import Model.*; import View.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import java.awt.*; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class UserController { private String databaseFile = "competitordata.txt"; private CompetitorList competitorList = new CompetitorList(); private UserView view; private void addCompetitors() { //load staff data from file BufferedReader buff = null; try { buff = new BufferedReader(new FileReader("competitordata.txt")); String inputLine = buff.readLine(); //read first line while(inputLine != null){ processLine(inputLine); //read next line inputLine = buff.readLine(); } } catch(FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(1); } catch (IOException e) { e.printStackTrace(); System.exit(1); } finally { try{ buff.close(); } catch (IOException ioe) { //don't do anything } } } private void processLine(String inputLine) { // Split line into parts String values[] = inputLine.split(",(?![^\\[]*\\])"); // Ensure the case-insensitive match for CompetitorLevel CompetitorLevel level; try { // Trim the string to remove leading/trailing spaces level = CompetitorLevel.valueOf(values[3].trim().toUpperCase()); } catch (IllegalArgumentException e) { System.out.println("Invalid CompetitorLevel: " + values[3]); return; } // Extract other values int compNo = Integer.parseInt(values[0].trim()); Name name = new Name(values[1].trim()); String country = values[2].trim(); int age = Integer.parseInt(values[4].trim()); String email = values[5].trim(); double overallScore = Double.parseDouble(values[8].trim()); // Extract scores from the array excluding the last element String scoresString = values[6].trim(); // assuming scores start at index 6 scoresString = scoresString.substring(1, scoresString.length() - 1); // remove leading '[' and trailing ']' int[] scores = Arrays.stream(scoresString.split(",")) .map(String::trim) .mapToInt(Integer::parseInt) .toArray(); // Determine the category and create the appropriate competitor type Competitor competitor; if (values[values.length - 2].trim().equals("Boxing")) { competitor = new BoxingCompetitor(name, country, level, age, email, scores); } else if (values[values.length - 2].trim().equals("Cycling")) { competitor = new CyclingCompetitor(name, country, level, age, email, scores); } else { // Handle unknown category or provide appropriate fallback System.out.println("Unknown category: " + values[values.length - 1]); return; } competitor.setCompetitorNumber(compNo); competitor.setOverallScore(overallScore); // Add to the list competitorList.addDetails(competitor); } public UserController(UserView view){ this.view = view; addCompetitors(); this.view.viewTable(e -> { JFrame tableFrame = new JFrame("Competitors Table"); tableFrame.setSize(600, 400); // Get the list of competitors ArrayList<Competitor> competitors = competitorList.getCompetitors(); // Create a table model with column names String[] columnNames = {"Competitor Number", "Name", "Country", "Level", "Age", "Email", "Category", "Score", "Overall Score"}; DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0); // Populate the table model with competitor data for (Competitor competitor : competitors) { Object[] rowData = { competitor.getCompetitorNumber(), competitor.getName().getFullName(), competitor.getCountry(), competitor.getLevel(), competitor.getAge(), competitor.getEmail(), competitor.getCategory(), Arrays.toString(competitor.getScoreArray()), competitor.getOverallScore() }; tableModel.addRow(rowData); } // Create a JTable with the table model JTable table = new JTable(tableModel); // Enable sorting TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(tableModel); table.setRowSorter(sorter); JScrollPane scrollPane = new JScrollPane(table); tableFrame.add(scrollPane); // Add sorting options JComboBox<String> sortingOptions = new JComboBox<>(new String[]{ "Competitor Number Asc", "Competitor Number Desc", "Name Asc", "Name Desc", "Overall Score Asc", "Overall Score Desc" }); sortingOptions.addActionListener(event -> { String selectedOption = (String) sortingOptions.getSelectedItem(); switch (selectedOption) { case "Competitor Number Asc": sorter.setRowFilter(null); sorter.setSortKeys(Collections.singletonList(new RowSorter.SortKey(0, SortOrder.ASCENDING))); break; case "Competitor Number Desc": sorter.setRowFilter(null); sorter.setSortKeys(Collections.singletonList(new RowSorter.SortKey(0, SortOrder.DESCENDING))); break; case "Name Asc": sorter.setRowFilter(null); sorter.setSortKeys(Collections.singletonList(new RowSorter.SortKey(1, SortOrder.ASCENDING))); break; case "Name Desc": sorter.setRowFilter(null); sorter.setSortKeys(Collections.singletonList(new RowSorter.SortKey(1, SortOrder.DESCENDING))); break; case "Overall Score Asc": sorter.setRowFilter(null); sorter.setSortKeys(Collections.singletonList(new RowSorter.SortKey(8, SortOrder.ASCENDING))); break; case "Overall Score Desc": sorter.setRowFilter(null); sorter.setSortKeys(Collections.singletonList(new RowSorter.SortKey(8, SortOrder.DESCENDING))); break; default: sorter.setRowFilter(null); } }); tableFrame.add(sortingOptions, BorderLayout.NORTH); tableFrame.setVisible(true); }); this.view.registerCompetitor(e -> { new RegisterView(competitorList); }); this.view.viewScores(e -> { new ScoreView(competitorList); }); this.view.viewAttributes(e -> { new AttributesView(competitorList); }); this.view.viewShortDetails(e -> { new ShortDetailsView(competitorList); }); this.view.viewFullDetails(e -> { new FullDetailsView(competitorList); }); this.view.editDetails(e -> { new EditView(competitorList); }); this.view.removeCompetitor(e -> { new RemoveView(competitorList); }); this.view.close(e -> { competitorList.generateFinalReport("final_report.txt"); System.exit(0); }); } }
import type { Photo } from "@/utils/types"; import Image from "next/image"; import { useState } from 'react'; import RequestEditModal from "./RequestEditModal"; import EditModal from "./EditModal"; export default function ImageCard({ photo }: { photo: Photo }) { const { urls, alt_description } = photo; const [isRequestEditModalOpen, setRequestEditModalOpen] = useState(false); const [isEditModalOpen, setEditModalOpen] = useState(false); const [imageUrl, setImageUrl] = useState(urls.regular); const handleEditModalClose = (url?: string) => { setEditModalOpen(false); if (url) { setImageUrl(url); } }; return ( <div className="flex flex-col px-2 mb-10 block w-1/5"> <div className="after:content group relative after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:shadow-highlight"> <Image alt={alt_description ?? ''} className="transform rounded-lg brightness-90 transition will-change-auto group-hover:brightness-110" style={{ transform: 'translate3d(0, 0, 0)' }} src={imageUrl} width={480} height={320} sizes="(max-width: 640px) 100vw, (max-width: 1280px) 50vw, (max-width: 1536px) 33vw, 25vw" /> </div> <div className="flex mt-3 gap-5 mx-3"> <button className="simple-button px-2 py-1 flex-1" onClick={() => setEditModalOpen(true)}>Edit</button> <button className="simple-button px-2 py-1 flex-1" onClick={() => setRequestEditModalOpen(true)}>Request Edit</button> </div> <RequestEditModal isOpen={isRequestEditModalOpen} setOpen={setRequestEditModalOpen} url={imageUrl}/> <EditModal isOpen={isEditModalOpen} onClose={handleEditModalClose} url={imageUrl}/> </div> ); }
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require '../vendor/phpmailer/phpmailer/src/Exception.php'; require '../vendor/phpmailer/phpmailer/src/PHPMailer.php'; require '../vendor/phpmailer/phpmailer/src/SMTP.php'; function sendemail($email, $name) { try { $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'mail.direinttechexpo.com'; $mail->SMTPAuth = true; $mail->Username = '[email protected]'; $mail->Password = 'Dire@Expo_2024'; $mail->SMTPSecure = 'ssl'; $mail->Port = 465; $mail->setFrom('[email protected]'); $mail->addAddress($email); $mail->isHTML(true); $mail->Subject = 'Congratulations!'.$name .' has been approved for ICT Expo'; $email_template = " <html> <head> <style> /* Put your CSS styles here */ body { font-family: Arial, sans-serif; background-color: #f1f1f1; padding: 20px; max-width: 600px; margin: 0 auto; } h2 { color: #333333; margin-top: 0; margin-bottom: 20px; } p { color: #555555; font-size: 16px; line-height: 1.5; margin-bottom: 20px; } a { color: #ffffff; text-decoration: none; } .button { display: inline-block; background-color: #4CAF50; color: #ffffff; text-decoration: none; padding: 10px 20px; border-radius: 5px; transition: background-color 0.3s ease; } .button:hover { background-color: #45a049; } .logo { display: block; margin: 0 auto; max-width: 200px; height: auto; margin-bottom: 20px; } </style> </head> <body> <img src='company_logo.png' alt='Company Logo' class='logo'> <h2>Congratulations! Your company has been approved for ICT Expo</h2> <p> Thank you for registering with ICT Expo. We are pleased to inform you that your company's exhibition application has been approved. Your booth has been confirmed for the upcoming event. </p> <p> For further assistance or any inquiries, please do not hesitate to contact us using the following information: </p> <p> Email: <a href='mailto:[email protected]'>[email protected]</a><br> Phone: +1 123-456-7890 </p> <p> We look forward to seeing you at the event! </p> <p>Best regards,<br>ICT Expo Team</p> </body> </html> "; $mail->Body = $email_template; // Enable debugging mode $mail->SMTPDebug = 2; if ($mail->send()) { echo "<script> window.location.href = 'approve.php';alert('Message has been sent.');</script>"; } else { throw new Exception("Message could not be sent. Mailer Error: {$mail->ErrorInfo}"); } } catch (Exception $e) { echo "<script>alert('Message could not be sent. Mailer Error: " . $e->getMessage() . "');</script>"; } } if (isset($_GET['id'])) { $id = $_GET['id']; include_once('dbcon.php'); $sql = "UPDATE exhibitors SET approve = 1 WHERE id = '$id'"; if ($mysqli->query($sql) === TRUE) { // Retrieve the exhibitor's email and company name from the database $emailResult = $mysqli->query("SELECT email, company_name FROM exhibitors WHERE id = '$id'"); if ($emailResult && $emailResult->num_rows > 0) { $emailRow = $emailResult->fetch_assoc(); $exhibitorEmail = $emailRow['email']; $exhibitorName = $emailRow['company_name']; // Call the sendemail() function to send the verification email sendemail($exhibitorEmail, $exhibitorName); echo "<script>alert('Record updated successfully.'); window.location.href = 'approve.php';</script>"; } else { echo "<script>alert('Email not found in the database.'); window.location.href = 'approve.php';</script>"; } } else { echo "<script>alert('Error updating record: " . $mysqli->error . "'); window.location.href = 'approve.php';</script>"; } // Close the database connection $mysqli->close(); } else { echo "<script>alert('No ID provided.'); window.location.href = 'approve.php';</script>"; }
import Head from 'next/head' import { useEffect, useState } from 'react' import SignupLayout from '../../components/layouts/SignupLayout' import ChooseMoviesView from '../../components/simpleSetup/ChooseMoviesView' import { getOptions } from '../../components/APIHelpers/toFetchDataObjects' import { fetchedContentType, fetchedMoviesPropsData } from '../../components/helpers/types' const ChooseMoviesPage: React.FC<fetchedContentType> = ({ moviesData, seriesData }) => { const [fetchedContentObjects, setfetchedContentObjects] = useState<fetchedMoviesPropsData[]>([]) useEffect(() => { let linksArray: fetchedMoviesPropsData[] = [] for (const key in moviesData.results) { if (moviesData.results.hasOwnProperty(key)) { const movie = moviesData.results[key] const posterPath = movie.poster_path const movieTitle = movie.title linksArray.push({ posterPath, movieTitle }) } } for (const key in seriesData.results) { if (seriesData.results.hasOwnProperty(key)) { const series = seriesData.results[key] const posterPath = series.poster_path const movieTitle = series.name linksArray.push({ posterPath, movieTitle }) } } setfetchedContentObjects(linksArray) }, []) return ( <> <Head> <title>Choose Movie | Netflix</title> <meta name="description" content="Choose your favorite movies and series" /> </Head> <SignupLayout> <ChooseMoviesView fetchedContent={fetchedContentObjects} /> </SignupLayout> </> ) } export default ChooseMoviesPage export async function getStaticProps() { try { const moviesResponse = await fetch( 'https://api.themoviedb.org/3/movie/top_rated?language=en-US&page=1', getOptions, ) const moviesData = await moviesResponse.json() const seriesResponse = await fetch( 'https://api.themoviedb.org/3/tv/top_rated?language=en-US&page=1', getOptions, ) const seriesData = await seriesResponse.json() return { props: { moviesData, seriesData, }, } } catch (error) { return { props: { moviesData: error, seriesData: error, }, } } }
from app import db import celery import pptx from pptx import Presentation import fitz from PIL import Image from celery import shared_task from celery.utils.log import get_task_logger import io logger = get_task_logger(__name__) def extract_text_from_pptx(pptx_path): presentation = Presentation(pptx_path) text = [] for slide_number, slide in enumerate(presentation.slides): for shape in slide.shapes: if hasattr(shape, 'text'): text.append(shape.text) text = " ".join(text) return text def extract_text_from_pdf(pdf_path): text = '' # Open the PDF file with fitz.open(pdf_path) as pdf_document: # Iterate through each page for page_number in range(pdf_document.page_count): # Get the page page = pdf_document.load_page(page_number) # Extract text from the page text += page.get_text() return text def extract_text_from_text(text_path): text = '' with open(text_path) as fin: text = ''.join(fin.readlines()) return text @shared_task() def scrape(file_id): media = db.media_sources.find_one({'id': file_id}) if media['scraped']: return match media['type']: case 'application/pdf': pdf_text = extract_text_from_pdf(media['location']) db.media_sources.update_one({'id': file_id}, {'$set': {'scraped': True, 'scraped_text': pdf_text}}) case 'application-vnd.openxmlformats-officedocument.presentationml.presentation': pptx_text = extract_text_from_pptx(media['location']) db.media_sources.update_one({'id': file_id}, {'$set': {'scraped': True, 'scraped_text': pptx_text}}) case 'plain/text': text_text = extract_text_from_text(media['location']) db.media_sources.update_one({'id': file_id}, {'$set': {'scraped': True, 'scraped_text': text_text}})
# 40. Combination Sum II ## 解題程式碼 ```javascript var combinationSum2 = function (candidates, target) { const result = []; candidates = candidates.sort((a, b) => a - b); const backTracking = (sum, path, index) => { if (sum > target) return; if (sum === target) { result.push([...path]); return; } for (let i = index; i < candidates.length; i++) { if (i !== index && candidates[i] === candidates[i - 1]) continue; path.push(candidates[i]); backTracking(sum + candidates[i], path, i + 1); path.pop(candidates[i]); } }; backTracking(0, [], 0); return result; }; ``` ## 解題思路、演算法 從 39 題再加點變化的題目,這題的 input candidates 會包含重複的元素,所以要先做排序,然後在子陣列碰到相同元素就 continue,去避免例如 : candidates = [1, 1, 2, 6, 7, 10],第一個 1 和各元素組合的情況例如 [1, 2, 6]、[1, 2, 7]、[1, 6] 和第二個 1 元素組合的情況重複。 這樣才不會把重複的 combination 加到最終結果中。 ![](https://upload.cc/i1/2024/04/26/rSBtef.png) ## 解法的時間、空間複雜度 時間複雜度: O(2^n) 空間複雜度: O(n) ## 參考資料 [Combination Sum II - Backtracking - Leetcode 40 - Python](https://youtu.be/rSA3t6BDDwg)
import axios from 'axios'; import {UsersResponseType} from '../redux/users-reducer'; import {ProfileType} from '../redux/profile-reducer'; const instance = axios.create({ withCredentials: true, baseURL: 'https://social-network.samuraijs.com/api/1.0/', headers: { 'API-KEY': 'eb07f558-5d2f-47f9-adac-eb8b66d5228c' } }); export const usersAPI = { getUsers(currentPage: number, pageSize: number) { return instance.get<UsersResponseType>(`users?page=${currentPage}&count=${pageSize}`) .then(response => response.data); }, follow(userId: number) { return instance.post(`follow/${userId}`) }, unfollow(userId: number) { return instance.delete(`follow/${userId}`) }, getProfile(userId: string) { return profileAPI.getProfile(userId) } } export const profileAPI = { getProfile(userId: string) { return instance.get<ProfileType>(`profile/` + userId) }, getStatus(userId: string) { return instance.get<string>(`profile/status/` + userId) }, updateStatus(status: string) { return instance.put(`profile/status`, {status}) } } export const authAPI = { me() { return instance.get(`auth/me`) }, login(email: string, password: string, rememberMe: boolean = false) { return instance.post(`auth/login`, {email, password, rememberMe}) }, logout() { return instance.delete(`auth/login`) } }
#include<bits/stdc++.h> #include<iostream> using namespace std; class Node{ public: bool flag; Node* links[26]; Node(){ // constructor to initialize nodes. flag = 0; for(int i = 0;i < 26;i++) links[i] = NULL; } }; class Trie{ public: Node* root; Trie(){ root = new Node(); } // function to insert the string in the trie data structure. void insert(string s){ Node* node = root; for(int i = 0;i < s.size();i++){ if(node->links[s[i] - 'a'] == NULL){ node->links[s[i] - 'a'] = new Node(); } node = node->links[s[i] - 'a']; } node->flag= 1; } // function to reverse the flag variable of the above Node class void reverseFlag(string s){ Node* node = root; for(int i = 0; i < s.size(); i++){ node = node->links[s[i] - 'a']; } node->flag=!(node->flag); } // function to find the string in trie data structure bool find(string s){ Node* node = root; for(int i = 0; i < s.size(); i++){ if(node->links[s[i] - 'a']==NULL) return 0; node = node->links[s[i] - 'a']; } return node->flag; } }; Trie trie; // function to check the given string is a compound word or not. bool compoundWord(string s) { vector<bool> dp(s.size()+1, 0); dp[0] = true; for(int i=1; i<=s.size(); i++){ for(int j=0; j<i; j++){ if(dp[j] && trie.find(s.substr(j, i-j))){ dp[i] = true; break; } } } return dp[s.size()]; } // function to find the Longest compound word and the Second longest compound word. void solve(vector<string>&v, int n){ string Longest_Compound_Word=""; string Second_Longest_Compound_Word=""; for(auto it:v) { trie.insert(it); } for(int i=0;i<n;i++){ string temp=v[i]; trie.reverseFlag(temp); if(compoundWord(temp) and temp.size()>Longest_Compound_Word.size()){ Longest_Compound_Word = temp; } trie.reverseFlag(temp); } for(int i=0;i<n;i++){ string temp=v[i]; if(temp==Longest_Compound_Word) { continue; } trie.reverseFlag(temp); if(compoundWord(temp) and temp.size()>Second_Longest_Compound_Word.size()){ Second_Longest_Compound_Word = temp; } trie.reverseFlag(temp); } cout << "Longest Compound Word: " << Longest_Compound_Word<<endl; cout << "Second Longest Compound Word: " << Second_Longest_Compound_Word; } int main(){ vector<string> v; //taking input from Input_01 file. ifstream inputFile("Input_01.txt"); if (!inputFile.is_open()) { cout << "Failed to open the file." << endl; return 1; } string line; auto start_time = chrono::high_resolution_clock::now(); while (getline(inputFile, line)) { v.push_back(line); } int n= v.size(); inputFile.close(); solve(v,n); auto end_time = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::milliseconds>(end_time - start_time); cout << "\nTime taken to process the file: " << duration.count() << " milliseconds" << endl; cout << endl; v.clear(); // taking input from Input_02 file. ifstream inputFile1("Input_02.txt"); if (!inputFile1.is_open()) { cerr << "Failed to open the file." << endl; return 1; } start_time = chrono::high_resolution_clock::now(); while (getline(inputFile1, line)) { v.push_back(line); } n= v.size(); inputFile1.close(); solve(v,n); end_time = chrono::high_resolution_clock::now(); duration = chrono::duration_cast<chrono::milliseconds>(end_time - start_time); cout << "\nTime taken to process the file: " << duration.count() << " milliseconds" << endl; return 0; }
from permuted_tree import merkelize, mk_branch, verify_branch, mk_multi_branch, verify_multi_branch from utils import get_power_cycle, get_pseudorandom_indices from poly_utils import PrimeField from fft import fft # Generate an FRI proof that the polynomial that has the specified # values at successive powers of the specified root of unity has a # degree lower than maxdeg_plus_1 # # We use maxdeg+1 instead of maxdeg because it's more mathematically # convenient in this case. def prove_low_degree(values, root_of_unity, maxdeg_plus_1, modulus, exclude_multiples_of=0, sample_indices=[]): f = PrimeField(modulus) # If the degree we are checking for is less than or equal to 32, # use the polynomial directly as a proof if maxdeg_plus_1 <= 16: return [[x.to_bytes(32, 'big') for x in values]] # Calculate the set of x coordinates xs = get_power_cycle(root_of_unity, modulus) assert len(values) == len(xs), "invalid root_of_unity or values" # Put the values into a Merkle tree. This is the root that the # proof will be checked against m = merkelize(values) # Select a pseudo-random x coordinate special_x = int.from_bytes(m[1], 'big') % modulus # Calculate the "column" at that x coordinate # (see https://vitalik.ca/general/2017/11/22/starks_part_2.html) # We calculate the column by Lagrange-interpolating each row, and not # directly from the polynomial, as this is more efficient quarter_len = len(xs)//4 x_polys = f.multi_interp_4( [[xs[i+quarter_len*j] for j in range(4)] for i in range(quarter_len)], [[values[i+quarter_len*j] for j in range(4)] for i in range(quarter_len)] ) column = [f.eval_quartic(p, special_x) for p in x_polys] m2 = merkelize(column) if(len(sample_indices) == 0): # Pseudo-randomly select y indices to sample sample_indices = get_pseudorandom_indices(m2[1], len(column), 16, exclude_multiples_of=exclude_multiples_of) else: # fold sample indices sample_indices = [y % len(column) for y in sample_indices] # Compute the positions for the values in the polynomial poly_positions = sum([[y + (len(xs) // 4) * j for j in range(4)] for y in sample_indices], []) # This component of the proof, including Merkle branches o = [m2[1], mk_multi_branch(m2, sample_indices), mk_multi_branch(m, poly_positions)] # Recurse... return [o] + prove_low_degree(column, f.exp(root_of_unity, 4), maxdeg_plus_1 // 4, modulus, exclude_multiples_of=exclude_multiples_of, sample_indices=sample_indices) # Verify an FRI proof def verify_low_degree_proof(merkle_root, root_of_unity, proof, maxdeg_plus_1, modulus, exclude_multiples_of=0): f = PrimeField(modulus) # Calculate which root of unity we're working with testval = root_of_unity roudeg = 1 while testval != 1: roudeg *= 2 testval = (testval * testval) % modulus # roudeg = size # Powers of the given root of unity 1, p, p**2, p**3 such that p**4 = 1 quartic_roots_of_unity = [1, f.exp(root_of_unity, roudeg // 4), f.exp(root_of_unity, roudeg // 2), f.exp(root_of_unity, roudeg * 3 // 4)] # Verify the recursive components of the proof sample_indices = [] for prf in proof[:-1]: root2, column_branches, poly_branches = prf # print('Verifying degree <= %d' % maxdeg_plus_1) # Calculate the pseudo-random x coordinate special_x = int.from_bytes(merkle_root, 'big') % modulus if (len(sample_indices) == 0): # Calculate the pseudo-randomly sampled y indices sample_indices = get_pseudorandom_indices(root2, roudeg // 4, 16, exclude_multiples_of=exclude_multiples_of) else: # fold sampled indices sample_indices = [y % (roudeg // 4) for y in sample_indices] # Compute the positions for the values in the polynomial poly_positions = sum([[y + (roudeg // 4) * j for j in range(4)] for y in sample_indices], []) # Verify Merkle branches column_values = verify_multi_branch(root2, sample_indices, column_branches) # print("column_values.len", len(column_values)) poly_values = verify_multi_branch(merkle_root, poly_positions, poly_branches) # For each y coordinate, get the x coordinates on the row, the values on # the row, and the value at that y from the column xcoords = [] rows = [] columnvals = [] for i, y in enumerate(sample_indices): # The x coordinates from the polynomial x1 = f.exp(root_of_unity, y) xcoords.append([(quartic_roots_of_unity[j] * x1) % modulus for j in range(4)]) # The values from the original polynomial row = [int.from_bytes(x, 'big') for x in poly_values[i*4: i*4+4]] columnvals.append(int.from_bytes(column_values[i], 'big')) # Verify for each selected y coordinate that the four points from the # polynomial and the one point from the column that are on that y # coordinate are on the same deg < 4 polynomial polys = f.multi_interp_4(xcoords, rows) for p, c in zip(polys, columnvals): assert f.eval_quartic(p, special_x) == c, "failed in low degree test" # Update constants to check the next proof merkle_root = root2 root_of_unity = f.exp(root_of_unity, 4) maxdeg_plus_1 //= 4 roudeg //= 4 # Verify the direct components of the proof data = [int.from_bytes(x, 'big') for x in proof[-1]] assert maxdeg_plus_1 <= 16, "the last verification should be less than 16 degree" # Check the Merkle root matches up mtree = merkelize(data) assert mtree[1] == merkle_root, "invalid merkle root" # Check the degree of the data powers = get_power_cycle(root_of_unity, modulus) if exclude_multiples_of: pts = [x for x in range(len(data)) if x % exclude_multiples_of] else: pts = range(len(data)) poly = f.lagrange_interp([powers[x] for x in pts[:maxdeg_plus_1]], [data[x] for x in pts[:maxdeg_plus_1]]) for x in pts[maxdeg_plus_1:]: assert f.eval_poly_at(poly, powers[x]) == data[x], "failed in low degree test" return True
from sys import stdin from collections import deque def bfs(graph, x, y, visited): n = len(graph) queue = deque() queue.append((x, y)) graph[x][y] = 0 visited[x][y] = True num_houses = 1 while queue: x, y = queue.popleft() for i in range(4): nx, ny = x + dx[i], y + dy[i] if 0 <= nx < n and 0 <= ny < n and graph[nx][ny] == 1 and not visited[nx][ny]: num_houses += 1 graph[nx][ny] = 0 visited[nx][ny] = True queue.append((nx, ny)) return num_houses try: n = int(stdin.readline()) graph = [list(map(int, input().strip())) for _ in range(n)] visited = [[False] * n for _ in range(n)] complexes = [] for i in range(n): for j in range(n): if graph[i][j] == 1 and not visited[i][j]: complexes.append(bfs(graph, i, j, visited)) complexes.sort() print(len(complexes)) for size in complexes: print(size) except Exception as e: print(f"An error occurred: {e}")
exports.run = async (_client, msg, args, _content, _command, Discord, config) => { //Check the permissions. if (!msg.member.hasPermission("MANAGE_MESSAGES")) { const notEnoughPermsMessage = new Discord.MessageEmbed() .setColor("#8b0000") .setTimestamp() .setFooter(`Denegado a ${msg.member.displayName}`) .setTitle("Error") .setDescription("No tienes permisos para hacer esto."); msg.channel.send({embed: notEnoughPermsMessage}); return; } //Store the mention of the member. const memberMention = msg.guild.member(msg.mentions.users.first() || msg.guild.members.cache.get(args[0])); //Check if there is a mention if (!memberMention) { const invalidMemberMessage = new Discord.MessageEmbed() .setColor("#8b0000") .setTimestamp() .setFooter(`Denegado a ${msg.member.displayName}`) .setTitle("Error") .setDescription("Menciona a un usuario válido."); msg.channel.send({embed: invalidMemberMessage}); return; } //Check if the member has the permission to punish. if (memberMention.hasPermission("MANAGE_MESSAGES")) { const canNotPunishMessage = new Discord.MessageEmbed() .setColor("#8b0000") .setTimestamp() .setFooter(`Denegado a ${msg.member.displayName}`) .setTitle("Error") .setDescription("No puedo silenciar a este usuario."); msg.channel.send({embed: canNotPunishMessage}); return; } //You can't punish your self. if (memberMention.id === msg.author.id) { const canNotPunishYouMessage = new Discord.MessageEmbed() .setColor("#8b0000") .setTimestamp() .setFooter(`Denegado a ${msg.member.displayName}`) .setTitle("Error") .setDescription("No puedes silenciarte a ti mismo."); msg.channel.send({embed: canNotPunishYouMessage}); return; } //Store the default server role, in this case is the "Jugador" role. const defaultRole = msg.guild.roles.cache.find((x) => x.name === '⁃ Jugador'); //Store the role that we want to use to mute in a variable. let mutedRole = msg.guild.roles.cache.find((role) => role.name === "⁃ Silenciado"); //Check if the role exist. if (!mutedRole) { //If it doesn't exists, then create it. try { //Create it. mutedRole = await msg.guild.roles.create({ data: { name: "⁃ Silenciado", color: "#a57474", permissions: [] } }); //Overwrite permissions. msg.guild.channels.cache.forEach(async (channel) => { await channel.updateOverwrite(mutedRole, { SEND_MESSAGES: false, ADD_REACTIONS: false }); }); } catch(e) { //Catch and log the error. console.log(e); } } const ms = require('ms'); //The second argument will be the mute time. const muteTime = args[1]; //Check if we have the time argument and return if we don't have it. if(!muteTime) { let embed = new Discord.MessageEmbed() .setColor("#8b0000") .setTimestamp() .setFooter(`Denegado a ${msg.member.displayName}`) .setTitle("Error") .setDescription(` Por favor, especifica una cantidad de tiempo válida usando el sufijo para días (d), horas (h), minutos (m) y segundos (s). Este comando no ha sido tan probado y perfeccionado, por lo que se recomienda no especificar valores tan altos. A continuación, se muestra un ejemplo del uso correcto: \`-mute @ZetaStormy 1d Spam\` Silencia a ZetaStormy por 1 día con motivo "Spam". `); msg.channel.send({embed}); return; } //Create the reason variable and verify if it is empty. let reason = args.slice(2).join(' '); if(!reason) reason = "Mal comportamiento"; //Add the mute role to the member. await(memberMention.roles.add(mutedRole.id)); //Remove the default role to the member, so it doesn't overwrite the permissions. await(memberMention.roles.remove(defaultRole.id)); //Check if the bot can delete the command message. if (msg.deletable) msg.delete(); const sucessMessage = new Discord.MessageEmbed() .setColor("#ff8c00") .setTimestamp() .setFooter(`Sancionado por ${msg.member.displayName}`) .setTitle("Lithium - Sanciones") .setDescription(` **Sanción:** Silenciado **Tag:** ${memberMention.user.tag} **ID:** ${memberMention.user.id} **Motivo:** ${reason} **Tiempo:** ${ms(ms(muteTime))} `); //Find the log channel in the configuration and send the embed. msg.guild.channels.cache.find((x) => x.id === config.muteLogChannel).send({embed: sucessMessage}); //Send the embed to the channel msg.channel.send({embed: sucessMessage}); //Set the timeout of the mute using the muteTime and create a function inside the setTimeout function to do some stuff. setTimeout(function() { //Remove the mute role. memberMention.roles.remove(mutedRole.id); //Add the default role again. memberMention.roles.add(defaultRole.id); //Create the embed to say that the member is no longer muted. const noLongerMutedMessage = new Discord.MessageEmbed() .setColor("#ff8c00") .setFooter(`Sancionado por ${msg.member.displayName}`) .setTitle("Lithium - Sanciones") .setTimestamp() .setDescription(`<@${memberMention.id}> ya no está silenciado.`); //Find the mute log channel and send this embed msg.guild.channels.cache.find((x) => x.id === config.muteLogChannel).send({embed: noLongerMutedMessage}); //Send this message to the channel where the member was muted. msg.channel.send({embed: noLongerMutedMessage}); }, ms(muteTime)); //Specify the timeout time. } //Information for the help command. exports.help = { name: "Mute", category: "Moderación", description: "Silencia a un usuario.", usage: "Mute [@Usuario] [1s/m/h/d]" }
import os import click import pickle # from typing import Any import numpy as np import scipy from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report from sklearn.metrics import precision_recall_fscore_support import mlflow from mlflow.entities import ViewType from mlflow.tracking import MlflowClient import warnings # Ignore all warnings # warnings.filterwarnings("ignore") # Filter the specific warning message, MLflow autologging encountered a warning # warnings.filterwarnings("ignore", category=UserWarning, module="setuptools") warnings.filterwarnings("ignore", category=UserWarning, message="Setuptools is replacing distutils.") warnings.filterwarnings("ignore", category=UserWarning, message="Distutils was imported before Setuptools,*") def load_pickle( filename: str, data_path: str ) -> tuple( [ scipy.sparse._csr.csr_matrix, np.ndarray ] ): file_path = os.path.join(data_path, filename) with open(file_path, "rb") as f_in: return pickle.load(f_in) def train_and_log_model(data_path, params, experiment_name): """The main training pipeline""" # Load train, val and test Data X_train, y_train = load_pickle("train.pkl", data_path) X_val, y_val = load_pickle("val.pkl", data_path) X_test, y_test = load_pickle("test.pkl", data_path) # print(type(X_train), type(y_train)) # MLflow settings # Build or Connect Database Offline mlflow.set_tracking_uri("sqlite:///mlflow.db") # Connect Database Online # mlflow.set_tracking_uri("http://127.0.0.1:5000") # Build or Connect mlflow experiment EXPERIMENT_NAME = experiment_name mlflow.set_experiment(EXPERIMENT_NAME) # before your training code to enable automatic logging of sklearn metrics, params, and models # mlflow.sklearn.autolog() with mlflow.start_run(nested=True): # Optional: Set some information about Model mlflow.set_tag("developer", "muce") mlflow.set_tag("algorithm", "Machine Learning") mlflow.set_tag("train-data-path", f'{data_path}/train.pkl') mlflow.set_tag("valid-data-path", f'{data_path}/val.pkl') mlflow.set_tag("test-data-path", f'{data_path}/test.pkl') # Set Model params information RF_PARAMS = ['n_estimators', 'max_depth', 'min_samples_split', 'min_samples_leaf', 'random_state', 'n_jobs'] for param in RF_PARAMS: params[param] = int(params[param]) # Log the model params to the tracking server mlflow.log_params(params) # Build Model rf = RandomForestClassifier(**params) rf.fit(X_train, y_train) # Log the validation and test Metric to the tracking server y_pred_val = rf.predict(X_val) y_pred_test = rf.predict(X_test) pr_fscore_val = precision_recall_fscore_support(y_val, y_pred_val, average='weighted') pr_fscore_test = precision_recall_fscore_support(y_test, y_pred_test, average='weighted') # Extract the F1-score from the tuple weighted_f1_score_val = pr_fscore_val[2] weighted_f1_score_test = pr_fscore_test[2] mlflow.log_metric("weighted_f1_score_val", weighted_f1_score_val) mlflow.log_metric("weighted_f1_score_test", weighted_f1_score_test) # print("weighted_f1_score_val", weighted_f1_score_val) # Log the model # Option1: Just only model in log mlflow.sklearn.log_model(sk_model = rf, artifact_path = "model_mlflow") # print(f"default artifacts URI: '{mlflow.get_artifact_uri()}'") return None def run_register_model(data_path="./output", top_n=5) -> None: """The main optimization pipeline""" # Parameters EXPERIMENT_NAME = "random-forest-best-models" HPO_EXPERIMENT_NAME = "random-forest-hyperopt" client = MlflowClient("sqlite:///mlflow.db") # Retrieve the top_n model runs and log the models experiment = client.get_experiment_by_name(HPO_EXPERIMENT_NAME) runs = client.search_runs( experiment_ids=experiment.experiment_id, run_view_type=ViewType.ACTIVE_ONLY, max_results=top_n, order_by=["metrics.weighted_f1_score_val DESC"] ) for run in runs: train_and_log_model(data_path=data_path, params=run.data.params, experiment_name=EXPERIMENT_NAME) # Select the model with the lowest test RMSE experiment = client.get_experiment_by_name(EXPERIMENT_NAME) best_run = client.search_runs( experiment_ids=experiment.experiment_id, run_view_type=ViewType.ACTIVE_ONLY, max_results=1, order_by=["metrics.weighted_f1_score_test DESC"] )[0] # Register the best model run_id = best_run.info.run_id model_uri = f"runs:/{run_id}/model" model_name = "rf-best-model" mlflow.register_model(model_uri, name=model_name) # print("Test weighted_f1_score_test of the best model: {:.4f}".format(best_run.data.metrics["weighted_f1_score_test"])) return None if __name__ == '__main__': run_register_model()
package cn.cloud9.domain; import cn.cloud9.dto.BaseDTO; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotBlank; import java.util.Date; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * 供应商信息表 */ @ApiModel(value = "供应商信息表") @Data @EqualsAndHashCode(callSuper = true) @AllArgsConstructor @NoArgsConstructor @TableName(value = "stock_provider") public class Provider extends BaseDTO { private static final long serialVersionUID = 1758684954536853834L; /** * 供应商id */ @TableId(value = "provider_id", type = IdType.INPUT) @ApiModelProperty(value = "供应商id") private Long providerId; /** * 供应商地址 */ @TableField(value = "provider_address") @ApiModelProperty(value = "供应商地址") private String providerAddress; /** * 供应商名称 */ @NotBlank(message = "供应商名称不能为空") @TableField(value = "provider_name") @ApiModelProperty(value = "供应商名称") private String providerName; /** * 联系人名称 */ @NotBlank(message = "联系人名称不能为空") @TableField(value = "contact_name") @ApiModelProperty(value = "联系人名称") private String contactName; /** * 联系人手机 */ @NotBlank(message = "联系人手机不能为空") @TableField(value = "contact_mobile") @ApiModelProperty(value = "联系人手机") private String contactMobile; /** * 联系人电话 */ @TableField(value = "contact_tel") @ApiModelProperty(value = "联系人电话") private String contactTel; /** * 银行账号 */ @NotBlank(message = "银行账号不能为空") @TableField(value = "bank_account") @ApiModelProperty(value = "银行账号") private String bankAccount; /** * 状态(0正常 1停用)sys_normal_disable */ @NotBlank(message = "状态不能为空") @TableField(value = "`status`") @ApiModelProperty(value = "状态(0正常 1停用)sys_normal_disable") private String status; /** * 创建时间 */ @TableField(value = "create_time") @ApiModelProperty(value = "创建时间") private Date createTime; /** * 更新时间 */ @TableField(value = "update_time") @ApiModelProperty(value = "更新时间") private Date updateTime; /** * 创建者 */ @TableField(value = "create_by") @ApiModelProperty(value = "创建者") private String createBy; /** * 更新者 */ @TableField(value = "update_by") @ApiModelProperty(value = "更新者") private String updateBy; public static final String COL_PROVIDER_ID = "provider_id"; public static final String COL_PROVIDER_ADDRESS = "provider_address"; public static final String COL_PROVIDER_NAME = "provider_name"; public static final String COL_CONTACT_NAME = "contact_name"; public static final String COL_CONTACT_MOBILE = "contact_mobile"; public static final String COL_CONTACT_TEL = "contact_tel"; public static final String COL_BANK_ACCOUNT = "bank_account"; public static final String COL_STATUS = "status"; public static final String COL_CREATE_TIME = "create_time"; public static final String COL_UPDATE_TIME = "update_time"; public static final String COL_CREATE_BY = "create_by"; public static final String COL_UPDATE_BY = "update_by"; }
// Package is provides functions for checking types and values. package is import ( "reflect" "strings" "github.com/n4x2/zoo/constraints" "github.com/n4x2/zoo/regex" ) // Alpha checks if the value is letters a-z or A-Z. func Alpha(v string) bool { return regex.Alpha.MatchString(v) } // AlphaDash checks if the value is letters, numbers, dash, and // underscore. func AlphaDash(v string) bool { return regex.AlphaDash.MatchString(v) } // AlphaNumeric checks if the value is letters and numbers. func AlphaNumeric(v string) bool { return regex.AlphaNumeric.MatchString(v) } // ASCII checks if the value is ASCII characters. func ASCII(v string) bool { return regex.ASCII.MatchString(v) } // Bool checks if the value is a boolean. func Bool(v interface{}) bool { _, ok := v.(bool) return ok } // Byte checks if the value is a byte. func Byte(v interface{}) bool { _, ok := v.(byte) return ok } // Contain checks if v is present in s. func Contain[S ~[]E, E comparable](s S, v E) bool { for i := range s { if v == s[i] { return true } } return false } // ContainOneOf checks if part of ss is present in s. func ContainOneOf[S comparable](s []S, ss []S) bool { for i := range ss { if Contain(s, ss[i]) { return true } } return false } // Email checks if the value is valid email. func Email(v string) bool { return regex.Email.MatchString(v) } // Equal checks if two comparable values are equal. func Equal[T comparable](v, vv T) bool { return v == vv } // Error checks if the value is an error. func Error(v interface{}) bool { _, ok := v.(error) return ok } // Float checks if the value is a float32 or float64. func Float(v interface{}) bool { switch v.(type) { case float32, float64: return true default: return false } } // GreaterThan checks if 'v' is greater than 'p'. func GreaterThan[T constraints.Number](v, p T) bool { return v > p } // GreaterThanEqual checks if 'v' is greater than or equal 'p'. func GreaterThanEqual[T constraints.Number](v, p T) bool { return v >= p } // Int checks if the value is an integer. func Int(v interface{}) bool { switch v.(type) { case int, int8, int16, int32, int64: return true default: return false } } // Latitude checks if the is valid latitude. func Latitude(v string) bool { return regex.Latitude.MatchString(v) } // LessThan checks if 'v' is less than 'p'. func LessThan[T constraints.Number](v, p T) bool { return v < p } // LessThanEqual checks if 'v' is less than or equal 'p'. func LessThanEqual[T constraints.Number](v, p T) bool { return v <= p } // Longitude checks if the value is valid longitude. func Longitude(v string) bool { return regex.Longitude.MatchString(v) } // Lowercase checks if the value is lower case. func Lowercase(v string) bool { return strings.ToLower(v) == v } // Number checks if the value is numbers. func Number(v string) bool { return regex.Number.MatchString(v) } // Numeric checks if the value is numeric type: integer or // floating-point. func Numeric(v string) bool { return regex.Numeric.MatchString(v) } // Range checks if 'v' in range 'b' and 'e'. func Range[T constraints.Number](b, e, v T) bool { return v >= b && v <= e } // Rune checks if the value is a rune. func Rune(v interface{}) bool { _, ok := v.(rune) return ok } // Slice checks if the value is a slice. func Slice(v interface{}) bool { s := reflect.ValueOf(v) return s.Kind() == reflect.Slice } // String checks if the value is a string. func String(v interface{}) bool { _, ok := v.(string) return ok } // Struct checks if the value is a struct. func Struct(v interface{}) bool { s := reflect.ValueOf(v) return s.Kind() == reflect.Struct } // Uint checks if the value is an unsigned integer. func Uint(v interface{}) bool { switch v.(type) { case uint, uint8, uint16, uint32, uint64: return true default: return false } } // ULID checks if the value is valid ULID. func ULID(v string) bool { return regex.ULID.MatchString(v) } // Uppercase checks if the value is upper case. func Uppercase(v string) bool { return strings.ToUpper(v) == v } // UUID checks if the value is valid UUID. func UUID(v string) bool { return regex.UUID.MatchString(v) }
load @wavebond/snow/amazonaws.com/dms/2016-01-01/base/boolean-optional take form boolean-optional load @wavebond/snow/amazonaws.com/dms/2016-01-01/base/integer-optional take form integer-optional load @wavebond/snow/amazonaws.com/dms/2016-01-01/base/tag-list take form tag-list load @wavebond/snow/amazonaws.com/dms/2016-01-01/base/vpc-security-group-id-list take form vpc-security-group-id-list load @wavebond/snow/base/string take form string form create-replication-instance-message, name <CreateReplicationInstanceMessage> note <> take replication-instance-identifier, name <ReplicationInstanceIdentifier> like string note <The replication instance identifier. This parameter is stored as a lowercase string. Constraints: - Must contain 1-63 alphanumeric characters or hyphens. - First character must be a letter. - Can't end with a hyphen or contain two consecutive hyphens. Example: `myrepinstance`> take allocated-storage, name <AllocatedStorage> like integer-optional void take note <The amount of storage (in gigabytes) to be initially allocated for the replication instance.> take replication-instance-class, name <ReplicationInstanceClass> like string note <The compute and memory capacity of the replication instance as defined for the specified replication instance class. For example to specify the instance class dms.c4.large, set this parameter to `"dms.c4.large"`. For more information on the settings and capacities for the available replication instance classes, see [Selecting the right DMS replication instance for your migration](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html#CHAP_ReplicationInstance.InDepth).> take vpc-security-group-ids, name <VpcSecurityGroupIds> like vpc-security-group-id-list void take note <Specifies the VPC security group to be used with the replication instance. The VPC security group must work with the VPC containing the replication instance.> take availability-zone, name <AvailabilityZone> like string void take note <The Availability Zone where the replication instance will be created. The default value is a random, system-chosen Availability Zone in the endpoint's Amazon Web Services Region, for example: `us-east-1d`> take replication-subnet-group-identifier, name <ReplicationSubnetGroupIdentifier> like string void take note <A subnet group to associate with the replication instance.> take preferred-maintenance-window, name <PreferredMaintenanceWindow> like string void take note <The weekly time range during which system maintenance can occur, in Universal Coordinated Time (UTC). Format: `ddd:hh24:mi-ddd:hh24:mi` Default: A 30-minute window selected at random from an 8-hour block of time per Amazon Web Services Region, occurring on a random day of the week. Valid Days: Mon, Tue, Wed, Thu, Fri, Sat, Sun Constraints: Minimum 30-minute window.> take multi-az, name <MultiAZ> like boolean-optional void take note <Specifies whether the replication instance is a Multi-AZ deployment. You can't set the `AvailabilityZone` parameter if the Multi-AZ parameter is set to `true`.> take engine-version, name <EngineVersion> like string void take note <The engine version number of the replication instance. If an engine version number is not specified when a replication instance is created, the default is the latest engine version available.> take auto-minor-version-upgrade, name <AutoMinorVersionUpgrade> like boolean-optional void take note <A value that indicates whether minor engine upgrades are applied automatically to the replication instance during the maintenance window. This parameter defaults to `true`. Default: `true`> take tags, name <Tags> like tag-list void take note <One or more tags to be assigned to the replication instance.> take kms-key-id, name <KmsKeyId> like string void take note <An KMS key identifier that is used to encrypt the data on the replication instance. If you don't specify a value for the `KmsKeyId` parameter, then DMS uses your default encryption key. KMS creates the default encryption key for your Amazon Web Services account. Your Amazon Web Services account has a different default encryption key for each Amazon Web Services Region.> take publicly-accessible, name <PubliclyAccessible> like boolean-optional void take note <Specifies the accessibility options for the replication instance. A value of `true` represents an instance with a public IP address. A value of `false` represents an instance with a private IP address. The default value is `true`.> take dns-name-servers, name <DnsNameServers> like string void take note <A list of custom DNS name servers supported for the replication instance to access your on-premise source or target database. This list overrides the default name servers supported by the replication instance. You can specify a comma-separated list of internet addresses for up to four on-premise DNS name servers. For example: `"1.1.1.1,2.2.2.2,3.3.3.3,4.4.4.4"`> take resource-identifier, name <ResourceIdentifier> like string void take note <A friendly name for the resource identifier at the end of the `EndpointArn` response parameter that is returned in the created `Endpoint` object. The value for this parameter can have up to 31 characters. It can contain only ASCII letters, digits, and hyphen ('-'). Also, it can't end with a hyphen or contain two consecutive hyphens, and can only begin with a letter, such as `Example-App-ARN1`. For example, this value might result in the `EndpointArn` value `arn:aws:dms:eu-west-1:012345678901:rep:Example-App-ARN1`. If you don't specify a `ResourceIdentifier` value, DMS generates a default identifier value for the end of `EndpointArn`.>
let back; // CSV 파일 경로 const csvFilePath = 'data/shopping_on.csv'; let topTags = []; // 상위 태그 배열 초기화 let tagImages = {}; // 태그 이미지 객체 초기화 // 전역 변수 let tagCounts; let maleRatio; let femaleRatio; let ageGroupRatios; // 태그 이미지 객체를 저장할 객체 function preload() { back = loadImage('data/cloud.png'); // 배경이미지 파일 경로 font = loadFont('data/NanumSquareB.ttf'); // 상위 3개 태그 이미지 불러오기 } function setup() { createCanvas(400, 400); loadAndProcessCSV(); textFont(font); // 글꼴 설정 } function draw() { background(back); textSize(25); text('현시간 구매 TOP3',115,50); // 상위 3개 태그 이미지 출력하기 let x = 33; // 이미지 시작 위치 x 좌표 let y = 150; // 이미지 시작 위치 y 좌표 let imageSize = 100; // 이미지 크기 let imageGap = 20; // 이미지 간격 for (let i = 0; i < topTags.length; i++) { let tag = topTags[i]; let tagImage = tagImages[tag]; image(tagImage, x, y, imageSize, imageSize); x += imageSize + imageGap; } textSize(15); text(topTags,120,300); } // 현재 시간대를 가져오는 함수 function getTimeGroup() { const currentHour = new Date().getHours(); if (currentHour >= 2 && currentHour < 6) { return 'A'; } else if (currentHour >= 6 && currentHour < 10) { return 'B'; } else if (currentHour >= 10 && currentHour < 14) { return 'C'; } else if (currentHour >= 14 && currentHour < 18) { return 'D'; } else if (currentHour >= 18 && currentHour < 22) { return 'E'; } else { return 'F'; } } // CSV 파일을 비동기적으로 로드하고 처리하는 함수 function loadAndProcessCSV() { const currentTimeGroup = getTimeGroup(); // CSV 파일 로드 const table = loadTable(csvFilePath, 'csv', 'header', function () { const data = table.getRows(); // 현재 시간대에 속하는 데이터 필터링 const filteredData = data.filter((row) => row.get('시간대').charAt(0) === currentTimeGroup); // 태그별 건수 합계 계산 tagCounts = {}; for (const row of filteredData) { const tag = row.get('TAG'); const count = parseInt(row.get('건수합계')); if (!tagCounts[tag]) { tagCounts[tag] = count; } else { tagCounts[tag] += count; } } // 상위 3개 태그 추출 topTags = Object.keys(tagCounts).sort((a, b) => tagCounts[b] - tagCounts[a]).slice(0, 3); // 상위 3개 태그 이미지 불러오기 for (const tag of topTags) { console.log(tag.substring(0, 1)) let tagImage = loadImage('data/' + tag.substring(0, 1) + '.png'); tagImages[tag] = tagImage; } // 출력 console.log('상위 3개 태그:', topTags); console.log('건수 합계:', tagCounts); console.log('남성 비율:', maleRatio); console.log('여성 비율:', femaleRatio); console.log('연령대 비율:', ageGroupRatios); }); }
# auth blueprint / kinda like a sub-app / module import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for ) from werkzeug.security import check_password_hash, generate_password_hash from blog.db import get_db bp = Blueprint('auth', __name__, url_prefix='/auth') @bp.route('/register', methods=('GET', 'POST')) def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' if error is None: try: db.execute( "INSERT INTO user (username, password) VALUES (?, ?)", (username, generate_password_hash(password)), ) db.commit() except db.IntegrityError: error = f"User {username} is already registered." else: return redirect(url_for("auth.login")) flash(error) return render_template('auth/register.html') @bp.route('/login', methods=('GET', 'POST')) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None user = db.execute( 'SELECT * FROM user WHERE username = ?', (username,) ).fetchone() if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html') # funkcja udostepniana innym do wykonywania przed requestami odbierajaca uzytkownika z sesji i dane o nim z db, bo w sesji zapisane tylko id @bp.before_app_request def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute( 'SELECT * FROM user WHERE id = ?', (user_id,) ).fetchone() @bp.route('/logout') def logout(): session.clear() return redirect(url_for('index')) # wlasny wrapper mozliwy do wykorzystania jako decorator sprawdzajacy czy istnieje jakis zalogowany uzytkownik, jesli nie to redirect, jesli tak to zwraca co wrappuje def login_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for('auth.login')) return view(**kwargs) return wrapped_view
package types import ( "fmt" "gopkg.in/yaml.v3" ) const ( // DefaultSendEnabled enabled DefaultSendEnabled = true // DefaultReceiveEnabled enabled DefaultReceiveEnabled = true ) // NewParams creates a new parameter configuration for the ibc transfer module func NewParams(enableSend, enableReceive bool) Params { return Params{ SendEnabled: enableSend, ReceiveEnabled: enableReceive, } } // DefaultParams is the default parameter configuration for the ibc-transfer module func DefaultParams() Params { return NewParams(DefaultSendEnabled, DefaultReceiveEnabled) } func (p Params) String() string { out, err := yaml.Marshal(p) if err != nil { panic(err) } return string(out) } // Validate all ibc-transfer module parameters func (p Params) Validate() error { if err := validateEnabled(p.SendEnabled); err != nil { return err } return validateEnabled(p.ReceiveEnabled) } func validateEnabled(i interface{}) error { _, ok := i.(bool) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } return nil }
<div class="page-layout simple card fullwidth inner-scroll p-12" fxLayout="column" fxLayoutGap="12px" > <!-- FILTRO --> <mat-card> <form [formGroup]="form" novalidate fxLayoutGap="12px"> <!-- CURRICULO --> <mat-form-field appearance="outline" fxFlex="1 0 auto"> <mat-label>Currículo</mat-label> <mat-select fxLayout="column" formControlName="codigoCurriculo"> <mat-option *ngIf="curriculos.length <= 0 && !carregandoCurriculos" disabled > <span>Nenhum registro encontrado</span> </mat-option> <mat-option *ngIf="carregandoCurriculos" disabled> <span>Carregando currículos...</span> </mat-option> <div *ngFor="let curriculo of curriculos"> <mat-option [value]="curriculo.codigo"> {{ curriculo.descricaoCurso }} - {{ curriculo.ano }} </mat-option> </div> </mat-select> </mat-form-field> <!-- CURRICULO --> <!-- PERIODO --> <mat-form-field fxFlex.gt-sm="12" appearance="outline"> <mat-label>Períodos</mat-label> <mat-select placeholder="Período" formControlName="periodo"> <mat-option *ngFor="let periodo of periodos" [value]="periodo.codigo" > {{ periodo.descricao }} </mat-option> </mat-select> </mat-form-field> <!-- PERIODO --> <!-- SEMESTRE --> <mat-form-field appearance="outline" fxFlex.gt-sm="12" fxFlex="1 0 auto" > <mat-label>Semestre</mat-label> <mat-select fxLayout="column" formControlName="semestre"> <div *ngFor="let semestre of semestres"> <mat-option [value]="semestre"> {{ retornarDescricaoSemestre(semestre) }} </mat-option> </div> </mat-select> </mat-form-field> <!-- SEMESTRE --> <!-- ANO --> <mat-form-field fxFlex.gt-sm="12" appearance="outline"> <mat-label>Ano</mat-label> <input formControlName="ano" matInput class="primary-color-input border-radius-4" name="primary color" mask="0000" /> </mat-form-field> <!-- ANO --> <!-- BOTOES PESQUISA --> <div class="mat-form-field-wrapper" fxLayoutAlign="center center" fxLayoutGap="12px" > <button mat-raised-button color="accent" [disabled]="pesquisandoHorarios" (click)="pesquisarHorarios()" class="p-8" fxLayoutAlign="center center" matTooltip="Pesquisar horários" > <mat-spinner *ngIf="pesquisandoHorarios" diameter="20" ></mat-spinner> <mat-icon *ngIf="!pesquisandoHorarios">search</mat-icon> </button> <button *ngIf="habilitarBotaoLimpar" mat-raised-button (click)="limparPesquisa()" matTooltip="Limpar pesquisa" > Limpar </button> </div> <!-- BOTOES PESQUISA --> </form> </mat-card> <!-- FILTRO --> <!-- HORARIOS --> <mat-card fxLayout="column" fxFlex="100" style="overflow-y: scroll;" fusePerfectScrollbar > <div fxLayout.gt-sm="row wrap" fxLayoutAlign.gt-sm="center space-between" > <span class="texto-informativo" *ngIf="horarios.length <= 0"> <p> Clique em adicionar horários (+) para adicionar um novo horário. </p> </span> <ng-container *ngFor="let horario of horarios"> <horario-card fxFlex.gt-sm="25" fxFlex="100" class="m-24" ($editar)="editarHorario($event)" ($remover)="removerHorario($event)" ($selecionar)="selecionarHorario($event)" [horario]="horario" ></horario-card> </ng-container> </div> </mat-card> <button class="botao-flutuante" (click)="adicionarHorarios()" mat-fab matTooltip="Adicionar novo horário" > <mat-icon>add</mat-icon> </button> <!-- HORARIOS --> </div>
#pragma once /* * Adplug - Replayer for many OPL2/OPL3 audio file formats. * Copyright (C) 1999 - 2003 Simon Peter, <[email protected]>, et al. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * xsm.h - eXtra Simple Music Player, by Simon Peter <[email protected]> */ #include "player.h" class XsmPlayer : public Player { public: DISABLE_COPY( XsmPlayer ) static Player* factory() { return new XsmPlayer(); } XsmPlayer() = default; ~XsmPlayer() override = default; bool load(const std::string& filename) override; bool update() override; void rewind(const boost::optional<size_t>& subsong) override; size_t framesUntilUpdate() const override; std::string type() const override { return "eXtra Simple Music"; } private: struct Row { uint8_t data[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; }; std::vector<Row> m_music{}; size_t m_lastRow = 0; size_t m_currentRow = 0; bool m_songEnd = false; void playNote(int c, int note, int octv); };
import Moralis from "moralis/dist/moralis.js"; /** * Save json file to ipfs * * @param {string} name * @param {object} json * @returns Promise */ const saveJsonToIPFS = async (name: string, json: object): Promise<any> => { const file = new Moralis.File(name + ".json", { base64: btoa(JSON.stringify(json)), }); await file.saveIPFS(); return file; }; /** * Save base64 image to ipfs * * @param {string} name * @param {object} json * @returns Promise */ const saveBase64ImageToIPFS = async (name: string, image: string): Promise<any> => { const file = new Moralis.File(name + ".png", { base64: image }); await file.saveIPFS(); return file; }; /** * Save base64 image to ipfs * * @param {string} name * @param {object} json * @returns Promise */ const saveBlobToIPFS = async (name: string, image: string): Promise<any> => { const file = new Moralis.File(name + ".png", { base64: image }); await file.saveIPFS(); return file; }; export const useIPFS = () => { return { saveJsonToIPFS, saveBase64ImageToIPFS }; };
import { ChainId } from "@pancakeswap/chains"; import cron from "node-cron"; import { Address, PublicClient } from "viem"; import { redisClient } from ".."; import { getViemClient } from "../blockchain/client"; import { AppLogger } from "../util/logger"; import CronJob from "./utils/conUtils"; import { cronLock } from "./utils/cronLock"; import { LoadBalancerBatcher, loadBalancer } from "./utils/loadBalancerBatcher"; import { formatedAdjustedDateOverflow } from "../util/utils"; export abstract class SharedCronTask extends AppLogger { protected job: CronJob; protected schedule: string; protected supportedChains: ChainId[]; protected loadBalancer: LoadBalancerBatcher<unknown>; constructor(jobId: string, schedule: string, supportedChains: ChainId[]) { super(); this.schedule = schedule; this.supportedChains = supportedChains; this.job = new CronJob(jobId, process, this.getLogger(jobId)); } protected abstract mainFunction( chainId: ChainId, subscribers: Address[] | string[], provider?: PublicClient ): Promise<void>; protected abstract init(chainId: ChainId): Promise<void>; protected async executeCronTask<T extends string>( chainId: ChainId, subscribers: T[], provider?: PublicClient, overrideMainFunction?: ( chainId: ChainId, subscribers: Address[] | string[], provider?: PublicClient ) => Promise<void> ) { if (!this.supportedChains.includes(chainId)) return; this.job.cronJob = cron.schedule(this.schedule, async () => { const currentJobBatch = LoadBalancerBatcher.getLoadBalancerInstance<ChainId>(`${this.job.jobName}`)?.currentGroup; if (currentJobBatch && !currentJobBatch.includes(chainId)) return; try { await cronLock.addToQueue(`${this.job.jobName}-${chainId}`, async () => { this.job.log.info(`${this.job.jobName} for ${chainId} chain - started`); overrideMainFunction ? await overrideMainFunction(chainId, subscribers, provider) : await this.mainFunction(chainId, subscribers, provider); this.job.log.info(`${this.job.jobName} for ${chainId} chain - finished \n`); if (currentJobBatch) loadBalancer.getNextGroup<ChainId>(`${this.job.jobName}`); }); } catch (error) { this.job.log.error(`Error in ${this.job.jobName}for ${chainId} chain: ${error}`); } }); } protected async calculateNewCronSchedule(endTime: number, secondsBuffer?: number, minutesBuffer?: number) { const roundEndTime = new Date(endTime * 1000); let hour = roundEndTime.getUTCHours(); let minute = roundEndTime.getUTCMinutes() + minutesBuffer; let second = roundEndTime.getUTCSeconds() + secondsBuffer; const { newSecond, newMinute, newHour } = formatedAdjustedDateOverflow(second, minute, hour); return `${newSecond} ${newMinute} ${newHour} * * * *`; } protected getClient(chainId: ChainId): PublicClient { const provider = getViemClient({ chainId }); return provider; } protected async getSubscribers(): Promise<string[]> { const subscribers = await redisClient.getSubscribers<string>("subscribers"); return subscribers; } protected async getFormattedSubscribers(): Promise<Address[]> { const subscribersFormatted = await redisClient.getSubscribers<Address>("subscribers_formatted"); return subscribersFormatted; } }
#!/usr/bin/python3 """ A script that adds the State object “Louisiana” to the database hbtn_0e_6_usa and prints the new state's id. """ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from model_state import Base, State import sys if __name__ == "__main__": username, password, database = sys.argv[1:4] engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}' .format(username, password, database), pool_pre_ping=True) Session = sessionmaker(bind=engine) session = Session() new_state = State(name="Louisiana") session.add(new_state) session.commit() print(new_state.id) session.close()
package az.lahza.iamrich.view import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.produceState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import az.lahza.iamrich.model.Crypto import az.lahza.iamrich.util.Resource import az.lahza.iamrich.viewmodel.CryptoDetailViewModel import coil.annotation.ExperimentalCoilApi import coil.compose.rememberImagePainter @OptIn(ExperimentalCoilApi::class) @Composable fun CryptoDetailScreen( id: String, price: String, navController: NavController, viewModel: CryptoDetailViewModel= hiltViewModel(), ) { val cryptoItem = produceState<Resource<Crypto>>(initialValue = Resource.Loading()) { value = viewModel.getCrypto(id) }.value Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.primary), contentAlignment = Alignment.Center ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { when(cryptoItem){ is Resource.Success<*> -> { val selectedCrypto = cryptoItem.data?.get(0) if (selectedCrypto != null) { Text(text = selectedCrypto.name, fontSize = 40.sp, modifier = Modifier.padding(2.dp), fontWeight = FontWeight.Bold, color = Color.Black, textAlign = TextAlign.Center ) } if (selectedCrypto != null) { Image(painter = rememberImagePainter(data = selectedCrypto.logo_url), contentDescription = selectedCrypto.name, modifier = Modifier .padding(16.dp) .size(200.dp, 200.dp) .clip(CircleShape) .border(2.dp, Color.Gray, CircleShape) ) } Text(text = price, fontSize = 40.sp, modifier = Modifier.padding(2.dp), fontWeight = FontWeight.Bold, color = Color.Black, textAlign = TextAlign.Center ) } is Resource.Error -> { Text(cryptoItem.message!!) } is Resource.Loading -> { CircularProgressIndicator(color = Color.Blue) } } } } }
#include <benchmark/benchmark.h> #ifndef FASTNOISE_PERLINNOISE_HPP_INCLUDED #define FASTNOISE_PERLINNOISE_HPP_INCLUDED #ifdef __GNUC__ #pragma GCC system_header #endif #ifdef __clang__ #pragma clang system_header #endif #include "FastNoise/FastNoise.h" #endif /* static void generate_3d_word(benchmark::State &state) { auto size = state.range(0); siv::PerlinNoise::seed_type seed = 2510586073u; generatorv1 gen = generatorv1(seed); for (auto _ : state) { std::vector<std::unique_ptr<Chunk>> chunks = std::move(gen.generateChunks(0, 0, 0, size, 1, size, true)); benchmark::DoNotOptimize(chunks); benchmark::ClobberMemory(); } state.SetItemsProcessed(state.iterations() * size * size); state.SetBytesProcessed(state.iterations() * size * size * sizeof(Chunk)); } BENCHMARK(generate_3d_word)->Name("generate_3d_word")->RangeMultiplier(2)->Range(1, 8)->ThreadRange(1, 1); static void generate_3d_chunk(benchmark::State &state) { auto size = state.range(0); siv::PerlinNoise::seed_type seed = 2510586073u; generatorv1 gen = generatorv1(seed); for (auto _ : state) { std::unique_ptr<Chunk> _chunk = std::move(gen.generateChunk(0, 0, 0, true)); benchmark::DoNotOptimize(_chunk); benchmark::ClobberMemory(); } state.SetItemsProcessed(state.iterations()); state.SetBytesProcessed(state.iterations() * sizeof(Chunk)); } BENCHMARK(generate_3d_chunk)->Name("generate_3d_chunk")->RangeMultiplier(2)->Range(1, 1)->ThreadRange(1, 1); static void generate_2d_word(benchmark::State &state) { auto size = state.range(0); siv::PerlinNoise::seed_type seed = 2510586073u; generatorv1 gen = generatorv1(seed); for (auto _ : state) { std::vector<std::unique_ptr<Chunk>> chunks = std::move(gen.generateChunks(0, 0, 0, size, 1, size, false)); benchmark::DoNotOptimize(chunks); benchmark::ClobberMemory(); } state.SetItemsProcessed(state.iterations() * size * size); state.SetBytesProcessed(state.iterations() * size * size * sizeof(Chunk)); } BENCHMARK(generate_2d_word)->Name("generate_2d_word")->RangeMultiplier(2)->Range(1, 8)->ThreadRange(1, 1); static void generate_2d_chunk(benchmark::State &state) { auto size = state.range(0); siv::PerlinNoise::seed_type seed = 2510586073u; generatorv1 gen = generatorv1(seed); for (auto _ : state) { std::unique_ptr<Chunk> _chunk = std::move(gen.generateChunk(0, 0, 0, false)); benchmark::DoNotOptimize(_chunk); benchmark::ClobberMemory(); } state.SetItemsProcessed(state.iterations()); state.SetBytesProcessed(state.iterations() * sizeof(Chunk)); } BENCHMARK(generate_2d_chunk)->Name("generate_2d_chunk")->RangeMultiplier(2)->Range(1, 1)->ThreadRange(1, 1); */ #include <string> #include <iostream> #include <benchmark/benchmark.h> static void DoSetup(const benchmark::State& state) { } static void DoTeardown(const benchmark::State& state) { } template<typename T> static void BasicBench(benchmark::State& state) { const auto range = state.range(0); std::string str; benchmark::DoNotOptimize(str); for (auto _ : state) { str = std::to_string(range); benchmark::ClobberMemory(); //state.PauseTiming(); //state.SkipWithError("No path found"); //state.ResumeTiming(); } // state.counters["range"] = range; state.SetItemsProcessed(state.iterations() * range * range); state.SetBytesProcessed(state.iterations() * range * range * sizeof(uint64_t)); } BENCHMARK(BasicBench<uint64_t>) ->Name("BasicBench") ->RangeMultiplier(4) ->Range(16, 256) ->ThreadRange(1, 1) ->Unit(benchmark::kNanosecond) ->Setup(DoSetup) ->Teardown(DoTeardown) ->MeasureProcessCPUTime() ->UseRealTime(); int main(int argc, char** argv) { ::benchmark::Initialize(&argc, argv); ::benchmark::RunSpecifiedBenchmarks(); }
package com.sedsoftware.common.domain.entity import com.sedsoftware.common.domain.type.RemindiePeriod import com.sedsoftware.common.domain.type.RemindieType import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.getDayEnd import kotlinx.datetime.getDayStart import kotlin.test.Test import kotlin.test.assertEquals class RemindieExtTest { @Test fun toNearestShot_test() { val timeZone = TimeZone.currentSystemDefault() // Oneshot - not fired val today1 = LocalDateTime(2020, 11, 7, 13, 13) val created1 = LocalDateTime(2020, 11, 7, 12, 13) val shot1 = LocalDateTime(2020, 11, 7, 18, 33) val remindie1 = Remindie( createdTimestamp = 1, createdDate = created1, targetTime = shot1, creationTimeZone = timeZone, title = "Oneshot - not fired", description = "Do something cool", type = RemindieType.CALL, period = RemindiePeriod.NONE, each = 0 ) assertEquals( remindie1.toNextShot(today1), NextShot( remindie = remindie1, target = shot1, isFired = false ) ) // Oneshot - fired val today2 = LocalDateTime(2020, 11, 7, 22, 13) val created2 = LocalDateTime(2020, 11, 7, 12, 13) val shot2 = LocalDateTime(2020, 11, 7, 18, 33) val remindie2 = Remindie( createdTimestamp = 2, createdDate = created2, targetTime = shot2, creationTimeZone = timeZone, title = "Oneshot - fired", description = "Do something cool", type = RemindieType.CALL, period = RemindiePeriod.NONE, each = 0 ) assertEquals( remindie2.toNextShot(today2), NextShot( remindie = remindie2, target = shot2, isFired = true ) ) // Periodical val today3 = LocalDateTime(2020, 11, 7, 22, 13) val created3 = LocalDateTime(2020, 11, 7, 12, 13) val shot3 = LocalDateTime(2020, 11, 7, 18, 33) val remindie3 = Remindie( createdTimestamp = 3, createdDate = created3, targetTime = shot3, creationTimeZone = timeZone, title = "Oneshot - hourly 3", description = "Do something cool", type = RemindieType.CALL, period = RemindiePeriod.HOURLY, each = 3 ) assertEquals( remindie3.toNextShot(today3), NextShot( remindie = remindie3, target = LocalDateTime(2020, 11, 8, 0, 33), isFired = false ) ) val today4 = LocalDateTime(2020, 11, 7, 22, 13) val created4 = LocalDateTime(2020, 11, 7, 12, 13) val shot4 = LocalDateTime(2020, 11, 7, 18, 33) val remindie4 = Remindie( createdTimestamp = 4, createdDate = created4, targetTime = shot4, creationTimeZone = timeZone, title = "Oneshot - daily 2", description = "Do something cool", type = RemindieType.CALL, period = RemindiePeriod.DAILY, each = 2 ) assertEquals( remindie4.toNextShot(today4), NextShot( remindie = remindie4, target = LocalDateTime(2020, 11, 9, 18, 33), isFired = false ) ) val today5 = LocalDateTime(2020, 11, 7, 22, 13) val created5 = LocalDateTime(2020, 11, 7, 12, 13) val shot5 = LocalDateTime(2020, 11, 7, 18, 33) val remindie5 = Remindie( createdTimestamp = 5, createdDate = created5, targetTime = shot5, creationTimeZone = timeZone, title = "Oneshot - weekly 2", description = "Do something cool", type = RemindieType.CALL, period = RemindiePeriod.WEEKLY, each = 2 ) assertEquals( remindie5.toNextShot(today5), NextShot( remindie = remindie5, target = LocalDateTime(2020, 11, 21, 18, 33), isFired = false ) ) val today6 = LocalDateTime(2020, 11, 7, 22, 13) val created6 = LocalDateTime(2020, 11, 7, 12, 13) val shot6 = LocalDateTime(2020, 11, 7, 18, 33) val remindie6 = Remindie( createdTimestamp = 6, createdDate = created6, targetTime = shot6, creationTimeZone = timeZone, title = "Oneshot - monthly 14", description = "Do something cool", type = RemindieType.CALL, period = RemindiePeriod.MONTHLY, each = 14 ) assertEquals( remindie6.toNextShot(today6), NextShot( remindie = remindie6, target = LocalDateTime(2022, 1, 7, 18, 33), isFired = false ) ) } @Test fun getShots_test() { val timeZone = TimeZone.currentSystemDefault() val created = LocalDateTime(2020, 11, 22, 10, 0) val today = LocalDateTime(2020, 11, 23, 18, 0) val remindie1 = Remindie( createdTimestamp = 1, createdDate = created, targetTime = LocalDateTime(2020, 11, 23, 22, 0), creationTimeZone = timeZone, title = "Daily at 22:00", description = "Do something cool", type = RemindieType.CALL, period = RemindiePeriod.DAILY, each = 1 ) val remindie2 = Remindie( createdTimestamp = 2, createdDate = created, targetTime = LocalDateTime(2020, 10, 27, 1, 2), creationTimeZone = timeZone, title = "Weekly at 12:13", description = "Do something cool", type = RemindieType.CALL, period = RemindiePeriod.WEEKLY, each = 1 ) val remindie3 = Remindie( createdTimestamp = 3, createdDate = created, targetTime = LocalDateTime(2020, 12, 11, 23, 34), creationTimeZone = timeZone, title = "Monthly at 23:34", description = "Do something cool", type = RemindieType.CALL, period = RemindiePeriod.MONTHLY, each = 1 ) // test daily val shots1 = remindie1.getShots( from = LocalDateTime(2020, 11, 20, 22, 0).getDayStart(), to = LocalDateTime(2020, 11, 29, 22, 0).getDayEnd(), today = today ) assertEquals(shots1.size, 7) // test weekly val shots2 = remindie2.getShots( from = LocalDateTime(2020, 11, 20, 22, 0).getDayStart(), to = LocalDateTime(2020, 12, 6, 22, 0).getDayEnd(), today = today ) assertEquals(shots2.size, 2) // test monthly val shots3 = remindie3.getShots( from = LocalDateTime(2020, 11, 20, 22, 0).getDayStart(), to = LocalDateTime(2021, 3, 30, 12, 12).getDayEnd(), today = today ) assertEquals(shots3.size, 4) } }
const fs = require('fs'); const path = require('path'); // remeber to install colors package // npm -D i colors require("colors"); // import fs from 'fs'; // import path from 'path'; const componentName = process.argv[2]; if (!componentName) { console.error('Please specify a component name.'); process.exit(1); } // generate directory path for new page in /src/page/componentName // const pageDirectoryPath = path.join(__dirname, 'src', 'pages', componentName); const pageDirectoryPath = `./src/pages/${componentName.toLocaleLowerCase()}`; // check if path already exists if (fs.existsSync(pageDirectoryPath)) { console.error( `Page ${pageDirectoryPath} already exists.`.red ); process.exit(1); } fs.mkdirSync(pageDirectoryPath); const componentLayoutContent = ` import { Outlet } from "react-router-dom"; interface ${componentName}LayoutProps { } export function ${componentName}Layout({}:${componentName}LayoutProps){ return ( <div className='w-full h-full'> <Outlet/> </div> ); }; `; const componentContent = ` interface ${componentName}Props { } export function ${componentName}({}:${componentName}Props){ return ( <div className='w-full h-full min-h-screen flex items-center justify-center'> ${componentName} component </div> ); }; `; fs.writeFileSync(`${pageDirectoryPath}/${componentName}Layout.tsx`,componentLayoutContent); fs.writeFileSync(`${pageDirectoryPath}/${componentName}.tsx`, componentContent); console.log(`Created directory: ${pageDirectoryPath}`); console.log(`Created component file: ${componentName}Layout.tsx`, `${componentName}.tsx`);
#ifndef ATOM_H #define ATOM_H #include <bits/stdc++.h> #include <math.h> #include <algorithm> #include <iostream> #include <memory> #include <numeric> #include <ostream> #include <set> #include <sstream> #include <string> namespace symbolicAlgebra { class Expression; } namespace symbolicAlgebra::implementation { class Utilities; } namespace symbolicAlgebra::implementation { class Atom { public: enum class AtomType { ANY, VARIABLE, NUMBER_INT, NUMBER_RAT, NUMBER_FRAC, CONSTANT, SUM, PRODUCT, POWER, SIN, COS, LOG }; std::vector<std::unique_ptr<Atom>> args; AtomType type; Atom(); explicit Atom(AtomType type); Atom(AtomType type, std::unique_ptr<Atom> arg); Atom(AtomType type, std::unique_ptr<Atom> arg1, std::unique_ptr<Atom> arg2); Atom(AtomType type, std::vector<std::unique_ptr<Atom>> args); Atom(const Atom& atom); Atom& operator=(const Atom& atom); virtual ~Atom(); virtual std::unique_ptr<Atom> copy() const = 0; virtual void print(std::ostream& stream) const = 0; virtual bool canBeEvaluated() const = 0; virtual double evaluate() const = 0; virtual std::unique_ptr<Atom> substitute(const std::string& variableName, const std::unique_ptr<Atom>& node) const = 0; virtual void getVariablesNames(std::set<std::string>& names) const = 0; virtual std::unique_ptr<Atom> differentiate(const std::string& variable) const = 0; virtual std::unique_ptr<Atom> simplify() const = 0; virtual std::unique_ptr<Atom> expand() const = 0; virtual bool compare(const std::unique_ptr<Atom>& other) const = 0; virtual std::unique_ptr<Atom> coefficient(const std::unique_ptr<Atom>& node) const = 0; static inline bool isNumber(const std::unique_ptr<Atom>& atom) { return (atom->type == AtomType::NUMBER_INT || atom->type == AtomType::NUMBER_RAT || atom->type == AtomType::NUMBER_FRAC); } static inline bool isOperator(const std::unique_ptr<Atom>& atom) { return (atom->type == AtomType::SUM || atom->type == AtomType::PRODUCT || atom->type == AtomType::POWER); } static inline bool isOperand(const std::unique_ptr<Atom>& atom) { return (atom->type == AtomType::NUMBER_INT || atom->type == AtomType::NUMBER_RAT || atom->type == AtomType::NUMBER_FRAC || atom->type == AtomType::CONSTANT || atom->type == AtomType::VARIABLE); } static inline bool isFunction(const std::unique_ptr<Atom>& atom) { return (atom->type == AtomType::SIN || atom->type == AtomType::COS || atom->type == AtomType::LOG); } friend std::ostream& operator<<(std::ostream& stream, const Atom& atom); }; } // namespace symbolicAlgebra::implementation #endif /* ATOM_H */
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {ProductsListComponent} from "./components/products-list/products-list.component"; import {LoginComponent} from "./components/login/login.component"; import {RegisterComponent} from "./components/register/register.component"; import {NotFoundPageComponent} from "./components/not-found-page/not-found-page.component"; import {MainLayoutComponent} from "./components/main-layout/main-layout.component"; import {ProductDetailsComponent} from "./components/product-details/product-details.component"; import {CartComponent} from "./components/cart/cart.component"; import {AuthGuard} from "./Guards/auth.guard"; const routes: Routes = [ {path: "", component: MainLayoutComponent, children: [ {path: "products", component: ProductsListComponent}, {path: "", redirectTo: "products", pathMatch: "full"}, {path: "products/:id", component: ProductDetailsComponent}, {path: "cart", component: CartComponent, canActivate: [AuthGuard]}, {path: "login", component: LoginComponent}, {path: "register", component: RegisterComponent}, ]}, {path: "**", component: NotFoundPageComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
function inv = nbin_inv (x, r, p) %NBIN_INV Inverse of Negative binomial cumulative distribution function (inv). % % Y = NBIN_CDF(X,R,P) Returns inverse of the Negative binomial cdf with % parameters R and P, at the values in X. % % The size of Y is the common size of the input arguments. A scalar input % functions as a constant matrix of the same size as the other inputs. % % Copyright (c) 1995-1997, 2007 Kurt Hornik % This software is distributed under the GNU General Public % Licence (version 3 or later); please refer to the file % Licence.txt, included with the software, for details. if (nargin ~= 3) error('3 parameters must be provided'); end if (~isscalar(r) || ~isscalar(p)) if ((size(x,1) ~= size(r,1)) || (size(r,1) ~= size(p,1))) error ('nbinpdf: x, r and p must be of common size or scalar'); end end inv = zeros (size (x)); k = find(isnan(x) | (x<0) | (x>1) | (r<1) | isinf(r) | (p<0) | (p>1)); if (any(k)) inv(k) = NaN; end k = find((x==1) & (r>0) & (r<Inf) & (p>=0) & (p<=1)); if (any(k)) inv(k) = Inf; end k = find((x>=0) & (x<1) & (r>0) & (r<Inf) & (p>0) & (p<=1)); if (any (k)) m = zeros (size (k)); x = x(k); if (isscalar (r) && isscalar (p)) s = p^r*ones(size(k)); while (1) l = find(s<x); if (any(l)) m(l) = m(l) + 1; s(l) = s(l) + nbin_pdf(m(l), r, p); else break; end end else r = r(k); p = p(k); s = p.^r; while (1) l = find(s < x); if (any(l)) m(l) = m(l) + 1; s(l) = s(l) + nbin_pdf(m(l), r(l), p(l)); else break; end end end inv(k) = m; end end
<!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>DongHoDemNguoc</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } .container { width: 600px; height: 200px; background-color: #f2f1ed; margin: 0 auto; text-align: center; padding: 12px } .countdownTime { display: flex; font-weight: bold; justify-content: center; align-items: center; margin: 0 auto; } .countdownTime div { margin-top: 30px; } .countdownTime h3 { color: red; font-size: 38px; background-color: #fff; border: 1px solid #ccc; margin: 20px; box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.2); padding: 8px } .bg-chicken { width: 550px; height: 450px; border: 1px solid #ccc; position: relative; margin: 20px auto; } .chickenBtn:hover { background-color: blue; cursor: pointer; } </style> </head> <body> <div class="container"> <h3>DRAF <span style="color:red">COUNTDOWN</span></h3> <div class="countdownTime"> <div> <p>HOUR</p> <h3 id="hour-countdown"> </h3> </div> <div> <p>MINUTE</p> <h3 id="minute-countdown"> </h3> </div> <div> <p>SECOND </p> <h3 id="second-countdown"> </h3> </div> </div> <div class="bg-chicken"> <h3>Scores: <span id="score"></span></h3> <div id="textChicken"></div> <div id="chicken"></div> </div> </div> </body> <script> var score = 0; var index = 10; //HÀM ĐỒNG HỒ ĐẾM NGƯỢC THEO GIÂY. function run() { let today = new Date let hourCountdown = today.getHours(); let minuteCountdown = today.getMinutes(); let secondCountdown = today.getSeconds(); //dùng phương thức setInterval để đếm ngược //CÁCH-1: // myInterval = setInterval(run, 1000); //CÁCH-2: setInterval(function () { secondCountdown--; if (secondCountdown <= 0) { console.log(secondCountdown); minuteCountdown -= 1; secondCountdown = 59; } if (minuteCountdown == -1) { hourCountdown -= 1; minuteCountdown = 59; } document.getElementById("hour-countdown").innerHTML = hourCountdown; document.getElementById("minute-countdown").innerHTML = minuteCountdown; document.getElementById("second-countdown").innerHTML = secondCountdown; }, 1000) } run(); function textChicken() { if (index > 0) { index-- document.getElementById("textChicken").innerHTML = "Gà con sẽ xuất hiện sau " + index + " giây"; } else { index = 10; } setTimeout(textChicken, 1000); } textChicken(); let chicken = document.getElementById("chicken"); let chickenImg = document.createElement("img"); var chickenInterval = ""; function addChicken() { chickenImg.src = "chicken.gif"; chickenImg.width = Math.floor((Math.random() * 300) - 50); chickenImg.style.position = "absolute"; chickenImg.style.top = Math.floor(Math.random() * 300) + "px"; chickenImg.style.left = Math.floor(Math.random() * 400) + "px"; chickenImg.style.right = Math.floor(Math.random() * 400) + "px"; chickenImg.classList.add("chickenBtn"); chickenImg.onclick = function () { chickenImg.src = ""; if (chickenImg.width <= 50) { score += 5; } else if (chickenImg.width <= 150) { score += 3; } else if (chickenImg.width <= 250) { score++; } document.getElementById("score").innerHTML = score; } chicken.appendChild(chickenImg); setTimeout(addChicken, 11000); } addChicken(); function hideChicken() { chickenImg.src = ""; setTimeout(hideChicken, 5000); } hideChicken(); </script> </html>
import sys import argparse import gymnasium as gym import math import random import matplotlib import matplotlib.pyplot as plt from collections import namedtuple, deque from itertools import count from tree import SumTree from utils import set_seed import csv import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class ReplayBuffer: def __init__(self, state_size, action_size, buffer_size, device): # state, action, reward, next_state, done self.state = torch.empty(buffer_size, state_size, dtype=torch.float) self.action = torch.empty(buffer_size, action_size, dtype=torch.float) self.reward = torch.empty(buffer_size, dtype=torch.float) self.next_state = torch.empty(buffer_size, state_size, dtype=torch.float) self.done = torch.empty(buffer_size, dtype=torch.int) self.count = 0 self.real_size = 0 self.size = buffer_size self.device = device def add(self, transition): state, action, reward, next_state, done = transition # store transition in the buffer self.state[self.count] = torch.as_tensor(state) self.action[self.count] = torch.as_tensor(action) self.reward[self.count] = torch.as_tensor(reward) self.next_state[self.count] = torch.as_tensor(next_state) self.done[self.count] = torch.as_tensor(done) # update counters self.count = (self.count + 1) % self.size self.real_size = min(self.size, self.real_size + 1) def sample(self, batch_size): assert self.real_size >= batch_size sample_idxs = np.random.choice(self.real_size, batch_size, replace=False) batch = ( self.state[sample_idxs].to(self.device), self.action[sample_idxs].to(self.device), self.reward[sample_idxs].to(self.device), self.next_state[sample_idxs].to(self.device), self.done[sample_idxs].to(self.device) ) return batch class DQN(nn.Module): def __init__(self, n_observations, n_actions): super(DQN, self).__init__() self.layer1 = nn.Linear(n_observations, 24) self.layer2 = nn.Linear(24, 24) self.layer3 = nn.Linear(24, n_actions) # Called with either one element to determine next action, or a batch # during optimization. Returns tensor([[left0exp,right0exp]...]). def forward(self, x): x = F.silu(self.layer1(x)) x = F.silu(self.layer2(x)) return self.layer3(x) def main(): print(f"Trial: {sys.argv[1]}") # BATCH_SIZE is the number of transitions sampled from the replay buffer # GAMMA is the discount factor as mentioned in the previous section # EPS_START is the starting value of epsilon # EPS_END is the final value of epsilon # EPS_DECAY controls the rate of exponential decay of epsilon, higher means a slower decay # TAU is the update rate of the target network # LR is the learning rate of the ``AdamW`` optimizer BATCH_SIZE = 64 GAMMA = 0.99 EPS_START = 0.9 EPS_END = 0.01 EPS_DECAY = 1000 TAU = 0.005 LR = 1e-4 TRAIN_START = 1000 steps_done = 0 with open(f'data/no_frill_doubledqn_trial{sys.argv[1]}.csv', 'w', newline='') as csvfile: fieldnames = ['episode', 'duration'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() env = gym.make("CartPole-v1") # torch.manual_seed(sys.argv[1]) set_seed(env, int(sys.argv[1])) device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") # Initialize replay memory D to capacity N N = 50_000 replay_mem = ReplayBuffer(4, 1, N, device) # Initialize action-value function Q with random weights policy_net = DQN(4, 2).to(device) target_net = DQN(4, 2).to(device) # target_net = DQN(4, 2).to(device) optimizer = optim.AdamW(policy_net.parameters(), lr=LR) # For episode 1 --> M for i in range(600): # Initialize the environment and get it's state. Do any preprocessing here state, info = env.reset() state = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0) for t in range(500): # With probability epislon, select random action a_t sample = random.random() eps_threshold = EPS_END + (EPS_START - EPS_END) * \ math.exp(-1. * steps_done / EPS_DECAY) if sample <= eps_threshold: a_t = torch.tensor([[env.action_space.sample()]], device=device, dtype=torch.long) # otherwise select a_t = max_a Q*(state, action; theta) # t.max(1) will return the largest column value of each row. # second column on max result is index of where max element was # found, so we pick action with the larger expected reward. else: with torch.no_grad(): a_t = policy_net(state).max(1)[1].view(1, 1) # execute action, a_t, in emulator aka env observation, reward, terminated, truncated, _ = env.step(a_t.item()) # set s_{t+1} = s_t, a_t, x_{t+1} reward = torch.tensor([reward], device=device) done = terminated or truncated next_state = observation next_state = torch.tensor(next_state, dtype=torch.float32, device=device).unsqueeze(0) # store transition (s_t, a_t, r_t, s_{t+1}) in D replay_mem.add((state, a_t, reward, next_state, int(done))) # sample minibatch (s_j, a_j, r_j, s_{j+1}) (b=64) of transitions from D if replay_mem.real_size > TRAIN_START: state_b, action_b, reward_b, next_state_b, done_b = replay_mem.sample(BATCH_SIZE) # Q(s′,argmax a ′Q(s ′,a ′;θ i);θ i−) Q_next = target_net(next_state_b).max(1)[0] y_i = reward + (1-done_b) * GAMMA * Q_next # Compute Q(s_t, a) - the model computes Q(s_t), then we select the Q = policy_net(state_b)[torch.arange(len(action_b)), action_b.to(torch.long).flatten()] loss = torch.mean((y_i - Q)**2) optimizer.zero_grad() loss.backward() optimizer.step() with torch.no_grad(): # Soft update of the target network's weights # θ′ ← τ θ + (1 −τ )θ′ for tp, sp in zip(target_net.parameters(), policy_net.parameters()): tp.data.copy_((1 - TAU) * tp.data + TAU * sp.data) state = next_state # increment global step counter for steps_done += 1 if done: writer.writerow({"episode": i, "duration":t}) csvfile.flush() break if __name__=="__main__": main()
/* Copyright 2022-2022 Stephane Cuillerdier (aka aiekick) 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. */ #pragma once #include <Headers/Globals.h> #include <ImGuiPack.h> #include <ctools/cTools.h> #include <ctools/Logger.h> #include <ctools/ConfigAbstract.h> #include <LumoBackend/Systems/FrameActionSystem.h> #include <LumoBackend/Graph/Graph.h> #include <LumoBackend/Interfaces/GuiInterface.h> #include <Gaia/Interfaces/iService.h> #include <Gaia/Interfaces/iSurface.h> #include <Frontend/MainFrontend.h> #include <Backend/MainBackend.h> #include <functional> #include <string> #include <vector> #include <map> /* Actions behavior : new project : - unsaved : - add action : show unsaved dialog - add action : new project - saved : - add action : new project open project : - unsaved : - add action : show unsaved dialog - add action : open project - saved : - add action : open project re open project : - unsaved : - add action : show unsaved dialog - add action : re open project - saved : - add action : re open project save project : - never saved : - add action : save as project - saved in a file beofre : - add action : save project save as project : - add action : save as project Close project : - unsaved : - add action : show unsaved dialog - add action : Close project - saved : - add action : Close project Close app : - unsaved : - add action : show unsaved dialog - add action : Close app - saved : - add action : Close app Unsaved dialog behavior : - save : - insert action : save project - save as : - insert action : save as project - continue without saving : - quit unsaved dialog - cancel : - clear actions open font : - add action : open font close font : - ok : - glyphs selected : - add action : show a confirmation dialog (ok/cancel for lose glyph selection) - add action : close font - no glyph selected : - add action : close font - cancel : - clear actions confirmation dialog for close font : - ok : - quit the dialog - cancel : - clear actions */ class MainFrontend : public gaia::iService, public gaia::iSurface<ct::ivec2>, public conf::ConfigAbstract, public GuiInterface { private: MainFrontendWeak m_This; MainBackendWeak m_MainBackend; bool m_ShowImGui = false; bool m_ShowMetric = false; ImFont* m_ToolbarFontPtr = nullptr; ImVec2 m_DisplayPos = ImVec2(0, 0); // viewport ImVec2 m_DisplaySize = ImVec2(1280, 720); bool m_ShowAboutDialog = false; // show about dlg bool m_SaveDialogIfRequired = false; // open save options dialog (save / save as / continue without saving / cancel) bool m_SaveDialogActionWasDone = false; // if action was done by save options dialog FrameActionSystem m_ActionSystem; public: static MainFrontendPtr create(); static bool sCentralWindowHovered; public: virtual ~MainFrontend(); bool init() override; void unit() override; bool isValid() const override; bool isThereAnError() const override; void setBackend(const MainBackendWeak& vBackend); void SelectNode(const BaseNodeWeak& vNode); void SelectNodeForGraphOutput(const NodeSlotWeak& vSlot, const ImGuiMouseButton& vButton); void Display(const uint32_t& vCurrentFrame); FrameActionSystem* GetActionSystem() { return &m_ActionSystem; } void setSize(const ct::ivec2& vSize) override; const ct::ivec2& getSize() const override; bool resize(const ct::ivec2& vNewSize) override; bool DrawWidgets(const uint32_t& vCurrentFrame, ImGuiContext* vContextPtr, const std::string& vUserDatas) override; bool DrawOverlays(const uint32_t& vCurrentFrame, const ImRect& vRect, ImGuiContext* vContextPtr, const std::string& vUserDatas) override; bool DrawDialogsAndPopups(const uint32_t& vCurrentFrame, const ImVec2& vMaxSize, ImGuiContext* vContextPtr, const std::string& vUserDatas) override; void OpenAboutDialog(); public: // save : on quit or project loading void IWantToCloseTheApp(); // user want close app, but we want to ensure its saved public: // drop void JustDropFiles(int count, const char** paths); private: // save : on quit or project loading void OpenUnSavedDialog(); // show a dialog because the project file is not saved void CloseUnSavedDialog(); // show a dialog because the project file is not saved bool ShowUnSavedDialog(); // show a dilaog because the project file is not saved public: // actions // via menu void Action_Menu_NewProject(); void Action_Menu_OpenProject(); void Action_Menu_ReOpenProject(); void Action_Menu_SaveProject(); void Action_Menu_SaveAsProject(); void Action_Menu_CloseProject(); void Action_Window_CloseApp(); private: // actions // via the unsaved dialog bool Action_UnSavedDialog_SaveProject(); void Action_UnSavedDialog_SaveAsProject(); void Action_UnSavedDialog_Cancel(); // others void Action_OpenUnSavedDialog_IfNeeded(); void Action_Cancel(); // dialog funcs to be in actions bool Display_NewProjectDialog(); bool Display_OpenProjectDialog(); bool Display_SaveProjectDialog(); public: // configuration std::string getXml(const std::string& vOffset, const std::string& vUserDatas = "") override; bool setFromXml(tinyxml2::XMLElement* vElem, tinyxml2::XMLElement* vParent, const std::string& vUserDatas = "") override; private: bool m_build() override; bool m_build_themes(); void m_drawMainMenuBar(); void m_drawMainStatusBar(); void m_drawLeftButtonBar(); void m_CanMouseAffectRendering(); };
use std::collections::BTreeMap; use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_json::value::Value; use tera::Context; use crate::render::Render; #[derive(Clone, Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct Vars { #[serde(flatten)] pub map: BTreeMap<String, Value>, } fn render_value<S: AsRef<str>>(value: &mut Value, context: &Context, place: S) -> Result<()> { match value { Value::String(s) => *s = s.render(context, format!("variables in {}", place.as_ref()))?, Value::Object(m) => { for (_, v) in m.iter_mut() { render_value(v, context, place.as_ref())?; } } Value::Array(a) => { for v in a.iter_mut() { render_value(v, context, place.as_ref())?; } } _ => {} } Ok(()) } impl Vars { pub fn new(map: BTreeMap<String, Value>) -> Self { Self { map } } pub fn extend(&mut self, other: Self) { self.map.extend(other.map); } pub fn context(&self) -> Result<Context> { let context = Context::from_serialize(self)?; Ok(context) } } impl Render for Vars { fn render<S: AsRef<str>>(&self, context: &Context, place: S) -> Result<Self> { let mut new_map = BTreeMap::new(); for (name, value) in &self.map { let mut value = value.to_owned(); render_value(&mut value, context, place.as_ref())?; new_map.insert(name.to_string(), value); } Ok(Self::new(new_map)) } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. use crate::cast::*; /// Attempts to cast an `ArrayDictionary` with index type K into /// `to_type` for supported types. /// /// K is the key type pub(crate) fn dictionary_cast<K: ArrowDictionaryKeyType>( array: &dyn Array, to_type: &DataType, cast_options: &CastOptions, ) -> Result<ArrayRef, ArrowError> { use DataType::*; match to_type { Dictionary(to_index_type, to_value_type) => { let dict_array = array .as_any() .downcast_ref::<DictionaryArray<K>>() .ok_or_else(|| { ArrowError::ComputeError( "Internal Error: Cannot cast dictionary to DictionaryArray of expected type".to_string(), ) })?; let keys_array: ArrayRef = Arc::new(PrimitiveArray::<K>::from(dict_array.keys().to_data())); let values_array = dict_array.values(); let cast_keys = cast_with_options(&keys_array, to_index_type, cast_options)?; let cast_values = cast_with_options(values_array, to_value_type, cast_options)?; // Failure to cast keys (because they don't fit in the // target type) results in NULL values; if cast_keys.null_count() > keys_array.null_count() { return Err(ArrowError::ComputeError(format!( "Could not convert {} dictionary indexes from {:?} to {:?}", cast_keys.null_count() - keys_array.null_count(), keys_array.data_type(), to_index_type ))); } let data = cast_keys.into_data(); let builder = data .into_builder() .data_type(to_type.clone()) .child_data(vec![cast_values.into_data()]); // Safety // Cast keys are still valid let data = unsafe { builder.build_unchecked() }; // create the appropriate array type let new_array: ArrayRef = match **to_index_type { Int8 => Arc::new(DictionaryArray::<Int8Type>::from(data)), Int16 => Arc::new(DictionaryArray::<Int16Type>::from(data)), Int32 => Arc::new(DictionaryArray::<Int32Type>::from(data)), Int64 => Arc::new(DictionaryArray::<Int64Type>::from(data)), UInt8 => Arc::new(DictionaryArray::<UInt8Type>::from(data)), UInt16 => Arc::new(DictionaryArray::<UInt16Type>::from(data)), UInt32 => Arc::new(DictionaryArray::<UInt32Type>::from(data)), UInt64 => Arc::new(DictionaryArray::<UInt64Type>::from(data)), _ => { return Err(ArrowError::CastError(format!( "Unsupported type {to_index_type:?} for dictionary index" ))); } }; Ok(new_array) } _ => unpack_dictionary::<K>(array, to_type, cast_options), } } // Unpack a dictionary where the keys are of type <K> into a flattened array of type to_type pub(crate) fn unpack_dictionary<K>( array: &dyn Array, to_type: &DataType, cast_options: &CastOptions, ) -> Result<ArrayRef, ArrowError> where K: ArrowDictionaryKeyType, { let dict_array = array.as_dictionary::<K>(); let cast_dict_values = cast_with_options(dict_array.values(), to_type, cast_options)?; take(cast_dict_values.as_ref(), dict_array.keys(), None) } /// Attempts to encode an array into an `ArrayDictionary` with index /// type K and value (dictionary) type value_type /// /// K is the key type pub(crate) fn cast_to_dictionary<K: ArrowDictionaryKeyType>( array: &dyn Array, dict_value_type: &DataType, cast_options: &CastOptions, ) -> Result<ArrayRef, ArrowError> { use DataType::*; match *dict_value_type { Int8 => pack_numeric_to_dictionary::<K, Int8Type>(array, dict_value_type, cast_options), Int16 => pack_numeric_to_dictionary::<K, Int16Type>(array, dict_value_type, cast_options), Int32 => pack_numeric_to_dictionary::<K, Int32Type>(array, dict_value_type, cast_options), Int64 => pack_numeric_to_dictionary::<K, Int64Type>(array, dict_value_type, cast_options), UInt8 => pack_numeric_to_dictionary::<K, UInt8Type>(array, dict_value_type, cast_options), UInt16 => pack_numeric_to_dictionary::<K, UInt16Type>(array, dict_value_type, cast_options), UInt32 => pack_numeric_to_dictionary::<K, UInt32Type>(array, dict_value_type, cast_options), UInt64 => pack_numeric_to_dictionary::<K, UInt64Type>(array, dict_value_type, cast_options), Decimal128(_, _) => { pack_numeric_to_dictionary::<K, Decimal128Type>(array, dict_value_type, cast_options) } Decimal256(_, _) => { pack_numeric_to_dictionary::<K, Decimal256Type>(array, dict_value_type, cast_options) } Utf8 => pack_byte_to_dictionary::<K, GenericStringType<i32>>(array, cast_options), LargeUtf8 => pack_byte_to_dictionary::<K, GenericStringType<i64>>(array, cast_options), Binary => pack_byte_to_dictionary::<K, GenericBinaryType<i32>>(array, cast_options), LargeBinary => pack_byte_to_dictionary::<K, GenericBinaryType<i64>>(array, cast_options), _ => Err(ArrowError::CastError(format!( "Unsupported output type for dictionary packing: {dict_value_type:?}" ))), } } // Packs the data from the primitive array of type <V> to a // DictionaryArray with keys of type K and values of value_type V pub(crate) fn pack_numeric_to_dictionary<K, V>( array: &dyn Array, dict_value_type: &DataType, cast_options: &CastOptions, ) -> Result<ArrayRef, ArrowError> where K: ArrowDictionaryKeyType, V: ArrowPrimitiveType, { // attempt to cast the source array values to the target value type (the dictionary values type) let cast_values = cast_with_options(array, dict_value_type, cast_options)?; let values = cast_values.as_primitive::<V>(); let mut b = PrimitiveDictionaryBuilder::<K, V>::with_capacity(values.len(), values.len()); // copy each element one at a time for i in 0..values.len() { if values.is_null(i) { b.append_null(); } else { b.append(values.value(i))?; } } Ok(Arc::new(b.finish())) } // Packs the data as a GenericByteDictionaryBuilder, if possible, with the // key types of K pub(crate) fn pack_byte_to_dictionary<K, T>( array: &dyn Array, cast_options: &CastOptions, ) -> Result<ArrayRef, ArrowError> where K: ArrowDictionaryKeyType, T: ByteArrayType, { let cast_values = cast_with_options(array, &T::DATA_TYPE, cast_options)?; let values = cast_values .as_any() .downcast_ref::<GenericByteArray<T>>() .unwrap(); let mut b = GenericByteDictionaryBuilder::<K, T>::with_capacity(values.len(), 1024, 1024); // copy each element one at a time for i in 0..values.len() { if values.is_null(i) { b.append_null(); } else { b.append(values.value(i))?; } } Ok(Arc::new(b.finish())) }
Array#each_cons(cnt)はselfからcnt個ずつ要素を取り出しブロックに渡します。ブロック引数には配列で渡されます。 取り出す要素は、[要素1, 要素2, 要素3], [要素2, 要素3, 要素4] ...と1つづ前に進みます。 似たメソッドにArray#each_slick(cnt)があります。 以下が、それぞれの実行結果です。 (1..10).each_cons(3) {|arr| p arr } # <実行結果> # [1, 2, 3] # [2, 3, 4] # [3, 4, 5] # [4, 5, 6] # [5, 6, 7] # [6, 7, 8] # [7, 8, 9] # [8, 9, 10] (1..10).each_slice(3) {|arr| p arr } # <実行結果> # [1, 2, 3] # [4, 5, 6] # [7, 8, 9] # [10] Rubyではメソッド内で定数を定義することができません。 複数回メソッドを呼び出した場合に、定数が不定となるため定義できません。 宣言された場合は、SyntaxErrorが発生します。 Hash#delete(:key)はレシーバーからkeyの項目を削除します。 このメソッドは破壊的メソッドです。 次の表が、問題文と選択肢のメソッドの一覧と意味です。 メソッド名 意味 find_all, select 各要素に対してブロックを評価した結果が、真である要素の配列を作成し返します find, detect 要素に対してブロックを評価した結果が、最初に真になった要素を返します collect, map 各要素に対してブロックを評価した結果を配列に格納し返します delete_if, reject! ブロックを評価した値が真になった最初の要素を返します a+ recode 1 recode 2 recode 3 RECODE 1 RECODE 2 RECODE 3 a+はファイルを読み込みモード + 追記書き込みモードで開きます。 ファイルの読み込みは、ファイルの先頭から行いますが、書き込みは、ファイルの末尾に行います。 f.rewindでファイルポインタをファイルの先頭に移動したとしても、ファイルの末尾に書き込まれます。 w+ 空ファイルになります。 w+は新規作成・読み込み + 書き込みモードで開きます。 既にファイルが存在する場合は、空になります。 r+ RECODE 1 RECODE 2 RECODE 3 r+は読み込み + 書き込みモードで開きます。 ----- p [1,2,3,4].map do |e| e * e end do ... endと{ ... }を比べた場合、{ ... }の方が結合度が強いです。 問題の式の場合、do ... endの結合度が弱いため、p([1, 2, 3, 4].map)が評価されます。 問題のように式の内容を直接使用する際は、{ ... }を使用します。 ----- strip 文字列の先頭と末尾の空白文字(\t\r\n\f\v)を取り除きます。 strip! 文字列の先頭と末尾の空白文字(\t\r\n\f\v)を破壊的に取り除きます。 chomp 末尾から改行コードを取り除きます。 chop 末尾の文字を取り除きます。ただし、文字列の末尾が"\r\n"であれば、2文字とも取り除きます。 ----- to_s 文字列 to_i 整数 to_f 浮動小数点 to_r 有理数 to_c 複素数 to_sym シンボル
/* eslint-disable react/prop-types */ import { Formik, Form, Field } from "formik"; import { Box, Button, Flex, FormLabel, Image, Radio, SimpleGrid, Text, } from "@chakra-ui/react"; // import { quizData } from "../database/data"; import { GoArrowLeft, GoArrowRight } from "react-icons/go"; import { useDispatch } from "react-redux"; import { addOrUpdateAnsweredObject, changeTimeUp } from "../app/slice/frontend"; const Questions = ({ questionNumber, setQuestionNumber, quizData }) => { const dispatch = useDispatch(); const initialValues = quizData.reduce((acc, question) => { return { ...acc, [`Question ${question._id}`]: "" }; }, {}); const onChange = (e) => { const { value } = e.target; const id = quizData[questionNumber]._id; const option = quizData[questionNumber].options.find( (each) => each.option === value ); const index = questionNumber; const newObject = { id, option, index }; dispatch(addOrUpdateAnsweredObject(newObject)); }; const onSubmit = () => { dispatch(changeTimeUp(true)); }; const nextQuestion = () => { setQuestionNumber((prev) => prev + 1); }; const prevQuestion = () => { setQuestionNumber((prev) => prev - 1); }; return ( <Formik initialValues={initialValues} onSubmit={onSubmit}> {() => ( <Form> <Box mb={"25px"}> {quizData[questionNumber].question.image && ( <Flex justifyContent={"center"} mb={"10px"}> <Box width={"100%"} height={{ base: "200px", md: "220px", lg: "300px", }} > <Image w={"100%"} h={"100%"} objectFit={"fit"} alt="Question Image" src={quizData[questionNumber].question.image} /> </Box> </Flex> )} <Text as={"h1"} textAlign={"center"}> {quizData[questionNumber].question.question} </Text> </Box> <Box mb={"40px"}> <Field name={`Question ${quizData[questionNumber]._id}`}> {({ field, form }) => { // console.log(field); return ( <SimpleGrid columns={{ base: 1, lg: 2 }} spacing={7}> {quizData[questionNumber].options.map((each) => ( <Box key={each._id}> <Radio {...field} id={each.option} type="radio" value={each.option} isChecked={field.value === each.option} display={"none"} onChange={(e) => { onChange(e); form.setFieldValue( `Question ${quizData[questionNumber]._id}`, e.target.value ); }} /> <FormLabel htmlFor={each.option} style={{ width: "100%" }} > <Box border={ field.value === each.option ? "2px solid #ce151f" : "1px solid black" } p={"10px"} className="cursor active" h={"100%"} > <Text> {each.option}. {each.answerText} </Text> </Box> </FormLabel> </Box> ))} </SimpleGrid> ); }} </Field> </Box> <Flex justifyContent={questionNumber === 0 ? "flex-end" : "space-between"} > {questionNumber !== 0 && ( <Button type="button" bgColor={"#b8bcbd"} color={"black"} width={"45%"} size={{ base: "sm", md: "md", lg: "lg" }} leftIcon={<GoArrowLeft />} onClick={prevQuestion} _hover={{ bgColor: "rgb(184, 188, 189, 0.6)", }} className="active" > Previous </Button> )} {questionNumber !== quizData.length - 1 && ( <Button type="button" bgColor={"#ce151f"} color={"white"} width={"45%"} size={{ base: "sm", md: "md", lg: "lg" }} rightIcon={<GoArrowRight />} onClick={nextQuestion} _hover={{ bgColor: "rgb(206, 21, 31, 0.6)", }} className="active" > Next </Button> )} {questionNumber === quizData.length - 1 && ( <Button type="submit" bgColor={"#ce151f"} color={"white"} width={"45%"} size={{ base: "sm", md: "md", lg: "lg" }} _hover={{ bgColor: "rgb(206, 21, 31, 0.6)", }} className="active" > Submit </Button> )} </Flex> </Form> )} </Formik> ); }; export default Questions;
from numbers import Number from _common_decl cimport * from cython.operator cimport dereference as deref from _cy_affine cimport cy_Affine, get_Affine, is_transform cdef class cy_GenericInterval: """ Represents all numbers between min and max. Corresponds to GenericInterval in 2geom. min and max can be arbitrary python object, they just have to implement arithmetic operations and comparison - fractions.Fraction works. This is a bit experimental, it leak memory right now. """ cdef GenericInterval[WrappedPyObject]* thisptr def __cinit__(self, u = 0, v = None): """Create GenericInterval from either one or two values.""" if v is None: self.thisptr = new GenericInterval[WrappedPyObject]( WrappedPyObject(u) ) else: self.thisptr = new GenericInterval[WrappedPyObject]( WrappedPyObject(u), WrappedPyObject(v) ) def __str__(self): """str(self)""" return "[{}, {}]".format(self.min(), self.max()) def __repr__(self): """repr(self)""" if self.is_singular(): return "GenericInterval({})".format( str(self.min()) ) return "GenericInterval({}, {})".format( str(self.min()) , str(self.max()) ) def __dealloc__(self): del self.thisptr @classmethod def from_Interval(self, i): """Create GenericInterval with same minimum and maximum as argument.""" return cy_GenericInterval( i.min(), i.max() ) @classmethod def from_list(self, lst): """Create GenericInterval containing all values in list.""" if len(lst) == 0: return cy_GenericInterval() ret = cy_GenericInterval(lst[0]) for i in lst[1:]: ret.expand_to(i) return ret def min(self): """Return minimal value of interval.""" return self.thisptr.min().getObj() def max(self): """Return maximal value of interval.""" return self.thisptr.max().getObj() def extent(self): """Return difference between maximal and minimal value.""" return self.thisptr.extent().getObj() def middle(self): """Return midpoint of interval.""" return self.thisptr.middle().getObj() def is_singular(self): """Test for one-valued interval.""" return self.thisptr.isSingular() def set_min(self, val): """Set minimal value.""" self.thisptr.setMin( WrappedPyObject(val) ) def set_max(self, val): """Set maximal value.""" self.thisptr.setMax( WrappedPyObject(val) ) def expand_to(self, val): """Create smallest superset of self containing value.""" self.thisptr.expandTo( WrappedPyObject(val) ) def expand_by(self, val): """Push both boundaries by value.""" self.thisptr.expandBy( WrappedPyObject(val) ) def union_with(self, cy_GenericInterval interval): """self = self | other""" self.thisptr.unionWith( deref(interval.thisptr) ) def contains(self, other): """Check if interval contains value.""" return self.thisptr.contains( WrappedPyObject(other) ) def contains_interval(self, cy_GenericInterval other): """Check if interval contains every point of interval.""" return self.thisptr.contains( deref(other.thisptr) ) def intersects(self, cy_GenericInterval other): """Check for intersecting intervals.""" return self.thisptr.intersects(deref( other.thisptr )) def __neg__(self): """Return interval with negated boundaries.""" return wrap_GenericInterval(-deref(self.thisptr)) def _add_pyobj(self, X): return wrap_GenericInterval(deref(self.thisptr) + WrappedPyObject(X) ) def _sub_pyobj(self, X): return wrap_GenericInterval(deref(self.thisptr) - WrappedPyObject(X) ) def _add_interval(self, cy_GenericInterval I): return wrap_GenericInterval(deref(self.thisptr)+deref(I.thisptr)) def _sub_interval(self, cy_GenericInterval I): return wrap_GenericInterval(deref(self.thisptr)-deref(I.thisptr)) def __add__(cy_GenericInterval self, other): """Add interval or value to self. Interval I+J consists of all values i+j such that i is in I and j is in J Interval I+x consists of all values i+x such that i is in I. """ if isinstance(other, cy_GenericInterval): return self._add_interval(other) else: return self._add_pyobj(other) def __sub__(cy_GenericInterval self, other): """Substract interval or value. Interval I-J consists of all values i-j such that i is in I and j is in J Interval I-x consists of all values i-x such that i is in I. """ if isinstance(other, cy_GenericInterval): return self._sub_interval(other) else: return self._sub_pyobj(other) def __or__(cy_GenericInterval self, cy_GenericInterval I): """Return a union of two intervals""" return wrap_GenericInterval(deref(self.thisptr)|deref(I.thisptr)) def _eq(self, cy_GenericInterval other): return deref(self.thisptr)==deref(other.thisptr) def _neq(self, cy_GenericInterval other): return deref(self.thisptr)!=deref(other.thisptr) def __richcmp__(cy_GenericInterval self, other, op): """Intervals are not ordered.""" if op == 2: return self._eq(other) elif op == 3: return self._neq(other) cdef cy_GenericInterval wrap_GenericInterval(GenericInterval[WrappedPyObject] p): cdef GenericInterval[WrappedPyObject] * retp = new GenericInterval[WrappedPyObject](WrappedPyObject(0)) retp[0] = p cdef cy_GenericInterval r = cy_GenericInterval.__new__( cy_GenericInterval, 0, 0) r.thisptr = retp return r cdef class cy_GenericOptInterval: """Class representing optionally empty interval. Empty interval has False bool value, and using methods that require non-empty interval will result in ValueError. This is supposed to be used this way: >>> C = A & B >>> if C: >>> print C.min() This class represents GenericOptInterval with python object boundaries. It tries to model behaviour of std::optional. """ cdef GenericOptInterval[WrappedPyObject]* thisptr def __cinit__(self, u = None, v = None): """Create interval from boundaries. Using no arguments, you will end up with empty interval.""" if u is None: self.thisptr = new GenericOptInterval[WrappedPyObject]() elif v is None: self.thisptr = new GenericOptInterval[WrappedPyObject](WrappedPyObject(u)) else: self.thisptr = new GenericOptInterval[WrappedPyObject](WrappedPyObject(u), WrappedPyObject(v) ) def __bool__(self): """Logical value of interval, False only for empty interval.""" return not self.thisptr.isEmpty() def __str__(self): """str(self)""" if not self: return "[]" return "[{}, {}]".format(self.Interval.min(), self.Interval.max()) def __repr__(self): """repr(self)""" if not self: return "GenericOptInterval()" if self.Interval.isSingular(): return "GenericOptInterval({})".format( str(self.Interval.min()) ) return "GenericOptInterval({}, {})".format( str(self.Interval.min()) , str(self.Interval.max()) ) def __dealloc__(self): del self.thisptr @classmethod def from_Interval(self, i): """Create interval from existing interval.""" if hasattr(i, "isEmpty"): if i.isEmpty(): return cy_GenericOptInterval() else: return cy_GenericOptInterval.from_Interval(i.Interval) return cy_GenericOptInterval( i.min(), i.max() ) @classmethod def from_list(self, lst): """Create interval containing all values in list. Empty list will result in empty interval.""" if len(lst) == 0: return cy_GenericOptInterval() ret = cy_GenericOptInterval(lst[0]) for i in lst[1:]: ret.Interval.expandTo(i) return ret property Interval: """Get underlying GenericInterval.""" def __get__(self): if self.is_empty(): raise ValueError("Interval is empty.") else: return wrap_GenericInterval(self.thisptr.get()) def is_empty(self): """Check whether interval is empty set.""" return self.thisptr.isEmpty() def union_with(self, cy_GenericOptInterval o): """self = self | other""" self.thisptr.unionWith( deref(o.thisptr) ) def intersect_with(cy_GenericOptInterval self, cy_GenericOptInterval o): """self = self & other""" self.thisptr.intersectWith( deref(o.thisptr) ) def __or__(cy_GenericOptInterval self, cy_GenericOptInterval o): """Return a union of two intervals.""" return wrap_GenericOptInterval(deref(self.thisptr) | deref(o.thisptr)) def __and__(cy_GenericOptInterval self, cy_GenericOptInterval o): """Return an intersection of two intervals.""" return wrap_GenericOptInterval(deref(self.thisptr) & deref(o.thisptr)) def __richcmp__(cy_GenericOptInterval self, cy_GenericOptInterval o, int op): """Intervals are not ordered.""" if op == 2: return deref(self.thisptr) == deref(o.thisptr) elif op == 3: return deref(self.thisptr) != deref(o.thisptr) return NotImplemented def _get_Interval_method(self, name): def f(*args, **kwargs): if self.is_empty(): raise ValueError("GenericOptInterval is empty.") else: return self.Interval.__getattribute__(name)(*args, **kwargs) return f def __getattr__(self, name): Interval_methods = set(['contains', 'contains_interval', 'expand_by', 'expand_to', 'extent', 'from_Interval', 'from_list', 'intersects', 'is_singular', 'max', 'middle', 'min', 'set_max', 'set_min', 'union_with']) if name in Interval_methods: return self._get_Interval_method(name) else: raise AttributeError("GenericOptInterval instance has no attribute \"{}\"".format(name)) def _wrap_Interval_method(self, name, *args, **kwargs): if self.isEmpty(): raise ValueError("GenericOptInterval is empty.") else: return self.Interval.__getattr__(name)(*args, **kwargs) #declaring these by hand, because they take fixed number of arguments, #which is enforced by cython def __neg__(self): """Return interval with negated boundaries.""" return self._wrap_Interval_method("__sub__") def __add__(cy_Interval self, other): """Add interval or value to self. Interval I+J consists of all values i+j such that i is in I and j is in J Interval I+x consists of all values i+x such that i is in I. """ return self._wrap_Interval_method("__add__", other) def __sub__(cy_Interval self, other): """Substract interval or value. Interval I-J consists of all values i-j such that i is in I and j is in J Interval I-x consists of all values i-x such that i is in I. """ return self._wrap_Interval_method("__sub__", other) cdef cy_GenericOptInterval wrap_GenericOptInterval(GenericOptInterval[WrappedPyObject] p): cdef GenericOptInterval[WrappedPyObject] * retp = new GenericOptInterval[WrappedPyObject]() retp[0] = p cdef cy_GenericOptInterval r = cy_GenericOptInterval.__new__(cy_GenericOptInterval) r.thisptr = retp return r cdef class cy_Interval: """Class representing interval on real line. Corresponds to Interval class in 2geom. """ def __cinit__(self, u = None, v = None): """Create interval from it's boundaries. One argument will create interval consisting that value, no arguments create Interval(0). """ if u is None: self.thisptr = new Interval() elif v is None: self.thisptr = new Interval(<Coord>float(u)) else: self.thisptr = new Interval(<Coord>float(u), <Coord>float(v)) def __str__(self): """str(self)""" return "[{}, {}]".format(self.min(), self.max()) def __repr__(self): """repr(self)""" if self.is_singular(): return "Interval({})".format( str(self.min()) ) return "Interval({}, {})".format( str(self.min()) , str(self.max()) ) def __dealloc__(self): del self.thisptr @classmethod def from_Interval(c, i): """Create Interval with same boundaries as argument.""" return cy_Interval( i.min(), i.max() ) @classmethod def from_list(cls, lst): """Create interval containing all values in a list.""" if len(lst) == 0: return cy_Interval() ret = cy_Interval(lst[0]) for i in lst[1:]: ret.expand_to(i) return ret def min(self): """Return minimal boundary.""" return self.thisptr.min() def max(self): """Return maximal boundary.""" return self.thisptr.max() def extent(self): """Return length of interval.""" return self.thisptr.extent() def middle(self): """Return middle value.""" return self.thisptr.middle() def set_min(self, Coord val): """Set minimal value.""" self.thisptr.setMin(val) def set_max(self, Coord val): """Set maximal value.""" self.thisptr.setMax(val) def expand_to(self, Coord val): """Set self to smallest superset of set containing value.""" self.thisptr.expandTo(val) def expand_by(self, Coord amount): """Move both boundaries by amount.""" self.thisptr.expandBy(amount) def union_with(self, cy_Interval a): """self = self | other""" self.thisptr.unionWith(deref( a.thisptr )) # Not exposing this - deprecated # def __getitem__(self, unsigned int i): # return deref(self.thisptr)[i] def is_singular(self): """Test if interval contains only one value.""" return self.thisptr.isSingular() def isFinite(self): """Test for finiteness of interval's extent.""" return self.thisptr.isFinite() def contains(cy_Interval self, other): """Test if interval contains number.""" return self.thisptr.contains(float(other)) def contains_interval(cy_Interval self, cy_Interval other): """Test if interval contains another interval.""" return self.thisptr.contains( deref(other.thisptr) ) def intersects(self, cy_Interval val): """Test for intersection of intervals.""" return self.thisptr.intersects(deref( val.thisptr )) def interior_contains(cy_Interval self, other): """Test if interior of iterval contains number.""" return self.thisptr.interiorContains(float(other)) def interior_contains_interval(cy_Interval self, cy_Interval other): """Test if interior of interval contains another interval.""" return self.thisptr.interiorContains( <Interval &> deref(other.thisptr) ) def interior_intersects(self, cy_Interval val): """Test for intersection of interiors of two points.""" return self.thisptr.interiorIntersects(deref( val.thisptr )) def _cmp_Interval(cy_Interval self, cy_Interval other, op): if op == 2: return deref(self.thisptr) == deref(other.thisptr) elif op == 3: return deref(self.thisptr) != deref(other.thisptr) def _cmp_IntInterval(cy_Interval self, cy_IntInterval other, op): if op == 2: return deref(self.thisptr) == deref(other.thisptr) elif op == 3: return deref(self.thisptr) != deref(other.thisptr) def __richcmp__(cy_Interval self, other, op): """Intervals are not ordered.""" if isinstance(other, cy_Interval): return self._cmp_Interval(other, op) elif isinstance(other, cy_IntInterval): return self._cmp_IntInterval(other, op) def __neg__(self): """Return interval with negated boundaries.""" return wrap_Interval(-deref(self.thisptr)) def _add_number(self, Coord X): return wrap_Interval(deref(self.thisptr)+X) def _sub_number(self, Coord X): return wrap_Interval(deref(self.thisptr)-X) def _mul_number(self, Coord X): return wrap_Interval(deref(self.thisptr)*X) def _add_interval(self, cy_Interval I): return wrap_Interval(deref(self.thisptr)+deref(I.thisptr)) def _sub_interval(self, cy_Interval I): return wrap_Interval(deref(self.thisptr)-deref(I.thisptr)) def _mul_interval(self, cy_Interval I): return wrap_Interval(deref(self.thisptr)*deref(I.thisptr)) def __mul__(cy_Interval self, other): """Multiply interval by interval or number. Multiplying by number simply multiplies boundaries, multiplying intervals creates all values that can be written as product i*j of i in I and j in J. """ if isinstance(other, Number): return self._mul_number(float(other)) else: return self._mul_interval(other) def __add__(cy_Interval self, other): """Add interval or value to self. Interval I+J consists of all values i+j such that i is in I and j is in J Interval I+x consists of all values i+x such that i is in I. """ if isinstance(other, Number): return self._add_number(float(other)) else: return self._add_interval(other) def __sub__(cy_Interval self, other): """Substract interval or value. Interval I-J consists of all values i-j such that i is in I and j is in J Interval I-x consists of all values i-x such that i is in I. """ if isinstance(other, Number): return self._sub_number(float(other)) else: return self._sub_interval(other) def __div__(cy_Interval self, Coord s): """Divide boundaries by number.""" return wrap_Interval(deref(self.thisptr)/s) def __or__(cy_Interval self, cy_Interval I): """Return union of two intervals.""" return wrap_Interval(deref(self.thisptr)|deref(I.thisptr)) def round_outwards(self): """Create the smallest IntIterval that is superset.""" return wrap_IntInterval(self.thisptr.roundOutwards()) def round_inwards(self): """Create the largest IntInterval that is subset.""" return wrap_OptIntInterval(self.thisptr.roundInwards()) cdef cy_Interval wrap_Interval(Interval p): cdef Interval * retp = new Interval() retp[0] = p cdef cy_Interval r = cy_Interval.__new__(cy_Interval) r.thisptr = retp return r cdef class cy_OptInterval: """Class representing optionally empty interval on real line. Empty interval has False bool value, and using methods that require non-empty interval will result in ValueError. This is supposed to be used this way: >>> C = A & B >>> if C: >>> print C.min() This class represents OptInterval. It tries to model behaviour of std::optional. """ def __cinit__(self, u = None, v = None): """Create optionally empty interval form it's endpoints. No arguments will result in empty interval. """ if u is None: self.thisptr = new OptInterval() elif v is None: self.thisptr = new OptInterval(<Coord>float(u)) else: self.thisptr = new OptInterval(<Coord>float(u), <Coord>float(v)) def __bool__(self): """Only empty interval is False.""" return not self.thisptr.isEmpty() def __str__(self): """str(self)""" if not self: return "[]" return "[{}, {}]".format(self.Interval.min(), self.Interval.max()) def __repr__(self): """repr(self)""" if not self: return "OptInterval()" if self.Interval.isSingular(): return "OptInterval({})".format( str(self.Interval.min()) ) return "OptInterval({}, {})".format( str(self.Interval.min()) , str(self.Interval.max()) ) def __dealloc__(self): del self.thisptr @classmethod def from_Interval(cls, i): """Create interval from other (possibly empty) interval.""" if hasattr(i, "isEmpty"): if i.isEmpty(): return cy_OptInterval() else: return cy_OptInterval.from_Interval(i.Interval) return cy_OptInterval( i.min(), i.max() ) @classmethod def from_list(self, lst): """Create interval containing all values in list. Empty list will result in empty interval.""" if len(lst) == 0: return cy_OptInterval() ret = cy_OptInterval(lst[0]) for i in lst[1:]: ret.Interval.expandTo(i) return ret property Interval: """Get underlying Interval.""" def __get__(self): if self.is_empty(): raise ValueError("Interval is empty.") else: return wrap_Interval(self.thisptr.get()) def is_empty(self): """Test for empty interval.""" return self.thisptr.isEmpty() def union_with(self, cy_OptInterval o): """self = self | other""" self.thisptr.unionWith( deref(o.thisptr) ) def intersect_with(cy_OptInterval self, cy_OptInterval o): """self = self & other""" self.thisptr.intersectWith( deref(o.thisptr) ) def __or__(cy_OptInterval self, cy_OptInterval o): """Return union of intervals.""" return wrap_OptInterval(deref(self.thisptr) | deref(o.thisptr)) def __and__(cy_OptInterval self, cy_OptInterval o): """Return intersection of intervals.""" return wrap_OptInterval(deref(self.thisptr) & deref(o.thisptr)) def _get_Interval_method(self, name): def f(*args, **kwargs): if self.is_empty(): raise ValueError("OptInterval is empty.") else: return self.Interval.__getattribute__(name)(*args, **kwargs) return f def __getattr__(self, name): Interval_methods = set(['contains', 'contains_interval', 'expand_by', 'expand_to', 'extent', 'from_Interval', 'from_list', 'interior_contains', 'interior_contains_interval', 'interior_intersects', 'intersects', 'isFinite', 'is_singular', 'max', 'middle', 'min', 'round_inwards', 'round_outwards', 'set_max', 'set_min', 'union_with']) if name in Interval_methods: return self._get_Interval_method(name) else: raise AttributeError("OptInterval instance has no attribute \"{}\"".format(name)) def _wrap_Interval_method(self, name, *args, **kwargs): if self.isEmpty(): raise ValueError("OptInterval is empty.") else: return self.Interval.__getattr__(name)(*args, **kwargs) #declaring these by hand, because they take fixed number of arguments, #which is enforced by cython def __neg__(self): """Return interval with negated boundaries.""" return self._wrap_Interval_method("__sub__") def __mul__(cy_Interval self, other): """Multiply interval by interval or number. Multiplying by number simply multiplies boundaries, multiplying intervals creates all values that can be written as product i*j of i in I and j in J. """ return self._wrap_Interval_method("__mul__", other) def __add__(cy_Interval self, other): """Add interval or value to self. Interval I+J consists of all values i+j such that i is in I and j is in J Interval I+x consists of all values i+x such that i is in I. """ return self._wrap_Interval_method("__add__", other) def __sub__(cy_Interval self, other): """Substract interval or value. Interval I-J consists of all values i-j such that i is in I and j is in J Interval I-x consists of all values i-x such that i is in I. """ return self._wrap_Interval_method("__sub__", other) def __div__(cy_Interval self, other): """Divide boundaries by number.""" return self._wrap_Interval_method("__div__", other) cdef cy_OptInterval wrap_OptInterval(OptInterval p): cdef OptInterval * retp = new OptInterval() retp[0] = p cdef cy_OptInterval r = cy_OptInterval.__new__(cy_OptInterval) r.thisptr = retp return r cdef class cy_IntInterval: """Class representing interval of integers. Corresponds to IntInterval class in 2geom. """ cdef IntInterval* thisptr def __cinit__(self, u = None, v = None): """Create interval from it's boundaries. One argument will create interval consisting that value, no arguments create IntInterval(0). """ if u is None: self.thisptr = new IntInterval() elif v is None: self.thisptr = new IntInterval(<IntCoord>int(u)) else: self.thisptr = new IntInterval(<IntCoord>int(u), <IntCoord>int(v)) def __str__(self): """str(self)""" return "[{}, {}]".format(self.min(), self.max()) def __repr__(self): """repr(self)""" if self.is_singular(): return "IntInterval({})".format( str(self.min()) ) return "IntInterval({}, {})".format( str(self.min()) , str(self.max()) ) def __dealloc__(self): del self.thisptr @classmethod def from_Interval(cls, i): return cy_IntInterval( int(i.min()), int(i.max()) ) @classmethod def from_list(cls, lst): if len(lst) == 0: return cy_IntInterval() ret = cy_IntInterval(lst[0]) for i in lst[1:]: ret.expand_to(i) return ret def min(self): """Return minimal boundary.""" return self.thisptr.min() def max(self): """Return maximal boundary.""" return self.thisptr.max() def extent(self): """Return length of interval.""" return self.thisptr.extent() def middle(self): """Return middle value.""" return self.thisptr.middle() def set_min(self, IntCoord val): """Set minimal value.""" self.thisptr.setMin(val) def set_max(self, IntCoord val): """Set maximal value.""" self.thisptr.setMax(val) def expand_to(self, IntCoord val): """Set self to smallest superset of set containing value.""" self.thisptr.expandTo(val) def expand_by(self, IntCoord amount): """Move both boundaries by amount.""" self.thisptr.expandBy(amount) def union_with(self, cy_IntInterval a): """self = self | other""" self.thisptr.unionWith(deref( a.thisptr )) # Not exposing this - deprecated # def __getitem__(self, unsigned int i): # return deref(self.thisptr)[i] def is_singular(self): """Test if interval contains only one value.""" return self.thisptr.isSingular() def contains(cy_IntInterval self, other): """Test if interval contains number.""" return self.thisptr.contains(<IntCoord> int(other)) def contains_interval(cy_IntInterval self, cy_IntInterval other): """Test if interval contains another interval.""" return self.thisptr.contains( deref(other.thisptr) ) def intersects(self, cy_IntInterval val): """Test for intersection with other interval.""" return self.thisptr.intersects(deref( val.thisptr )) def __richcmp__(cy_IntInterval self, cy_IntInterval other, op): """Intervals are not ordered.""" if op == 2: return deref(self.thisptr) == deref(other.thisptr) elif op == 3: return deref(self.thisptr) != deref(other.thisptr) def __neg__(self): """Negate interval's endpoints.""" return wrap_IntInterval(-deref(self.thisptr)) def _add_number(self, IntCoord X): return wrap_IntInterval(deref(self.thisptr)+X) def _sub_number(self, IntCoord X): return wrap_IntInterval(deref(self.thisptr)-X) def _add_interval(self, cy_IntInterval I): return wrap_IntInterval(deref(self.thisptr)+deref(I.thisptr)) def _sub_interval(self, cy_IntInterval I): return wrap_IntInterval(deref(self.thisptr)-deref(I.thisptr)) def __add__(cy_IntInterval self, other): """Add interval or value to self. Interval I+J consists of all values i+j such that i is in I and j is in J Interval I+x consists of all values i+x such that i is in I. """ if isinstance(other, Number): return self._add_number(int(other)) else: return self._add_interval(other) def __sub__(cy_IntInterval self, other): """Substract interval or value. Interval I-J consists of all values i-j such that i is in I and j is in J Interval I-x consists of all values i-x such that i is in I. """ if isinstance(other, Number): return self._sub_number(int(other)) else: return self._sub_interval(other) def __or__(cy_IntInterval self, cy_IntInterval I): """Return union of two intervals.""" return wrap_IntInterval(deref(self.thisptr)|deref(I.thisptr)) cdef cy_IntInterval wrap_IntInterval(IntInterval p): cdef IntInterval * retp = new IntInterval() retp[0] = p cdef cy_IntInterval r = cy_IntInterval.__new__(cy_IntInterval) r.thisptr = retp return r cdef class cy_OptIntInterval: """Class representing optionally empty interval of integers. Empty interval has False bool value, and using methods that require non-empty interval will result in ValueError. This is supposed to be used this way: >>> C = A & B >>> if C: >>> print C.min() This class represents OptIntInterval. It tries to model behaviour of std::optional. """ cdef OptIntInterval* thisptr def __cinit__(self, u = None, v = None): """Create optionally empty interval form it's endpoints. No arguments will result in empty interval. """ if u is None: self.thisptr = new OptIntInterval() elif v is None: self.thisptr = new OptIntInterval(<IntCoord>int(u)) else: self.thisptr = new OptIntInterval(<IntCoord>int(u), <IntCoord>int(v)) def __bool__(self): """Only empty interval is False.""" return not self.thisptr.isEmpty() def __str__(self): """str(self)""" if not self: return "[]" return "[{}, {}]".format(self.Interval.min(), self.Interval.max()) def __repr__(self): """repr(self)""" if not self: return "OptIntInterval()" if self.Interval.isSingular(): return "OptIntInterval({})".format( str(self.Interval.min()) ) return "OptIntInterval({}, {})".format( str(self.Interval.min()) , str(self.Interval.max()) ) def __dealloc__(self): del self.thisptr @classmethod def from_Interval(self, i): """Create interval from other (possibly empty) interval.""" if hasattr(i, "isEmpty"): if i.isEmpty(): return cy_OptIntInterval() else: return cy_OptIntInterval.from_Interval(i.Interval) return cy_OptIntInterval( i.min(), i.max() ) @classmethod def from_list(self, lst): """Create interval containing all values in list. Empty list will result in empty interval.""" if len(lst) == 0: return cy_OptIntInterval() ret = cy_OptIntInterval(lst[0]) for i in lst[1:]: ret.Interval.expandTo(i) return ret property Interval: """Get underlying interval.""" def __get__(self): return wrap_IntInterval(self.thisptr.get()) def is_empty(self): """Test for empty interval.""" return self.thisptr.isEmpty() def union_with(self, cy_OptIntInterval o): """self = self | other""" self.thisptr.unionWith( deref(o.thisptr) ) def intersect_with(cy_OptIntInterval self, cy_OptIntInterval o): """self = self & other""" self.thisptr.intersectWith( deref(o.thisptr) ) def __or__(cy_OptIntInterval self, cy_OptIntInterval o): """Return a union of two intervals.""" return wrap_OptIntInterval(deref(self.thisptr) | deref(o.thisptr)) def __and__(cy_OptIntInterval self, cy_OptIntInterval o): """Return an intersection of two intervals.""" return wrap_OptIntInterval(deref(self.thisptr) & deref(o.thisptr)) #TODO decide how to implement various combinations of comparisons! def _get_Interval_method(self, name): def f(*args, **kwargs): if self.is_empty(): raise ValueError("OptInterval is empty.") else: return self.Interval.__getattribute__(name)(*args, **kwargs) return f def __getattr__(self, name): Interval_methods = set(['contains', 'contains_interval', 'expand_by', 'expand_to', 'extent', 'from_Interval', 'from_list', 'intersects', 'is_singular', 'max', 'middle', 'min', 'set_max', 'set_min', 'union_with']) if name in Interval_methods: return self._get_Interval_method(name) else: raise AttributeError("OptIntInterval instance has no attribute \"{}\"".format(name)) def _wrap_Interval_method(self, name, *args, **kwargs): if self.isEmpty(): raise ValueError("OptIntInterval is empty.") else: return self.Interval.__getattr__(name)(*args, **kwargs) #declaring these by hand, because they take fixed number of arguments, #which is enforced by cython def __neg__(self): """Negate interval's endpoints.""" return self._wrap_Interval_method("__sub__") def __add__(cy_Interval self, other): """Add interval or value to self. Interval I+J consists of all values i+j such that i is in I and j is in J Interval I+x consists of all values i+x such that i is in I. """ return self._wrap_Interval_method("__add__", other) def __sub__(cy_Interval self, other): """Substract interval or value. Interval I-J consists of all values i-j such that i is in I and j is in J Interval I-x consists of all values i-x such that i is in I. """ return self._wrap_Interval_method("__sub__", other) cdef cy_OptIntInterval wrap_OptIntInterval(OptIntInterval p): cdef OptIntInterval * retp = new OptIntInterval() retp[0] = p cdef cy_OptIntInterval r = cy_OptIntInterval.__new__(cy_OptIntInterval) r.thisptr = retp return r cdef class cy_GenericRect: """Class representing axis aligned rectangle, with arbitrary corners. Plane in which the rectangle lies can have any object as a coordinates, as long as they implement arithmetic operations and comparison. This is a bit experimental, corresponds to GenericRect[C] templated with (wrapped) python object. """ cdef GenericRect[WrappedPyObject]* thisptr def __cinit__(self, x0=0, y0=0, x1=0, y1=0): """Create rectangle from it's top-left and bottom-right corners.""" self.thisptr = new GenericRect[WrappedPyObject](WrappedPyObject(x0), WrappedPyObject(y0), WrappedPyObject(x1), WrappedPyObject(y1)) def __str__(self): """str(self)""" return "Rectangle with dimensions {}, topleft point {}".format( str(self.dimensions()), str(self.min())) def __repr__(self): """repr(self)""" return "Rect({}, {}, {}, {})".format( str(self.left()), str(self.top()), str(self.right()), str(self.bottom()) ) def __dealloc__(self): del self.thisptr @classmethod def from_intervals(self, I, J): """Create rectangle from two intervals. First interval corresponds to side parallel with x-axis, second one with side parallel with y-axis.""" return cy_GenericRect(I.min(), I.max(), J.min(), J.max()) @classmethod def from_list(cls, lst): """Create rectangle containing all points in list. These points are represented simply by 2-tuples. """ ret = cy_GenericRect() for a in lst: ret.expand_to(a) return ret @classmethod def from_xywh(cls, x, y, w, h): """Create rectangle from topleft point and dimensions.""" return wrap_GenericRect( from_xywh(WrappedPyObject(x), WrappedPyObject(y), WrappedPyObject(w), WrappedPyObject(h))) def __getitem__(self, Dim2 d): """self[i]""" return wrap_GenericInterval( deref(self.thisptr)[d] ) def min(self): """Get top-left point.""" return wrap_PyPoint( self.thisptr.min() ) def max(self): """Get bottom-right point.""" return wrap_PyPoint( self.thisptr.max() ) def corner(self, unsigned int i): """Get corners (modulo) indexed from 0 to 3.""" return wrap_PyPoint( self.thisptr.corner(i) ) def top(self): """Get top coordinate.""" return self.thisptr.top().getObj() def bottom(self): """Get bottom coordinate.""" return self.thisptr.bottom().getObj() def left(self): """Get left coordinate.""" return self.thisptr.left().getObj() def right(self): """Get right coordinate.""" return self.thisptr.right().getObj() def width(self): """Get width.""" return self.thisptr.width().getObj() def height(self): """Get height.""" return self.thisptr.height().getObj() #For some reason, Cpp aspectRatio returns Coord. def aspectRatio(self): """Get ratio between width and height.""" return float(self.width())/float(self.height()) def dimensions(self): """Get dimensions as tuple.""" return wrap_PyPoint( self.thisptr.dimensions() ) def midpoint(self): """Get midpoint as tuple.""" return wrap_PyPoint( self.thisptr.midpoint() ) def area(self): """Get area.""" return self.thisptr.area().getObj() def has_zero_area(self): """Test for area being zero.""" return self.thisptr.hasZeroArea() def max_extent(self): """Get bigger value from width, height.""" return self.thisptr.maxExtent().getObj() def min_extent(self): """Get smaller value from width, height.""" return self.thisptr.minExtent().getObj() def intersects(self, cy_GenericRect r): """Check if rectangle intersects another rectangle.""" return self.thisptr.intersects(deref( r.thisptr )) def contains(self, r): """Check if rectangle contains point represented as tuple.""" if not isinstance(r, tuple): raise TypeError("Tuple required to create point.") return self.thisptr.contains( make_PyPoint(r) ) def contains_rect(self, cy_GenericRect r): """Check if rectangle contains another rect.""" return self.thisptr.contains( deref(r.thisptr) ) def set_left(self, val): """Set left coordinate.""" self.thisptr.setLeft( WrappedPyObject(val) ) def set_right(self, val): """Set right coordinate.""" self.thisptr.setRight( WrappedPyObject(val) ) def set_top(self, val): """Set top coordinate.""" self.thisptr.setTop( WrappedPyObject(val) ) def set_bottom(self, val): """Set bottom coordinate.""" self.thisptr.setBottom( WrappedPyObject(val) ) def set_min(self, p): """Set top-left point.""" self.thisptr.setMin(make_PyPoint(p)) def set_max(self, p): """Set bottom-right point.""" self.thisptr.setMax(make_PyPoint(p)) def expand_to(self, p): """Expand rectangle to contain point represented as tuple.""" self.thisptr.expandTo(make_PyPoint(p)) def union_with(self, cy_GenericRect b): """self = self | other.""" self.thisptr.unionWith(deref( b.thisptr )) def expand_by(self, x, y = None): """Expand both intervals. Either expand them both by one value, or each by different value. """ if y is None: self.thisptr.expandBy(WrappedPyObject(x)) else: self.thisptr.expandBy(WrappedPyObject(x), WrappedPyObject(y)) def __add__(cy_GenericRect self, p): """Offset rectangle by point.""" return wrap_GenericRect( deref(self.thisptr) + make_PyPoint(p) ) def __sub__(cy_GenericRect self, p): """Offset rectangle by -point.""" return wrap_GenericRect( deref(self.thisptr) - make_PyPoint(p) ) def __or__(cy_GenericRect self, cy_GenericRect o): """Return union of two rects - it's actually bounding rect of union.""" return wrap_GenericRect( deref(self.thisptr) | deref( o.thisptr )) def __richcmp__(cy_GenericRect self, cy_GenericRect o, int op): """Rectangles are not ordered.""" if op == 2: return deref(self.thisptr) == deref(o.thisptr) if op == 3: return deref(self.thisptr) != deref(o.thisptr) cdef PyPoint make_PyPoint(p): return PyPoint( WrappedPyObject(p[0]), WrappedPyObject(p[1]) ) #D2[WrappedPyObject] is converted to tuple cdef wrap_PyPoint(PyPoint p): return (p[0].getObj(), p[1].getObj()) cdef cy_GenericRect wrap_GenericRect(GenericRect[WrappedPyObject] p): cdef WrappedPyObject zero = WrappedPyObject(0) cdef GenericRect[WrappedPyObject] * retp = new GenericRect[WrappedPyObject](zero, zero, zero, zero) retp[0] = p cdef cy_GenericRect r = cy_GenericRect.__new__(cy_GenericRect) r.thisptr = retp return r cdef class cy_Rect: """Class representing axis-aligned rectangle in 2D real plane. Corresponds to Rect class in 2geom.""" def __cinit__(self, Coord x0=0, Coord y0=0, Coord x1=0, Coord y1=0): """Create Rect from coordinates of its top-left and bottom-right corners.""" self.thisptr = new Rect(x0, y0, x1, y1) def __str__(self): """str(self)""" return "Rectangle with dimensions {}, topleft point {}".format(str(self.dimensions()), str(self.min())) def __repr__(self): """repr(self)""" return "Rect({}, {}, {}, {})".format( str(self.left()), str(self.top()), str(self.right()), str(self.bottom())) def __dealloc__(self): del self.thisptr @classmethod def from_points(cls, cy_Point p0, cy_Point p1): """Create rectangle from it's top-left and bottom-right corners.""" return wrap_Rect( Rect(deref(p0.thisptr), deref(p1.thisptr)) ) @classmethod def from_intervals(cls, I, J): """Create rectangle from two intervals representing its sides.""" return wrap_Rect( Rect( float(I.min()), float(J.min()), float(I.max()), float(J.max()) ) ) @classmethod def from_list(cls, lst): """Create rectangle containing all points in list.""" if lst == []: return cy_Rect() if len(lst) == 1: return cy_Rect.from_points(lst[0], lst[0]) ret = cy_Rect.from_points(lst[0], lst[1]) for a in lst: ret.expand_to(a) return ret @classmethod def from_xywh(cls, x, y, w, h): """Create rectangle from it's topleft point and dimensions.""" return wrap_Rect( from_xywh(<Coord> x, <Coord> y, <Coord> w, <Coord> h) ) @classmethod def infinite(self): """Create infinite rectangle.""" return wrap_Rect(infinite()) def __getitem__(self, Dim2 d): """self[d]""" return wrap_Interval( deref(self.thisptr)[d] ) def min(self): """Get top-left point.""" return wrap_Point( self.thisptr.min() ) def max(self): """Get bottom-right point.""" return wrap_Point( self.thisptr.max() ) def corner(self, unsigned int i): """Get corners (modulo) indexed from 0 to 3.""" return wrap_Point( self.thisptr.corner(i) ) def top(self): """Get top coordinate.""" return self.thisptr.top() def bottom(self): """Get bottom coordinate.""" return self.thisptr.bottom() def left(self): """Get left coordinate.""" return self.thisptr.left() def right(self): """Get right coordinate.""" return self.thisptr.right() def width(self): """Get width.""" return self.thisptr.width() def height(self): """Get height.""" return self.thisptr.height() def aspect_ratio(self): """Get ratio between width and height.""" return self.thisptr.aspectRatio() def dimensions(self): """Get dimensions as point.""" return wrap_Point( self.thisptr.dimensions() ) def midpoint(self): """Get midpoint.""" return wrap_Point( self.thisptr.midpoint() ) def area(self): """Get area.""" return self.thisptr.area() def has_zero_area(self, Coord eps = EPSILON): """Test for area being zero.""" return self.thisptr.hasZeroArea(eps) def max_extent(self): """Get bigger value from width, height.""" return self.thisptr.maxExtent() def min_extent(self): """Get smaller value from width, height.""" return self.thisptr.minExtent() def intersects(self, cy_Rect r): """Check if rectangle intersects another rectangle.""" return self.thisptr.intersects(deref( r.thisptr )) def contains(self, cy_Point r): """Check if rectangle contains point.""" return self.thisptr.contains( deref(r.thisptr) ) def contains_rect(self, cy_Rect r): """Check if rectangle contains another rect.""" return self.thisptr.contains( deref(r.thisptr) ) def interior_intersects(self, cy_Rect r): """Check if interior of self intersects another rectangle.""" return self.thisptr.interiorIntersects(deref( r.thisptr )) def interior_contains(self, cy_Point other): """Check if interior of self contains point.""" return self.thisptr.interiorContains( deref( (<cy_Point> other).thisptr ) ) def interior_contains_rect(self, other): """Check if interior of self contains another rectangle.""" if isinstance(other, cy_Rect): return self.thisptr.interiorContains( deref( (<cy_Rect> other).thisptr ) ) elif isinstance(other, cy_OptRect): return self.thisptr.interiorContains( deref( (<cy_OptRect> other).thisptr ) ) def set_left(self, Coord val): """Set left coordinate.""" self.thisptr.setLeft(val) def set_right(self, Coord val): """Set right coordinate.""" self.thisptr.setRight(val) def set_top(self, Coord val): """Set top coordinate.""" self.thisptr.setTop(val) def set_bottom(self, Coord val): """Set bottom coordinate.""" self.thisptr.setBottom(val) def set_min(self, cy_Point p): """Set top-left point.""" self.thisptr.setMin( deref( p.thisptr ) ) def set_max(self, cy_Point p): """Set bottom-right point.""" self.thisptr.setMax( deref( p.thisptr )) def expand_to(self, cy_Point p): """Expand rectangle to contain point represented as tuple.""" self.thisptr.expandTo( deref( p.thisptr ) ) def union_with(self, cy_Rect b): """self = self | other.""" self.thisptr.unionWith(deref( b.thisptr )) def expand_by(cy_Rect self, x, y = None): """Expand both intervals. Either expand them both by one value, or each by different value. """ if y is None: if isinstance(x, cy_Point): self.thisptr.expandBy( deref( (<cy_Point> x).thisptr ) ) else: self.thisptr.expandBy( <Coord> x) else: self.thisptr.expandBy( <Coord> x, <Coord> y) def __add__(cy_Rect self, cy_Point p): """Offset rectangle by point.""" return wrap_Rect( deref(self.thisptr) + deref( p.thisptr ) ) def __sub__(cy_Rect self, cy_Point p): """Offset rectangle by -point.""" return wrap_Rect( deref(self.thisptr) - deref( p.thisptr ) ) def __mul__(cy_Rect self, t): """Apply transform to rectangle.""" cdef Affine at if is_transform(t): at = get_Affine(t) return wrap_Rect( deref(self.thisptr) * at ) def __or__(cy_Rect self, cy_Rect o): """Return union of two rects - it's actually bounding rect of union.""" return wrap_Rect( deref(self.thisptr) | deref( o.thisptr )) def __richcmp__(cy_Rect self, o, int op): """Rectangles are not ordered.""" if op == 2: if isinstance(o, cy_Rect): return deref(self.thisptr) == deref( (<cy_Rect> o).thisptr) elif isinstance(o, cy_IntRect): return deref(self.thisptr) == deref( (<cy_IntRect> o).thisptr) if op == 3: if isinstance(o, cy_Rect): return deref(self.thisptr) != deref( (<cy_Rect> o).thisptr) elif isinstance(o, cy_IntRect): return deref(self.thisptr) != deref( (<cy_IntRect> o).thisptr) def round_inwards(self): """Create OptIntRect rounding inwards.""" return wrap_OptIntRect(self.thisptr.roundInwards()) def round_outwards(self): """Create IntRect rounding outwards.""" return wrap_IntRect(self.thisptr.roundOutwards()) @classmethod def distanceSq(cls, cy_Point p, cy_Rect rect): """Compute square of distance between point and rectangle.""" return distanceSq( deref(p.thisptr), deref(rect.thisptr) ) @classmethod def distance(cls, cy_Point p, cy_Rect rect): """Compute distance between point and rectangle.""" return distance( deref(p.thisptr), deref(rect.thisptr) ) cdef cy_Rect wrap_Rect(Rect p): cdef Rect* retp = new Rect() retp[0] = p cdef cy_Rect r = cy_Rect.__new__(cy_Rect) r.thisptr = retp return r cdef class cy_OptRect: """Class representing optionally empty rect in real plane. This class corresponds to OptRect in 2geom, and it tries to mimic the behaviour of std::optional. In addition to OptRect methods, this class passes calls for Rect methods to underlying Rect class, or throws ValueError when it's empty. """ def __cinit__(self, x0=None, y0=None, x1=None, y1=None): """Create OptRect from coordinates of top-left and bottom-right corners. No arguments will result in empty rectangle. """ if x0 is None: self.thisptr = new OptRect() else: self.thisptr = new OptRect( float(x0), float(y0), float(x1), float(y1) ) def __str__(self): """str(self)""" if self.is_empty(): return "Empty OptRect." return "OptRect with dimensions {}, topleft point {}".format(str(self.dimensions()), str(self.min())) def __repr__(self): """repr(self)""" if self.is_empty(): return "OptRect()" return "OptRect({}, {}, {}, {})".format( str(self.left()), str(self.top()), str(self.right()), str(self.bottom())) def __dealloc__(self): del self.thisptr @classmethod def from_points(cls, cy_Point p0, cy_Point p1): """Create rectangle from it's top-left and bottom-right corners.""" return wrap_OptRect( OptRect(deref(p0.thisptr), deref(p1.thisptr)) ) @classmethod def from_intervals(cls, I, J): """Create rectangle from two intervals representing its sides.""" if hasattr(I, "isEmpty"): if I.isEmpty(): return cy_OptRect() if hasattr(J, "isEmpty"): if J.isEmpty(): return cy_OptRect() return wrap_OptRect( OptRect( float(I.min()), float(J.min()), float(I.max()), float(J.max()) ) ) @classmethod def from_rect(cls, r): """Create OptRect from other, possibly empty, rectangle.""" if hasattr(r, "isEmpty"): if r.isEmpty(): return cy_OptRect() return cy_OptRect( r.min().x, r.min().y, r.max().x, r.max().y ) @classmethod def from_list(cls, lst): """Create OptRect containing all points in the list. Empty list will result in empty OptRect. """ if lst == []: return cy_OptRect() if len(lst) == 1: return cy_OptRect.from_points(lst[0], lst[0]) ret = cy_OptRect.from_points(lst[0], lst[1]) for a in lst: ret.expand_to(a) return ret property Rect: """Get underlying Rect.""" def __get__(self): if self.is_empty(): raise ValueError("Rect is empty.") else: return wrap_Rect(self.thisptr.get()) def __bool__(self): """OptRect is False only when it's empty.""" return not self.thisptr.isEmpty() def is_empty(self): """Check for OptRect containing no points.""" return self.thisptr.isEmpty() def intersects(self, other): """Check if rectangle intersects another rectangle.""" if isinstance(other, cy_Rect): return self.thisptr.intersects( deref( (<cy_Rect> other).thisptr ) ) elif isinstance(other, cy_OptRect): return self.thisptr.intersects( deref( (<cy_OptRect> other).thisptr ) ) def contains(self, cy_Point r): """Check if rectangle contains point.""" return self.thisptr.contains( deref(r.thisptr) ) def contains_rect(self, other): """Check if rectangle contains another rect.""" if isinstance(other, cy_Rect): return self.thisptr.contains( deref( (<cy_Rect> other).thisptr ) ) elif isinstance(other, cy_OptRect): return self.thisptr.contains( deref( (<cy_OptRect> other).thisptr ) ) def union_with(self, other): """self = self | other.""" if isinstance(other, cy_Rect): self.thisptr.unionWith( deref( (<cy_Rect> other).thisptr ) ) elif isinstance(other, cy_OptRect): self.thisptr.unionWith( deref( (<cy_OptRect> other).thisptr ) ) def intersect_with(self, other): """self = self & other.""" if isinstance(other, cy_Rect): self.thisptr.intersectWith( deref( (<cy_Rect> other).thisptr ) ) elif isinstance(other, cy_OptRect): self.thisptr.intersectWith( deref( (<cy_OptRect> other).thisptr ) ) def expand_to(self, cy_Point p): """Expand rectangle to contain point represented as tuple.""" self.thisptr.expandTo( deref(p.thisptr) ) def __or__(cy_OptRect self, cy_OptRect other): """Return union of two rects - it's actually bounding rect of union.""" return wrap_OptRect( deref(self.thisptr) | deref(other.thisptr) ) def __and__(cy_OptRect self, other): """Return intersection of two rectangles.""" if isinstance(other, cy_Rect): return wrap_OptRect( deref(self.thisptr) & deref( (<cy_Rect> other).thisptr) ) elif isinstance(other, cy_OptRect): return wrap_OptRect( deref(self.thisptr) & deref( (<cy_OptRect> other).thisptr) ) def __richcmp__(cy_OptRect self, other, op): """Rectangles are not ordered.""" if op == 2: if isinstance(other, cy_Rect): return deref(self.thisptr) == deref( (<cy_Rect> other).thisptr ) elif isinstance(other, cy_OptRect): return deref(self.thisptr) == deref( (<cy_OptRect> other).thisptr ) elif op == 3: if isinstance(other, cy_Rect): return deref(self.thisptr) != deref( (<cy_Rect> other).thisptr ) elif isinstance(other, cy_OptRect): return deref(self.thisptr) != deref( (<cy_OptRect> other).thisptr ) return NotImplemented def _get_Rect_method(self, name): def f(*args, **kwargs): if self.is_empty(): raise ValueError("OptRect is empty.") else: return self.Rect.__getattribute__(name)(*args, **kwargs) return f def __getattr__(self, name): Rect_methods = set(['area', 'aspectRatio', 'bottom', 'contains', 'contains_rect', 'corner', 'dimensions', 'distance', 'distanceSq', 'expand_by', 'expand_to', 'has_zero_area', 'height', 'infinite', 'interior_contains', 'interior_contains_rect', 'interior_intersects', 'intersects', 'left', 'max', 'max_extent', 'midpoint', 'min', 'min_extent', 'right', 'round_inwards', 'round_outwards', 'set_bottom', 'set_left', 'set_max', 'set_min', 'set_right', 'set_top', 'top', 'union_with', 'width']) if name in Rect_methods: return self._get_Rect_method(name) else: raise AttributeError("OptRect instance has no attribute \"{}\"".format(name)) def _wrap_Rect_method(self, name, *args, **kwargs): if self.isEmpty(): raise ValueError("OptRect is empty.") else: return self.Rect.__getattr__(name)(*args, **kwargs) #declaring these by hand, because they take fixed number of arguments, #which is enforced by cython def __getitem__(self, i): """self[d]""" return self._wrap_Rect_method("__getitem__", i) def __add__(self, other): """Offset rectangle by point.""" return self._wrap_Rect_method("__add__", other) def __mul__(self, other): """Apply transform to rectangle.""" return self._wrap_Rect_method("__mul__", other) def __sub__(self, other): """Offset rectangle by -point.""" return self._wrap_Rect_method("__sub__", other) cdef cy_OptRect wrap_OptRect(OptRect p): cdef OptRect* retp = new OptRect() retp[0] = p cdef cy_OptRect r = cy_OptRect.__new__(cy_OptRect) r.thisptr = retp return r cdef class cy_IntRect: """Class representing axis-aligned rectangle in 2D with integer coordinates. Corresponds to IntRect class (typedef) in 2geom.""" cdef IntRect* thisptr def __cinit__(self, IntCoord x0=0, IntCoord y0=0, IntCoord x1=0, IntCoord y1=0): """Create IntRect from coordinates of its top-left and bottom-right corners.""" self.thisptr = new IntRect(x0, y0, x1, y1) def __str__(self): """str(self)""" return "IntRect with dimensions {}, topleft point {}".format( str(self.dimensions()), str(self.min())) def __repr__(self): """repr(self)""" return "IntRect({}, {}, {}, {})".format( str(self.left()), str(self.top()), str(self.right()), str(self.bottom())) def __dealloc__(self): del self.thisptr @classmethod def from_points(cls, cy_IntPoint p0, cy_IntPoint p1): """Create rectangle from it's top-left and bottom-right corners.""" return wrap_IntRect( IntRect(deref(p0.thisptr), deref(p1.thisptr)) ) @classmethod def from_intervals(cls, I, J): """Create rectangle from two intervals representing its sides.""" return cy_IntRect( int(I.min()), int(J.min()), int(I.max()), int(J.max()) ) @classmethod def from_list(cls, lst): """Create rectangle containing all points in list.""" if lst == []: return cy_IntRect() if len(lst) == 1: return cy_IntRect(lst[0], lst[0]) ret = cy_IntRect(lst[0], lst[1]) for a in lst: ret.expand_to(a) return ret #didn't manage to declare from_xywh for IntRect @classmethod def from_xywh(cls, x, y, w, h): """Create rectangle from it's topleft point and dimensions.""" return cy_IntRect(int(x), int(y), int(x) + int(w), int(y) + int(h) ) def __getitem__(self, Dim2 d): """self[d]""" return wrap_IntInterval( deref(self.thisptr)[d] ) def min(self): """Get top-left point.""" return wrap_IntPoint( self.thisptr.i_min() ) def max(self): """Get bottom-right point.""" return wrap_IntPoint( self.thisptr.i_max() ) def corner(self, unsigned int i): """Get corners (modulo) indexed from 0 to 3.""" return wrap_IntPoint( self.thisptr.i_corner(i) ) def top(self): """Get top coordinate.""" return self.thisptr.top() def bottom(self): """Get bottom coordinate.""" return self.thisptr.bottom() def left(self): """Get left coordinate.""" return self.thisptr.left() def right(self): """Get right coordinate.""" return self.thisptr.right() def width(self): """Get width.""" return self.thisptr.width() def height(self): """Get height.""" return self.thisptr.height() def aspect_ratio(self): """Get ratio between width and height.""" return self.thisptr.aspectRatio() def dimensions(self): """Get dimensions as IntPoint.""" return wrap_IntPoint( self.thisptr.i_dimensions() ) def midpoint(self): """Get midpoint.""" return wrap_IntPoint( self.thisptr.i_midpoint() ) def area(self): """Get area.""" return self.thisptr.area() def has_zero_area(self): """Test for area being zero.""" return self.thisptr.hasZeroArea() def max_extent(self): """Get bigger value from width, height.""" return self.thisptr.maxExtent() def min_extent(self): """Get smaller value from width, height.""" return self.thisptr.minExtent() def intersects(self, cy_IntRect r): """Check if rectangle intersects another rectangle.""" return self.thisptr.intersects(deref( r.thisptr )) def contains(self, cy_IntPoint r): """Check if rectangle contains point.""" return self.thisptr.contains( deref(r.thisptr) ) def contains_rect(self, cy_IntRect r): """Check if rectangle contains another rect.""" return self.thisptr.contains( deref(r.thisptr) ) def set_left(self, IntCoord val): """Set left coordinate.""" self.thisptr.setLeft(val) def set_right(self, IntCoord val): """Set right coordinate.""" self.thisptr.setRight(val) def set_top(self, IntCoord val): """Set top coordinate.""" self.thisptr.setTop(val) def set_bottom(self, IntCoord val): """Set bottom coordinate.""" self.thisptr.setBottom(val) def set_min(self, cy_IntPoint p): """Set top-left point.""" self.thisptr.setMin( deref( p.thisptr ) ) def set_max(self, cy_IntPoint p): """Set bottom-right point.""" self.thisptr.setMax( deref( p.thisptr )) def expand_to(self, cy_IntPoint p): """Expand rectangle to contain point represented as tuple.""" self.thisptr.expandTo( deref( p.thisptr ) ) def union_with(self, cy_IntRect b): """self = self | other.""" self.thisptr.unionWith(deref( b.thisptr )) def expand_by(cy_IntRect self, x, y = None): """Expand both intervals. Either expand them both by one value, or each by different value. """ if y is None: if isinstance(x, cy_IntPoint): self.thisptr.expandBy( deref( (<cy_IntPoint> x).thisptr ) ) else: self.thisptr.expandBy( <IntCoord> x) else: self.thisptr.expandBy( <IntCoord> x, <IntCoord> y) def __add__(cy_IntRect self, cy_IntPoint p): """Offset rectangle by point.""" return wrap_IntRect( deref(self.thisptr) + deref( p.thisptr ) ) def __sub__(cy_IntRect self, cy_IntPoint p): """Offset rectangle by -point.""" return wrap_IntRect( deref(self.thisptr) - deref( p.thisptr ) ) def __or__(cy_IntRect self, cy_IntRect o): """Return union of two rects - it's actually bounding rect of union.""" return wrap_IntRect( deref(self.thisptr) | deref( o.thisptr )) def __richcmp__(cy_IntRect self, cy_IntRect o, int op): """Rectangles are not ordered.""" if op == 2: return deref(self.thisptr) == deref(o.thisptr) if op == 3: return deref(self.thisptr) != deref(o.thisptr) cdef cy_IntRect wrap_IntRect(IntRect p): cdef IntRect* retp = new IntRect() retp[0] = p cdef cy_IntRect r = cy_IntRect.__new__(cy_IntRect) r.thisptr = retp return r cdef class cy_OptIntRect: """Class representing optionally empty rect in with integer coordinates. This class corresponds to OptIntRect in 2geom, and it tries to mimic the behaviour of std::optional. In addition to OptIntRect methods, this class passes calls for IntRect methods to underlying IntRect class, or throws ValueError when it's empty. """ cdef OptIntRect* thisptr def __cinit__(self, x0=None, y0=None, x1=None, y1=None): """Create OptIntRect from coordinates of top-left and bottom-right corners. No arguments will result in empty rectangle. """ if x0 is None: self.thisptr = new OptIntRect() else: self.thisptr = new OptIntRect( int(x0), int(y0), int(x1), int(y1) ) def __str__(self): """str(self)""" if self.isEmpty(): return "Empty OptIntRect" return "OptIntRect with dimensions {}, topleft point {}".format( str(self.Rect.dimensions()), str(self.Rect.min())) def __repr__(self): """repr(self)""" if self.isEmpty(): return "OptIntRect()" return "OptIntRect({}, {}, {}, {})".format( str(self.Rect.left()), str(self.Rect.top()), str(self.Rect.right()), str(self.Rect.bottom())) def __dealloc__(self): del self.thisptr @classmethod def from_points(cls, cy_IntPoint p0, cy_IntPoint p1): """Create rectangle from it's top-left and bottom-right corners.""" return wrap_OptIntRect( OptIntRect(deref(p0.thisptr), deref(p1.thisptr)) ) @classmethod def from_intervals(cls, I, J): """Create rectangle from two intervals representing its sides.""" if hasattr(I, "isEmpty"): if I.isEmpty(): return cy_OptIntRect() if hasattr(J, "isEmpty"): if J.isEmpty(): return cy_OptIntRect() return wrap_OptIntRect( OptIntRect( int(I.min()), int(J.min()), int(I.max()), int(J.max()) ) ) @classmethod def from_rect(cls, r): """Create OptIntRect from other, possibly empty, rectangle.""" if hasattr(r, "isEmpty"): if r.isEmpty(): return cy_OptIntRect() return cy_OptIntRect( r.min().x, r.min().y, r.max().x, r.max().y ) @classmethod def from_list(cls, lst): """Create OptIntRect containing all points in the list. Empty list will result in empty OptIntRect. """ if lst == []: return cy_OptIntRect() if len(lst) == 1: return cy_OptIntRect.from_points(lst[0], lst[0]) ret = cy_OptIntRect.from_points(lst[0], lst[1]) for a in lst: ret.expand_to(a) return ret property Rect: """Get underlying IntRect.""" def __get__(self): return wrap_IntRect(self.thisptr.get()) def __bool__(self): """OptIntRect is False only when it's empty.""" return not self.thisptr.isEmpty() def is_empty(self): """Check for OptIntRect containing no points.""" return self.thisptr.isEmpty() def intersects(cy_OptIntRect self, other): """Check if rectangle intersects another rectangle.""" if isinstance(other, cy_IntRect): return self.thisptr.intersects( deref( (<cy_IntRect> other).thisptr ) ) elif isinstance(other, cy_OptIntRect): return self.thisptr.intersects( deref( (<cy_OptIntRect> other).thisptr ) ) def contains(self, cy_IntPoint other): """Check if rectangle contains point.""" return self.thisptr.contains( deref(other.thisptr) ) def contains_rect(cy_OptIntRect self, other): """Check if rectangle contains another rectangle.""" if isinstance(other, cy_IntRect): return self.thisptr.contains( deref( (<cy_IntRect> other).thisptr ) ) elif isinstance(other, cy_OptIntRect): return self.thisptr.contains( deref( (<cy_OptIntRect> other).thisptr ) ) def union_with(cy_OptIntRect self, other): """self = self | other.""" if isinstance(other, cy_IntRect): self.thisptr.unionWith( deref( (<cy_IntRect> other).thisptr ) ) elif isinstance(other, cy_OptIntRect): self.thisptr.unionWith( deref( (<cy_OptIntRect> other).thisptr ) ) def intersect_with(cy_OptIntRect self, other): """self = self & other.""" if isinstance(other, cy_IntRect): self.thisptr.intersectWith( deref( (<cy_IntRect> other).thisptr ) ) elif isinstance(other, cy_OptIntRect): self.thisptr.intersectWith( deref( (<cy_OptIntRect> other).thisptr ) ) def expand_to(self, cy_IntPoint p): """Expand rectangle to contain point.""" self.thisptr.expandTo( deref(p.thisptr) ) def __or__(cy_OptIntRect self, cy_OptIntRect other): """Return union of two rects - it's actually bounding rect of union.""" return wrap_OptIntRect( deref(self.thisptr) | deref(other.thisptr) ) def __and__(cy_OptIntRect self, other): """Return intersection of two rectangles.""" if isinstance(other, cy_IntRect): return wrap_OptIntRect( deref(self.thisptr) & deref( (<cy_IntRect> other).thisptr) ) elif isinstance(other, cy_OptIntRect): return wrap_OptIntRect( deref(self.thisptr) & deref( (<cy_OptIntRect> other).thisptr) ) def __richcmp__(cy_OptIntRect self, other, op): """Rectangles are not ordered.""" if op == 2: if isinstance(other, cy_IntRect): return deref(self.thisptr) == deref( (<cy_IntRect> other).thisptr ) elif isinstance(other, cy_OptIntRect): return deref(self.thisptr) == deref( (<cy_OptIntRect> other).thisptr ) elif op == 3: if isinstance(other, cy_IntRect): return deref(self.thisptr) != deref( (<cy_IntRect> other).thisptr ) elif isinstance(other, cy_OptIntRect): return deref(self.thisptr) != deref( (<cy_OptIntRect> other).thisptr ) def _get_Rect_method(self, name): def f(*args, **kwargs): if self.is_empty(): raise ValueError("OptIntRect is empty.") else: return self.Rect.__getattribute__(name)(*args, **kwargs) return f def __getattr__(self, name): Rect_methods = set(['area', 'aspect_ratio', 'bottom', 'contains', 'contains_rect', 'corner', 'dimensions', 'expand_by', 'expand_to', 'from_intervals', 'from_list', 'from_points', 'from_xywh', 'has_zero_area', 'height', 'intersects', 'left', 'max', 'max_extent', 'midpoint', 'min', 'min_extent', 'right', 'set_bottom', 'set_left', 'set_max', 'set_min', 'set_right', 'set_top', 'top', 'union_with', 'width']) if name in Rect_methods: return self._get_Rect_method(name) else: raise AttributeError("OptIntRect instance has no attribute \"{}\"".format(name)) def _wrap_Rect_method(self, name, *args, **kwargs): if self.isEmpty(): raise ValueError("OptIntRect is empty.") else: return self.Rect.__getattr__(name)(*args, **kwargs) #declaring these by hand, because they take fixed number of arguments, #which is enforced by cython def __getitem__(self, i): """self[d]""" return self._wrap_Rect_method("__getitem__", i) def __add__(self, other): """Offset rectangle by point.""" return self._wrap_Rect_method("__add__", other) def __sub__(self, other): """Offset rectangle by -point.""" return self._wrap_Rect_method("__sub__", other) cdef cy_OptIntRect wrap_OptIntRect(OptIntRect p): cdef OptIntRect* retp = new OptIntRect() retp[0] = p cdef cy_OptIntRect r = cy_OptIntRect.__new__(cy_OptIntRect) r.thisptr = retp return r
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using KSPMock; using Moq; using NUnit.Framework; using OrbitPOInts.Data.POI; using OrbitPOInts.Tests.Mocks; namespace OrbitPOInts.Tests { #if TEST [Parallelizable(ParallelScope.None)] [TestFixture] public class SettingsE2ETests { private CelestialBody testBody; private int defaultPoiPropChangedWhileNotResettingCount = 0; private int configuredPoiPropChangedCount = 0; private bool _registered; private void OnInstanceDestroyed(object senderSettings) => Assert.IsFalse(true, "should not have been called"); private void OnDefaultPoiOnPropertyChanged(object senderPoi, PropertyChangedEventArgs args) { var resettablePoi = senderPoi as ResettablePoi; Assert.IsNotNull(resettablePoi, "sender is not a ResettablePoi"); // dont count operations during reset if (resettablePoi.IsResetting) return; defaultPoiPropChangedWhileNotResettingCount += 1; } private void OnConfiguredPoiPropChanged(object senderSettings, object senderPoi, PropertyChangedEventArgs args) => configuredPoiPropChangedCount += 1; private void Register(bool register = true) { if (register) { Assert.IsFalse(_registered, "registered(true) should only be called once per run"); Settings.InstanceDestroyed += OnInstanceDestroyed; foreach (var defaultPoi in Settings.GetAllDefaultPois()) defaultPoi.PropertyChanged += OnDefaultPoiOnPropertyChanged; Settings.Instance.ConfiguredPoiPropChanged += OnConfiguredPoiPropChanged; _registered = true; return; } Assert.IsTrue(_registered, "registered(false) should only be called once per run"); Settings.InstanceDestroyed -= OnInstanceDestroyed; foreach (var defaultPoi in Settings.GetAllDefaultPois()) defaultPoi.PropertyChanged -= OnDefaultPoiOnPropertyChanged; Settings.Instance.ConfiguredPoiPropChanged -= OnConfiguredPoiPropChanged; _registered = false; } [OneTimeSetUp] public void OneTimeSetup() { var mockTerrainService = new Mock<ITerrainService>(); mockTerrainService.Setup(c => c.TerrainAltitude(It.IsAny<double>(), It.IsAny<double>(), It.IsAny<bool>())).Returns(1); testBody = new MockCelestialBody(mockTerrainService.Object) { bodyName = "TestBody", hillSphere = 1, sphereOfInfluence = 1, minOrbitalDistance = 1, atmosphere = true, atmosphereDepth = 1, Radius = 1, }; FlightGlobals.Bodies = new List<CelestialBody> { testBody }; CelestialBodyCache.ClearCache(); } private void ResetCountersAndFlags() { defaultPoiPropChangedWhileNotResettingCount = 0; configuredPoiPropChangedCount = 0; } [SetUp] public void Setup() { Settings.ResetInstance(); ResetCountersAndFlags(); Register(); } [TearDown] public void TearDown() { Register(false); } // TODO: This test is bloated private void AssertGlobalStateForBody(CelestialBody body) { ResetCountersAndFlags(); var tag = $"[Global: {(body ? body.bodyName : "null")}]"; // sanity check Assert.IsEmpty(Settings.Instance.ConfiguredPois, $"{tag}: expected ConfiguredPois to be empty "); var targetType = PoiType.Atmosphere; Assert.IsTrue(Settings.Instance.GetGlobalEnableFor(body, targetType)); var globalAtmospherePoi = Settings.Instance.TestGetGlobalPoiFor(body, targetType); Assert.IsTrue(Settings.IsDefaultPoi(globalAtmospherePoi), $"{tag}: globalAtmospherePoi is not a default POI"); var globalAtmosphereResettablePoi = globalAtmospherePoi as ResettablePoi; Assert.IsNotNull(globalAtmosphereResettablePoi, $"{tag}: globalAtmospherePoi is not a ResettablePoi"); Assert.IsTrue(globalAtmosphereResettablePoi.Sealed, $"{tag}: globalAtmospherePoi is not sealed"); Assert.IsTrue(globalAtmospherePoi.Enabled, $"{tag}: globalAtmospherePoi should be enabled by default"); globalAtmospherePoi.Enabled = false; Assert.GreaterOrEqual(defaultPoiPropChangedWhileNotResettingCount, 1, $"{tag}: defaultPoiPropChangedWhileNotResettingCount was not called"); Assert.AreEqual(1, defaultPoiPropChangedWhileNotResettingCount, $"{tag}: defaultPoiPropChangedWhileNotResettingCount was called more than expected"); Assert.AreEqual(0, configuredPoiPropChangedCount, $"{tag}: configuredPoiPropChangedCount was called"); Assert.IsTrue(globalAtmospherePoi.Enabled, $"{tag}: globalAtmospherePoi did not reset"); Assert.IsNotEmpty(Settings.Instance.ConfiguredPois, $"{tag}: globalAtmospherePoi should have been copied into ConfiguredPois"); Assert.AreEqual(1, Settings.Instance.ConfiguredPois.Count, $"{tag}: ConfiguredPois should only contain 1 poi"); Assert.IsFalse(Settings.Instance.ConfiguredPois.First().Enabled, $"{tag}: Enabled=false for atmospherePoi did not persist during copy"); Assert.IsFalse(Settings.Instance.GetGlobalEnableFor(body, targetType), $"{tag}: Enabled=false for atmospherePoi did not persist or GetGlobalEnableFor is returning wrong result"); var globalConfiguredAtmospherePoi = Settings.Instance.TestGetGlobalPoiFor(body, targetType); Assert.IsFalse(globalConfiguredAtmospherePoi is ResettablePoi, $"{tag}: globalConfiguredAtmospherePoi should not be a ResettablePoi"); Assert.IsTrue(PoiSameTargetComparer.StaticEquals(globalAtmospherePoi, globalConfiguredAtmospherePoi), $"{tag}: globalConfiguredAtmospherePoi should be the same target"); Assert.IsFalse(PoiComparer.StaticEquals(globalAtmospherePoi, globalConfiguredAtmospherePoi), $"{tag}: globalConfiguredAtmospherePoi was cloned into ConfiguredPois with same values"); Assert.IsFalse(globalConfiguredAtmospherePoi.Enabled, $"{tag}: globalAtmospherePoi was not cloned into ConfiguredPois when we changed Enabled to false"); Func<POI, bool> whereTargetType = poi => poi.Type == targetType; var configuredNull = Settings.Instance.GetConfiguredPoisFor(body).Where(whereTargetType); Assert.IsNotNull(configuredNull); Assert.AreEqual(1, configuredNull.Count(), $"{tag}: we only expected 1 configured poi for our testBody"); Assert.IsFalse(configuredNull.FirstOrDefault().Enabled); defaultPoiPropChangedWhileNotResettingCount = 0; Assert.IsFalse(Settings.Instance.GetGlobalEnableFor(body, targetType), $"{tag}: impossible state? this should still be false"); Assert.Contains(globalConfiguredAtmospherePoi, Settings.Instance.ConfiguredPois.ToList(), $"{tag}: globalConfiguredAtmospherePoi should still exist in ConfiguredPois"); globalConfiguredAtmospherePoi.Enabled = true; Assert.IsTrue(globalConfiguredAtmospherePoi.Enabled, $"{tag}: globalConfiguredAtmospherePoi should not reset"); Assert.IsEmpty(Settings.Instance.ConfiguredPois, $"{tag}: ConfiguredPois should now be empty; globalConfiguredAtmospherePoi was no longer diverging from default and should have been removed."); Assert.IsTrue(Settings.Instance.GetGlobalEnableFor(body, targetType), $"{tag}: globalConfiguredAtmospherePoi was potentially overriden by default"); } [Test] public void ConfiguredPois_GetGlobalEnableFor_GlobalStateTest_ReturnsCorrectValue() { AssertGlobalStateForBody(null); } [Test] public void ConfiguredPois_GetGlobalEnableFor_TestBodyStateTest_ReturnsCorrectValue() { AssertGlobalStateForBody(testBody); } [Test] public void ConfiguredPois_GetGlobalEnableFor_MultiStateTest_ReturnsCorrectValue() { AssertGlobalStateForBody(null); AssertGlobalStateForBody(null); AssertGlobalStateForBody(testBody); AssertGlobalStateForBody(testBody); AssertGlobalStateForBody(null); AssertGlobalStateForBody(testBody); } } #endif }
import React, { useContext, useEffect, useState } from 'react'; import CartContext from '../../store/cart-context'; import CartIcon from '../Cart/CartIcon'; import classes from './HeaderCartButton.module.css'; const HeaderCartButton = (props) => { const [btnIsHighlighted, setBtnIsHighLighted] = useState(false); const cartCtx = useContext(CartContext); const classesButton = `${classes.button} ${btnIsHighlighted ? classes.bump : ''}`; const { items } = cartCtx; const numberOfCartItem = items.reduce((currentNumber, item) => { return currentNumber + item.amount; }, 0); useEffect(() => { if (items.length === 0) { return; } setBtnIsHighLighted(true); const timer = setTimeout(() => { setBtnIsHighLighted(false); }, 300); return () => { clearTimeout(timer); }; }, [items]); return ( <button className={classesButton} onClick={props.onShowCart}> <span className={classes.icon}> <CartIcon /> </span> <span> Your Cart </span> <span className={classes.badge}> {numberOfCartItem} </span> </button> ); }; export default HeaderCartButton;
import { ComposableMap, Geographies, Geography, Marker } from "react-simple-maps" import { useEffect, useState } from "react"; import { Tooltip } from "react-tooltip"; import { useApiContext } from "../../../contexts/APIcontext.jsx"; const geoUrl = "https://raw.githubusercontent.com/deldersveld/topojson/master/world-countries.json" export const GeoChart = () => { const [markers, setMarkers] = useState([]) const [tooltipContent, setTooltipContent] = useState("") const { filteredSearchInput, loading } = useApiContext() const getMarkers = () => { let arr = [] filteredSearchInput.forEach(item => { arr.push({ name: item.name, recclass: item.recclass, mass: item.mass, year: new Date(item.year).getFullYear(), coordinates: [item.reclong, item.reclat] }) }) setMarkers(arr) } useEffect(() => { if (filteredSearchInput.length > 0) { getMarkers() } }, [filteredSearchInput]) const showTooltip = (name, recclass, mass, year) => { setTooltipContent(` Name: <b>${name}</b> <br/> Reclass: <b>${recclass}</b> <br/> Mass: <b>${mass}</b> <br/> Year: <b>${year}</b> `) } return ( <> {!loading && ( <div> <ComposableMap> <Geographies geography={geoUrl}> {({ geographies }) => geographies.map((geo) => ( <Geography key={geo.rsmKey} geography={geo} /> )) } </Geographies> {markers.map(({ name, recclass, mass, year, coordinates }) => ( coordinates[0] !== undefined && ( <Marker key={name} coordinates={coordinates} className="my-anchor-element" data-tooltip-html={tooltipContent} onMouseEnter={() => { showTooltip(name, recclass, mass, year) }} onMouseLeave={() => { setTooltipContent(""); }} > <circle r={5} fill="#F00" stroke="#fff" strokeWidth={2} /> </Marker> ) ))} </ComposableMap> <Tooltip anchorSelect=".my-anchor-element" place="top" /> </div> )} </> ) }
import { faker } from "@faker-js/faker"; import { formatPlacesLived, formatYears, getRandomDateFromYear, getAgeFromBirthday, } from "../../utils/populateHelperFunctions"; import { LifeEventData } from "../../../../types/IUser"; export const getLifeEvents = (birthday: Date) => { const age = getAgeFromBirthday(birthday); birthday; const lifeEvents: LifeEventData[] = []; let currentAge = 0; let currentCity = faker.location.city(); let currentJob; const yearsStartJob: number[] = []; let jobCounter = 0; let goingToCollege = false; let graduatedHighSchool = false; const yearsGraduateSchool: number[] = []; let educationCounter = 0; const placesLived: { city: string; country: string; dateMovedIn: Date }[] = []; let currentRelationship; const birthPlace = { city: currentCity, country: faker.location.country(), dateMovedIn: birthday, }; lifeEvents.push({ title: "Born", description: `Born in ${birthPlace.city}, ${birthPlace.country}`, date: birthday, }); placesLived.push(birthPlace); while (currentAge < age) { if (faker.datatype.boolean(0.05)) { currentCity = faker.location.city(); const country = faker.location.country(); const dateMovedIn = getRandomDateFromYear( birthday.getFullYear() + currentAge, ); lifeEvents.push({ title: "Moved", description: `Moved to ${currentCity}, ${country}`, date: dateMovedIn, }); placesLived.push({ city: currentCity, country, dateMovedIn, }); } if ( currentAge >= 18 && !graduatedHighSchool && faker.datatype.boolean(0.95) ) { yearsGraduateSchool.push(birthday.getFullYear() + currentAge); graduatedHighSchool = true; goingToCollege = faker.datatype.boolean(0.8); } if ( currentAge === 22 + educationCounter * 5 && faker.datatype.boolean(0.8) && goingToCollege && educationCounter === 0 ) { yearsGraduateSchool.push(birthday.getFullYear() + currentAge); educationCounter++; goingToCollege = false; } if ( currentAge >= 23 + educationCounter * 5 && faker.datatype.boolean(0.1) && educationCounter === 1 ) { yearsGraduateSchool.push(birthday.getFullYear() + currentAge); educationCounter++; goingToCollege = false; } // Check job events if ( currentAge >= 22 && !currentJob && !goingToCollege && faker.datatype.boolean(0.8) && jobCounter === 0 ) { currentJob = true; yearsStartJob.push(birthday.getFullYear() + currentAge); } if (currentAge >= 23 && currentJob && faker.datatype.boolean(0.1)) { jobCounter++; yearsStartJob.push(birthday.getFullYear() + currentAge); } // relationship events if ( currentAge >= 20 && faker.datatype.boolean(0.2) && !currentRelationship ) { lifeEvents.push({ title: "Married", description: `Got married to ${faker.person.firstName()} ${faker.person.lastName()}`, date: getRandomDateFromYear(birthday.getFullYear() + currentAge), }); currentRelationship = true; } const childEvent = { title: "Had a child", description: `Had a child named ${faker.person.firstName()}`, date: getRandomDateFromYear(birthday.getFullYear() + currentAge), }; if ( currentAge >= 22 && currentAge <= 30 && faker.datatype.boolean(0.15) && currentRelationship ) { lifeEvents.push(childEvent); } if ( currentAge >= 31 && currentAge <= 40 && faker.datatype.boolean(0.05) && currentRelationship ) { lifeEvents.push(childEvent); } const petEvent = { title: "Adopted a pet", description: `Adopted a pet named ${faker.animal.dog()}`, date: getRandomDateFromYear(birthday.getFullYear() + currentAge), }; if (currentAge >= 20 && faker.datatype.boolean(0.075)) { lifeEvents.push(petEvent); } if (currentAge >= 30 && faker.datatype.boolean(0.05)) { lifeEvents.push(petEvent); } currentAge++; } const formattedYearsStartJob = formatYears(yearsStartJob); const formattedYearsGraduateSchool = formatYears(yearsGraduateSchool); const formattedPlacesLived = formatPlacesLived(placesLived); return { lifeEvents, yearsStartJob: formattedYearsStartJob, yearsGraduateSchool: formattedYearsGraduateSchool, placesLived: formattedPlacesLived, }; };
import React, { useEffect, useState } from "react"; import { fetchMe } from "../api/users"; import AllPost from "./AllPost"; import { postMessage } from "../api/messages"; import { fetchPosts } from "../api/post"; import { deletePost } from "../api/post"; import useAuth from "../hooks/useAuth"; import { Link, useNavigate, useParams } from "react-router-dom"; import ViewPost from "./ViewPost"; export default function ProfilePage() { const navigate = useNavigate(); const [myProfile, setMyProfile] = useState({}); const [posts, setPosts] = useState([]); const { token, user } = useAuth(); const { id } = useParams; const messages = user.messages || []; console.log("Post from profile:", posts); useEffect(() => { async function myPage() { const fetchProfile = await fetchMe(token); console.log("result in ProfilePage:", fetchProfile); setMyProfile(fetchProfile.data.posts); setPosts(fetchProfile.data.posts); //this allows me to map through the post arrays // console.log(fetchProfile.data.posts); // ask why fetchProfile is reading success:false //answer: had to change [myPost, setMyPost] = useState({}) and import useAuth; } myPage(); }, [token]); return ( <div className="profile-page"> <h1 className="Profilepage-header">Profile Page</h1> <h2>My Post:</h2> {posts.map((post) => { return ( <div className="Profilepage-post" key={post._id}> <h4>{post.title}</h4> <p>{post.description}</p> <p>{post.price}</p> <p>{post.location}</p> <h3>Messages:</h3> {post.messages.map((message) => { return <p>{message.content}</p>; })} </div> ); })} <h2>My Messages:</h2> {messages.map((message) => { return ( <div className="messages"> <h3>From: {message.fromUser.username}</h3> <p>Message: {message.content}</p> <p>Post: {message.post.title}</p> <p>Author: {message.post.author.username}</p> </div> ); })} {/* {user.id === posts.author._id && <p>{user.messages}</p>} */} </div> ); }
package api import ( "encoding/json" "net/http" "github.com/adinovcina/golang-setup/tools/logger" status "github.com/adinovcina/golang-setup/tools/network/statuscodes" "github.com/adinovcina/golang-setup/tools/paging" ) // BaseResponse structure that will have on all responses from all APIs. type BaseResponse struct { Data interface{} `json:"data"` RequestID string `json:"requestID"` Errors []Error `json:"errors"` } // PaginatedResponse contains response when we use basic pagination. type PaginatedResponse struct { Results any `json:"results"` Pagination paging.Paginator `json:"pagination"` } // PaginatedCursorResponse contains response when we use cursos pagination. type PaginatedCursorResponse struct { Results any `json:"results"` Pagination paging.PaginatorCursor `json:"pagination"` } // Error object that will contain details of the error. type Error struct { Message string `json:"errorMessage"` Code int `json:"errorCode"` } // Token contains all important data for the token. type Token struct { Token string `json:"token"` RefreshToken string `json:"refreshToken"` } func (l *BaseResponse) Error(customStatus int) { l.Errors = append(l.Errors, Error{Code: customStatus, Message: status.ErrorStatusText(customStatus)}) } func (r *BaseResponse) HasErrors() bool { return len(r.Errors) <= 0 } func ErrorResponse(response *BaseResponse, statusCode int, w http.ResponseWriter, r *http.Request, err error) { // If error is not nil, log the error if err != nil { requestData := RequestData(r) logger.Error().Err(err).Msgf("request_id: %s", requestData.RequestID) } // If there is no explicit error defined, return internal error message if len(response.Errors) == 0 { response.Error(status.InternalServerError) } jsonResponse(response, statusCode, w) } // RequestData to retrieve the Data object from the context. // The *Data* object will be initialized if not present already. func RequestData(r *http.Request) *Data { return MiddlewareDataFromContext(r.Context()) } func SuccessResponse(response *BaseResponse, statusCode int, w http.ResponseWriter) { if response == nil { response = new(BaseResponse) } jsonResponse(response, statusCode, w) } func jsonResponse(response *BaseResponse, statusCode int, w http.ResponseWriter) { // Set content type only if there is response data if statusCode != http.StatusNoContent { w.Header().Set("Content-Type", "application/json") } marshaledData, err := json.Marshal(response) if err != nil { logger.Error().Err(err).Msg("marshaling response data failed") response = &BaseResponse{ Errors: []Error{{Code: status.InvalidResponseBody, Message: status.ErrorStatusText(status.InvalidResponseBody)}}, } marshaledData, _ = json.Marshal(response) } w.WriteHeader(statusCode) writeResponseData(statusCode, marshaledData, w) } func writeResponseData(statusCode int, data []byte, w http.ResponseWriter) { if statusCode != http.StatusNoContent { if _, err := w.Write(data); err != nil { logger.Error().Err(err).Msg("write failed") } } } func ValidateRequestData(requestData interface{}, r *http.Request, validationFunc func() (bool, *BaseResponse), ) (bool, *BaseResponse) { response := new(BaseResponse) // Validate if body is empty since we require some input if r.Body == nil { response.Error(status.EmptyBody) return false, response } // Decode body err := json.NewDecoder(r.Body).Decode(requestData) if err != nil { response.Error(status.IncorrectBodyFormat) return false, response } defer r.Body.Close() return validationFunc() }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sect2 PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN" "http://www.docbook.org/xml/4.3/docbookx.dtd"> <!-- section history: 2008-01-04 ude: replaced calloutlist with orderedlist 2007-10-23 j.h: updated en;fr to v2.4 2007-05-19 Added Spanish translation by AntI 2007-02-08 added 'no' by KoSt 2006-07-27 en revised by scb 2006-02-25 fixed invalid image reference 2005/10/18 zh_CN removed by romanofski - missing translation --> <sect2 id="gimp-file-save-as"> <title>Save as</title> <indexterm> <primary>Image</primary> <secondary>Save image</secondary> <tertiary>Save as</tertiary> </indexterm> <indexterm> <primary>Save as</primary> </indexterm> <para> The <guimenuitem>Save as</guimenuitem> command displays the <quote>Save Image</quote> dialog. In its basic form, as shown below, this gives you a text box to assign a name to the file, and a drop-down list of bookmarks to select a directory to save it in. Normally the file format is determined by the extension you use in the file name (i.e., .jpg for a JPEG file). You can use the <guilabel>Select File Type</guilabel> option expander to pick a different file type, but you should avoid doing this unless absolutely necessary, to avoid confusion. </para> <para> If the directory you want is not in the list of bookmarks, click on <guilabel>Browse for other folders</guilabel> to expand the dialog to its full form. You can find an explanation of the layout, and help on creating and using bookmarks, in the <link linkend="gimp-using-fileformats">Files</link> section. </para> <para> If you saved the image previously and don't need to change the file name or any of the options, you can use the <link linkend="gimp-file-save">Save</link> command instead. </para> <sect3> <title>Activating the Command</title> <itemizedlist> <listitem> <para> You can access to this command from the image menubar through <menuchoice> <guimenu>File</guimenu> <guimenuitem>Save as</guimenuitem> </menuchoice>, </para> </listitem> <listitem> <para> or by using the keyboard shortcut <keycombo> <keycap>Shift</keycap> <keycap>Ctrl</keycap><keycap>S</keycap> </keycombo>. </para> </listitem> </itemizedlist> </sect3> <sect3> <title>The basic <quote>Save Image</quote> dialog</title> <para> There are two different forms of the <guimenu>Save Image</guimenu> dialog. The simple form only lets you type in the filename and choose the directory the file should be saved in. If the folder you want is not on the list, you can type in the path to the directory, along with the filename. You can also click on the small triangle to display the full folder browser. You can also choose the image format, by selecting the file extension (e.g., <filename class="extension">.xcf</filename> or <filename class="extension">.png</filename>). </para> <figure> <title>The basic <quote>Save Image</quote> dialog</title> <mediaobject> <imageobject> <imagedata fileref="images/menus/file/save-as.png" format="PNG"/> </imageobject> </mediaobject> </figure> </sect3> <sect3> <title>The <quote>Save Image</quote> dialog with a Browser</title> <figure> <title>The <quote>Save Image</quote> dialog (Browser)</title> <mediaobject> <imageobject> <imagedata format="PNG" fileref="images/menus/file/save-as-browse.png"/> </imageobject> </mediaobject> </figure> <orderedlist> <listitem> <para> The left panel is divided into two parts. The upper part lists your main directories and your storage devices; you cannot modify this list. The lower part lists your bookmarks; you can add or remove <emphasis>bookmarks</emphasis>. To add a bookmark, select a directory or a file in the middle panel and click on the <guibutton>Add</guibutton> button at the bottom of the left panel. You can also use the <guilabel>Add to bookmarks</guilabel> command in the context menu, which you get by clicking the right mouse button. You can delete a bookmark by selecting it and clicking on the <guibutton>Remove</guibutton> button. </para> </listitem> <listitem> <para> The middle panel displays a list of the files in the current directory. Change your current directory by double left-clicking on a directory in this panel. Select a file with a single left click. You can then save to the file you have selected by clicking on the <guibutton>Save</guibutton> button. Note that a double left click saves the file directly. </para> <para> You can right click on the middle panel to access the <emphasis>Show Hidden Files</emphasis> command. </para> </listitem> <listitem> <para> The selected image is displayed in the <guilabel>Preview </guilabel> window if it is an image created by <acronym>GIMP</acronym>. File size, resolution and the image's composition are displayed below the preview window. </para> <para> If your image has been modified by another program, click on the preview to update it. </para> </listitem> <listitem> <para>Enter the filename of the new image file here.</para> <note> <para> If the image has already been saved, <acronym>GIMP</acronym> suggests the same filename to you. If you click on <emphasis>Save</emphasis>, the file is overwritten. </para> </note> </listitem> <listitem> <para> This drop-down list is only available in the basic form of the dialog. It provides a list of bookmarks for selecting a directory in which to save your file. </para> </listitem> <listitem> <para> Above the middle panel, the path of the current directory is displayed. You can navigate along this path by clicking on one of the buttons. </para> </listitem> <listitem> <para> If you want to save the image into a folder that doesn't yet exist, you can create it by clicking on <guilabel>Create Folder</guilabel> and following the instructions. </para> </listitem> <listitem> <para> This button shows <guilabel>All Images</guilabel> by default. This means that all images will be displayed in the middle panel, whatever their file type. By developing this list, you can choose to show only one type of file. </para> </listitem> <listitem> <para> At <guilabel>Select File Type</guilabel>, you have to select the file format for saving the file. If you select <guilabel>By Extension</guilabel>, the file type is determined by the extension you add to the name, for example, <quote>.jpg</quote> for JPEG format. </para> <note> <para> To preserve all the components of your image when you save it — the layers, channels, etc. — use ".xcf" format, which is the <acronym>GIMP</acronym>'s native format. </para> </note> </listitem> </orderedlist> </sect3> </sect2>
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common'; import { ApiOperation, ApiTags } from '@nestjs/swagger'; import { SchedulesService } from '@modules/schedules/schedules.service'; import { CurrentUser } from '@common/decorators/current-user.decorator'; import { IJwtPayload } from '@modules/tokens/interfaces/jwt-payload.interface'; import { CreateScheduleDto } from '@modules/schedules/dto/create-schedule.dto'; @ApiTags('Расписание пользователя') @Controller('schedules') export class SchedulesController { constructor(private readonly scheduleService: SchedulesService) {} @ApiOperation({ summary: 'Получение всех расписаний' }) @Get('/') async findAll(@CurrentUser() user: IJwtPayload) { return await this.scheduleService.findAll(user.id); } @Get('/completed') async findAllCompleted(@CurrentUser() user: IJwtPayload) { return await this.scheduleService.findAllCompleted(user.id); } @Get('/canceled') async findAllCanceled(@CurrentUser() user: IJwtPayload) { return await this.scheduleService.findAllCanceled(user.id); } @ApiOperation({ summary: 'Получение расписания по id' }) @Get(':id') async findOne(@Param('id') id: number, @CurrentUser() user: IJwtPayload) { return await this.scheduleService.findOne(id, user.id); } @ApiOperation({ summary: 'Создание расписания' }) @Post('/') async create(@CurrentUser() user: IJwtPayload, @Body() scheduleDto: CreateScheduleDto) { return await this.scheduleService.create(user.id, scheduleDto); } @ApiOperation({ summary: 'Обновление расписания' }) @Put(':id') async update( @Param('id') id: number, @CurrentUser() user: IJwtPayload, @Body() scheduleDto: CreateScheduleDto ) { return await this.scheduleService.update(id, user.id, scheduleDto); } @ApiOperation({ summary: 'Удаление расписания' }) @Delete(':id') async delete(@Param('id') id: number, @CurrentUser() user: IJwtPayload) { return await this.scheduleService.delete(id, user.id); } @ApiOperation({ summary: 'Отменить запись' }) @Put('/cancel/:id') async cancel(@Param('id') id: number, @CurrentUser() user: IJwtPayload) { return await this.scheduleService.cancel(id, user.id); } @ApiOperation({ summary: 'Отменить запись' }) @Put('/complete/:id') async complete(@Param('id') id: number, @CurrentUser() user: IJwtPayload) { return await this.scheduleService.compete(id, user.id); } @ApiOperation({ summary: 'Получение свободных слотов по выбранной дате' }) @Get('slots/free/:date') async findFreeTimeSlots(@Param('date') date: string, @CurrentUser() user: IJwtPayload) { return await this.scheduleService.findFreeTimeSlots(user.id, date); } }
#include <iostream> enum PermissionFlags { Read = 0x01, // 0001 Write = 0x02, // 0010 Execute = 0x04, // 0100 All = Read | Write | Execute// 0111 }; void checkPermissions(unsigned char permissions) { std::cout << "Permissions: "; if (permissions & Read) std::cout << "Read "; if (permissions & Write) std::cout << "Write "; if (permissions & Execute) std::cout << "Execute"; std::cout << std::endl; } int main() { unsigned char myPermissions = Read | Execute;// 0101 checkPermissions(myPermissions); myPermissions |= Write;// 0111 checkPermissions(myPermissions); myPermissions &= ~Read;// 1110 checkPermissions(myPermissions); return 0; }
// // ManufacturerDetailViewController.swift // iBeer // // Created by Francisco Javier Gallego Lahera on 27/12/21. // import UIKit class ManufacturerDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: Outlets @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var establishmentDateLabel: UILabel! @IBOutlet weak var originLabel: UILabel! @IBOutlet weak var numberOfBeersLabel: UILabel! @IBOutlet weak var logoImageView: UIImageView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var orderByButton: UIButton! @IBOutlet weak var editButton: UIBarButtonItem! // MARK: Variables var manufacturer: Manufacturer! { didSet { numberOfBeersLabel.text = "\(manufacturer.beers.count)" switch orderType { case .name: manufacturer.beers.sort { $0.name > $1.name } case .calories: manufacturer.beers.sort { $0.calories > $1.calories } case .abv: manufacturer.beers.sort { $0.abv > $1.abv } } Model.shared.updateManufacturer(manufacturer) } } var orderType = OrderType.name { didSet { switch orderType { case .name: manufacturer.beers.sort { $0.name > $1.name } case .calories: manufacturer.beers.sort { $0.calories > $1.calories } case .abv: manufacturer.beers.sort { $0.abv > $1.abv } } orderByButton.setTitle("Ordenar por: \(orderType.rawValue)", for: .normal) UserDefaults.standard.set(orderType.rawValue, forKey: "orderType") } } // MARK: Methods init?(coder: NSCoder, manufacturer: Manufacturer) { self.manufacturer = manufacturer super.init(coder: coder) } required init?(coder: NSCoder) { super.init(coder: coder) } override func viewDidLoad() { super.viewDidLoad() if let logoData = manufacturer.logoData, let image = UIImage(data: logoData) { logoImageView.image = image } else { logoImageView.image = UIImage(named: Constants.kUnknownImageName)! } tableView.delegate = self tableView.dataSource = self nameLabel.text = manufacturer.name establishmentDateLabel.text = manufacturer.formattedEstablishmentDate numberOfBeersLabel.text = "\(manufacturer.beers.count)" originLabel.text = manufacturer.origin.rawValue // Order Type - loading from preferences. let orderTypePreferences = UserDefaults.standard.string(forKey: "orderType") ?? OrderType.name.rawValue orderType = OrderType(rawValue: orderTypePreferences) ?? .name orderByButton.setTitle("Ordenar por: \(orderType.rawValue)", for: .normal) } // Support methods func getBeersForSection(_ section: Int) -> [Beer] { let type = BeerType.allCases[section] let filteredBeers = manufacturer.beers.filter { $0.type == type } return filteredBeers } // Outlet actions @IBAction func editButtonTapped(_ sender: Any) { let isEditing = tableView.isEditing editButton.title = !isEditing ? "Hecho" : "Editar" tableView.setEditing(!isEditing, animated: true) } @IBAction func addBeerTapped(_ sender: UIButton) { let alertController = UIAlertController(title: "Tipo de Cerveza", message: "Elige un tipo de cerveza.", preferredStyle: .actionSheet) alertController.popoverPresentationController?.sourceView = sender for type in BeerType.allCases { alertController.addAction(UIAlertAction(title: type.rawValue, style: .default, handler: { [weak self] _ in self?.manufacturer.addBeer(Beer(name: "Nueva Cerveza", abv: 0.0, calories: 0, type: type, imageData: nil)) let beerTypeIndex = BeerType.allCases.firstIndex(of: type)! self?.tableView.reloadSections([beerTypeIndex], with: .automatic) })) } present(alertController, animated: true) } @IBAction func orderByTapped(_ sender: UIButton) { let alertController = UIAlertController(title: "Elige el filtro", message: "El orden se hará de mayor a menor.", preferredStyle: .actionSheet) alertController.popoverPresentationController?.sourceView = sender alertController.addAction(UIAlertAction(title: "Nombre", style: .default, handler: { [weak self] _ in self?.orderType = .name self?.tableView.reloadData() })) alertController.addAction(UIAlertAction(title: "Aporte calórico", style: .default, handler: { [weak self] _ in self?.orderType = .calories self?.tableView.reloadData() })) alertController.addAction(UIAlertAction(title: "Graduación", style: .default, handler: { [weak self] _ in self?.orderType = .abv self?.tableView.reloadData() })) present(alertController, animated: true) } @IBSegueAction func beerSegue(_ coder: NSCoder, sender: Any?) -> EditBeerTableViewController? { if let cell = sender as? UITableViewCell { let cellIndexPath = tableView.indexPath(for: cell)! let cellBeer = getBeersForSection(cellIndexPath.section)[cellIndexPath.row] return EditBeerTableViewController(coder: coder, beer: cellBeer) } return nil } @IBAction func unwindToManufacturerDetailViewController(segue: UIStoryboardSegue) { guard segue.identifier == "SaveBeerUnwind", let sourceView = segue.source as? EditBeerTableViewController else { return } if let _ = tableView.indexPathForSelectedRow { let beer = sourceView.beer manufacturer.updateBeer(beer) tableView.reloadData() } } func numberOfSections(in tableView: UITableView) -> Int { BeerType.allCases.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { BeerType.allCases[section].rawValue } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let type = BeerType.allCases[section] return manufacturer.beers.filter { $0.type == type }.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BeerCell") as! BeerTableViewCell let type = BeerType.allCases[indexPath.section] let beer = manufacturer.beers.filter { $0.type == type }[indexPath.row] let name = beer.name let imageData = beer.imageData cell.configure(name: name, logoData: imageData) cell.showsReorderControl = true return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let beerToDelete = getBeersForSection(indexPath.section)[indexPath.row] manufacturer.removeBeer(beerToDelete) tableView.reloadSections([indexPath.section], with: .automatic) } } // func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // true // } // // func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { // // } }
using AbstractDifferentiation using Test using FiniteDifferences, ForwardDiff, Zygote const AD = AbstractDifferentiation const FDM = FiniteDifferences ## FiniteDifferences struct FDMBackend1{A} <: AD.AbstractFiniteDifference alg::A end FDMBackend1() = FDMBackend1(central_fdm(5, 1)) const fdm_backend1 = FDMBackend1() # Minimal interface function AD.jacobian(ab::FDMBackend1, f, xs...) return FDM.jacobian(ab.alg, f, xs...) end struct FDMBackend2{A} <: AD.AbstractFiniteDifference alg::A end FDMBackend2() = FDMBackend2(central_fdm(5, 1)) const fdm_backend2 = FDMBackend2() AD.@primitive function pushforward_function(ab::FDMBackend2, f, xs...) return function (vs) ws = FDM.jvp(ab.alg, f, tuple.(xs, vs)...) return length(xs) == 1 ? (ws,) : ws end end struct FDMBackend3{A} <: AD.AbstractFiniteDifference alg::A end FDMBackend3() = FDMBackend3(central_fdm(5, 1)) const fdm_backend3 = FDMBackend3() AD.@primitive function value_and_pullback_function(ab::FDMBackend3, f, xs...) value = f(xs...) function fd3_pullback(vs) # Supports only single output _vs = vs isa AbstractVector ? vs : only(vs) return FDM.j′vp(ab.alg, f, _vs, xs...) end return value, fd3_pullback end ## ## ForwardDiff struct ForwardDiffBackend1 <: AD.AbstractForwardMode end const forwarddiff_backend1 = ForwardDiffBackend1() function AD.jacobian(ab::ForwardDiffBackend1, f, xs) if xs isa Number return (ForwardDiff.derivative(f, xs),) elseif xs isa AbstractArray out = f(xs) if out isa Number return (adjoint(ForwardDiff.gradient(f, xs)),) else return (ForwardDiff.jacobian(f, xs),) end elseif xs isa Tuple error(typeof(xs)) else error(typeof(xs)) end end AD.primal_value(::ForwardDiffBackend1, ::Any, f, xs) = ForwardDiff.value.(f(xs...)) struct ForwardDiffBackend2 <: AD.AbstractForwardMode end const forwarddiff_backend2 = ForwardDiffBackend2() AD.@primitive function pushforward_function(ab::ForwardDiffBackend2, f, xs...) # jvp = f'(x)*v, i.e., differentiate f(x + h*v) wrt h at 0 return function (vs) if xs isa Tuple @assert length(xs) <= 2 if length(xs) == 1 (ForwardDiff.derivative(h -> f(xs[1] + h * vs[1]), 0),) else ForwardDiff.derivative(h -> f(xs[1] + h * vs[1], xs[2] + h * vs[2]), 0) end else ForwardDiff.derivative(h -> f(xs + h * vs), 0) end end end AD.primal_value(::ForwardDiffBackend2, ::Any, f, xs) = ForwardDiff.value.(f(xs...)) ## ## Zygote struct ZygoteBackend1 <: AD.AbstractReverseMode end const zygote_backend1 = ZygoteBackend1() AD.@primitive function value_and_pullback_function(ab::ZygoteBackend1, f, xs...) # Supports only single output value, back = Zygote.pullback(f, xs...) function zygote_pullback(vs) _vs = vs isa AbstractVector ? vs : only(vs) return back(_vs) end return value, zygote_pullback end @testset "defaults" begin @testset "Utils" begin test_higher_order_backend( fdm_backend1, fdm_backend2, fdm_backend3, zygote_backend1, forwarddiff_backend2 ) end @testset "FiniteDifferences" begin @testset "Derivative" begin test_derivatives(fdm_backend1) test_derivatives(fdm_backend2) test_derivatives(fdm_backend3) end @testset "Gradient" begin test_gradients(fdm_backend1) test_gradients(fdm_backend2) test_gradients(fdm_backend3) end @testset "Jacobian" begin test_jacobians(fdm_backend1) test_jacobians(fdm_backend2) test_jacobians(fdm_backend3) end @testset "Hessian" begin test_hessians(fdm_backend1) test_hessians(fdm_backend2) test_hessians(fdm_backend3) end @testset "jvp" begin test_jvp(fdm_backend1; test_types=false) test_jvp(fdm_backend2; vaugmented=true) test_jvp(fdm_backend3) end @testset "j′vp" begin test_j′vp(fdm_backend1) test_j′vp(fdm_backend2) test_j′vp(fdm_backend3) end @testset "Lazy Derivative" begin test_lazy_derivatives(fdm_backend1) test_lazy_derivatives(fdm_backend2) test_lazy_derivatives(fdm_backend3) end @testset "Lazy Gradient" begin test_lazy_gradients(fdm_backend1) test_lazy_gradients(fdm_backend2) test_lazy_gradients(fdm_backend3) end @testset "Lazy Jacobian" begin test_lazy_jacobians(fdm_backend1) test_lazy_jacobians(fdm_backend2; vaugmented=true) test_lazy_jacobians(fdm_backend3) end @testset "Lazy Hessian" begin test_lazy_hessians(fdm_backend1) test_lazy_hessians(fdm_backend2) test_lazy_hessians(fdm_backend3) end end @testset "ForwardDiff" begin @testset "Derivative" begin test_derivatives(forwarddiff_backend1; multiple_inputs=false) test_derivatives(forwarddiff_backend2) end @testset "Gradient" begin test_gradients(forwarddiff_backend1; multiple_inputs=false) test_gradients(forwarddiff_backend2) end @testset "Jacobian" begin test_jacobians(forwarddiff_backend1; multiple_inputs=false) test_jacobians(forwarddiff_backend2) end @testset "Hessian" begin test_hessians(forwarddiff_backend1; multiple_inputs=false) test_hessians(forwarddiff_backend2) end @testset "jvp" begin test_jvp(forwarddiff_backend1; multiple_inputs=false) test_jvp(forwarddiff_backend2; vaugmented=true) end @testset "j′vp" begin test_j′vp(forwarddiff_backend1; multiple_inputs=false) test_j′vp(forwarddiff_backend2) end @testset "Lazy Derivative" begin test_lazy_derivatives(forwarddiff_backend1; multiple_inputs=false) test_lazy_derivatives(forwarddiff_backend2) end @testset "Lazy Gradient" begin test_lazy_gradients(forwarddiff_backend1; multiple_inputs=false) test_lazy_gradients(forwarddiff_backend2) end @testset "Lazy Jacobian" begin test_lazy_jacobians(forwarddiff_backend1; multiple_inputs=false) test_lazy_jacobians(forwarddiff_backend2; vaugmented=true) end @testset "Lazy Hessian" begin test_lazy_hessians(forwarddiff_backend1; multiple_inputs=false) test_lazy_hessians(forwarddiff_backend2) end end @testset "Zygote" begin @testset "Derivative" begin test_derivatives(zygote_backend1) end @testset "Gradient" begin test_gradients(zygote_backend1) end @testset "Jacobian" begin test_jacobians(zygote_backend1) end @testset "Hessian" begin # Zygote over Zygote problems backends = AD.HigherOrderBackend((forwarddiff_backend2, zygote_backend1)) test_hessians(backends) backends = AD.HigherOrderBackend((zygote_backend1, forwarddiff_backend1)) test_hessians(backends) # fails: # backends = AD.HigherOrderBackend((zygote_backend1,forwarddiff_backend2)) # test_hessians(backends) end @testset "jvp" begin test_jvp(zygote_backend1) end @testset "j′vp" begin test_j′vp(zygote_backend1) end @testset "Lazy Derivative" begin test_lazy_derivatives(zygote_backend1) end @testset "Lazy Gradient" begin test_lazy_gradients(zygote_backend1) end @testset "Lazy Jacobian" begin test_lazy_jacobians(zygote_backend1) end @testset "Lazy Hessian" begin # Zygote over Zygote problems backends = AD.HigherOrderBackend((forwarddiff_backend2, zygote_backend1)) test_lazy_hessians(backends) backends = AD.HigherOrderBackend((zygote_backend1, forwarddiff_backend1)) test_lazy_hessians(backends) end end end
package io.webwidgets.core; import java.io.*; import java.util.*; import java.sql.*; import java.net.*; import java.util.function.BiFunction; import net.danburfoot.shared.Util; import net.danburfoot.shared.CoreDb; import net.danburfoot.shared.ArgMap; import net.danburfoot.shared.FileUtils; import net.danburfoot.shared.RunnableTech.*; import net.danburfoot.shared.Util.SyscallWrapper; import net.danburfoot.shared.CoreDb.QueryCollector; import io.webwidgets.core.CoreUtil.*; import io.webwidgets.core.WidgetOrg.*; import io.webwidgets.core.AuthLogic.*; import io.webwidgets.core.MailSystem.*; import io.webwidgets.core.DataServer.*; import io.webwidgets.core.PluginCentral.*; import io.webwidgets.core.BlobDataManager.*; public class FastTest4Basic { // For several of the tests in this package, we need a user, currently use my username private static WidgetUser getTestDburfootUser() { return WidgetUser.lookup("dburfoot"); } public static class CheckUserHardReference extends DescRunnable { public String getDesc() { return "WidgetUser objects are immutable and unique\n" + "This test checks that if you load a WidgetUser object twice, you get the same object back"; } public void runOp() { WidgetUser heather1 = WidgetUser.valueOf("heather"); WidgetUser heather2 = WidgetUser.valueOf("heather"); // Util.pf("H1 = %s, H2 = %s\n", heather1, heather2); Util.massert(heather1 == heather2, "WidgetUser objects must be unique, hard equals must work"); WidgetItem moodlog = new WidgetItem(WidgetUser.valueOf("heather"), "mood"); Util.massert(heather1 == moodlog.theOwner); boolean allow = AuthChecker.build().directSetAccessor(heather1).directDbWidget(moodlog).allowRead(); Util.massert(allow, "Must allow access to owner"); } } public static class AccessCheck extends DescRunnable { public String getDesc() { return "Checks that authentication logic is working properly for a couple of hardcoded pages\n" + "For Heather's pages, requires that dburfoot and heather can access\n" + "For dburfoot pages, requires that only dburfoot can access"; } public void runOp() { Set<WidgetUser> adminheather = Util.setify(getTestDburfootUser(), WidgetUser.valueOf("heather")); for(WidgetUser wuser : WidgetUser.values()) { WidgetItem probe = new WidgetItem(WidgetUser.valueOf("heather"), "mood"); boolean allow = AuthChecker.build().directSetAccessor(wuser).directDbWidget(probe).allowRead(); boolean expect = adminheather.contains(wuser); Util.massert(allow == expect, "Got allow=%s but expected %s for wuser=%s", allow, expect, wuser); } for(WidgetUser wuser : WidgetUser.values()) { String page = getHeatherPage(); boolean allow = AuthChecker.build().widgetFromUrl(page).directSetAccessor(wuser).allowRead(); boolean expect = adminheather.contains(wuser); Util.massert(allow == expect, "Got allow=%s but expected %s for wuser=%s", allow, expect, wuser); } for(WidgetUser wuser : WidgetUser.values()) { String page = getDburfootPage(); boolean allow = AuthChecker.build().widgetFromUrl(page).directSetAccessor(wuser).allowRead(); boolean expect = wuser == getTestDburfootUser(); Util.massert(allow == expect, "Got allow=%s but expected %s for wuser=%s", allow, expect, wuser); } } private String getHeatherPage() { return "https://webwidgets.io/u/heather/mood/main.jsp"; } private String getDburfootPage() { return "https://webwidgets.io/u/dburfoot/life/main.jsp"; } } public static class MainUserConfigCheck extends DescRunnable { public String getDesc() { return "Checks the following 3 sets are equal:\n" + "The user_name records in the MASTER database\n" + "The folders in the widget base DB directory\n" + "The folders in the widget base code directory\n"; } public void runOp() { Set<String> codeset = getFolderKidSet(new File(CoreUtil.getWidgetCodeDir())); { codeset.remove("admin"); codeset.remove("exadmin"); codeset.remove("resin-data"); codeset.remove("WEB-INF"); } { Set<String> checkset = getFolderKidSet(new File(CoreUtil.WIDGET_DB_DIR)); Util.massert(checkset.equals(codeset), "Have Check set:\n%s\nCode set:\n%s\n", checkset, codeset); Util.pf("Success, DB set equals code-dir set, have %d items\n", checkset.size()); } { Set<String> checkset = Util.map2set(WidgetUser.values(), user -> user.toString()); Util.massert(checkset.equals(codeset), "Have Check set:\n%s\nCode set:\n%s\n", checkset, codeset); Util.pf("Success, WidgetUser set equals code-dir set, have %d items\n", checkset.size()); } } private static Set<String> getFolderKidSet(File basedir) { Util.massert(basedir.exists() && basedir.isDirectory(), "Basedir must be a directory"); return Util.map2set(Util.listify(basedir.listFiles()), file -> file.getName()); } } public static class TestWuserDataLoad extends ArgMapRunnable { public void runOp() { for(WidgetUser user : WidgetUser.values()) { Util.massert(user.haveUserEntry(), "Did not find USER entry for user %s", user); } WidgetUser dburfoot = WidgetUser.lookup("dburfoot"); Util.massert(dburfoot.isAdmin()); Util.massertEqual(dburfoot.getEmail(), "[email protected]", "Dburfoot email is reported as %s but expected %s"); Util.pf("Success, found user entries for all WidgetUser records\n"); } } // At some point, had an issue where I copied the AutoGen from one user to another // That is bad news, because now I'm updating a different user's data!!! public static class TestUserNameAutoGen extends DescRunnable { int _lineCount = 0; int _fileCount = 0; int _userCount = 0; public String getDesc() { return "Test that the username of the widget Owner is present in all of the autogen JS files"; } public void runOp() { for(WidgetUser user : WidgetUser.values()) { checkUser(user); } Util.pf("Checked %d users, %d files, %d lines\n", _userCount, _fileCount, _lineCount); } private void checkUser(WidgetUser user) { String deftag = String.format("widgetOwner : \"%s\"", user.toString()); for(WidgetItem dbitem : user.getUserWidgetList()) { File jsdir = WebUtil.getAutoGenJsDir(dbitem); Util.massert(jsdir.exists() && jsdir.isDirectory(), "Problem with autogen JS dir %s", jsdir); for(File jsfile : jsdir.listFiles()) { List<String> jslist = FileUtils.getReaderUtil().setFile(jsfile).readLineListE(); int hits = Util.countPred(jslist, js -> js.contains(deftag)); Util.massert(hits >= 1, "Failed to find expected tag %s in autogen file %s", deftag, jsfile); _fileCount++; _lineCount += jslist.size(); } } _userCount++; } } public static class ServerPageAuthInclude extends DescRunnable { int _okayCount = 0; int _errCount = 0; public String SEARCH_TAG = "../admin/AuthInclude.jsp_inc"; public String getDesc() { return "Check that all the JSPs in the directory " + CoreUtil.getWidgetCodeDir() + "\n" + "Contain the Auth Include tag " + SEARCH_TAG + "\n" + "This is the crucial include file to ensure proper authentication checks"; } public void runOp() { File startdir = new File(CoreUtil.getWidgetCodeDir()); recurseCheck(startdir, 0); Util.massert(_errCount == 0, "Got %d error paths, see above", _errCount); Util.massert(_okayCount > 20, "Should have at least 20 JSP checks"); Util.pf("Success, checked %d JSP files\n", _okayCount); } private void recurseCheck(File thefile, int depth) { if(thefile.getAbsolutePath().contains(CoreUtil.WIDGET_ADMIN_DIR)) { return; } if(thefile.getAbsolutePath().contains("dburfoot/docview")) { return; } if(thefile.isDirectory()) { for(File sub : thefile.listFiles()) { recurseCheck(sub, depth+1); } } if(!thefile.getAbsolutePath().endsWith(".jsp")) { return; } // These are base-level .JSPs if(depth <= 2) { return; } for(String special : Util.listify("docview", "biz")) { String search = "dburfoot/" + special; if(thefile.getAbsolutePath().contains(search)) { return; } } List<String> data = FileUtils.getReaderUtil() .setFile(thefile) .readLineListE(); int cp = Util.countPred(data, s -> s.indexOf(SEARCH_TAG) > -1); Util.massert(cp <= 1, "Got MULTIPLE %d hits for file %s", cp, thefile); for(String special : Util.listify("LogIn")) { if(thefile.getAbsolutePath().endsWith(special + ".jsp")) { Util.massert(cp == 0, "Expected ZERO Auths in special file %s", thefile.getAbsolutePath()); return; } } if(cp == 1) { _okayCount += 1; return; } _errCount += 1; Util.pferr("Failed to find AuthInclude in JSP file %s\n", thefile); } } public static class CheckUserDirExist extends DescRunnable { public String getDesc() { return "Check that the user base dir exists for all the current WidgetUsers"; } public void runOp() { for(WidgetUser wuser : WidgetUser.values()) { File basedir = wuser.getUserBaseDir(); Util.massert(basedir.exists(), "Base directory for user %s does not exist", basedir); } } } public static class PluginLoadCheck extends DescRunnable { public String getDesc() { return "Check that the plugins can load without any misconfiguration errors\n" + "Errors are things like class name typos, missing constructors, etc"; } public void runOp() { IBlobStorage blobtool = PluginCentral.getStorageTool(); Util.pf("Loaded blob storage tool %s\n", blobtool.getClass().getName()); IMailSender mailtool = PluginCentral.getMailPlugin(); Util.pf("Loaded mail plugin %s\n", mailtool.getClass().getName()); } } public static class DeleteGimpTable extends DescRunnable { public String getDesc() { return "Delete the dumb old gimp files"; } public void runOp() { boolean modokay = _argMap.getBit("modokay", false); List<WidgetItem> problist = Util.vector(); for(WidgetUser wuser : WidgetUser.values()) { for(WidgetItem witem : wuser.getUserWidgetList()) { // This doens't work, filters out the __ prefixes // Set<String> nameset = witem.getDbTableNameSet(); Set<String> nameset = CoreDb.getLiteTableNameSet(witem); Set<String> badset = Util.filter2set(nameset, name -> name.contains("gimp")); if(!badset.isEmpty()) { Util.pf("Found badset %s for %s\n", badset, witem); problist.add(witem); } } } if(problist.isEmpty()) { Util.pf("Success, No bad Widgets found\n"); return; } Util.massert(modokay, "Found %d errors, see above", problist.size()); Util.pf("Going to delete from %d Widgets as above, okay?", problist.size()); if(!Util.checkOkay("Okay to delete?")) { Util.pf("Quitting\n"); return; } for(WidgetItem witem : problist) { String dropper = Util.sprintf("DROP TABLE __gimp"); CoreDb.execSqlUpdate(dropper, witem); Util.pf("Fixed Widget %s\n", witem); } } } public static class CheckUserAutoGen extends DescRunnable { public String getDesc() { return "Check that the JS autogen file exists for all widgets\n" + "Also checks that the LiteTableInfo data spool code runs for all widgets\n" + "The point is to check that there is no config issues or naming issues in the DB files"; } public void runOp() { int errcount = 0; int tablecount = 0; int widgetcount = 0; for(WidgetUser wuser : WidgetUser.values()) { if(!wuser.haveLocalDb()) { continue; } List<WidgetItem> itemlist = wuser.getUserWidgetList(); for(WidgetItem witem : itemlist) { for(String dbname : witem.getDbTableNameSet()) { if(dbname.startsWith("__")) { continue; } // nodatamode = true, this makes it run much faster LiteTableInfo tinfo = new LiteTableInfo(witem, dbname, true); Optional<File> autofile = tinfo.findAutoGenFile(); Util.massert(autofile.isPresent(), "JS data path for widget %s::%s does not exist", witem, dbname); try { tinfo.runSetupQuery(); List<String> datalist = tinfo.composeDataRecSpool(); } catch (Exception ex) { Util.pferr("Got exception on widget %s, table %s\n", witem, dbname); ex.printStackTrace(); errcount++; } tablecount++; } } widgetcount += itemlist.size(); } Util.massert(errcount == 0, "Got %d errors, see above", errcount); Util.pf("Checked %d tables for %d widgets and %d users\n", tablecount, widgetcount, WidgetUser.values().size()); } } public static class SuiteRunner extends DescRunnable implements CrontabRunnable { public static final String FAST_TEST_MARKER = CoreUtil.peelSuffix(FastTest4Basic.class.getSimpleName(), "Basic"); public String getDesc() { return "Inspects to find the other inner classes in this class\n" + "And runs them as unit tests\n" + "Any ArgMapRunnable inner class you put in this file will run as a unit test"; } public void runOp() throws Exception { for(ArgMapRunnable amr : getTestList()) { Util.pf("Running test: %s\n", amr.getClass().getSimpleName()); amr.initFromArgMap(new ArgMap()); amr.runOp(); } } @SuppressWarnings( "deprecation" ) public List<ArgMapRunnable> getTestList() { List<String> allclass = Util.loadClassNameListFromDir(new File(CoreUtil.JCLASS_BASE_DIR)); List<String> biglist = Util.filter2list(allclass, s -> s.contains(FAST_TEST_MARKER)); List<ArgMapRunnable> amrlist = Util.map2list(biglist, s -> { try { ArgMapRunnable amr = (ArgMapRunnable) Class.forName(s).newInstance(); return amr; } catch (Exception ex) { return null; } }); return Util.filter2list(amrlist, amr -> amr != null && amr.getClass() != this.getClass()); } } public static class CheckMailBoxConfig extends DescRunnable { public String getDesc() { return "For all WidgetUsers with a mailbox, check that the mailbox is properly configured"; } public void runOp() { // CREATE TABLE outgoing (id int, sent_at_utc varchar(19), send_target_utc varchar(19), recipient varchar(100), // subject varchar(100), email_content varchar(1000), is_text smallint, primary key(id)); Set<String> expectedcol = Util.setify("id", "sent_at_utc", "send_target_utc", "recipient", "subject", "email_content", "is_text"); for(WidgetUser probe : WidgetUser.values()) { WidgetItem mailbox = new WidgetItem(probe, MailSystem.MAILBOX_WIDGET_NAME); if(!mailbox.getLocalDbFile().exists()) { continue; } Util.pf("Found mailbox for user %s, checking configuration\n", probe); QueryCollector qcol = CoreUtil.tableQuery(mailbox, MailSystem.MAILBOX_DB_TABLE, Optional.of(10)); for(ArgMap onemap : qcol.recList()) { for(String col : expectedcol) { Util.massert(onemap.keySet().contains(col), "Missing expected column %s", col); } } } } } public static class CheckUrlWidgetLookup extends DescRunnable { public String getDesc() { return "Check logic of looking up WidgetItem from URL"; } public void runOp() { { WidgetItem dbbase = getTestDburfootUser().baseWidget(); for(String baseurl : getDbBaseList()) { WidgetItem probe = WebUtil.getWidgetFromUrl(baseurl); Util.massert(dbbase.equals(probe), "Wanted %s but got %s", dbbase, probe); } } LinkedList<String> otherlist = Util.linkedlistify(getOtherList()); while(!otherlist.isEmpty()) { String url = otherlist.poll(); WidgetUser wuser = WidgetUser.valueOf(otherlist.poll()); WidgetItem witem = new WidgetItem(wuser, otherlist.poll()); WidgetItem probe = WebUtil.getWidgetFromUrl(url); Util.massert(witem.equals(probe), "Expected %s but got %s", witem, probe); } } private List<String> getDbBaseList() { return Arrays.asList( "https://webwidgets.io/u/dburfoot/", "https://webwidgets.io/u/dburfoot", "https://webwidgets.io/u/dburfoot/index.jsp", "https://webwidgets.io/u/dburfoot/widget.jsp" ); } private List<String> getOtherList() { return Arrays.asList( "https://webwidgets.io/u/d57tm/index.jsp", "d57tm", "base", "https://webwidgets.io/u/dburfoot/links/widget.jsp", "dburfoot", "links" /* "https://webwidgets.io/u/dburfoot/links/", "dburfoot", "links" */ ); } } public static class TestGuessMimeType extends DescRunnable { public String getDesc() { // https://stackoverflow.com/questions/19845213/how-to-get-the-methodinfo-of-a-java-8-method-reference return "Simple test of the method java.net.URLConnection::guessContentTypeFromName" + "Blob Storage code relies on this method to assign mime types based on file names"; } public void runOp() { LinkedList<String> data = buildInputData(); while(!data.isEmpty()) { String input = data.poll(); String expected = data.poll(); String observed = java.net.URLConnection.guessContentTypeFromName(input); Util.massertEqual(expected, observed, "Expected %s but found %s for input %s", input); } } private static LinkedList<String> buildInputData() { return Util.linkedlistify( "myImg.jpg", "image/jpeg", "DumbBookStoreSign.jpeg", "image/jpeg", "Dans' Great Picture.png", "image/png", "Dans' Great Picture.pdf", "application/pdf", // "2_2022 0806 Andeesheh Open House Agenda for distribution.xlsx", "...", // "DansSmartDocument.doc", "application/msword" "Dans' Great Picture.gif", "image/gif", "Dans' Great Picture.mp3", "audio/mpeg" ); } } public static class CheckNewBlobAddress extends DescRunnable { public String getDesc() { return "Simple Check of new blob address tech"; } public void runOp() { LinkedList<Object> input = buildInputData(); while(!input.isEmpty()) { int recordid = Util.cast(input.poll()); String expected = Util.cast(input.poll()); String observed = BlobDataManager.getBlobFileName(recordid); Util.massertEqual(expected, observed, "Expected/Observed: \n\t%s\n\t%s"); } Random myrand = new Random(); for(int attempt : Util.range(1000)) { int probe = myrand.nextInt(); String bfile = BlobDataManager.getBlobFileName(probe); Util.massert(bfile.length() == "blob__P0000000005".length(), "Result was %s", bfile); String search = (probe+"").replaceAll("-", ""); Util.massert(bfile.contains(search)); } Util.pf("Success, blob formatting worked okay\n"); } private static LinkedList<Object> buildInputData() { return Util.linkedlistify( 5, "blob__P0000000005", 1_426_625_285, "blob__P1426625285", -1_426_625_285, "blob__N1426625285", 426_625_285, "blob__P0426625285", -426_625_285, "blob__N0426625285", 100, "blob__P0000000100", -100, "blob__N0000000100", 0, "blob__P0000000000", Integer.MAX_VALUE, "blob__P" + Integer.MAX_VALUE, Integer.MIN_VALUE, ("blob__N" + Integer.MIN_VALUE).replaceAll("-", "") ); } } public static class GoogleSyncTest extends CoreCommand.GoogleSyncAdmin { WidgetItem DB_CHORE_WIDGET = new WidgetItem(getTestDburfootUser(), "chores"); public String getDesc() { return "Test version of the GoogleSyncAdmin\n" + "Uploads the Widget " + DB_CHORE_WIDGET; } public void runOp() { super.runOp(); Util.massert(opSuccess, "Sync operation failed"); } @Override public WidgetItem getDbItem() { return DB_CHORE_WIDGET; } } public static class EmailComposeLinkMagic extends DescRunnable { public String getDesc() { return "Test that the reflection magic works"; } public void runOp() { { BiFunction<ValidatedEmail, WidgetUser, String> myfunc = MailSystem.getEmailComposeLink(); String result = myfunc.apply(ValidatedEmail.from("[email protected]"), getTestDburfootUser()); Util.pf("Result is %s\n", result); } { BiFunction<ValidatedEmail, WidgetUser, Boolean> myfunc = MailSystem.getEmailControlSend(); boolean result = myfunc.apply(ValidatedEmail.from("[email protected]"), getTestDburfootUser()); Util.pf("Result is %s\n", result); } } } public static class Base64EncodeTest extends DescRunnable { public String getDesc() { return "Test of Base 64 encode / decode"; } // TODO: add more data here, including maybe Chinese, etc public void runOp() { backAndForthTest("[email protected]"); } private static void backAndForthTest(String original) { String encoded = CoreUtil.base64Encode(original); String decoded = CoreUtil.base64Decode(encoded); Util.massert(decoded.equals(original), "Encoded %s but decoded %s", original, decoded); } } public static class PingWwioSite extends DescRunnable { public String getDesc() { return "Just ping the WWIO site, get a simple page"; } public void runOp() throws Exception { for(String relpath : getRelativePathList()) { String fullurl = String.format("https://%s%s", WebUtil.WWIO_DOMAIN, relpath); URLConnection connection = new URL(fullurl).openConnection(); InputStream response = connection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtils.in2out(response, baos); int rsize = baos.size(); Util.massert(rsize > 1000, "Got only %d bytes of response data", rsize); Util.pf("Success, pinged page %s and received %d bytes of response\n", fullurl, rsize); } } private static List<String> getRelativePathList() { return Arrays.asList( "", "/u/admin/EmailControl.jsp?sender=dburfoot", "/docs/JsFileDoc.jsp", "/docs/PythonDoc.jsp", "/docs/WidgetSetup.jsp", "/docs/GoogleExport.jsp", "/u/admin/AdminMain.jsp", "/u/admin/ImportWidget.jsp", "/u/admin/ChangePass.jsp", "/u/admin/Bounce2Home.jsp", "/u/admin/MailRunner.jsp" // "/u/admin/GoogleSyncMain.jsp" ); } } public static class TestLoadPluginInfo extends DescRunnable { public String getDesc() { return "Confirm that the Plugin config and classes can be successfully loaded"; } public void runOp() { var classmap = PluginCentral.getPluginClassMap(); Util.pf("Success, loaded plugins successfully, map is %s\n", classmap); } } public static class CheckDataIncludeError extends DescRunnable { private int _goodCount = 0; private int _baddCount = 0; public String getDesc() { return "Confirm that the DataInclude parser behaves as appropriate, including errors when bad data is passed"; } public void runOp() { checkResult(""); checkResult("tables=my_table", DataIncludeArg.tables); checkResult("widgetname=danstuff&tables=my_table", DataIncludeArg.tables, DataIncludeArg.widgetname); checkResult("no_data=true&widgetname=dantench", DataIncludeArg.widgetname, DataIncludeArg.no_data); checkError("table=my_table", "Invalid DataServer include"); checkError("no_data", "invalid Key=Value term"); checkError("tables=dantech&tables=mytech", "Duplicate DataServer include argument __tables__"); Util.pf("Success, got %d good and %d bad expected results\n", _goodCount, _baddCount); } private void checkError(String query, String messagetag) { try { ArgMap amap = DataServer.buildIncludeMap(query); Util.massert(false, "Failed to throw exception as expected"); } catch (Exception ex) { Util.massert(ex.getMessage().contains(messagetag), "Failed to find tag %s in error %s", messagetag, ex.getMessage()); } _baddCount++; } private void checkResult(String query, DataIncludeArg... expect) { ArgMap amap = DataServer.buildIncludeMap(query); Util.massert(amap.size() == expect.length); for(DataIncludeArg darg : expect) { Util.massert(amap.containsKey(darg.toString()), "Missing argument %s", darg); } _goodCount++; } } public static class CheckAdminUserCount extends ArgMapRunnable { public void runOp() { List<WidgetUser> adminlist = Util.filter2list(WidgetUser.values(), user -> user.isAdmin()); Util.massert(adminlist.size() == 1, "No admin users found"); Util.pf("success, found %d admin users\n", adminlist.size()); Set<String> adminset = Util.map2set(adminlist, user -> user.toString()); Util.massert(adminset.contains("dburfoot")); } } public static class CheckMasterDbSetup extends DescRunnable { public String getDesc() { return "Checks that the MASTER DB is setup properly\n" + "The file must exist in the right place, and have SQL statements\n" + "That agree with what is specified in the Java code"; } public void runOp() { WidgetUser shared = WidgetUser.buildBackDoorSharedUser(); WidgetItem master = new WidgetItem(shared, CoreUtil.MASTER_WIDGET_NAME); { File dbfile = master.getLocalDbFile(); Util.massert(dbfile.exists(), "Master DB file expected at %s, does not exist", dbfile); } String query = "SELECT * FROM sqlite_master"; QueryCollector qcol = QueryCollector.buildAndRun(query, master); Map<String, String> create = Util.map2map(qcol.recList(), amap -> amap.getStr("name"), amap -> amap.getStr("sql")); for(MasterTable mtable : MasterTable.values()) { String observed = create.getOrDefault(mtable.toString(), "Not Present"); String expected = mtable.createSql; Util.massert(observed.equals(expected), "For table %s, have DB SQL vs expected SQL:\n\t%s\n\t%s", mtable, observed, expected ); } Util.pf("Success, checked %d MasterTable definitions\n", MasterTable.values().length); } } }
"use client"; import { useAppSelector } from "@/hooks"; import { Box, Button, Flex, FormControl, FormLabel, Input, Text, useToast, } from "@chakra-ui/react"; import { useState, FormEvent, ChangeEvent } from "react"; import { useAppDispatch } from "@/hooks"; import { clearCart } from "@/features/cart.slice"; import useCartTotal from "@/hooks/useCartTotal"; import { useRouter } from "next/navigation"; export default function PaymentComponent() { const cartItems = useAppSelector((state) => state.shoppingCartSlice.items); const totalPrice = useCartTotal(); const router = useRouter(); var [input, setInput] = useState({ user_email: "", user_first_name: "", user_last_name: "", }); const toast = useToast(); const dispatch = useAppDispatch(); const handleSubmit = async (event: FormEvent<HTMLFormElement>) => { if (cartItems.length === 0) { return toast({ title: "Please select some product before confirming payment", description: "", status: "error", duration: 5000, position: "top", isClosable: true, }); } event.preventDefault(); Array.from(document.querySelectorAll("input")).forEach( (input) => (input.value = "") ); dispatch(clearCart()); toast({ title: "Order Placed Successfully", description: "", status: "success", duration: 5000, position: "top", isClosable: true, }); router.push("/"); }; const handleChange = (event: ChangeEvent<HTMLInputElement>) => { const { name, value } = event.target; setInput((prevInput) => ({ ...prevInput, [name]: value, })); }; return ( <> {cartItems.length > 0 && ( <Box id="signin" display="flex" flexDir="column" justifyContent="center" > <Box marginX={{ base: "11%", md: "22%", lg: "26%" }}> <Text fontWeight={700} fontSize="3xl"> Checkout </Text> </Box> <Box width={{ base: "85%", md: "60%", xl: "50%", }} border="10px" p={5} mr="auto" ml="auto" mb="5%" > <Flex flexDir="column"> <form onSubmit={(e) => handleSubmit(e)}> <FormControl id="email" isRequired> <FormLabel fontSize="18px">Email address</FormLabel> <Input type="email" placeholder="type your email here" name="user_email" _focus={{ zIndex: "0", borderColor: "#3182ce", }} onChange={(e) => handleChange(e)} /> </FormControl> <Box display="flex" marginTop="30px"> <FormControl id="first-name" isRequired> <FormLabel fontSize="18px">First Name</FormLabel> <Input type="text" placeholder="first name" name="user_first_name" _focus={{ zIndex: "0", borderColor: "#3182ce", }} onChange={handleChange} width="77%" /> </FormControl> <FormControl id="Last-name" isRequired> <FormLabel fontSize="18px">Last Name</FormLabel> <Input type="text" placeholder="last name" name="user_last_name" _focus={{ zIndex: "0", borderColor: "#3182ce", }} onChange={handleChange} /> </FormControl> </Box> <Box display="flex" backgroundColor="#F7F7F7" justifyContent="space-between" marginTop="40px" > <Box padding="1rem"> <Text>Product</Text> </Box> <Box padding="1rem"> <Text>Total</Text> </Box> </Box> <Box display="flex" flexDirection="column" justifyContent="space-between" > {cartItems.map((item) => { return ( <Box key={item.id} display="flex" justifyContent="space-between" padding="1rem" > <Box> <Text> {item.title} x {item.quantity} </Text> </Box> <Box> <Text>&#36;{item.total_price}</Text> </Box> </Box> ); })} </Box> <Box display="flex" justifyContent="space-between" marginTop="10px" > <Box padding="1rem"> <Text fontWeight={700}>Total</Text> </Box> <Box padding="1rem"> <Text fontWeight={700}>&#36;{totalPrice.toFixed(2)}</Text> </Box> </Box> <button type="submit" className="mt-4 p-2 bg-black text-white font-bold rounded-md mx-5" > CONFIRM PURCHASE </button> </form> </Flex> </Box> </Box> )} </> ); }
<template> <div class="event base-grid"> <template v-if="event"> <div class="event__title content"> <p class="event__title__date"> {{ event.date.weekday }} {{ event.date.day }}. {{ event.date.month }} {{ event.date.year }}</p> <div class="event__title__headline frame-br"> <h1 v-html="event.title"></h1> </div> </div> <div class="event__image full"> <img v-if="event.image" :src="event.image" :alt="event.title"> </div> <EventInfo :event="event" /> <div class="event__content content"> <div class="rendered-content" v-html="event.content"></div> <div v-if="event.spotify || event.website" class="event__content__tags"> <Tag v-if="event.spotify" content="Spotify" :url="event.spotify" /> <Tag v-if="event.website" content="Website" :url="event.website" /> </div> </div> <QuickLook :event="event" /> <div class="event__owner content"> <template v-if="event.presenter"> <p> <Tag content="Präsentiert von" /><a class="event__owner__link" target="_blank" :href="event.presenter.url">{{ event.presenter.title }}</a> </p> </template> <template v-if="event.organizer"> <p> <Tag content="Veranstalter" /><a class="event__owner__link" target="_blank" :href="event.organizer.url">{{ event.organizer.title }}</a> </p> </template> <template v-else> <p> <Tag content="Veranstalter" /> Verein Lilienthal e.V. </p> </template> </div> </template> </div> </template> <script> import utils from '../utils' import Tag from '../components/Tag' import EventInfo from '../components/EventInfo' import QuickLook from '../components/QuickLook' export default { name: 'Event', components: { EventInfo, Tag, QuickLook }, data: function () { return { event: null } }, methods: { getContent: async function (id) { this.$store.commit('isLoading', true); await utils.get.content('events?include[]=' + id) .then(res => this.event = utils.map.events(res, true)[0]) .then(this.$store.commit('isLoading', false)) .catch(err => utils.error.route(err)); }, isPresent: function () { if (this.$store.getters.getEvent(this.$route.params.id)) { this.event = this.$store.getters.getEvent(this.$route.params.id); } else { this.getContent(this.$route.params.id); } } }, mounted: function () { this.isPresent(); }, watch: { $route() { this.isPresent(); } } } </script> <style lang="scss"> .event { position: relative; width: 100%; &__title { margin-top: -25px; transform: translateY(25px); &__date { @include font(subline); text-decoration: underline; margin: var(--paddingSmall) 0; } &__headline { display: inline-block; padding: 12px; background-color: var(--white); &::before { background-color: var(--white); } } } &__image { min-height: 25px; img { width: 100%; vertical-align: middle; } } &__content { margin-bottom: -2px; border-top: 2px solid var(--black); .rendered-content { margin-top: -2px; } &__tags { margin-top: var(--containerSpacingHeight); padding: 0 var(--contentSpacingWidth) calc(var(--containerSpacingHeight) - 20px) var(--contentSpacingWidth); } } &__owner { margin: 20px 0; &__link { text-decoration: underline; } } } </style>
// ignore_for_file: avoid_print, unused_local_variable, dangling_library_doc_comments /// overview-1 int opCount = 0; int performOp(int a, int b) { opCount += 1; // Mutating global variable! return a + b; } /// overview-1 /// overview-2 int multiply(int a, int b) { print('multipying $a x $b'); // Side effect! return a * b; } /// overview-2 /// overview-3 final class Tracker { int count = 0; Tracker(); } int doubleHeadAndSum(int a, int b, Tracker tracker) { tracker.count += 1; // Modifying a field on the Tracker parameter return a + b * a; } /// overview-3 /// overview-4 bool fireMissile(int passcode) { if (passcode == 123) { return true; } else { throw Exception('Missle launch aborted: Invalid passcode!'); } } /// overview-4 /// overview-5 int pureAdd(int a, int b) => a + b; /// overview-5 /// overview-6 final class Counter { int count = 0; Counter add() { count += 1; return this; } } final counter = Counter(); final b = counter.add(); final resA = b.count; final resB = b.count; final areEqual = resA == resB; // Both values here equal 1 /// overview-6 void snippet7() { /// overview-7 final counter = Counter(); // final b = a.add(); // We replace all occurances of b with a.add(); final resA = counter.add().count; final resB = counter.add().count; final areEqual = resA == resB; // Oh no! resA == 1 while resB == 2! /// overview-7 }
import Combine import ComposableArchitecture import Core import MacAppRoute import TestSupport import XCTest import XExpect @testable import App @testable import Gertie @MainActor final class AppReducerTests: XCTestCase { func testDidFinishLaunching_Exhaustive() async { let (store, _) = AppReducer.testStore(exhaustive: true) let extSetup = mock(always: FilterExtensionState.installedButNotRunning) store.deps.filterExtension.setup = extSetup.fn let setUserToken = spy(on: UUID.self, returning: ()) store.deps.api.setUserToken = setUserToken.fn let filterStateSubject = PassthroughSubject<FilterExtensionState, Never>() store.deps.filterExtension.stateChanges = { filterStateSubject.eraseToAnyPublisher() } store.deps.storage.loadPersistentState = { .mock } store.deps.app.isLaunchAtLoginEnabled = { false } let enableLaunchAtLogin = mock(always: ()) store.deps.app.enableLaunchAtLogin = enableLaunchAtLogin.fn let startRelaunchWatcher = mock(always: ()) store.deps.app.startRelaunchWatcher = startRelaunchWatcher.fn await store.send(.application(.didFinishLaunching)) await store.receive(.loadedPersistentState(.mock)) { $0.user = .init(data: .mock) $0.history.userConnection = .established(welcomeDismissed: true) } await expect(extSetup.invocations).toEqual(1) await store.receive(.filter(.receivedState(.installedButNotRunning))) { $0.filter.extension = .installedButNotRunning } await store.receive(.startProtecting(user: .mock)) await store.receive(.websocket(.connectedSuccessfully)) await expect(setUserToken.invocations).toEqual([UserData.mock.token]) await expect(enableLaunchAtLogin.invocations).toEqual(1) await expect(startRelaunchWatcher.invocations).toEqual(1) let prevUser = store.state.user.data await store.receive(.checkIn(result: .success(.mock), reason: .startProtecting)) { $0.appUpdates.latestVersion = .init(semver: "2.0.4") $0.user.data?.screenshotsEnabled = true $0.user.data?.keyloggingEnabled = true $0.user.data?.screenshotFrequency = 333 $0.user.data?.screenshotSize = 555 $0.browsers = CheckIn.Output.mock.browsers } await store.receive(.user(.updated(previous: prevUser))) filterStateSubject.send(.notInstalled) await store.receive(.filter(.receivedState(.notInstalled))) { $0.filter.extension = .notInstalled } filterStateSubject.send(.installedButNotRunning) await store.receive(.filter(.receivedState(.installedButNotRunning))) { $0.filter.extension = .installedButNotRunning } filterStateSubject.send(completion: .finished) await store.send(.application(.willTerminate)) // cancel heartbeat } func testOnboardingDelegateSaveStepPersists() async { let (store, _) = AppReducer.testStore() let saveState = spy(on: Persistent.State.self, returning: ()) store.deps.storage.savePersistentState = saveState.fn await store.send(.onboarding(.delegate(.saveForResume(.at(step: .macosUserAccountType))))) await expect(saveState.invocations.value[0].resumeOnboarding) .toEqual(.at(step: .macosUserAccountType)) } func testDidFinishLaunching_EstablishesConnectionIfFilterOn() async { let (store, bgQueue) = AppReducer.testStore() store.deps.storage.loadPersistentState = { nil } store.deps.filterExtension.setup = { .installedAndRunning } let connectionEstablished = ActorIsolated(false) store.deps.filterXpc.establishConnection = { await connectionEstablished.setValue(true) return .success(()) } await store.send(.application(.didFinishLaunching)) await bgQueue.advance(by: .milliseconds(5)) await Task.repeatYield() await expect(connectionEstablished).toEqual(true) } func testDidFinishLaunching_NoPersistentUser() async { let (store, _) = AppReducer.testStore() store.deps.storage.loadPersistentState = { nil } await store.send(.application(.didFinishLaunching)) await store.receive(.loadedPersistentState(nil)) } func testHeartbeatClearSuspensionFallback() async { let now = Date() let (store, scheduler) = AppReducer.testStore { $0.filter.currentSuspensionExpiration = now.advanced(by: 60 * 3) } let time = ControllingNow(starting: now, with: scheduler) store.deps.date = time.generator await store.send(.application(.didFinishLaunching)) await time.advance(seconds: 60) await store.receive(.heartbeat(.everyMinute)) await time.advance(seconds: 60) await store.receive(.heartbeat(.everyMinute)) expect(store.state.filter.currentSuspensionExpiration).not.toBeNil() await time.advance(seconds: 60) await store.receive(.heartbeat(.everyMinute)) { $0.filter.currentSuspensionExpiration = nil } } } // helpers extension AppReducer { static func testStore<R: ReducerOf<AppReducer>>( exhaustive: Bool = false, mockDeps: Bool = true, reducer: R = AppReducer(), mutateState: @escaping (inout State) -> Void = { _ in } ) -> (TestStoreOf<AppReducer>, TestSchedulerOf<DispatchQueue>) { var state = State(appVersion: "1.0.0") mutateState(&state) let store = TestStore(initialState: state, reducer: { reducer }) store.useMainSerialExecutor = true store.exhaustivity = exhaustive ? .on : .off let scheduler = DispatchQueue.test if mockDeps { store.deps.date = .constant(Date(timeIntervalSince1970: 0)) store.deps.backgroundQueue = scheduler.eraseToAnyScheduler() store.deps.mainQueue = .immediate store.deps.monitoring = .mock store.deps.storage = .mock store.deps.storage.loadPersistentState = { .mock } store.deps.app = .mock store.deps.api = .mock store.deps.device = .mock store.deps.api.checkIn = { _ in .mock } store.deps.filterExtension = .mock store.deps.filterXpc = .mock store.deps.websocket = .mock } return (store, scheduler) } }
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AsyncStorage * @flow-weak */ 'use strict'; var NativeModules = require('NativeModules'); var RCTAsyncLocalStorage = NativeModules.AsyncLocalStorage; var RCTAsyncRocksDBStorage = NativeModules.AsyncRocksDBStorage; // We use RocksDB if available. var RCTAsyncStorage = RCTAsyncRocksDBStorage || RCTAsyncLocalStorage; /** * AsyncStorage is a simple, asynchronous, persistent, global, key-value storage * system. It should be used instead of LocalStorage. * * It is recommended that you use an abstraction on top of AsyncStorage instead * of AsyncStorage directly for anything more than light usage since it * operates globally. * * This JS code is a simple facad over the native iOS implementation to provide * a clear JS API, real Error objects, and simple non-multi functions. */ var AsyncStorage = { /** * Fetches `key` and passes the result to `callback`, along with an `Error` if * there is any. */ getItem: function( key: string, callback: (error: ?Error, result: ?string) => void ): void { RCTAsyncStorage.multiGet([key], function(errors, result) { // Unpack result to get value from [[key,value]] var value = (result && result[0] && result[0][1]) ? result[0][1] : null; callback((errors && convertError(errors[0])) || null, value); }); }, /** * Sets `value` for `key` and calls `callback` on completion, along with an * `Error` if there is any. */ setItem: function( key: string, value: string, callback: ?(error: ?Error) => void ): void { RCTAsyncStorage.multiSet([[key,value]], function(errors) { callback && callback((errors && convertError(errors[0])) || null); }); }, removeItem: function( key: string, callback: ?(error: ?Error) => void ): void { RCTAsyncStorage.multiRemove([key], function(errors) { callback && callback((errors && convertError(errors[0])) || null); }); }, /** * Merges existing value with input value, assuming they are stringified json. * * Not supported by all native implementations. */ mergeItem: function( key: string, value: string, callback: ?(error: ?Error) => void ): void { RCTAsyncStorage.multiMerge([[key,value]], function(errors) { callback && callback((errors && convertError(errors[0])) || null); }); }, /** * Erases *all* AsyncStorage for all clients, libraries, etc. You probably * don't want to call this - use removeItem or multiRemove to clear only your * own keys instead. */ clear: function(callback: ?(error: ?Error) => void) { RCTAsyncStorage.clear(function(error) { callback && callback(convertError(error)); }); }, /** * Gets *all* keys known to the system, for all callers, libraries, etc. */ getAllKeys: function(callback: (error: ?Error) => void) { RCTAsyncStorage.getAllKeys(function(error, keys) { callback(convertError(error), keys); }); }, /** * The following batched functions are useful for executing a lot of * operations at once, allowing for native optimizations and provide the * convenience of a single callback after all operations are complete. * * These functions return arrays of errors, potentially one for every key. * For key-specific errors, the Error object will have a key property to * indicate which key caused the error. */ /** * multiGet invokes callback with an array of key-value pair arrays that * matches the input format of multiSet. * * multiGet(['k1', 'k2'], cb) -> cb([['k1', 'val1'], ['k2', 'val2']]) */ multiGet: function( keys: Array<string>, callback: (errors: ?Array<Error>, result: ?Array<Array<string>>) => void ): void { RCTAsyncStorage.multiGet(keys, function(errors, result) { callback( (errors && errors.map((error) => convertError(error))) || null, result ); }); }, /** * multiSet and multiMerge take arrays of key-value array pairs that match * the output of multiGet, e.g. * * multiSet([['k1', 'val1'], ['k2', 'val2']], cb); */ multiSet: function( keyValuePairs: Array<Array<string>>, callback: ?(errors: ?Array<Error>) => void ): void { RCTAsyncStorage.multiSet(keyValuePairs, function(errors) { callback && callback( (errors && errors.map((error) => convertError(error))) || null ); }); }, /** * Delete all the keys in the `keys` array. */ multiRemove: function( keys: Array<string>, callback: ?(errors: ?Array<Error>) => void ): void { RCTAsyncStorage.multiRemove(keys, function(errors) { callback && callback( (errors && errors.map((error) => convertError(error))) || null ); }); }, /** * Merges existing values with input values, assuming they are stringified * json. * * Not supported by all native implementations. */ multiMerge: function( keyValuePairs: Array<Array<string>>, callback: ?(errors: ?Array<Error>) => void ): void { RCTAsyncStorage.multiMerge(keyValuePairs, function(errors) { callback && callback( (errors && errors.map((error) => convertError(error))) || null ); }); }, }; // Not all native implementations support merge. if (!RCTAsyncStorage.multiMerge) { delete AsyncStorage.mergeItem; delete AsyncStorage.multiMerge; } function convertError(error) { if (!error) { return null; } var out = new Error(error.message); out.key = error.key; // flow doesn't like this :( return out; } module.exports = AsyncStorage;
<nav class="navbar navbar-expand-lg" [ngClass]="{'no-user' : !currentUser || !isAuthenticated, 'collapsed': isNavBarCollapsed}"> <div class="navbar-logos" *ngIf="isAuthenticated"> <div class="programme-logo-container show-pointer" (click)="router.navigate(['app'])"> <img *ngIf="largeLogo$ | async as logo; else defaultLogo" class="logo fill" src="data:image/png;base64,{{logo.value}}" alt="Logo interreg programme"> <ng-template #defaultLogo> <img class="logo fill" src="assets/logos/InterregProgrammeLogo_96.png" alt="Logo interreg programme"> </ng-template> </div> </div> <!--Hamburger Menu--> <button jemsText mat-stroked-button class="navbar-toggler" [ngClass]="{'collapsed': isNavBarCollapsed}" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" name="toggle navigation" (click)="isNavBarCollapsed = !isNavBarCollapsed"> <mat-icon>menu</mat-icon> </button> <!-- Content --> <div class="navbar-right"> <div class="navbar-collapse collapse" [ngClass]="{'show': !isNavBarCollapsed}" id="navbarSupportedContent"> <ul class="navbar-navigation-items main-navigation-items" *ngIf="currentUser && isAuthenticated"> <ng-container> <li class="nav-item show-pointer" *ngFor="let item of menuItems$ | async" [ngClass]="{ 'active-not-collapsed': router.url.startsWith(item.route) && !isNavBarCollapsed, 'active-collapsed': router.url.startsWith(item.route) && isNavBarCollapsed }"> <a class="nav-link" (click)="isNavBarCollapsed = true; router.navigate([item.route], {queryParams: {version: null}, queryParamsHandling: 'merge'})" [routerLink]="item.route"> <mat-icon *ngIf="item.icon">{{item.icon}}</mat-icon> <span class="nav-text" jemsText maxLines="2">{{item.name | translate}}</span> </a> </li> </ng-container> </ul> <ul class="navbar-navigation-items secondary-navigation-items" [ngClass]="{'divide': !isNavBarCollapsed}"> <!-- Language selection --> <li class="nav-item language-list ml-2" *ngIf="languageSettings$ | async as languageSettings"> <mat-select #langSelect class="language-select" aria-label="{{'topbar.help.language.select' | translate}}" [value]="translate.currentLang" (selectionChange)="changeLanguage(langSelect.value)"> <mat-option *ngIf="!languageSettings.isDefaultAvailable && translate.currentLang === languageSettings.fallbackLanguage" [value]="languageSettings.fallbackLanguage" role="option"> <mat-label>{{'language.' + languageSettings.fallbackLanguage.toLowerCase() | translate}}</mat-label> </mat-option> <mat-option *ngFor="let lang of languageSettings.languages" [value]="lang" role="option"> <mat-label>{{'language.' + lang.toLowerCase() | translate}}</mat-label> </mat-option> </mat-select> </li> <!-- Help --> <li class="nav-item" [ngClass]="{'mt-2': !isNavBarCollapsed}"> <jems-help-menu></jems-help-menu> </li> <!-- Current user --> <li class="nav-item" *ngIf="isAuthenticated && (editUserItem$ | async) as item" [ngClass]="{'mt-2': !isNavBarCollapsed}"> <button mat-icon-button class="matmenu-trigger" aria-label="user button" [matMenuTriggerFor]="menu" aria-label="menu"> <mat-icon *ngIf="item.icon">{{item.icon}}</mat-icon> </button> <mat-menu #menu="matMenu" > <label class="matmenu-headline">{{'common.user' | translate}}</label> <ng-container> <a mat-menu-item (click)="router.navigate([item.route], {queryParams: {version: null}, queryParamsHandling: 'merge'})"> {{item.name | translate}} </a> </ng-container> <ng-container> <a mat-menu-item class="matmenu-heavy-link" (click)="logout()"> <span> {{'topbar.main.button.logout' | translate}}&nbsp; <mat-icon>logout</mat-icon> </span> </a> </ng-container> </mat-menu> </li> </ul> </div> </div> </nav>
import os from processfiles.timing import TimeTracker from processfiles.base import BaseProcessTracker class FileProcessTracker(BaseProcessTracker): def __init__(self, folder=None, restart=False, file_types=('csv',)): if folder is None: self.folder = os.getcwd() else: self.folder = os.path.abspath(folder) self.completed_list_path = os.path.join(self.folder, 'completed.txt') if restart: self.delete_completed_files() self.restart = restart self.load_completed_files() self.load_process_files(file_types=file_types) def file_generator(self): timer = TimeTracker(self.folder, restart=self.restart) num_items = len(self.process_list) for file in self.process_list: yield os.path.join(self.folder, file) self.add_to_completed(file) timer.time_estimate(num_items) # time_estimate is end \r, so this cancels the next output from writing over the final time estimate print('\n') def load_process_files(self, file_types): self.process_list = _load_to_process_files(self.folder, self.completed_list, file_types) def _load_to_process_files(folder, completed_list, file_types): files = _load_initial_file_list(folder, file_types) return [file for file in files if file not in completed_list] def _load_initial_file_list(folder, file_types): return [file for file in next(os.walk(folder))[2] if any([file.endswith(ending) for ending in file_types])]
struct ASNet{DO,TO,MP<:NamedTuple, P<:Union{Dict,Nothing},KB<:Union{Nothing, KnowledgeBase},S<:Union{Nothing,Matrix},G<:Union{Nothing,Matrix}} domain::DO type2obs::TO model_params::MP predicate2id::P kb::KB init_state::S goal_state::G function ASNet(domain::DO, type2obs::TO, model_params::MP, predicate2id::P, kb::KB, init::S, goal::G) where {DO,TO,MP<:NamedTuple,P,KB,S,G} @assert issubset((:message_passes, :residual), keys(model_params)) "Parameters of the model are not fully specified" @assert (init === nothing || goal === nothing) "Fixing init and goal state is bizzaare, as the extractor would always create a constant" new{DO,TO,MP,P,KB,S,G}(domain, type2obs, model_params, predicate2id, kb, init, goal) end end isspecialized(ex::ASNet) = (ex.predicate2id !== nothing) && (ex.kb !== nothing) hasgoal(ex::ASNet) = ex.goal_state !== nothing || ex.init_state !== nothing function ASNet(domain; message_passes = 2, residual = :linear) model_params = (;message_passes, residual) ASNet(domain, nothing, model_params, nothing, nothing, nothing, nothing) end function Base.show(io::IO, ex::ASNet) s = isspecialized(ex) ? "Specialized" : "Unspecialized" s *=" ASNet for $(ex.domain.name )" if isspecialized(ex) s *= " ($(length(ex.predicate2id)))" end print(io, s) end function specialize(ex::ASNet, problem) # map containing lists of objects of the same type type2obs = type2objects(ex.domain, problem) # create a map mapping predicates to their ID, which is pr predicates = mapreduce(union, values(ex.domain.predicates)) do p allgrounding(problem, p, type2obs) end predicate2id = Dict(reverse.(enumerate(predicates))) ex = ASNet(ex.domain, type2obs, ex.model_params, predicate2id, nothing, nothing, nothing) # just add fake input for a se to have something, it does not really matter what n = length(predicate2id) x = zeros(Float32, 0, n) kb = KnowledgeBase((;x1 = x)) sₓ = :x1 for i in 1:ex.model_params.message_passes input_to_gnn = last(keys(kb)) ds = encode_actions(ex, input_to_gnn) kb = append(kb, layer_name(kb, "gnn"), ds) if ex.model_params.residual !== :none #if there is a residual connection, add it kb = add_residual_layer(kb, keys(kb)[end-1:end], n) end end s = last(keys(kb)) kb = append(kb, :o, BagNode(ArrayNode(KBEntry(s, 1:n)), [1:n])) ASNet(ex.domain, type2obs, ex.model_params, predicate2id, kb, nothing, nothing) end """ type2objects(domain, problem) create a map of types to `problem.objects` including the type hierarchy example ```julia julia> domain.typetree Dict{Symbol, Vector{Symbol}} with 6 entries: :count => [] Symbol("fast-elevator") => [] :elevator => [Symbol("slow-elevator"), Symbol("fast-elevator")] :passenger => [] :object => [:elevator, :passenger, :count] Symbol("slow-elevator") => [] julia> problem.objtypes Dict{Const, Symbol} with 19 entries: fast0 => Symbol("fast-elevator") p0 => :passenger n4 => :count slow1-0 => Symbol("slow-elevator") p1 => :passenger p2 => :passenger p4 => :passenger n1 => :count p3 => :passenger n3 => :count slow0-0 => Symbol("slow-elevator") n0 => :count n2 => :count julia> type2objects(domain, problem) Dict{Symbol, Vector{Const}} with 6 entries: :count => [n4, n1, n3, n0, n2] Symbol("fast-elevator") => [fast0, fast1] :passenger => [p0, p1, p2, p4, p3] :elevator => [slow1-0, slow0-0, fast0, fast1] Symbol("slow-elevator") => [slow1-0, slow0-0] :object => [slow1-0, slow0-0, fast0, fast1, p0, p1, p2, p4, p3, n… ``` """ function type2objects(domain, problem) #first create a direct descendants type2obs = Dict{Symbol, Set{PDDL.Const}}() group_by_value!(type2obs, problem.objtypes) group_by_value!(type2obs, domain.constypes) kv = sort(collect(domain.typetree), lt = (i,j) -> i[1] ∈ j[2]) for (k, v) in kv v = filter(Base.Fix1(haskey, type2obs), v) isempty(v) && continue type2obs[k] = reduce(union, [type2obs[i] for i in v]) end Dict(k => collect(v) for (k,v) in type2obs) end function group_by_value!(o::Dict{K,Set{V}}, d::Dict{V,K}) where {V,K} for (k,v) in d push!(get!(o,v,Set{V}()), k) end o end function add_goalstate(ex::ASNet, problem, state = goalstate(ex.domain, problem)) ex = isspecialized(ex) ? ex : specialize(ex, problem) x = encode_state(ex, state) ASNet(ex.domain, ex.type2obs, ex.model_params, ex.predicate2id, ex.kb, nothing, x) end function add_initstate(ex::ASNet, problem, state = initstate(ex.domain, problem)) ex = isspecialized(ex) ? ex : specialize(ex, problem) x = encode_state(ex, state) ASNet(ex.domain, ex.type2obs, ex.model_params, ex.predicate2id, ex.kb, x, nothing) end function (ex::ASNet)(state) x = encode_state(ex::ASNet, state) if ex.goal_state !== nothing x = vcat(x, ex.goal_state) end if ex.init_state !== nothing x = vcat(ex.init_state, x) end kb = ex.kb kb = @set kb.kb.x1 = x kb end function encode_state(ex::ASNet, state) @assert isspecialized(ex) "Extractor is not specialized for a problem instance" x = zeros(Float32, 1, length(ex.predicate2id)) for p in PDDL.get_facts(state) x[ex.predicate2id[p]] = 1 end x end function encode_actions(ex::ASNet, kid::Symbol) actions = ex.domain.actions ns = tuple(keys(actions)...) xs = map(values(actions)) do action encode_action(ex, action, kid) end length(xs) == 1 ? only(xs) : ProductNode(NamedTuple{ns}(tuple(xs...))) end function encode_action(ex::ASNet, action::GenericAction, kid::Symbol) preds = allgrounding(action, ex.type2obs) # # This is filter to remove atoms with free variables # preds = map(preds) do atoms # filter(Base.Fix1(haskey, ex.predicate2id), atoms) # end encode_predicates(ex, preds, kid) end function encode_predicates(ex::ASNet, preds, kid::Symbol) l = length(first(preds)) xs = map(1:l) do i syms = [p[i] for p in preds] ArrayNode(KBEntry(kid, [ex.predicate2id[s] for s in syms])) end bags = [Int[] for _ in 1:length(ex.predicate2id)] for (j, ps) in enumerate(preds) for a in ps a ∉ keys(ex.predicate2id) && continue push!(bags[ex.predicate2id[a]], j) end end BagNode(ProductNode(tuple(xs...)), ScatteredBags(bags)) end """ allgrounding(problem::GenericProblem, p::Signature, type2obs::Dict) create all possible groundings of a predicate `p` for a `problem` """ function allgrounding(problem::GenericProblem, p::PDDL.Signature, type2obs::Dict) combinations = Iterators.product([type2obs[k] for k in p.argtypes]...) map(combinations) do args Julog.Compound(p.name, [a for a in args]) end |> vec end function allgrounding(problem::GenericProblem, p::PDDL.Signature) type2obs = map(unique(values(problem.objtypes))) do k k => [n for (n,v) in problem.objtypes if v == k] end |> Dict allgrounding(problem, p, type2obs) end """ allgrounding(action, type2obs) create all possible grounding of predicates in `action` while assuming objects with types in `type2obs` """ function allgrounding(action::GenericAction, type2obs::Dict) predicates = extract_predicates(action) allgrounding(action, predicates, type2obs) end function allgrounding(action::GenericAction, predicates::Vector{<:Term}, type2obs::Dict) types = [type2obs[k] for k in action.types] assignments = vec(collect(Iterators.product(types...))) as = map(assignments) do v assignment = Dict(zip(action.args, v)) [ground(p, assignment) for p in predicates] end end """ ground(p, assignement) ground variables in predicate `p` with assignment If the keys is missing in assignement, it might be constant and it is left as key """ function ground(p::Compound, assignment::Dict) Compound(p.name, [get(assignment, k, k) for k in p.args]) end function ground(p::Const, assignment::Dict) p end """ extract_predicates(action) extract all predicates from action while ommiting logical operators (:and, :not, :or) """ function extract_predicates(action::GenericAction) union(extract_predicates(action.precond), extract_predicates(action.effect)) end function extract_predicates(p::Compound) p.name ∈ (:and, :not, :or) && return(reduce(union, extract_predicates.(p.args))) [p] end function extract_predicates(p::Const) [p] end
<template> <div class="manager"> <!-- 这是头部导航栏 --> <div class="tabbar"> <div id="logo">后台管理系统</div> <div class="icon-setting"> <el-button icon="el-icon-search" circle type="primary" size="mini"></el-button> <el-button icon="el-icon-setting" circle type="primary" size="mini"></el-button> </div> </div> <div class="context"> <div class="menu"> <el-menu default-active="1-4-1" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose" :collapse="isCollapse"> <el-submenu index="1"> <template slot="title"> <i class="el-icon-location"></i> <span slot="title">用户管理</span> </template> <el-menu-item-group> <span slot="title">商品管理</span> <el-menu-item index="1-1">选项1</el-menu-item> <el-menu-item index="1-2">选项2</el-menu-item> </el-menu-item-group> <el-menu-item-group title="分组2"> <el-menu-item index="1-3">选项3</el-menu-item> </el-menu-item-group> <el-submenu index="1-4"> <span slot="title">选项4</span> <el-menu-item index="1-4-1">选项1</el-menu-item> </el-submenu> </el-submenu> <el-menu-item index="2"> <i class="el-icon-menu"></i> <span slot="title">订单管理</span> </el-menu-item> <el-menu-item index="4"> <i class="el-icon-setting"></i> <span slot="title">设置</span> </el-menu-item> </el-menu> </div> <nuxt /> </div> </div> </template> <script> export default { data() { return { isCollapse: false }; }, methods: { handleOpen(key, keyPath) { console.log(key, keyPath); }, handleClose(key, keyPath) { console.log(key, keyPath); } } } </script> <style lang="less"> .tabbar { width: 100vw; height: @tabbar-height; padding: 5px 10px; display: flex; line-height: calc(@tabbar-height - 10px); font-size: @font-size-small; font-weight: 800; justify-content: space-between; background-color: rgb(0, 200, 255); .icon-setting { display: flex; justify-content: center; align-items: center; } } .manager { width: 100%; height: calc(100vh - @tabbar-height); } .menu { width: @menu-width; height: calc(100vh - @tabbar-height); } .context { display: flex } </style>
<?php namespace App\Http\Controllers\Admin; use App\Designation; use App\EmployeeDetails; use App\Helper\Reply; use App\Http\Requests\Designation\StoreRequest; use App\Http\Requests\Designation\UpdateRequest; class ManageDesignationController extends AdminBaseController { public function __construct() { parent::__construct(); $this->pageTitle = 'app.menu.designation'; $this->pageIcon = 'icon-user'; $this->middleware(function ($request, $next) { if(!in_array('employees', $this->user->modules)){ abort(403); } return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $this->groups = Designation::with('members', 'members.user')->get(); return view('admin.designation.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.designation.create', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function quickCreate() { $this->teams = Designation::all(); return view('admin.designation.quick-create', $this->data); } /** * @param StoreRequest $request * @return array */ public function store(StoreRequest $request) { $group = new Designation(); $group->name = $request->designation_name; $group->save(); return Reply::redirect(route('admin.designations.index'), 'Designation created successfully.'); } /** * @param StoreRequest $request * @return array */ public function quickStore(StoreRequest $request) { $group = new Designation(); $group->name = $request->designation_name; $group->save(); $designations = Designation::all(); $teamData = ''; foreach ($designations as $team){ $selected = ''; if($team->id == $group->id){ $selected = 'selected'; } $teamData .= '<option '.$selected.' value="'.$team->id.'"> '.$team->name.' </option>'; } return Reply::successWithData('Group created successfully.', ['designationData' => $teamData]); } /** * Display the specified resource. *[ * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->designation = Designation::with('members', 'members.user')->findOrFail($id); return view('admin.designation.edit', $this->data); } /** * @param UpdateRequest $request * @param $id * @return array */ public function update(UpdateRequest $request, $id) { $group = Designation::find($id); $group->name = $request->designation_name; $group->save(); return Reply::redirect(route('admin.designations.index'), __('messages.updatedSuccessfully')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { EmployeeDetails::where('designation_id', $id)->update(['designation_id' => null]); Designation::destroy($id); return Reply::dataOnly(['status' => 'success']); } }
let user = require("../models/userModel"); let bcrypt = require("bcrypt"); let jwt = require("jsonwebtoken"); const userModel = require("../models/userModel"); let getUser = async (req, resp) => { try { resp.status(200).send(await user.findOne({ id: req.params.id })); } catch (error) { console.log(error); resp.status(500).send("Something went wrong!"); } }; let saveUser = async (req, resp) => { let dbUser = await userModel.findOne({ id: req.body.id }); if (dbUser) { resp.status(501).send("User already exist with his email id"); } else { let userDetails = req.body; let userPassword = await bcrypt.hash(userDetails.password, 10); try { await user.create({ id: userDetails.id, username: userDetails.username, phone: userDetails.phone, password: userPassword, role: userDetails.role, productsInCart: userDetails.productsInCart, products: userDetails.products, }); resp.status(201).send("User created"); } catch (error) { console.log(error); resp.status(500).send("Something went wrong!"); } } }; let updateUser = async (req, resp) => { let uId = req.params.id; let dbUser = await userModel.findOne({ id: uId }); let userUpdateDto = req.body; console.log("body: ", userUpdateDto); if (dbUser) { try { await userModel.updateOne({ id: uId }, { $set: userUpdateDto }); console.log("User details updated"); resp.status(200).send(await userModel.findOne({ id: uId })); } catch (error) { console.log("error"); resp.status(500).send("Something went wrong"); } } else { resp.status(404).send("User not found"); } }; let login = async (req, resp) => { let userDetails = req.body; let dbUser = await user.findOne({ id: userDetails.id }); if (dbUser) { try { let isPasswordEqual = await bcrypt.compare( userDetails.password, dbUser.password ); if (isPasswordEqual) { // JWT Token generation let token = jwt.sign( { username: dbUser.username, role: dbUser.role }, "NodeJsRestApi", { expiresIn: "5h", } ); resp.status(201).send({ id: dbUser.id, username: dbUser.username, phone: dbUser.phone, productsInCart: dbUser.productsInCart, products: dbUser.products, token: token, role: dbUser.role, }); } else { resp.status(401).send("User not authenticated"); } } catch (error) { resp.status(500).send("Something went wrong!"); } } else { resp.status(404).send("User not found!"); } }; let verifyAdminToken = (req, resp, next) => { let token; if (req.headers["authorization"]) { token = req.headers["authorization"].split(" ")[1]; } else { resp.status(401).send("Please provide access token"); } try { let jwtDetails = jwt.verify(token, "NodeJsRestApi"); if (jwtDetails && jwtDetails.role == "ADMIN") { next(); } else { resp.status(401).send("User not authenticated!"); } } catch (error) { console.log(error); resp.status(401).send("User not authenticated!"); } }; let verifyUserToken = (req, resp, next) => { let token; if (req.headers["authorization"]) { token = req.headers["authorization"].split(" ")[1]; } else { resp.status(401).send("Please provide access token"); } try { let jwtDetails = jwt.verify(token, "NodeJsRestApi"); if (jwtDetails && jwtDetails.role == "USER") { next(); } else { resp.status(401).send("User not authenticated!"); } } catch (error) { resp.status(401).send("User not authenticated!"); } }; let verifyAdminOrUserToken = (req, resp, next) => { let token; if (req.headers["authorization"]) { token = req.headers["authorization"].split(" ")[1]; } else { resp.status(401).send("Please provide access token"); } try { let jwtDetails = jwt.verify(token, "NodeJsRestApi"); if ( jwtDetails && (jwtDetails.role == "USER" || jwtDetails.role == "ADMIN") ) { next(); } else { resp.status(401).send("User not authenticated!"); } } catch (error) { resp.status(401).send("User not authenticated!"); } }; module.exports = { getUser, saveUser, login, updateUser, verifyAdminToken, verifyUserToken, verifyAdminOrUserToken, };
import React, { useCallback, useRef, useState } from 'react'; import auth from '@react-native-firebase/auth'; import { StyleSheet, View, TextInput, Button, Text, Alert } from 'react-native'; export default function Join({ navigation: { goBack } }) { const passwordRef = useRef(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [authLoading, setAuthLoading] = useState(false); const onSubmitEditingEmail = useCallback(() => { passwordRef.current.focus(); }, []); const onSubmitEditingPassword = () => { setAuthLoading(true); if (password === '') { Alert.alert('Password', 'Fill the password'); setAuthLoading(false); return; } auth() .createUserWithEmailAndPassword(email, password) .catch((error) => { console.log(error.code); console.log(password); if (error.code === 'auth/email-already-in-use') { Alert.alert( 'Check your email, please.', 'That email address is already in use!' ); setAuthLoading(false); return; } if (error.code === 'auth/invalid-email') { Alert.alert( 'Check your email, please.', 'That email address is invalid!' ); setAuthLoading(false); return; } if (error.code === 'auth/weak-password') { Alert.alert( 'Check your password, please.', 'Use stronger password by using 특수기호 or numbers' ); setAuthLoading(false); return; } }); }; return ( <View style={{ alignItems: 'center' }}> <TextInput style={styles.input} placeholder="email" onChangeText={(e) => { setEmail(e); }} textContentType="emailAddress" keyboardType="email-address" returnKeyType="next" autoCapitalize="none" onSubmitEditing={onSubmitEditingEmail} value={email} /> <TextInput style={[styles.input, { marginBottom: 30 }]} ref={passwordRef} onChangeText={(e) => { setPassword(e); }} secureTextEntry returnKeyType="done" placeholder="password" value={password} /> <View> {authLoading ? ( <Text>Creating account...</Text> ) : ( <Button title="join" onPress={() => { onSubmitEditingPassword(); }} /> )} </View> </View> ); } const styles = StyleSheet.create({ input: { marginTop: 10, }, });
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Main.SignOn"> <LinearLayout android:id="@+id/linearLayoutLogo" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <ImageView android:id="@+id/imageViewLogo" android:layout_width="200dp" android:layout_height="200dp" android:layout_marginBottom="32dp" android:adjustViewBounds="true" android:src="@drawable/portada" /> </LinearLayout> <TextView android:id="@+id/tv_register_form" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" android:text="@string/register_form" app:layout_constraintTop_toBottomOf="@+id/linearLayoutLogo" app:layout_constraintBottom_toTopOf="@+id/textInputLayoutName" android:textSize="30sp" /> <!-- //Se deberá almacenar nombre,--> <!-- correo, contraseña y opcionalmente una imagen.--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/textInputLayoutName" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:hint="@string/user" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/tv_register_form"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:imeOptions="actionNext" android:inputType="text" android:nextFocusForward="@id/editTextEmail" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/textInputLayoutEmail" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:hint="@string/email" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/textInputLayoutName"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:imeOptions="actionNext" android:inputType="textEmailAddress" android:nextFocusForward="@id/editTextPassword" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/textInputLayoutPassword" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:hint="@string/password" app:endIconMode="password_toggle" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/textInputLayoutEmail"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:imeOptions="actionNext" android:inputType="textPassword" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/textInputLayoutPasswordCheck" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:hint="@string/Repeat_password" app:endIconMode="password_toggle" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/textInputLayoutPassword"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/editTextPasswordCheck" android:layout_width="match_parent" android:layout_height="wrap_content" android:imeOptions="actionNext" android:inputType="textPassword" /> </com.google.android.material.textfield.TextInputLayout> <androidx.appcompat.widget.AppCompatButton android:id="@+id/btn_accept" android:layout_width="250dp" android:layout_height="wrap_content" android:text="@string/register" android:backgroundTint="?attr/colorPrimary" android:textColor="?attr/colorOnPrimary" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textInputLayoutPasswordCheck" app:layout_constraintBottom_toTopOf="@+id/btn_back" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/btn_back" android:layout_width="250dp" android:layout_height="wrap_content" android:text="@string/back" android:backgroundTint="?attr/colorPrimary" android:textColor="?attr/colorOnPrimary" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/btn_accept" app:layout_constraintBottom_toBottomOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
import styles from "./styles.module.scss"; import { MdReplay } from "react-icons/md"; import EditBtn from "../EditBtn"; import DeleteBtn from "../DeleteBtn"; const Table = ({ categoriesState, getData, loading }) => { return ( <div className={styles.main}> <div className={styles.head}> <button className={styles.refreshBtn} onClick={() => getData()}> <MdReplay /> </button> </div> {loading ? ( "loading..." ) : ( <div className={styles.content}> {categoriesState.map((item) => ( <div className={styles.itemDiv} key={item.id}> <p>{item.id}</p> <img className={styles.img} src={item.image} alt={item.name} /> <h4 id="title">{item.name}</h4> <div className={styles.buttons}> <EditBtn id="editBtn" getData={getData} data={{ name: item.name, image: item.image, id: item.id }} /> <DeleteBtn getData={getData} id={item.id} /> </div> </div> ))} </div> )} </div> ); }; export default Table;
/** * @jest-environment jsdom */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { parseUnits } from 'ethers/lib/utils' import { configure } from 'mobx' // This is needed to be able to mock mobx properties on a class configure({ safeDescriptors: false }) const { rootStore } = global const PPO_BALANCE = '2000' const PPO_DECIMALS = 18 const STAKE_VALUE = '100' const EXCEED_BALANCE = `${+PPO_BALANCE + +STAKE_VALUE}` let spyInstance: jest.SpyInstance let spyPPOTokenDecimalsNumber: jest.SpyInstance beforeAll(() => { spyInstance = jest .spyOn(rootStore.ppoTokenStore, 'tokenBalanceRaw', 'get') .mockReturnValue(parseUnits(PPO_BALANCE, PPO_DECIMALS)) spyPPOTokenDecimalsNumber = jest .spyOn(rootStore.ppoTokenStore, 'decimalsNumber', 'get') .mockReturnValue(PPO_DECIMALS) }) afterAll(() => { spyInstance.mockRestore() spyPPOTokenDecimalsNumber.mockRestore() }) describe('StakeStore tests', () => { it('should have proper state after input changes', () => { rootStore.stakeStore.setCurrentStakingValue(STAKE_VALUE) expect(rootStore.stakeStore.currentStakingValue).toBe(STAKE_VALUE) }) it('should allow to stake', async () => { const result = await rootStore.stakeStore.stake() expect(result).toStrictEqual({ success: true }) }) it('should verify input value and do nothing if value is less than balance', () => { expect(rootStore.stakeStore.currentStakingValue).toBe(STAKE_VALUE) }) it('should set isCurrentStakingValueValid to true when currentStakingValue is NOT 0', () => { expect(rootStore.stakeStore.isCurrentStakingValueValid).toBe(true) }) it('should NOT allow to stake', async () => { rootStore.stakeStore.setCurrentStakingValue(EXCEED_BALANCE) const result = await rootStore.stakeStore.stake() expect(result).toStrictEqual({ success: false }) }) it('should verify input value and do nothing if value is more than balance', () => { expect(rootStore.stakeStore.currentStakingValue).toBe(EXCEED_BALANCE) }) it('should set isCurrentStakingValueValid to false when currentStakingValue is 0', () => { rootStore.stakeStore.setCurrentStakingValue('0') expect(rootStore.stakeStore.isCurrentStakingValueValid).toBe(false) }) })
import React from "react"; import { CloseButton, Box } from "@mantine/core"; interface Props { label: string; value: string; subLabel?: string; startIcon?: React.ReactElement; onRemove?: () => void; onClick?: (value: string) => void; } export default function RootTag({ onRemove, onClick, label, value, startIcon, subLabel, }: Props) { const isClickable = typeof onClick === "function"; return ( <Box sx={(theme) => ({ display: "flex", cursor: "default", alignItems: "center", backgroundColor: theme.colorScheme === "dark" ? theme.colors.dark[4] : theme.white, border: `1px solid ${ theme.colorScheme === "dark" ? theme.colors.dark[4] : theme.colors.gray[4] }`, paddingLeft: startIcon ? 2 : 10, borderRadius: 4, "&:hover": { transition: "300ms", opacity: isClickable ? 0.65 : 1, cursor: isClickable ? "pointer" : "default", }, })} onClick={ isClickable ? (e: any) => { e.preventDefault(); e.stopPropagation(); onClick(value); } : undefined } > {startIcon} <Box sx={{ lineHeight: 1, fontSize: 12 }}> <div>{label}</div> {subLabel && ( <Box sx={(theme) => ({ lineHeight: 1, fontSize: 9, color: theme.colors.gray[5], marginTop: "3px", })} > {subLabel} </Box> )} </Box> {typeof onRemove === "function" && ( <CloseButton onMouseDown={onRemove} variant="transparent" size={22} iconSize={14} tabIndex={-1} /> )} </Box> ); }
import { Module, NestModule, MiddlewaresConsumer } from '@nestjs/common'; import { loggerMiddleware } from './common/middlewares/logger.middleware'; import { CatsModule } from './cats/cats.module'; import { AuthModule } from './auth/auth.module'; import { CatsController } from './cats/cats.controller'; @Module({ modules: [ CatsModule, AuthModule, ], }) export class ApplicationModule implements NestModule { configure(consumer: MiddlewaresConsumer): void { consumer.apply(loggerMiddleware).forRoutes(CatsController); } }
package mvc.controller; import mvc.model.User; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.IntStream; @RestController public class RestTemplateController { private static final Logger LOGGER = LogManager.getLogger(RestTemplateController.class); /** * this method sends 100 requests simultaneously */ @GetMapping("/test-user") public void findByIdTest() { List<CompletableFuture<User>> futures = IntStream.range(0, 100).boxed().map(i -> CompletableFuture.supplyAsync(() -> { RestTemplate restTemplate = new RestTemplate(); long id = i + 1; return restTemplate.getForObject("http://localhost:8080/user/" + id, User.class); })).toList(); CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); allFutures.thenRun(() -> futures.forEach(future -> { User user = future.join(); LOGGER.info("returned a user {}", user); }) ); } }
import { IsEnum, IsNumber, IsString, IsUUID } from 'class-validator'; import { PropertyType } from '../../../domain/property/property'; import type { UUID } from '../../../../types/uuid.type'; export class CreatePropertyRequestDto { @IsEnum(PropertyType) type!: PropertyType; @IsNumber() amount!: number; @IsString() note!: string; @IsString() name!: string; } export class UpdatePropertyAmountRequestDto { @IsNumber() amount!: number; } export class UpdatePropertyRequestDto { @IsNumber() amount!: number; @IsString() note!: string; @IsString() name!: string; } export class PropertyIdParams { @IsUUID() propertyId!: UUID; }
package com.app.server.repository.salesboundedcontext.sales; import com.app.server.repository.core.SearchInterface; import com.app.config.annotation.Complexity; import com.app.config.annotation.SourceCodeAuthorClass; import java.util.List; @SourceCodeAuthorClass(createdBy = "[email protected]", updatedBy = "[email protected]", versionNumber = "2", comments = "Repository for Material Master table Entity", complexity = Complexity.LOW) public interface MaterialRepository<T> extends SearchInterface { public List<T> findAll() throws Exception; public T save(T entity) throws Exception; public List<T> save(List<T> entity) throws Exception; public void delete(String id) throws Exception; public void update(T entity) throws Exception; public void update(List<T> entity) throws Exception; public List<T> findByBrandcode(String brandcode) throws Exception; public T findById(String materialcode) throws Exception; }
// <reference types="Cypress" /> import * as requests from '../support/commandsRequests'; import * as createSignal from '../support/commandsCreateSignal'; import { SIGNAL_DETAILS } from '../support/selectorsSignalDetails'; import { MANAGE_SIGNALS, FILTER } from '../support/selectorsManageIncidents'; const sizes = ['iphone-6', 'macbook-15']; sizes.forEach(size => { describe(`Adding notes to signal, resolution is: ${size}`, () => { beforeEach(() => { if (Cypress._.isArray(size)) { cy.viewport(size[0], size[1]); } else { cy.viewport(size); } }); before(() => { localStorage.setItem('accessToken', Cypress.env('token')); cy.server(); requests.createSignalOverviewMap(); cy.getManageSignalsRoutes(); cy.route('**/history').as('getHistory'); cy.route('/maps/topografie?bbox=*').as('getMap'); cy.route('/signals/v1/private/terms/categories/**').as('getTerms'); cy.visitFetch('/manage/incidents/'); cy.waitForManageSignalsRoutes(); }); it('Should show the signal details', () => { cy.get('[href*="/manage/incident/"]') .first() .click(); cy.wait('@getMap'); cy.wait('@getTerms'); cy.wait('@getHistory'); }); it('Should cancel adding a note', () => { cy.get(SIGNAL_DETAILS.inputNoteText).should('not.be.visible'); cy.get(SIGNAL_DETAILS.buttonSaveNote).should('not.be.visible'); cy.get(SIGNAL_DETAILS.buttonCancelNote).should('not.be.visible'); cy.get(SIGNAL_DETAILS.buttonAddNote).click(); cy.get(SIGNAL_DETAILS.buttonAddNote).should('not.be.visible'); cy.get(SIGNAL_DETAILS.inputNoteText).should('be.visible'); cy.get(SIGNAL_DETAILS.buttonSaveNote) .should('be.visible') .and('be.disabled'); cy.get(SIGNAL_DETAILS.buttonCancelNote) .should('be.visible') .click(); cy.get(SIGNAL_DETAILS.buttonAddNote).should('be.visible'); cy.get(SIGNAL_DETAILS.inputNoteText).should('not.be.visible'); cy.get(SIGNAL_DETAILS.buttonSaveNote).should('not.be.visible'); cy.get(SIGNAL_DETAILS.buttonCancelNote).should('not.be.visible'); }); it('Should add a note', () => { cy.server(); cy.postNoteRoutes(); const note1 = 'Ik hou van noteren, \nlekker noteletities maken. \nNou dat bevalt me wel.'; const note2 = 'Ik voeg gewoon nog een noteletitie toe, omdat het zo leuk is!'; createSignal.addNote(note1); cy.waitForPostNoteRoutes(); cy.get(SIGNAL_DETAILS.historyAction) .first() .should('contain', 'Notitie toegevoegd') .and('be.visible'); cy.get(SIGNAL_DETAILS.historyListItem) .first() .should('contain', note1) .and('be.visible'); createSignal.addNote(note2); cy.waitForPostNoteRoutes(); cy.get(SIGNAL_DETAILS.historyAction) .first() .should('contain', 'Notitie toegevoegd') .and('be.visible'); cy.get(SIGNAL_DETAILS.historyListItem) .first() .should('contain', note2) .and('be.visible'); }); it('Should filter notes', () => { cy.server(); localStorage.setItem('accessToken', Cypress.env('token')); cy.getManageSignalsRoutes(); cy.route('**/history').as('getHistory'); cy.route('/maps/topografie?bbox=*').as('getMap'); cy.route('/signals/v1/private/terms/categories/**').as('getTerms'); cy.route('/signals/v1/private/signals/?note_keyword=*').as('submitNoteFilter'); cy.visitFetch('/manage/incidents/'); cy.waitForManageSignalsRoutes(); cy.get(MANAGE_SIGNALS.buttonFilteren) .should('be.visible') .click(); cy.get(FILTER.inputSearchInNote).type('Noteletitie'); cy.get(FILTER.buttonSubmitFilter) .should('be.visible') .click(); cy.wait('@submitNoteFilter'); cy.get(MANAGE_SIGNALS.filterTagList).contains('Noteletitie'); cy.get('[href*="/manage/incident/"]') .first() .click(); cy.wait('@getMap'); cy.wait('@getTerms'); cy.wait('@getHistory'); cy.get(SIGNAL_DETAILS.historyAction) .should('contain', 'Notitie toegevoegd') .find(SIGNAL_DETAILS.historyListItem) .should('contain', 'noteletitie'); }); }); });
<?php namespace app\model; use think\Model; class CreditInquiryAttachment extends Model { protected $autoWriteTimestamp = true; protected $updateTime = false; protected $createTime = 'create_time'; /** * 编辑征信申请图片处理 * @return bool * @throws \think\db\exception\DataNotFoundException * @param $id 征信id $type '附件类型 AUTH授权证附件 APPROVAL审核附件 CREDIT征信报告', $newids 上传图片id串 * @author zhongjiaqi 4.21 */ public function filterCreditpic($id, $type, $newids) { $where = [ 'credit_inquiry_id' => $id, 'type' => $type, 'status' => 1 ]; $addids = []; // 新增的图片 $saveids = []; //与原来的对比 需要保留的图片 $data = $this->where($where)->column('attachment_id'); foreach ($newids as $k => $v) { if (in_array($v, $data)) { $saveids[] = $v; } else { $addids[] = $v; } } $delids = array_diff($data, $saveids); // 需要删除的图片 if (!empty($delids)) foreach ($delids as $key => $value) { if (!$this->updateCreditpic($id, $value, $type, ['status' => -1])) { return FALSE; } } $attach_pic = []; if (!empty($addids)) { foreach ($addids as $key => $value) { $attach_pic[] = [ 'credit_inquiry_id' => $id, 'type' => $type, 'attachment_id' => $value ]; } } return $this->saveAll($attach_pic); } /** * 更新征信图片 * @return bool * @throws \think\db\exception\DataNotFoundException * @param $data 与数据库字段对应的数组集合 $id 征信id $aid图片id $typeAUTH授权证附件 APPROVAL审核附件 CREDIT征信报告' * @author zhongjiaqi 4.21 */ public function updateCreditpic($id, $aid, $type, $data) { $where = [ 'credit_inquiry_id' => $id, 'type' => $type, 'attachment_id' => $aid ]; $res = $this->where($where)->update($data); return $flag = $res > 0 ? TRUE : FALSE; } /** * 查询图片url * @return bool * @throws \think\db\exception\DataNotFoundException * @param $type AUTH授权证附件 APPROVAL审核附件 CREDIT征信报告' $id 需要查询数据的用户id * @author zhongjiaqi 4.21 */ public function getUrl($id, $type) { $where = [ 'credit_inquiry_id' => $id, 'type' => $type, 'status' => 1 ]; $res = $this->where($where)->column('attachment_id'); $data = []; if ($res) { foreach ($res as $key => $value) { $this->Attachment = new Attachment(); $data[] = $this->Attachment->where('id', $value)->field('name,url,id,thum1')->find(); } foreach ($data as $key => $value) { $data[$key]['url'] = config('uploadFile.url') . $value['url']; $data[$key]['thumb_url'] = config('uploadFile.url') . "/" . $value['thum1']; } } return $data; } }
; ; 問題 2.63 ; ; 下の二つの手続きはそれぞれ二進木をリストに変換する. ; ; a. 二つの手続きはすべての木に対して同じ結果を生じるか. ; そうでなければ, 結果はどう違うか. ; 二つの手続きは図2.16のような木からどういうリストを生じるか. ; ; b. n個の要素の釣合っている木をリストに変換するのに必要なステップ数の増加の程度は, ; 二つの手続きで同じか. 違うなら, どちらがより遅く増加するか. ; (define (entry tree) (car tree)) (define (left-branch tree) (cadr tree)) (define (right-branch tree) (caddr tree)) (define (make-tree entry left right) (list entry left right)) (define (element-of-set? x set) (cond ((null? set) false) ((= x (entry set)) true) ((< x (entry set)) (element-of-set? x (left-branch set))) ((> x (entry set)) (element-of-set? x (right-branch set))))) (define (adjoin-set x set) (cond ((null? set) (make-tree x '() '())) ((= x (entry set)) set) ((< x (entry set)) (make-tree (entry set) (adjoin-set x (left-branch set)) (right-branch set))) ((> x (entry set)) (make-tree (entry set) (left-branch set) (adjoin-set x (right-branch set)))))) (define (tree->list-1 tree) (if (null? tree) '() (append (tree->list-1 (left-branch tree)) (cons (entry tree) (tree->list-1 (right-branch tree)))))) (define (tree->list-2 tree) (define (copy-to-list tree result-list) (if (null? tree) result-list (copy-to-list (left-branch tree) (cons (entry tree) (copy-to-list (right-branch tree) result-list))))) (copy-to-list tree '())) (print (tree->list-1 (make-tree 7 (make-tree 3 (make-tree 1 '() '()) (make-tree 5 '() '())) (make-tree 9 '() (make-tree 11 '() '()))))) (print (tree->list-2 (make-tree 7 (make-tree 3 (make-tree 1 '() '()) (make-tree 5 '() '())) (make-tree 9 '() (make-tree 11 '() '()))))) (print (tree->list-1 (make-tree 3 (make-tree 1 '() '()) (make-tree 7 (make-tree 5 '() '()) (make-tree 9 '() (make-tree 11 '() '())))))) (print (tree->list-2 (make-tree 3 (make-tree 1 '() '()) (make-tree 7 (make-tree 5 '() '()) (make-tree 9 '() (make-tree 11 '() '()))))))
package com.alphamstudios.hiscs; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Set; public class PairDevice extends AppCompatActivity { ListView deviceList; private BluetoothAdapter myBluetooth = null; public static String EXTRA_ADDRESS = "device_address"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pair_device); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); deviceList = findViewById(R.id.listView); myBluetooth = BluetoothAdapter.getDefaultAdapter(); if(myBluetooth == null) { // No bluetooth :( Toast.makeText(getApplicationContext(), "Bluetooth not available", Toast.LENGTH_LONG).show(); finish(); } else if(!myBluetooth.isEnabled()) { // Ask to turn on Bluetooth Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnBTon,1); } FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Refresh Paired Devices", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); pairedDevicesList(); } }); } private void pairedDevicesList() { Set<BluetoothDevice> pairedDevices = myBluetooth.getBondedDevices(); ArrayList list = new ArrayList(); if (pairedDevices.size() > 0) { for(BluetoothDevice bt : pairedDevices) { list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address } } else { Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); } final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list); deviceList.setAdapter(adapter); deviceList.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked } private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener() { public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3) { // Get the device MAC address, the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Make an intent to start next activity. Intent i = new Intent(PairDevice.this, MainActivity.class); //Change the activity. i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity startActivity(i); } }; }
package com.example.superagenda.data.network import com.example.superagenda.data.models.TaskModel import com.example.superagenda.data.network.response.ApiResponse import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.POST import retrofit2.http.Path interface TaskApi { @GET(Endpoints.GET_TASK_LIST) suspend fun retrieveTaskList(@Header("Authorization") token: String): ApiResponse<List<TaskModel>> @POST(Endpoints.UPDATE_TASK) suspend fun updateTask( @Header("Authorization") token: String, @Body taskModel: TaskModel ): ApiResponse<Map<String, Any>> @POST(Endpoints.NEW_TASK) suspend fun createTask( @Header("Authorization") token: String, @Body taskModel: TaskModel ): ApiResponse<Map<String, Any>> @POST(Endpoints.UPDATE_TASK_LIST) suspend fun updateTaskList( @Header("Authorization") token: String, @Body taskList: List<TaskModel> ): ApiResponse<Map<String, Any>> @DELETE("${Endpoints.DELETE_TASK}/{task_id}") suspend fun deleteTask( @Header("Authorization") token: String, @Path("task_id") taskId: String ): ApiResponse<Map<String, Any>> }
import React, { useState, useRef } from "react"; import Container from '@material-ui/core/Container' import clsx from "clsx"; import { makeStyles } from "@material-ui/core/styles"; import { Paper, Box, Button } from "@material-ui/core"; import { ButtonGroup } from "./button-group/button-group"; import { Drawer as MUIDrawer, } from "@material-ui/core/"; // import { useHistory } from "react-router"; //-------------- import-components -------------------- import { StartRecordBoardButton, StopRecordBoardButton, CameraMicroBox, RecordingView, UndoButton, EraserButton, RedoButton, } from "../../components"; // import ReactLocalStorageCache from "./ReactLocalStorageCache"; //-------------- drowing-component -------------------- import CanvasDraw from "react-canvas-draw"; //-------------- Tools-component -------------------- import BottomNavigation from "@material-ui/core/BottomNavigation"; import BottomNavigationAction from "@material-ui/core/BottomNavigationAction"; import TextField from "@material-ui/core/TextField"; //-------------- get firebase-configuration -------------------- import { app } from "../../services/base" import firebase from "firebase"; const drawerWidth = 690; const useStyles = makeStyles((theme) => ({ appBar: { zIndex: theme.zIndex.drawer + 0, }, drawer: { width: drawerWidth, flexShrink: 0, whiteSpace: "nowrap", }, drawerContainer: { overflow: "auto", }, drawerPaper: { width: drawerWidth, }, title: { flexGrow: 1, }, BtnStartSketchRec: { margin: theme.spacing(10, "auto"), }, styledComponents: { margin: theme.spacing(5, "auto"), // width: theme.spacing("auto") }, contentAlign: { margin: theme.spacing(5, "auto"), }, BtnStopSketchRec: { margin: theme.spacing(10, "auto"), }, content: { flexGrow: 1, padding: theme.spacing(0), }, toolsStyles: { // width: "fit-content", height: "fit-content", border: `2px solid ${theme.palette.divider}`, borderRadius: theme.shape.borderRadius, backgroundColor: theme.palette.background.paper, color: theme.palette.text.secondary, "& svg": { margin: theme.spacing(1.5), height: "50px", width: "50px", marginRight: "20px", marginLeft: "20px", }, "& hr": { margin: theme.spacing(0, 0.5), }, active: { background: "#f4f4f4", }, }, textFieldStyle: { '& > *': { margin: theme.spacing(1), width: '25ch', }, }, })); const colors = ["Black", "Green", "Yellow", "Blue", "Red", "Brown","Orange","Purple", "Pink", "Grey"]; const lineWidths = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; export function BoardLayout() { // eslint-disable-next-line no-lone-blocks /* Hook functions */ const classes = useStyles(); const canvasRef = useRef(null); const [value, setValue] = useState(1); const [selectedColor, setSelectedColor] = useState(colors[0]); const [selectedLineWidth, setSelectedLineWidth] = useState(lineWidths[4]); const [username, setUsername] = React.useState(""); const [sketchName, setSketchName] = React.useState(""); const [usernameError, setUsernameError] = useState(false); const [sketchNameError, setSketchNameError] = useState(false); const [urlSketch, setUrlSketch] = useState(""); const [sketchesTime, setSketchesTime] = useState(""); //-------------- get firebase-storage and firestore-API -------------------- const db = app.firestore(); const storage = app.storage(); const handleClear = () => { canvasRef.current.clear(); }; const handleUndo = () => { canvasRef.current.undo(); }; // const saveSketchLocal= () => { // localStorage.setItem("savedDrawing", canvasRef.current.getSaveData()); // } // ----------------------- setusername on firestore --------------------------- const getUserName = (e) => { setUsername(e.target.value); }; // ----------------------- setsketchname on firestore --------------------------- const getSketchName = (e) => { setSketchName(e.target.value); }; // -----------------------upload images as svg to the storage --------------------------- const onUploadCanvas = async (e) => { e.preventDefault(); setUsernameError(false); setSketchNameError(false); setSketchesTime(); if (username === "") { setUsernameError(true); } if (sketchName === "") { setSketchNameError(true); } if (!username && !sketchName) { return; } // Sending File to Firebase Storage const image = canvasRef.current.getDataURL(); const blob = await (await fetch(image)).blob(); const storageRef = storage.ref(); // const sketchesRef = storageRef.child("sketching/" + sketchName); // Create the file metadata var metadata = { contentType: "image/png", }; // Upload file and metadata to the object 'sketching' var uploadTask = storageRef .child("sketching/" + sketchName + ".png" ) .put(blob, metadata); // Listen for state changes, errors, and completion of the upload. uploadTask.on( firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed' (snapshot) => { // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log("Sketch Upload is " + progress + "% done"); switch (snapshot.state) { case firebase.storage.TaskState.PAUSED: // or 'paused' console.log(" Sketch Upload is paused"); break; case firebase.storage.TaskState.RUNNING: // or 'running' console.log("Sketch Upload is running"); break; default: console.log("Sketch Upload is now running"); } }, (error) => { // A full list of error codes is available at // https://firebase.google.com/docs/storage/web/handle-errors switch (error.code) { case "storage/unauthorized": // User doesn't have permission to access the object break; case "storage/canceled": // User canceled the upload break; case "storage/unknown": // Unknown error occurred, inspect error.serverResponse break; default: console.log("Sketch Upload is no running"); } }, () => { // Upload completed successfully, now we can get the download URL uploadTask.snapshot.ref.getDownloadURL().then( (downloadURL) => { db.collection("Sketching") .doc(username, sketchName, urlSketch, sketchesTime) .set({ username: username, sketchName: sketchName, urlSketch: downloadURL + ".png", createdAt: firebase.firestore.FieldValue.serverTimestamp(), }) .then(function () { console.log("UsersData successfully written!"); }) .catch(function (error) { console.error("Error writing UsersData: ", error); }); setUrlSketch(downloadURL); // console.log(downloadURL); }, (error) => { // failed to get download URL console.log(error); } ); } ); // if (username && sketchName) { // fetch("http://localhost:8000/Sketching", { // method: "POST", // headers: { "Content-type": "application/json" }, // body: JSON.stringify({ username, sketchName, urlSketch }), // }); // } }; // const onSketchesCreate = (e) => { // if (!username && sketchName) { // return; // } // db.collection("Sketching") // .doc(username, sketchName, urlSketch, sketchesTime) // .set({ // username: username, // sketchName: sketchName, // urlSketch: "", // sketchesTime: firebase.firestore.FieldValue.serverTimestamp(), // }) // .then(function () { // console.log("UsersData successfully written!"); // }) // .catch(function (error) { // console.error("Error writing UsersData: ", error); // }); // e.preventDefault(); // }; return ( <Container size="sm"> <MUIDrawer className={classes.drawer} variant="permanent" anchor="left" classes={{ paper: classes.drawerPaper }} // variant="persistent" > {/* Control SideBar Button */} <div> <Box className={clsx( classes.styledComponents, classes.BtnStartSketchRec )} sx={{ m: 2 }} > {/* SketchBoard Start recording from components RecordBoardButton */} <StartRecordBoardButton onClick={(e) => console.log("start")} /> </Box> </div> <div> <Box className={clsx(classes.styledComponents, classes.contentAlign)} sx={{ m: 2 }} > {/* RecordView for Video from components VideoRecorderComponent */} <RecordingView /> </Box> </div> <div> <Box className={clsx(classes.styledComponents, classes.contentAlign)} sx={{ m: 2 }} > <Paper elevation={1}> {/* Camera and Micro from components CameraMicroBox*/} <CameraMicroBox /> </Paper> </Box> </div> <div> <Box className={clsx(classes.styledComponents, classes.contentAlign)} sx={{ m: 2 }} > <Paper elevation={1}> {/* Utils Lists from components ToolsBox */} <BottomNavigation value={value} onChange={(event, value) => { setValue(value); }} className={classes.toolsStyles} > <BottomNavigationAction label="undo" value="undo" onClick={handleUndo} icon={<UndoButton />} /> <BottomNavigationAction label="eraser" value="eraser" // ToDo onClick={handleClear} icon={<EraserButton />} /> <ButtonGroup> <Button> <label>Colors:</label> <select value={selectedColor} onChange={(e) => setSelectedColor(e.target.value)} > {colors.map((color) => ( <option key={color} value={color}> {color} </option> ))} </select> </Button> <br /> <Button> <label>Brush-Radius:</label> <select value={selectedLineWidth} onChange={(e) => setSelectedLineWidth(e.target.value)} > {lineWidths.map((line) => ( <option key={line} value={line}> {line} </option> ))} </select> </Button> </ButtonGroup> <BottomNavigationAction label="redo" value="redo" // ToDo onClick={(e) => console.log(e.target.value)} icon={<RedoButton />} /> </BottomNavigation> </Paper> </Box> </div> <div> <Box sx={{ m: 10 }} // display="flex" // justifyContent="center" // className={clsx(classes.styledComponents, classes.BtnStopSketchRec)} > <form noValidate autoComplete="off" onSubmit={(e) => onUploadCanvas(e)} > <TextField className={classes.textFieldStyle} value={username} onChange={getUserName} onBlur={getUserName} id="outlined-basic" type="text" required label="Username" variant="outlined" inputProps={{ maxLength: 32, }} error={usernameError} /> <TextField className={classes.textFieldStyle} id="outlined-basic" value={sketchName} onChange={getSketchName} onBlur={getSketchName} required label="Sketchname" fullWidth variant="outlined" inputProps={{ maxLength: 32, }} error={sketchNameError} /> </form> {/* saving Sketch and Recording on Firebase */} <StopRecordBoardButton uploadSketch={(e) => onUploadCanvas(e)} // saveSketchLocal={() => saveSketchLocal()} /> </Box> </div> </MUIDrawer> {/** Drawing Area */} <div className={classes.content}> <CanvasDraw brushRadius={selectedLineWidth} brushColor={selectedColor} catenaryColor={selectedColor} canvasWidth={1872} canvasHeight={1360} hideGrid={true} enablePanAndZoom={true} style={{ border: "1px solid #000" }} ref={canvasRef } loadTimeOffset={10} /> </div> </Container> ); }
# coding=utf-8 # Copyright 2022 The Pax Authors. # # 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. """Gradient checkpoint policies that are supported by the `checkpoint` transform.""" import enum import jax @enum.unique class AutodiffCheckpointType(str, enum.Enum): """jax.checkpoint policy types.""" SAVE_NOTHING = 'save_nothing' SAVE_EVERYTHING = 'save_everything' SAVE_QKV_OUT_PROJ = 'save_qkv_out_proj' SAVE_OUT_PROJ = 'save_out_proj' SAVE_CONTEXT = 'save_context' SAVE_CONTEXT_AND_OUT_PROJ = 'save_encoded_and_out_proj' SAVE_DOT_ONLY = 'save_dot_only' SAVE_DOT_WITH_NO_BATCH_DIM = 'save_dot_with_no_batch_dims' SAVE_DOT_FOR_MLPERF_200B = 'save_dot_for_mlperf_200b' SAVE_ITERATION_INPUT = 'save_iteration_input' SAVE_TRANSFORMER_LAYER_OUTPUT = 'save_transformer_layer_output' SAVE_QUANTIZED = 'save_quantized' SAVE_QKV_OUT_PROJ_SEPARATE = 'save_qkv_out_proj_separate' SAVE_DOT_EXCEPT_LOGITS_FFN1 = 'save_dot_except_logits_ffn1' def custom_policy(checkpoint_policy: AutodiffCheckpointType): """Returns a JAX Autodiff checkpointing policy from the enum value.""" # TODO(zhangqiaorjc): Configure custom checkpoint policy in expt config # without introducing enum. if checkpoint_policy == AutodiffCheckpointType.SAVE_EVERYTHING: return jax.checkpoint_policies.everything_saveable if checkpoint_policy == AutodiffCheckpointType.SAVE_DOT_ONLY: return jax.checkpoint_policies.checkpoint_dots if checkpoint_policy == AutodiffCheckpointType.SAVE_DOT_WITH_NO_BATCH_DIM: return jax.checkpoint_policies.checkpoint_dots_with_no_batch_dims if checkpoint_policy == AutodiffCheckpointType.SAVE_QKV_OUT_PROJ: return jax.checkpoint_policies.save_only_these_names( 'combined_qkv_proj', 'out_proj' ) if checkpoint_policy == AutodiffCheckpointType.SAVE_QKV_OUT_PROJ_SEPARATE: return jax.checkpoint_policies.save_only_these_names( 'query_proj', 'value_proj', 'key_proj', 'out_proj' ) if checkpoint_policy == AutodiffCheckpointType.SAVE_CONTEXT: return jax.checkpoint_policies.save_only_these_names('context') if checkpoint_policy == AutodiffCheckpointType.SAVE_OUT_PROJ: return jax.checkpoint_policies.save_only_these_names('out_proj') if checkpoint_policy == AutodiffCheckpointType.SAVE_CONTEXT_AND_OUT_PROJ: return jax.checkpoint_policies.save_only_these_names('context', 'out_proj') if checkpoint_policy == AutodiffCheckpointType.SAVE_DOT_FOR_MLPERF_200B: return jax.checkpoint_policies.save_only_these_names( 'combined_qkv_proj', 'query_proj', 'value_proj', 'key_proj', 'context', 'out_proj', ) if checkpoint_policy == AutodiffCheckpointType.SAVE_QUANTIZED: return jax.checkpoint_policies.save_only_these_names( 'context', 'out_proj', 'combined_qkv_proj', 'qlhs', 'qrhs', 'lhs_scale', 'rhs_scale', ) if checkpoint_policy == AutodiffCheckpointType.SAVE_ITERATION_INPUT: return jax.checkpoint_policies.save_only_these_names('iteration_input') if checkpoint_policy == AutodiffCheckpointType.SAVE_TRANSFORMER_LAYER_OUTPUT: return jax.checkpoint_policies.save_only_these_names( 'transformer_layer_out' ) if checkpoint_policy == AutodiffCheckpointType.SAVE_DOT_EXCEPT_LOGITS_FFN1: return jax.checkpoint_policies.save_only_these_names( 'combined_qkv_proj', 'query_proj', 'value_proj', 'key_proj', 'context', 'out_proj', 'ffn2', ) assert checkpoint_policy == AutodiffCheckpointType.SAVE_NOTHING return jax.checkpoint_policies.nothing_saveable
# Fees Allo collects a fee on each pool that is created through the protocol. There are two fee mechanisms, a base fee and a percentage fee. ## Base Fee The base fee is a fixed amount that is charged when a pool is created. The base fee is paid in ETH and should be included in the `msg.value` when calling either method for creating a pool. The base fee amount can be checked by calling `getBaseFee()`. At time of writing, the base fee is set to 0 Eth. ## Percentage Fee The percentage fee is determined by the amount of funding in the pool and is charged when the pool is funded. The fee will be deducted from the funding amount. For example, if `fundPool()` is called with 1 Eth as the amount, 0.025 Eth will be deducted from the amount as the fee. The remaining 0.975 Eth will be used to fund the pool. The same applies for pools that use any ERC20 token. The percentage fee amount can be checked by calling `getFeePercentage()`. At time of writing the percentage fee is 2.5%. ### Fee Governance Fee amounts are determined through the [Gitcoin DAO governance process](https://gov.gitcoin.co/t/gitcoin-dao-governance-process-v3/10358).
package logic import ( "context" "github.com/IM-Lite/IM-Lite-Server/app/rpc/websocket/pb" "github.com/IM-Lite/IM-Lite-Server/common/xhttp" "google.golang.org/protobuf/proto" "github.com/IM-Lite/IM-Lite-Server/app/api/internal/svc" "github.com/IM-Lite/IM-Lite-Server/app/api/internal/types" "github.com/zeromicro/go-zero/core/logx" ) type GetConversationListLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewGetConversationListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetConversationListLogic { return &GetConversationListLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *GetConversationListLogic) GetConversationList(req *types.ReqGetConversationList) (resp *types.RespGetConversationList, ierr xhttp.ICodeErr) { listUserConversationResp, e := l.svcCtx.WebsocketService().ListUserConversation(l.ctx, &pb.ListUserConversationReq{ UserId: xhttp.GetUidFromCtx(l.ctx), }) if e != nil { l.Errorf("ListUserConversation error: %v", e) return &types.RespGetConversationList{}, xhttp.NewInternalErr() } else { l.Infof("ListUserConversation resp: %v", listUserConversationResp.String()) } resp = &types.RespGetConversationList{} var message = &pb.ConvDataList{} for _, conversation := range listUserConversationResp.UserConversations { message.List = append(message.List, &pb.ConvData{ ConvID: conversation.Id, MaxSeq: conversation.Seq, MinSeq: conversation.MinSeq, UnreadCount: conversation.Unread, }) } buf, _ := proto.Marshal(message) resp.Message = buf return }
interface ICategory { id: string name: string thumbnail: string } interface IColor { color: { color: string } } enum SizeEnum { XS = 'XS', S = 'S', M = 'M', L = 'L', XL = 'XL', XXL = 'XXL', } interface IProductSize { size: { size: SizeEnum } } interface IAddress { id: string address: string city: string city_code: string province: string province_code: string postal_code: string country: string subdistrict: string subdistrict_code: string village: string village_code: string } interface IProduct { id: string name: string thumbnail: string description: 'Ini adalah kain tenun dari lombe' price: number stock: number sold: number ratting: number condition: 'OLD' | 'NEW' weight: number length: number width: number seller_id: string category_id: string is_archived: boolean is_active: boolean created_at: Date updated_at: Date category: ICategory product_color: [IColor] product_size: [IProductSize] images: [ { id: string url: string } ] seller: { id: string firstname: string lastname: string auth: { email: string username: string } address: [IAddress] } } interface IUser { id: string firstname: string lastname: string image: string mobile: string role: 'ADMIN' | 'USER' auth_id: string is_blocked: boolean is_active: boolean created_at: Date updated_at: Date auth: { id: string email: string username: string created_at: Date } address: [IAddress] } interface IProvince { id: string name?: string } interface ICity { id: string province_id: string name: string } interface ISubdistrict { id: string regency_id: string name: string } interface IVillage { id: string name: string }
--- title: グループテンプレート description: コミュニティサイトを形成する一連の有線化済みのページや機能に対して、グループテンプレートコンソールにアクセスする方法を説明します。 contentOwner: Janice Kendall products: SG_EXPERIENCEMANAGER/6.5/COMMUNITIES topic-tags: administering content-type: reference docset: aem65 role: Admin exl-id: aed2c3f2-1b5e-4065-8cec-433abb738ef5 source-git-commit: 00b6f2f03470aca7f87717818d0dfcd17ac16bed workflow-type: tm+mt source-wordcount: '543' ht-degree: 3% --- # グループテンプレート {#group-templates} グループテンプレートコンソールは、 [サイトテンプレート](/help/communities/sites.md) コンソール。 どちらも、コミュニティサイトを形成する一連の事前に配線されたページと機能のブループリントです。 異なる点は、サイトテンプレートがメインコミュニティ用であり、グループテンプレートがコミュニティグループ用であり、サブコミュニティがメインコミュニティ内にネストされている点です。 コミュニティグループをサイトテンプレートに組み込むには、 [Groups 関数 [Groups かんすう ]](/help/communities/functions.md#groups-function) (テンプレート内で最初に使用することも、唯一の機能として使用することもできません)。 コミュニティの時点 [機能パック 1](/help/communities/deploy-communities.md#latestfeaturepack)の場合は、グループテンプレート内にグループ機能を含めることで、グループをネストできます。 コミュニティグループの作成に対するアクションが実行されると、そのグループのテンプレート(構造)が選択されます。 選択できる項目は、サイトまたはグループテンプレートに追加したときにグループ機能がどのように設定されたかによって異なります。 >[!NOTE] > >作成用のコンソール [コミュニティサイト](/help/communities/sites-console.md), [コミュニティサイトテンプレート](/help/communities/sites.md), [コミュニティグループテンプレート](/help/communities/tools-groups.md)、および [コミュニティ機能](/help/communities/functions.md) は、オーサー環境でのみ使用されます。 ## グループテンプレートコンソール {#group-templates-console} AEMオーサー環境でグループテンプレートコンソールにアクセスするには: * 選択 **ツール |コミュニティ |グループテンプレート,** グローバルナビゲーションから。 このコンソールには、 [コミュニティサイト](/help/communities/sites-console.md) を作成し、新しいグループテンプレートを作成できます。 ![コミュニティグループテンプレート](assets/groups-template.png) ## グループテンプレートを作成 {#create-group-template} グループテンプレートの作成を開始するには、「 `Create`. これにより、次の 3 つのサブパネルを含むサイトエディターパネルが表示されます。 ### 基本情報 {#basic-info} ![site-basic-info](assets/site-basic-info.png) 基本情報パネルで、名前と説明、およびテンプレートの有効/無効を設定します。 * **新規グループテンプレート名** テンプレート名 ID。 * **説明** テンプレートの説明。 * **無効/有効** テンプレートを参照可能にするかどうかを制御する切り替えスイッチ。 #### サムネール {#thumbnail} ![site-thumbnail](assets/site-thumbnail.png) (オプション)「画像をアップロード」アイコンを選択して、コミュニティサイトの作成者に対して、名前と説明に加えてサムネールを表示します。 #### 構造 {#structure} >[!CAUTION] > >AEM 6.1 Communities FP4 以前を操作する場合は、グループテンプレートにグループ機能を追加しないでください。 > >ネストされたグループ機能は、コミュニティで利用できます。 [FP1](/help/communities/communities.md#latestfeaturepack). > >グループ機能をテンプレートの最初の関数または唯一の関数として追加することは、まだできません。 ![グループテンプレートエディター](assets/template-editor.png) コミュニティ機能を追加するには、サイトメニューのリンクが表示される順に、右側から左にドラッグします。 スタイルは、サイトの作成時にテンプレートに適用されます。 例えば、フォーラムが必要な場合は、フォーラム機能をライブラリからドラッグし、テンプレートビルダーの下にドロップします。 その結果、フォーラム設定ダイアログが開きます。 詳しくは、 [関数コンソール](/help/communities/functions.md) を参照してください。 このテンプレートに基づくサブコミュニティサイト(グループ)に必要なその他のコミュニティ機能のドラッグ&amp;ドロップを続行します。 ![ドラッグ関数](assets/dragfunctions.png) 必要なすべての関数をテンプレートビルダー領域にドロップし、設定したら、「 」を選択します。 **保存** をクリックします。 ## グループテンプレートを編集 {#edit-group-template} メインでコミュニティグループを表示する場合 [グループテンプレートコンソール](#group-templates-console)の場合は、編集用に既存のグループテンプレートを選択できます。 グループテンプレートを編集しても、テンプレートから既に作成されているコミュニティサイトには影響しません。 直接 [コミュニティサイトを編集](/help/communities/sites-console.md#modify-structure)の構造が代わりに使用されます。 このプロセスは、 [グループテンプレートの作成](#create-group-template).
import { useState ,useEffect, useRef} from 'react' import './App.css' import Navbar from './components/navbar' import {Routes , Route, useLocation} from 'react-router-dom' import Home from './pages/home' import About from './pages/about' import Works from './pages/works' import Discourses from './pages/discourses' import Contact from './pages/contact' import Services from './pages/services' import ProjectDetails from './pages/projectPage' import { AnimatePresence } from 'framer-motion' const ContentSquare = ({ number, title, description }) => { return ( <div className="border border-black p-4 text-center"> <div className="flex items-center space-x-2"> <div className="text-4xl font-bold">{number}</div> <div className="text-xl font-bold">/{title}</div> </div> <p className='pt-5'>{description}</p> </div> ); }; function App() { const [isCollabOpen, setIsCollapOpen] = useState(false); const [bg,setBg] = useState(``) const [hideNav,setHideNav] = useState('') const [color,setColor] = useState(``) const location = useLocation() const listenScrollEvent = () => { const scrollY = window.scrollY; if(scrollY > 6000){ setBg('#d7dedc'); setColor('black'); }else if (scrollY > 4900) { setBg('#072326'); setColor('white'); } else if (scrollY > 4000 ){ setBg('#32484b') setColor('black') }else if (scrollY > 2300){ console.log(scrollY); setBg('rgb(218 218 218)') setColor('black') }else if (scrollY > 1900) { setBg('rgb(142, 142, 142)'); setColor('black'); } else { setBg('rgb(28 28 28)'); setColor('white'); } }; useEffect(() => { if (location.pathname === '/') { setBg('rgb(28 28 28)'); setColor('white'); window.addEventListener('scroll', listenScrollEvent); return () => { window.removeEventListener('scroll', listenScrollEvent); }; }else{ setBg('white') setColor('black'); } window.scroll(0,0) }, [location.pathname]); useEffect(() => { let scrollTimer; const handleScroll = () => { clearTimeout(scrollTimer); scrollTimer = setTimeout(() => { setHideNav(''); }, 200); setHideNav(true); }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, []); return ( <> <div className="App transtion duration-300 ease-out overflow-x-hidden" style={{backgroundColor:bg}} > <Navbar color={color} hide={hideNav} isCollabOpen={isCollabOpen} setIsCollapOpen={setIsCollapOpen}/> <div className='overflow-hidden' onClick={()=>setIsCollapOpen(false)}> <AnimatePresence mode='wait'> <Routes location={location} > <Route index path='/*' element={<Home bg={bg} colr={color} setIsCollapOpen={setIsCollapOpen} />} /> <Route path='/about' element={<About />} /> <Route path='/discourses' element={<Discourses />} /> <Route path='/contact' element={<Contact />} /> <Route path='/services' element={<Services />} /> <Route path='/works' element={<Works />} /> <Route path='/works/:id' element={<ProjectDetails />} /> </Routes> </AnimatePresence> </div> </div> </> ) } export default App
import React from 'react' import { useGlobalContext } from '../context/globalContext' import { dateFormat } from '../utils/dateFormat' import {FaGraduationCap, FaFileMedical, FaHouseUser, FaReceipt} from 'react-icons/fa' import {MdFastfood} from 'react-icons/md' import {GiClothes, GiNotebook} from 'react-icons/gi' import {BsFillClipboard2HeartFill} from 'react-icons/bs' const ExpenseItem = ({_id, amount, category, date, description, title, type, }) => { const {deleteExpense} = useGlobalContext() const getIcon = () => { switch(category){ case 'basicClothing': return <GiClothes /> case 'education': return <FaGraduationCap /> case 'essentialBills': return <FaReceipt /> case 'food': return <MdFastfood /> case 'healthCare': return <FaFileMedical /> case 'mortgage': return <FaHouseUser /> case 'personalCare': return <BsFillClipboard2HeartFill /> default: return <GiNotebook /> } } return ( <div className='border-2 border-accent mb-4 rounded-xl bg-secondary'> <div className='grid grid-cols-5 p-4'> <div className='col-span-4 flex gap-4'> <div className='w-16 h-16 bg-red-700 p-4 rounded-full text-text'>{getIcon()}</div> <div> <p className='text-lg capitalize'>{title}</p> <p className='text-sm text-gray-500 capitalize'>{category}</p> <p className='text-sm text-gray-500'>{description}</p> </div> </div> <div className=''> <p className='text-lg'>₱{amount}</p> <p className='text-sm text-gray-500'>{dateFormat(date)}</p> <button className='text-sm underline text-primary hover:text-text' onClick={() => deleteExpense(_id)}>Delete</button> </div> </div> </div> ) } export default ExpenseItem
<!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> Archana - Personal Portfolio Website </title> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css"> </head> <body> <!-- Navbar Section Start --> <header> <a href="#" class="logo"><span>Archana</span></a> <div class="bx bx-menu" id="menu-icon"></div> <ul class="navbar"> <li><a href="#home">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#skills">Skills</a></li> <li><a href="#services">Services</a></li> <li><a href="#contact">Contact</a></li> <div class="bx bx-moon" id="darkmode"></div> </ul> </header> <!-- Navbar Section End --> <!-- Home Section Start --> <section class="home" id="home"> <div class="social"> <a href="#"><i class='bx bxl-github'></i></a> <a href="#"><i class='bx bxl-instagram'></i></a> <a href="#"><i class='bx bxl-facebook'></i></a> </div> <div class="home-img"> <img src="main.png" alt=""> </div> <div class="home-text"> <span>Hello, I'm</span> <h1>Archana Dearth</h1> <h2>PHP Developer</h2> <p>Motivated and dedicated PHP developer with a strong <br> foundation in web development and a passion for <br> creating dynamic and interactive websites.</p> <a href="#contact" class="btn">Download CV</a> </div> </section> <!-- Home Section End --> <!-- About Section Start --> <section class="about" id="about"> <div class="heading"> <h2>About Me</h2> <span>Introduction</span> </div> <div class="about-container"> <div class="about-img"> <img src="main.png" alt=""> </div> <div class="about-text"> <p>Highly motivated PHP Developer with proficiency in HTML, CSS, and MySql. Passionate about creating dynamic and user-friendly web applications. Solid understanding of object-oriented programming principles and eager to apply my skills to contribute to innovative projects. Strong problem-solving abilities and a quick learner in a collaborative team environment.</p> <div class="information"> <div class="info-box"> <i class='bx bxs-user'></i> <span>Archana Dearth</span> </div> <div class="info-box"> <i class='bx bxs-phone'></i> <span>+91 9034775221</span> </div> <div class="info-box"> <i class='bx bxs-envelope'></i> <span>[email protected]</span> </div> </div> <a href="#" class="btn">Download CV</a> </div> </div> </section> <!-- About Section End --> <!-- Skills Section Start --> <section class="skills" id="skills"> <div class="heading"> <h2>Skills</h2> <span>My Skills</span> </div> <div class="skills-container"> <div class="bars"> <div class="bars-box"> <h3>HTML</h3> <span>70%</span> <div class="light-bar"></div> <div class="percent-bar html-bar"></div> </div> <div class="bars-box"> <h3>CSS</h3> <span>70%</span> <div class="light-bar"></div> <div class="percent-bar css-bar"></div> </div> <div class="bars-box"> <h3>PHP</h3> <span>80%</span> <div class="light-bar"></div> <div class="percent-bar js-bar"></div> </div> <div class="bars-box"> <h3>MySQL</h3> <span>65%</span> <div class="light-bar"></div> <div class="percent-bar react-bar"></div> </div> </div> <div class="skills-img"> <img src="main.png" alt="Skill"> </div> </div> </section> <!-- Skills Section End --> <!-- Services Section Start --> <section class="work services" id="services"> <div class="heading"> <h2>Project</h2> <span>I </span> </div> <!-- <div class="services-box"> <i class='bx bx-code-alt'></i> <h3>Web Development</h3> <a href="#">Learn More</a> </div> <div class="services-box"> <i class='bx bx-code-alt'></i> <h3>Web Development</h3> <a href="#">Learn More</a> </div> --> <div class="work_container bd-grid"> <div class="work_image"> <img src="../online-resume/assets/images/project1.jpg" alt="incredible" class="work_image-css" /> <p>Incredible India</p> </div> <div class="work_image"> <a href="https://github.com/sukhdeep-kaursidhu/newsportal"><img src="../online-resume/assets/images/project1.jpg" alt="news" class="work_image-css" /></a> <p>News</p> </div> </div> </section> <!-- Services Section End --> <!-- Contact Section Start --> <section class="contact" id="contact"> <div class="heading"> <h2>Contact</h2> <span>Connect With Us</span> </div> <div class="contact-form"> <form action=""> <input type="text" placeholder="Your Name"> <input type="email" name="" id="" placeholder="Your Email"> <textarea name="" id="" cols="30" rows="10" placeholder="Write Message Here..."></textarea> <input type="button" value="Send" class="contact-button"> </form> </div> </section> <!-- Contact Section End --> <div class="copyright"> &#169; Archana| All Right Reserved.</p> </div> <!-- Javascript --> <script src="script.js"></script> </body> </html>
package adapters import ( "context" "errors" "fmt" "time" "cloud.google.com/go/spanner" "github.com/google/uuid" "gitlab.cmpayments.local/creditcard/authorization/internal/data" "gitlab.cmpayments.local/creditcard/authorization/internal/entity" "gitlab.cmpayments.local/creditcard/authorization/internal/infrastructure/pos" mapping "gitlab.cmpayments.local/creditcard/authorization/internal/infrastructure/spanner" "gitlab.cmpayments.local/creditcard/authorization/internal/processing/cardinfo" "gitlab.cmpayments.local/creditcard/authorization/internal/processing/scheme/mastercard" "gitlab.cmpayments.local/creditcard/platform/currencycode" "google.golang.org/api/iterator" ) type RefundRepository struct { client *spanner.Client readTimeout time.Duration writeTimeout time.Duration } func NewRefundRepository( client *spanner.Client, readTimeout time.Duration, writeTimeout time.Duration) *RefundRepository { return &RefundRepository{ client: client, readTimeout: readTimeout, writeTimeout: writeTimeout, } } func (rr RefundRepository) CreateRefund(ctx context.Context, r entity.Refund) error { _, err := rr.client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error { statement := spanner.Statement{ SQL: ` INSERT INTO refunds ( refund_id, masked_pan, pan_token_id, amount, currency, localdatetime, source, customer_reference, psp_id, card_acceptor_id, card_acceptor_name, card_acceptor_postal_code, card_acceptor_city, card_acceptor_country, card_acceptor_category_code, created_at, status, card_scheme, card_issuer_id, card_issuer_name, card_issuer_countrycode ) VALUES ( @refund_id, @masked_pan, @pan_token_id, @amount, @currency, @localdatetime, @source, @customer_reference, @psp_id, @card_acceptor_id, @card_acceptor_name, @card_acceptor_postal_code, @card_acceptor_city, @card_acceptor_country, @card_acceptor_category_code, @created_at, 'new', @card_scheme, @card_issuer_id, @card_issuer_name, @card_issuer_countrycode )`, Params: mapCreateRefundParams(r), } ctx, cancel := context.WithTimeout(ctx, rr.writeTimeout) defer cancel() _, err := txn.Update(ctx, statement) return err }) return err } func mapCreateRefundParams(r entity.Refund) map[string]interface{} { return map[string]interface{}{ "refund_id": r.ID.String(), "masked_pan": r.Card.MaskedPan, "pan_token_id": r.Card.PanTokenID, "card_scheme": r.Card.Info.Scheme, "amount": r.Amount, "currency": r.Currency.Alpha3(), "localdatetime": r.LocalTransactionDateTime, "source": string(r.Source), "created_at": time.Now(), "customer_reference": mapping.NewNullString(r.CustomerReference), "psp_id": r.Psp.ID.String(), "card_issuer_id": mapping.NewNullString(r.Card.Info.IssuerID), "card_issuer_name": mapping.NewNullString(r.Card.Info.IssuerName), "card_issuer_countrycode": mapping.NewNullString(r.Card.Info.IssuerCountryCode), "card_product_id": mapping.NewNullString(r.Card.Info.ProductID), "card_program_id": mapping.NewNullString(r.Card.Info.ProgramID), "card_acceptor_name": r.CardAcceptor.Name, "card_acceptor_city": r.CardAcceptor.Address.City, "card_acceptor_country": r.CardAcceptor.Address.CountryCode, "card_acceptor_id": r.CardAcceptor.ID, "card_acceptor_postal_code": r.CardAcceptor.Address.PostalCode, "card_acceptor_category_code": r.CardAcceptor.CategoryCode, } } func (rr RefundRepository) CreateMastercardRefund(ctx context.Context, r entity.Refund) error { _, err := rr.client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error { statement := spanner.Statement{ SQL: ` INSERT INTO mastercard_refunds ( refund_id, network_reporting_date, financial_network_code, reference, banknet_reference_number, created_at, authorization_type, authorization_id_response, terminal_attendance, terminal_location, card_holder_presence, card_presence, card_capture_capabilities, transaction_status, transaction_security, card_holder_activated_terminal_level, card_data_terminal_input_capability_indicator, authorization_life_cycle, country_code, postal_code, card_product_id, card_program_id ) VALUES ( @refund_id, @network_reporting_date, @financial_network_code, @reference, @banknet_reference_number, @created_at, @authorization_type, @authorization_id_response, @terminal_attendance, @terminal_location, @card_holder_presence, @card_presence, @card_capture_capabilities, @transaction_status, @transaction_security, @card_holder_activated_terminal_level, @card_data_terminal_input_capability_indicator, @authorization_life_cycle, @country_code, @postal_code, @card_product_id, @card_program_id )`, Params: mapMastercardRefundParams(r), } ctx, cancel := context.WithTimeout(ctx, rr.writeTimeout) defer cancel() _, err := txn.Update(ctx, statement) return err }) return err } func (rr RefundRepository) CreateVisaRefund(ctx context.Context, r entity.Refund) error { stmt := spanner.NewStatement(` INSERT INTO visa_refunds (refund_id, created_at, transaction_identifier) VALUES (@refund_id, @created_at, @transaction_identifier) `) stmt.Params["refund_id"] = r.ID.String() stmt.Params["created_at"] = time.Now() stmt.Params["transaction_identifier"] = r.VisaSchemeData.Response.TransactionId _, err := rr.client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error { ctx, cancel := context.WithTimeout(ctx, rr.writeTimeout) defer cancel() _, err := txn.Update(ctx, stmt) return err }) return err } func mapMastercardRefundParams(r entity.Refund) map[string]interface{} { return map[string]interface{}{ "refund_id": r.ID.String(), "banknet_reference_number": mapping.NewNullString(r.MastercardSchemeData.Response.TraceID.BanknetReferenceNumber), "network_reporting_date": mapping.NewNullString(r.MastercardSchemeData.Response.TraceID.NetworkReportingDate), "financial_network_code": mapping.NewNullString(r.MastercardSchemeData.Response.TraceID.FinancialNetworkCode), "reference": mapping.NewNullString(r.CardSchemeData.Response.AuthorizationIDResponse), "created_at": time.Now(), "authorization_type": r.MastercardSchemeData.Request.AuthorizationType, "authorization_id_response": mapping.NewNullString(r.CardSchemeData.Response.AuthorizationIDResponse), "terminal_attendance": r.MastercardSchemeData.Request.PointOfServiceData.TerminalAttendance, "terminal_location": r.MastercardSchemeData.Request.PointOfServiceData.TerminalLocation, "card_holder_presence": r.MastercardSchemeData.Request.PointOfServiceData.CardHolderPresence, "card_presence": r.MastercardSchemeData.Request.PointOfServiceData.CardPresence, "card_capture_capabilities": r.MastercardSchemeData.Request.PointOfServiceData.CardCaptureCapabilities, "transaction_status": r.MastercardSchemeData.Request.PointOfServiceData.TransactionStatus, "transaction_security": r.MastercardSchemeData.Request.PointOfServiceData.TransactionSecurity, "card_holder_activated_terminal_level": r.MastercardSchemeData.Request.PointOfServiceData.CardHolderActivatedTerminalLevel, "card_data_terminal_input_capability_indicator": r.MastercardSchemeData.Request.PointOfServiceData.CardDataTerminalInputCapabilityIndicator, "authorization_life_cycle": r.MastercardSchemeData.Request.PointOfServiceData.AuthorizationLifeCycle, "country_code": r.MastercardSchemeData.Request.PointOfServiceData.CountryCode, "postal_code": r.MastercardSchemeData.Request.PointOfServiceData.PostalCode, "card_program_id": r.Card.Info.ProgramID, "card_product_id": r.Card.Info.ProductID, } } func (rr RefundRepository) GetRefund(ctx context.Context, pspID, refundID uuid.UUID) (entity.Refund, error) { stmt := spanner.Statement{ SQL: ` SELECT r.refund_id, r.status, r.masked_pan, r.pan_token_id, r.card_scheme, r.amount, r.currency, r.localdatetime, r.source, r.customer_reference, r.response_code, r.system_trace_audit_number, r.psp_id, r.transmitted_at, r.card_issuer_id, r.card_issuer_name, r.card_issuer_countrycode, r.cardholder_transaction_type_code, r.cardholder_from_account_type_code, r.cardholder_to_account_type_code, r.card_acceptor_name, r.card_acceptor_city, r.card_acceptor_country, r.card_acceptor_id, r.card_acceptor_postal_code, r.card_acceptor_category_code, p.name, r.point_of_service_pan_entry_mode, r.point_of_service_pin_entry_mode, p.prefix, m.network_reporting_date, m.financial_network_code, m.banknet_reference_number, m.authorization_type, m.authorization_id_response, m.terminal_attendance, m.terminal_location, m.card_holder_presence, m.card_presence, m.card_capture_capabilities, m.transaction_status, m.transaction_security, m.card_holder_activated_terminal_level, m.card_data_terminal_input_capability_indicator, m.authorization_life_cycle, m.country_code, m.postal_code, m.card_program_id, m.card_product_id FROM refunds AS r LEFT OUTER JOIN mastercard_refunds AS m ON r.refund_id = m.refund_id JOIN psp AS p ON r.psp_id = p.psp_id WHERE r.refund_id = @refund_id AND r.psp_id = @psp_id `, Params: map[string]interface{}{ "refund_id": refundID.String(), "psp_id": pspID.String(), }, } ctx, cancel := context.WithTimeout(ctx, rr.readTimeout) defer cancel() iter := rr.client.Single().Query(ctx, stmt) defer iter.Stop() row, err := iter.Next() if err != nil { if errors.Is(err, iterator.Done) { return entity.Refund{}, entity.ErrRecordNotFound } return entity.Refund{}, err } var cardScheme string if err = row.ColumnByName("card_scheme", &cardScheme); err != nil { return entity.Refund{}, err } switch cardScheme { case "mastercard": var m mastercardRefundRecord if err = row.ToStruct(&m); err != nil { return entity.Refund{}, err } return mapMastercardRowToRefundEntity(m), nil default: var r refundRecord if err = row.ToStructLenient(&r); err != nil { return entity.Refund{}, err } return mapRowToRefundEntity(r), nil } } func (rr RefundRepository) UpdateRefundResponse(ctx context.Context, r entity.Refund) error { stmt := spanner.Statement{ SQL: `UPDATE refunds SET status = @status, system_trace_audit_number = @system_trace_audit_number, updated_at = @updated_at, authorization_id_response = @authorization_id_response, retrieval_reference_number = @retrieval_reference_number, response_code = @response_code, transmitted_at = @transmitted_at, cardholder_transaction_type_code = @card_holder_transaction_type_code, cardholder_from_account_type_code = @cardholder_from_account_type_code, cardholder_to_account_type_code = @cardholder_to_account_type_code, point_of_service_pan_entry_mode = @point_of_service_pan_entry_mode, point_of_service_pin_entry_mode = @point_of_service_pin_entry_mode WHERE refund_id = @refund_id`, Params: mapUpdateRefundResponseParams(r), } _, err := rr.client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error { ctx, cancel := context.WithTimeout(ctx, rr.writeTimeout) defer cancel() rowCount, err := txn.Update(ctx, stmt) if err != nil { return fmt.Errorf("failed to update refund: %w", err) } if rowCount != 1 { return fmt.Errorf("no record found with ID: %s", r.ID.String()) } return err }) return err } func mapUpdateRefundResponseParams(r entity.Refund) map[string]interface{} { return map[string]interface{}{ "refund_id": r.ID.String(), "status": r.CardSchemeData.Response.Status.String(), "system_trace_audit_number": r.Stan, "updated_at": time.Now(), "response_code": mapping.NewNullString(r.CardSchemeData.Response.ResponseCode.Value), "authorization_id_response": mapping.NewNullString(r.CardSchemeData.Response.AuthorizationIDResponse), "retrieval_reference_number": mapping.NewNullString(r.CardSchemeData.Request.RetrievalReferenceNumber), "transmitted_at": r.ProcessingDate, "card_holder_transaction_type_code": r.CardSchemeData.Request.ProcessingCode.TransactionTypeCode, "cardholder_from_account_type_code": r.CardSchemeData.Request.ProcessingCode.FromAccountTypeCode, "cardholder_to_account_type_code": r.CardSchemeData.Request.ProcessingCode.ToAccountTypeCode, "point_of_service_pan_entry_mode": pos.PanEntryCode(r.CardSchemeData.Request.POSEntryMode.PanEntryMode), "point_of_service_pin_entry_mode": pos.PinEntryCode(r.CardSchemeData.Request.POSEntryMode.PinEntryMode), } } func (rr RefundRepository) GetAllRefunds(ctx context.Context, pspID uuid.UUID, filters entity.Filters, params map[string]interface{}) (entity.Metadata, []entity.Refund, error) { stmt := spanner.Statement{ SQL: fmt.Sprintf(` SELECT r.refund_id, r.psp_id, r.card_scheme, r.masked_pan, r.amount, r.currency, r.localdatetime, r.status, r.source, r.customer_reference, r.card_acceptor_city, r.card_acceptor_country, r.card_acceptor_category_code, r.card_acceptor_id, r.card_acceptor_postal_code, r.transmitted_at, r.response_code, r.created_at,r.updated_at, r.point_of_service_pin_entry_mode, r.point_of_service_pan_entry_mode, mr.authorization_type, mr.financial_network_code, mr.banknet_reference_number, mr.network_reporting_date FROM refunds r JOIN mastercard_refunds mr ON r.refund_id = mr.refund_id WHERE r.psp_id = @psp_id AND (r.transmitted_at = @transmitted_at OR @transmitted_at = '0001-01-01T00:00:00Z') AND (r.amount = @amount OR @amount = -1) AND (r.response_code = @response_code OR @response_code = '') ORDER BY r.transmitted_at %s LIMIT %v OFFSET %v`, filters.SortDirection(), filters.Limit()+1, // We fetch one extra record to see if we have fetched the last data set filters.Offset(), ), Params: map[string]interface{}{ "psp_id": pspID.String(), "transmitted_at": mapping.MapNullTimeStr(params["processingDate"]), "amount": params["amount"], "response_code": params["responseCode"], }, } var ( refunds []entity.Refund fetchedRecords = 0 ) ctx, cancel := context.WithTimeout(ctx, rr.readTimeout) defer cancel() iter := rr.client.Single().Query(ctx, stmt) defer iter.Stop() for { row, err := iter.Next() if err == iterator.Done { break } if err != nil { return entity.Metadata{}, nil, fmt.Errorf("cannot iterate over rows: %w", err) } var mrr mastercardRefundRecord if err := row.ToStruct(&mrr); err != nil { return entity.Metadata{}, nil, fmt.Errorf("cannot parse row into struct: %w", err) } refunds = append(refunds, mapMastercardRowToRefundEntity(mrr)) fetchedRecords++ } if int(iter.RowCount) > filters.Limit() { refunds = refunds[:len(refunds)-1] } metadata := entity.CalculateMetadata(fetchedRecords, filters.Page, filters.PageSize) return metadata, refunds, nil } type refundRecord struct { ID string `spanner:"refund_id"` Status string `spanner:"status"` MaskedPan string `spanner:"masked_pan"` PanTokenID string `spanner:"pan_token_id"` CardScheme string `spanner:"card_scheme"` Amount int64 `spanner:"amount"` Currency string `spanner:"currency"` LocalDateTime time.Time `spanner:"localdatetime"` Source string `spanner:"source"` CreatedAt time.Time `spanner:"created_at"` CustomerReference spanner.NullString `spanner:"customer_reference"` UpdatedAt spanner.NullTime `spanner:"updated_at"` ResponseCode spanner.NullString `spanner:"response_code"` Stan spanner.NullInt64 `spanner:"system_trace_audit_number"` PspID string `spanner:"psp_id"` TransmissionDate spanner.NullTime `spanner:"transmitted_at"` CardIssuerID spanner.NullString `spanner:"card_issuer_id"` CardIssuerName spanner.NullString `spanner:"card_issuer_name"` CardIssuerCountryCode spanner.NullString `spanner:"card_issuer_countrycode"` TransactionTypeCode spanner.NullString `spanner:"cardholder_transaction_type_code"` FromAccountTypeCode spanner.NullString `spanner:"cardholder_from_account_type_code"` ToAccountTypeCode spanner.NullString `spanner:"cardholder_to_account_type_code"` AcceptorName string `spanner:"card_acceptor_name"` AcceptorCity string `spanner:"card_acceptor_city"` AcceptorCountry string `spanner:"card_acceptor_country"` AcceptorID string `spanner:"card_acceptor_id"` AcceptorPostalCode spanner.NullString `spanner:"card_acceptor_postal_code"` CategoryCode string `spanner:"card_acceptor_category_code"` PanEntryMode string `spanner:"point_of_service_pan_entry_mode"` PinEntryMode string `spanner:"point_of_service_pin_entry_mode"` PspName spanner.NullString `spanner:"name"` PspPrefix spanner.NullString `spanner:"prefix"` } type mastercardRefundRecord struct { refundRecord NetworkReportingDate spanner.NullString `spanner:"network_reporting_date"` FinancialNetworkCode spanner.NullString `spanner:"financial_network_code"` BanknetReferenceNumber spanner.NullString `spanner:"banknet_reference_number"` Reference spanner.NullString `spanner:"reference"` AuthorizationType string `spanner:"authorization_type"` AuthorizationIDResponse spanner.NullString `spanner:"authorization_id_response"` TerminalAttendance spanner.NullInt64 `spanner:"terminal_attendance"` TerminalLocation spanner.NullInt64 `spanner:"terminal_location"` CardHolderPresence spanner.NullInt64 `spanner:"card_holder_presence"` CardPresence spanner.NullInt64 `spanner:"card_presence"` CardCaptureCapabilities spanner.NullInt64 `spanner:"card_capture_capabilities"` TransactionStatus spanner.NullInt64 `spanner:"transaction_status"` TransactionSecurity spanner.NullInt64 `spanner:"transaction_security"` CardHolderActivatedTerminalLevel spanner.NullInt64 `spanner:"card_holder_activated_terminal_level"` CardDataTerminalInputCapabilityIndicator spanner.NullInt64 `spanner:"card_data_terminal_input_capability_indicator"` AuthorizationLifeCycle spanner.NullString `spanner:"authorization_life_cycle"` CountryCode spanner.NullString `spanner:"country_code"` PostalCode spanner.NullString `spanner:"postal_code"` CardProductID string `spanner:"card_product_id"` CardProgramID string `spanner:"card_program_id"` } func mapMastercardRowToRefundEntity(mrr mastercardRefundRecord) entity.Refund { _, schemeResponseMessage := mastercard.MapResponseCode(mrr.ResponseCode.StringVal) return entity.Refund{ ID: uuid.MustParse(mrr.ID), Amount: int(mrr.Amount), Currency: currencycode.Must(mrr.Currency), CustomerReference: mrr.CustomerReference.StringVal, Source: entity.Source(mrr.Source), LocalTransactionDateTime: data.LocalTransactionDateTime(mrr.LocalDateTime), Status: entity.Status(mrr.Status), Stan: int(mrr.Stan.Int64), ProcessingDate: mrr.TransmissionDate.Time, CreatedAt: mrr.CreatedAt, Card: entity.Card{ MaskedPan: mrr.MaskedPan, PanTokenID: mrr.PanTokenID, Info: cardinfo.Range{ Scheme: mrr.CardScheme, ProductID: mrr.CardProductID, ProgramID: mrr.CardProgramID, IssuerID: mrr.CardIssuerID.StringVal, IssuerName: mrr.CardIssuerName.StringVal, IssuerCountryCode: mrr.CardIssuerCountryCode.StringVal, }, }, CardAcceptor: entity.CardAcceptor{ CategoryCode: mrr.CategoryCode, ID: mrr.AcceptorID, Name: mrr.AcceptorName, Address: entity.CardAcceptorAddress{ PostalCode: mrr.AcceptorPostalCode.StringVal, City: mrr.AcceptorCity, CountryCode: mrr.AcceptorCountry, }, }, Psp: entity.PSP{ ID: uuid.MustParse(mrr.PspID), Name: mrr.PspName.StringVal, }, CardSchemeData: entity.CardSchemeData{ Request: entity.CardSchemeRequest{ ProcessingCode: entity.ProcessingCode{ TransactionTypeCode: mrr.TransactionTypeCode.StringVal, FromAccountTypeCode: mrr.FromAccountTypeCode.StringVal, ToAccountTypeCode: mrr.ToAccountTypeCode.StringVal, }, POSEntryMode: entity.POSEntryMode{ PanEntryMode: pos.PanEntryFromCode(mrr.PanEntryMode), PinEntryMode: pos.PinEntryFromCode(mrr.PinEntryMode), }, }, Response: entity.CardSchemeResponse{ Status: entity.AuthorizationStatusFromString(mrr.Status), ResponseCode: entity.ResponseCode{ Value: mrr.ResponseCode.StringVal, Description: schemeResponseMessage, }, AuthorizationIDResponse: mrr.AuthorizationIDResponse.StringVal, }}, MastercardSchemeData: entity.MastercardSchemeData{ Request: entity.MastercardSchemeRequest{ AuthorizationType: entity.AuthorizationType(mrr.AuthorizationType), PointOfServiceData: entity.PointOfServiceData{ TerminalAttendance: int(mrr.TerminalAttendance.Int64), TerminalLocation: int(mrr.TerminalLocation.Int64), CardHolderPresence: int(mrr.CardHolderPresence.Int64), CardPresence: int(mrr.CardPresence.Int64), CardCaptureCapabilities: int(mrr.CardCaptureCapabilities.Int64), TransactionStatus: int(mrr.TransactionStatus.Int64), TransactionSecurity: int(mrr.TransactionSecurity.Int64), CardHolderActivatedTerminalLevel: int(mrr.CardHolderActivatedTerminalLevel.Int64), CardDataTerminalInputCapabilityIndicator: int(mrr.CardDataTerminalInputCapabilityIndicator.Int64), AuthorizationLifeCycle: mrr.AuthorizationLifeCycle.StringVal, CountryCode: mrr.CountryCode.StringVal, PostalCode: mrr.PostalCode.StringVal, }, }, Response: entity.MastercardSchemeResponse{ TraceID: entity.MTraceID{ NetworkReportingDate: mrr.NetworkReportingDate.StringVal, BanknetReferenceNumber: mrr.BanknetReferenceNumber.StringVal, FinancialNetworkCode: mrr.FinancialNetworkCode.StringVal, }, }, }, } } func mapRowToRefundEntity(r refundRecord) entity.Refund { _, schemeResponseMessage := mastercard.MapResponseCode(r.ResponseCode.StringVal) return entity.Refund{ ID: uuid.MustParse(r.ID), Amount: int(r.Amount), Currency: currencycode.Must(r.Currency), CustomerReference: r.CustomerReference.StringVal, Source: entity.Source(r.Source), LocalTransactionDateTime: data.LocalTransactionDateTime(r.LocalDateTime), Status: entity.Status(r.Status), Stan: int(r.Stan.Int64), ProcessingDate: r.TransmissionDate.Time, CreatedAt: r.CreatedAt, Card: entity.Card{ MaskedPan: r.MaskedPan, PanTokenID: r.PanTokenID, Info: cardinfo.Range{ Scheme: r.CardScheme, IssuerID: r.CardIssuerID.StringVal, IssuerName: r.CardIssuerName.StringVal, IssuerCountryCode: r.CardIssuerCountryCode.StringVal, }, }, CardAcceptor: entity.CardAcceptor{ CategoryCode: r.CategoryCode, ID: r.AcceptorID, Name: r.AcceptorName, Address: entity.CardAcceptorAddress{ PostalCode: r.AcceptorPostalCode.StringVal, City: r.AcceptorCity, CountryCode: r.AcceptorCountry, }, }, Psp: entity.PSP{ ID: uuid.MustParse(r.PspID), Name: r.PspName.StringVal, }, CardSchemeData: entity.CardSchemeData{ Request: entity.CardSchemeRequest{ ProcessingCode: entity.ProcessingCode{ TransactionTypeCode: r.TransactionTypeCode.StringVal, FromAccountTypeCode: r.FromAccountTypeCode.StringVal, ToAccountTypeCode: r.ToAccountTypeCode.StringVal, }, POSEntryMode: entity.POSEntryMode{ PanEntryMode: pos.PanEntryFromCode(r.PanEntryMode), PinEntryMode: pos.PinEntryFromCode(r.PinEntryMode), }, }, Response: entity.CardSchemeResponse{ Status: entity.AuthorizationStatusFromString(r.Status), ResponseCode: entity.ResponseCode{ Value: r.ResponseCode.StringVal, Description: schemeResponseMessage, }, }, }, } }
from tkinter import * from phones import * from tkinter import ttk def whichSelected () : print ("At %s of %d") % (select.curselection(), len(phonelist)) return int(select.curselection()[0]) def addEntry () : phonelist.append ([nameVar.get(), phoneVar.get()]) setSelect () def updateEntry() : phonelist[whichSelected()] = [nameVar.get(), phoneVar.get()] setSelect () def deleteEntry() : del phonelist[whichSelected()] setSelect () def loadEntry () : name, phone = phonelist[whichSelected()] nameVar.set(name) phoneVar.set(phone) def makeWindow () : global nameVar, phoneVar, select win = Tk() frame1 = Frame(win) frame1.pack() Label(frame1, text="Name").grid(row=0, column=0, sticky=W) nameVar = StringVar() name = Entry(frame1, textvariable=nameVar) name.grid(row=0, column=1, sticky=W) Label(frame1, text="Phone").grid(row=1, column=0, sticky=W) phoneVar= StringVar() phone= Entry(frame1, textvariable=phoneVar) phone.grid(row=1, column=1, sticky=W) frame2 = Frame(win) # Row of buttons frame2.pack() b1 = Button(frame2,text=" Add ",command=addEntry) b2 = Button(frame2,text="Update",command=updateEntry) b3 = Button(frame2,text="Delete",command=deleteEntry) b4 = Button(frame2,text=" Load ",command=loadEntry) b1.pack(side=LEFT); b2.pack(side=LEFT) b3.pack(side=LEFT); b4.pack(side=LEFT) frame3 = Frame(win) # select of names frame3.pack() scroll = Scrollbar(frame3, orient=VERTICAL) select = Listbox(frame3, yscrollcommand=scroll.set, height=6) scroll.config (command=select.yview) scroll.pack(side=RIGHT, fill=Y) select.pack(side=LEFT, fill=BOTH, expand=1) return win def setSelect () : phonelist.sort() select.delete(0,END) for name,phone in phonelist : select.insert (END, name) win = makeWindow() setSelect () win.mainloop()
import { fetchCurrentUserData } from "@/redux/currentUserData"; import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; const Profile = () => { const dispatch = useDispatch(); const userData = useSelector((state) => state.currentUserData.data); const status = useSelector((state) => state.currentUserData.status); const error = useSelector((state) => state.currentUserData.error); useEffect(() => { // Dispatch the fetchUserData action when the component mounts dispatch(fetchCurrentUserData()); }, [dispatch]); return ( <div> profile{" "} <div> {status === "loading" && <p>Loading...</p>} {status === "failed" && <p>Error: {error}</p>} {status === "succeeded" && ( <div> <h2>User Profile</h2> <p>Name: {userData.userName}</p> <p>ID: {userData.id}</p> <p>Company: {userData.companyName}</p> <p>Country: {userData.country}</p> {/* Add other fields as needed */} </div> )} </div> </div> ); }; export default Profile;
"use client"; import { Label } from "@/components/ui/label"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import Link from "next/link"; import { useForm } from "react-hook-form"; import { FcGoogle } from "react-icons/fc"; import toast from "react-hot-toast"; import { useRouter } from "next/navigation"; import { useState } from "react"; import Loading from "@/components/mymap/Loading/Loading"; import { handleLoginWithGoogle, handleResgiter } from "@/services/auth.service"; const SignUp = () => { const router = useRouter(); const [loading, setLoading] = useState(false); const handleRedirect = async () => { const res = await handleLoginWithGoogle(); if (res?.status === 200) { window.location.href = res?.data?.result?.urlRedirect; } }; const { register, handleSubmit, formState: { errors }, } = useForm(); const onSubmit = async (data) => { setLoading(true); const res = await handleResgiter(data); if (res?.data?.status === 200) { router.push("/auth/signin"); toast.success("Resgiter success!"); } else { toast.error("Email or Password incorrect!"); } setLoading(false); }; return ( <div> {loading && <Loading />} <div className="flex justify-center gap-6 mt-16"> <div> <h3 className="text-[2.5rem] mb-2 font-bold text-black"> Get started </h3> <p className="text-lg text-gray">with one of these services</p> <div> <Button onClick={handleRedirect} size="lg" className="flex items-center w-full my-4 font-semibold border boder-[#eee] text-[18px] border-solid bg-transparent text-black hover:bg-slate-600 hover:text-white" > <FcGoogle className="mr-2 text-[30px]" /> Sign in with Google </Button> </div> </div> <div className="flex flex-col border-l-2 border-solid border-blue1 pl-6 bg-white !z-[199] relative items-center justify-center"> <h3 className="mb-2 text-xl font-semibold"> with your email address </h3> <form onSubmit={handleSubmit(onSubmit)} className="w-[20rem] mx-auto flex flex-col" > <div className="grid w-full max-w-sm items-center gap-1.5 my-4"> <Label htmlFor="name">Name</Label> <Input type="text" id="name" placeholder="Enter your name" {...register("name", { required: true, })} /> </div> <p className="text-[#f73d7b] font-semibold text-[13.5px]"> {errors.name && "Please enter your name!"} </p> <div className="grid w-full max-w-sm items-center gap-1.5 my-4"> <Label htmlFor="email">Email</Label> <Input type="email" id="email" placeholder="Enter your email" {...register("email", { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, required: true, })} /> </div> <p className="text-[#f73d7b] font-semibold text-[13.5px]"> {errors.email && "Please enter the correct email format"} </p> <div className="grid w-full max-w-sm items-center gap-1.5 my-4"> <Label htmlFor="password">Password</Label> <Input type="password" id="password" placeholder="Enter your password" {...register("password", { required: true })} /> </div> <p className="text-[#f73d7b] font-semibold text-[13.5px]"> {errors.password && "Please enter your password!"} </p> <Button size="lg" className="w-full h-12 mt-4"> Sign Up </Button> <p className="text-center text-black mt-2"> Do not you have account?{" "} <Link className="text-[#f73d7b] font-semibold" href={"/auth/signin"} > Sign in </Link> </p> </form> </div> </div> </div> ); }; export default SignUp;
import React, { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import "./CSS/login.css"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faFacebookF, faGoogle, faTwitter, } from "@fortawesome/free-brands-svg-icons"; import Cookies from "js-cookie"; import axios from "axios"; // Axios 인스턴스 생성 const instance = axios.create({ baseURL: "http://ec2-54-180-87-8.ap-northeast-2.compute.amazonaws.com:8080", }); function Login() { const navigate = useNavigate(); const [formData, setFormData] = useState({ email: "", password: "", }); const [errorMessage, setErrorMessage] = useState(""); const [showErrorMessage, setShowErrorMessage] = useState(false); const [isOpen, setIsOpen] = useState(false); useEffect(() => { let timer; if (showErrorMessage) { timer = setTimeout(() => { setErrorMessage(""); setShowErrorMessage(false); }, 5000); } return () => { if (timer) { clearTimeout(timer); } }; }, [showErrorMessage]); const handleGoogleLogin = () => { // // Google OAuth 2.0 클라이언트 ID // const clientId = // "845142340290-3h2ko2t3qr3qabnj4mhl8b8mee8p9o4o.apps.googleusercontent.com"; // 여기에 클라이언트 ID를 넣으세요 // // Google OAuth 2.0 로그인 URL 생성 // const redirectUri = "http://localhost:3000/google-callback"; // const scope = "https://www.googleapis.com/auth/userinfo.email"; // 필요한 범위를 설정하세요 // const authUrl = `https://accounts.google.com/o/oauth2/auth?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=code`; // // Google 로그인 페이지로 이동 // window.location.href = authUrl; }; const handleSubmit = async (e) => { e.preventDefault(); const loginData = { email: formData.email, password: formData.password, }; try { const response = await instance.post("/api/users/login", loginData); if (response.status === 200) { const responseData = response.headers; console.log("Login successful:", responseData); const roles = response.data.roles; const userId = response.data.userId; const accessToken = responseData.authorization; const tokenParts = accessToken.split("."); const payload = JSON.parse(atob(tokenParts[1])); const expirationTimeInSeconds = payload.exp; Cookies.set("accessToken", accessToken, { path: "/" }); Cookies.set("accessTokenExpire", expirationTimeInSeconds, { path: "/", }); Cookies.set("refreshToken", responseData.refresh, { path: "/" }); Cookies.set("userRoles", roles, { path: "/" }); Cookies.set("userId", userId, { path: "/" }); setErrorMessage(""); navigate("/", { state: { roles } }); window.location.reload(); } else { console.error("Login failed. Try again!"); setErrorMessage("Login failed. Try again!"); setShowErrorMessage(true); } } catch (error) { console.error("Network error:", error); const errorMessage = error.response.data.message; setErrorMessage(errorMessage); setShowErrorMessage(true); } }; const closeModal = () => { setIsOpen(false); }; // Event handler for input changes const handleInputChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value, }); }; return ( <div className="login-container"> <div className="login-header-container"> <h1 className="login-title">MINIFLIX</h1> </div> <div className="login-form-container"> <form id="loginForm" onSubmit={handleSubmit}> <div className="login-input-container"> <input type="text" id="email" name="email" placeholder="이메일" autoComplete="username" className="login-input" onChange={handleInputChange} value={formData.email} /> </div> <div className="login-input-container"> <input type="password" id="password" name="password" placeholder="비밀번호" autoComplete="current-password" className="login-input" onChange={handleInputChange} value={formData.password} /> </div> <button type="submit" className="login-button"> 로그인 </button> <div className="login-error-message">{errorMessage}</div> </form> </div> <div className="login-social-buttons"> <button className="login-social-button"> <FontAwesomeIcon icon={faFacebookF} /> Facebook으로 로그인 </button> <button className="login-social-button"> <FontAwesomeIcon icon={faTwitter} /> Twitter로 로그인 </button> <button className="login-social-button" onClick={handleGoogleLogin}> <FontAwesomeIcon icon={faGoogle} style={{ color: "#EA4335" }} />{" "} Google로 로그인 </button> </div> </div> ); } export default Login;
package uconcurrent.producer_consumer; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author Kelly * @create 2020-04-26 14:32 * * 使用 lock 的生产者消费者 Demo */ public class ProducerConsumerDemo { public static void main(String[] args) { ShareData shareData = new ShareData(); new Thread(() -> { for (int i = 0; i < 5; i++) { try { shareData.increment(); } catch (Exception e) { e.printStackTrace(); } } }, "AA").start(); new Thread(()->{ for (int i = 0; i < 5; i++) { try { shareData.decrement(); } catch (Exception e) { e.printStackTrace(); } } }, "BB").start(); new Thread(()->{ for (int i = 0; i < 5; i++) { try { shareData.increment(); } catch (Exception e) { e.printStackTrace(); } } }, "CC").start(); new Thread(()->{ for (int i = 0; i < 5; i++) { try { shareData.decrement(); } catch (Exception e) { e.printStackTrace(); } } }, "DD").start(); } } class ShareData{ private int number = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); public void increment() throws Exception { lock.lock(); try { // 1. 判断 while (number != 0){ condition.await(); // 等待不能生产 } // 2. 干活 number++; System.out.println(Thread.currentThread().getName() + "\t" + number); // 3. 通知唤醒 condition.signalAll(); } catch (Exception e){ e.printStackTrace(); } finally { lock.unlock(); } } public void decrement() throws Exception { lock.lock(); try { // 1. 判断 while (number == 0){ condition.await(); // 等待,不能消费 } // 2. 干活 number--; System.out.println(Thread.currentThread().getName() + "\t" + number); // 3. 通知唤醒 condition.signalAll(); } catch (Exception e){ e.printStackTrace(); } finally { lock.unlock(); } } }
import { useState, useEffect } from 'react'; import Box from '@mui/material/Box'; import Alert from '@mui/material/Alert'; import IconButton from '@mui/material/IconButton'; import Collapse from '@mui/material/Collapse'; import CloseIcon from '@mui/icons-material/Close'; export default function TransitionAlerts({name, setSendForm}) { const [open, setOpen] = useState(false); useEffect(() => { setOpen(name !== ""); }, [name]); return ( <Box sx={{ width: '100%' }}> <Collapse in={open}> <Alert action={ <IconButton aria-label="close" color="inherit" size="small" onClick={() => { setOpen(false); setSendForm(""); }} > <CloseIcon fontSize="inherit" /> </IconButton> } sx={{ mb: 2 }} > Thank you {name}, we will contact you as soon as possible via email </Alert> </Collapse> </Box> ); }