text
stringlengths
184
4.48M
import { Router, ActivatedRoute } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { UserService } from '../services/user.service'; import { User } from '../shared/models/User'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm!: FormGroup; isSubmitted = false; returnUrl = ''; returnURL = '/Admin/' constructor(private formBuilder: FormBuilder, private userService: UserService, private activatedRoute: ActivatedRoute, private router: Router) { } ngOnInit(): void { this.loginForm = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]], password: ['', Validators.required], }); this.returnUrl = this.activatedRoute.snapshot.queryParams.returnUrl; this.returnURL = this.activatedRoute.snapshot.queryParams.returnURL; const isLoggedOut = localStorage.getItem('isLoggedOut'); if (isLoggedOut === 'true') { this.router.navigate(['/']); } localStorage.removeItem('isLoggedOut'); } get fc() { return this.loginForm.controls; } submit() { this.isSubmitted = true; if (this.loginForm.invalid) return; this.userService.login({ email: this.fc.email.value, password: this.fc.password.value }).subscribe((user: User) => { if (user.isAdmin == true) { this.router.navigateByUrl('/AdminFood'); } else { this.router.navigateByUrl(this.returnUrl); } }); } }
<!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 rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="color.css"> <title>Style Guide for Web Development</title> </head> <body> <header> <h1>Website Style Guide 101</h1> </header> <main> <nav> <h3>Navigation</h2> <ul> <li><a href="index.html">Main</a></li> </ul> <ul> <li><a href="colors.html">Colors</a></li> </ul> <ul> <li><a href="fonts.html">Fonts</a></li> </ul> <ul> <li><a href="text_styles.html">Text Styles</a></li> </ul> </nav> <div class="content"> <h2>Color Guide 101</h2> <p>In this Website, you will find some colors, fonts, and text styles that you may use on your next project. Use the navigation bar to explore!</p> <div class="color-container"> <div class="color-panel color-AliceBlue"><p>AliceBlue</p><p>#f0f8ff</p></div> <div class="color-panel color-AntiqueWhite"><p>AntiqueWhite</p><p>#faebd7</p></div> <div class="color-panel color-Aqua"><p>Aqua</p><p>#00ffff</p></div> <div class="color-panel color-Aquamarine"><p>Aquamarine</p><p>##7fffd4</p></div> <div class="color-panel color-Azure"><p>Azure</p><p>#f0ffff</p></div> <div class="color-panel color-Beige"><p>Beige</p><p>#f5f5dc</p></div> <div class="color-panel color-Bisque"><p>Bisque</p><p>#ffe4c4</p></div> <div class="color-panel color-Black"><p>Black</p><p>#000000</p></div> <div class="color-panel color-BlanchedAlmond"><p>BlanchedAlmond</p><p>#ffebcd</p></div> <div class="color-panel color-Blue"><p>Blue</p><p>#0000ff</p></div> <div class="color-panel color-BlueViolet"><p>BlueViolet</p><p>#8a2be2</p></div> <div class="color-panel color-Brown"><p>Brown</p><p>#a52a2a</p></div> <div class="color-panel color-BurlyWood"><p>BurlyWood</p><p>#deb887</p></div> <div class="color-panel color-CadetBlue"><p>CadetBlue</p><p>#5f9ea0</p></div> <div class="color-panel color-Chartreuse"><p>Chartreuse</p><p>#7fff00</p></div> <div class="color-panel color-Chocolate"><p>Chocolate</p><p>#d2691e</p></div> <div class="color-panel color-Coral"><p>Coral</p><p>#ff7f50</p></div> <div class="color-panel color-CornflowerBlue"><p>CornflowerBlue</p><p>#6495ed</p></div> <div class="color-panel color-Cornsilk"><p>Cornsilk</p><p>#fff8dc</p></div> <div class="color-panel color-Crimson"><p>Crimson</p><p>#dc143c</p></div> <div class="color-panel color-Cyan"><p>Cyan</p><p>#00ffff</p></div> <div class="color-panel color-DarkBlue"><p>DarkBlue</p><p>#00008b</p></div> <div class="color-panel color-DarkCyan"><p>DarkCyan</p><p>#008b8b</p></div> <div class="color-panel color-DarkGoldenRod"><p>DarkGoldenRod</p><p>#b8860b</p></div> </div> </div> </main> </body> </html>
package pokemon import ( "errors" "strings" ) type Type int const ( Normal Type = iota Fire Water Electric Grass Ice Fighting Poison Ground Flying Psychic Bug Rock Ghost Dragon Dark Steel ) func (t Type) String() string { return [...]string{"Normal", "Fire", "Water", "Electric", "Grass", "Ice", "Fighting", "Poison", "Ground", "Flying", "Psychic", "Bug", "Rock", "Ghost", "Dragon", "Dark", "Steel"}[t] } func StringToPokemonType(typeStr string) (Type, error) { switch strings.ToLower(typeStr) { case "normal": return Normal, nil case "fire": return Fire, nil case "water": return Water, nil case "electric": return Electric, nil case "grass": return Grass, nil case "ice": return Ice, nil case "fighting": return Fighting, nil case "poison": return Poison, nil case "ground": return Ground, nil case "flying": return Flying, nil case "psychic": return Psychic, nil case "bug": return Bug, nil case "rock": return Rock, nil case "ghost": return Ghost, nil case "dragon": return Dragon, nil case "dark": return Dark, nil case "steel": return Steel, nil default: return 0, errors.New("invalid Pokemon type") } } type Nature int const ( Adamant Nature = iota Bashful Bold Brave Calm Careful Docile Gentle Hardy Hasty Impish Jolly Lax Lonely Mild Modest Naive Naughty Quiet Quirky Rash Relaxed Sassy Serious Speed ) var NatureInfo = map[Nature][2]string{ Adamant: {"Attack", "SpecialAttack"}, Bashful: {"", ""}, Bold: {"Defense", "Attack"}, Brave: {"Attack", "Speed"}, Calm: {"SpecialDefense", "Attack"}, Careful: {"SpecialDefense", "SpecialAttack"}, Docile: {"", ""}, Gentle: {"SpecialDefense", "Defense"}, Hardy: {"", ""}, Hasty: {"Speed", "Defense"}, Impish: {"Defense", "SpecialAttack"}, Jolly: {"Speed", "SpecialAttack"}, Lax: {"Defense", "SpecialDefense"}, Lonely: {"Attack", "Defense"}, Mild: {"SpecialAttack", "Defense"}, Modest: {"SpecialAttack", "Attack"}, Naive: {"Speed", "SpecialDefense"}, Naughty: {"Attack", "SpecialDefense"}, Quiet: {"SpecialAttack", "Speed"}, Quirky: {"", ""}, Rash: {"SpecialAttack", "SpecialDefense"}, Relaxed: {"Defense", "Speed"}, Sassy: {"SpecialDefense", "Speed"}, Serious: {"", ""}, Speed: {"Speed", "Attack"}, }
import { useState } from "react"; import "./ExpenseItem.css" import ExpenseDate from "./ExpenseDate"; import Card from "../UI/Card"; import { FaTrash, FaEdit } from 'react-icons/fa'; import DeleteConfirmation from "../UI/DeleteConfirmation"; import EditConfirmation from "../UI/EditConfirmation"; const ExpenseItem = (props) => { const formattedAmount = Intl.NumberFormat('en-US').format(props.amount); const[showDeleteQuery, setShowDeleteQuery] = useState(false); const showDeleteQueryHandler = () => { setShowDeleteQuery(!showDeleteQuery); } const cancelDeleteHandler = () => {showDeleteQueryHandler()} const proceedDeleteHandler = () => { const deletedItem = [props.type, props.id] props.isDeleted(deletedItem); showDeleteQueryHandler(); console.log("deleted", deletedItem) } const[showEditQuery, setShowEditQuery] = useState(false); const showEditQueryHandler = () => { setShowEditQuery(!showEditQuery);} const cancelEditHandler = () => {showEditQueryHandler()}; const proceedEditHandler = () => { const editedItem = [props.category, props.amount, props.notes, props.date, props.type, props.id] props.isEdited(editedItem); showEditQueryHandler(); console.log(editedItem) } return ( <Card className="expense-item"> <ExpenseDate date={props.date}/> <div className="expense-item__description"> <h2>{props.category}</h2> <h3>{props.notes}</h3> <div className="expense-item__price">{formattedAmount}</div> <span className="edit__icon" onClick={showEditQueryHandler}><FaEdit /></span> <span className="trash__icon" onClick={showDeleteQueryHandler}><FaTrash /></span> </div> { showEditQuery && <EditConfirmation cancelEdit={cancelEditHandler} proceedEdit={proceedEditHandler}/> } { showDeleteQuery && <DeleteConfirmation cancelDelete={cancelDeleteHandler} proceedDelete={proceedDeleteHandler}/> } </Card> ) }; export default ExpenseItem;
import React, { Component } from "react"; import PatientService from "../services/PatientService"; import { Link } from "react-router-dom"; import '../css/Listpatient.css'; import { NavBarAdmin } from "../NavBarAdmin"; export class ListPatientComponent extends Component { constructor(props) { super(props); this.state = { patients: [], }; } componentDidMount() { PatientService.getAllPatients().then((res) => { console.log(res.data); this.setState({ patients: res.data }); }); } deletePatient(userId){ PatientService.deletePatient(userId).then(res => { this.setState({ patients: this.state.patients.filter(patient => patient.userId !== userId) }); alert("Deleted successfully"); }) } updatePatient(userId){ } render() { return ( <div> <NavBarAdmin/> <h2>Patient List</h2> <div className="row"> <table className="table table-striped table-inverse"> <thead className="thead-inverse"> <tr className="header"> {/* <th>User Id</th> */} <th>User Name</th> <th>Patient Name</th> <th>Address</th> <th>Password</th> <th>User mail id</th> <th>Phone Number</th> <th>Date of Birth</th> <th>Gender</th> <th>Actions</th> </tr> </thead> <tbody> { this.state.patients.map( patient => <tr key={patient.userId}> <td className="text-center align-middle">{patient.userName}</td> <td className="text-center align-middle">{patient.patientName}</td> <td className="text-center align-middle">{patient.address}</td> <td className="text-center align-middle">{patient.password}</td> <td className="text-center align-middle">{patient.userEmail}</td> <td className="text-center align-middle">{patient.phoneNo}</td> <td className="text-center align-middle">{patient.dob}</td> <td className="text-center align-middle">{patient.gender}</td> <div> <td className="button"> <button type="button" className="warning" style={{ marginRight: "10px" }}> <Link to={"/updatepatientbyid/" + patient.userId} > Update </Link> </button> <button className="danger" onClick={() => this.deletePatient(patient.userId)}>Delete</button> </td> </div> </tr> ) } </tbody> </table> </div> </div> ) } }
// Product Sum // Write a function that takes in a "special" array and returns its product sum. // A "special" array is a non-empty array that contains either integers or other // "special" arrays. The product sum of a "special" array is the sum of its // elements, where "special" arrays inside it are summed themselves and then // multiplied by their level of depth. // The depth of a "special" array is how far nested it is. For instance, the // depth of [] is 1; the depth of the inner array in // [[]] is 2; the depth of the innermost array in // [[[]]] is 3. // Therefore, the product sum of [x, y] is x + y; the // product sum of [x, [y, z]] is x + 2 * (y + z); the // product sum of [x, [y, [z]]] is x + 2 * (y + 3z). // array = [5, 2, [7, -1], 3, [6, [-13, 8], 4]] // 12 // calculated as: 5 + 2 + 2 * (7 - 1) + 3 + 2 * (6 + 3 * (-13 + 8) + 4) // First Solution // O(nlog(n)) time | O(1) space - where n is the number of students function productSum(array, depth = 1) { // Write your code here. let totalSum = 0; for (item of array) { if (Array.isArray(item)) { totalSum += productSum(item, depth + 1); } else { totalSum += item; console.log("totalSum: ", totalSum); } } return totalSum * depth; } // Do not edit the line below. exports.productSum = productSum;
package org.scratch.game.service; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.scratch.game.config.ConfigProperties; import org.scratch.game.domain.GameResult; import org.scratch.game.domain.LostGameResult; import org.scratch.game.domain.WonGameResult; import org.scratch.game.service.impl.MatrixEvaluationServiceImpl; public class MatrixEvaluationServiceTest { private MatrixEvaluationService matrixEvaluationService; @BeforeEach public void setup() { matrixEvaluationService = new MatrixEvaluationServiceImpl(); ConfigProperties.initialize(System.getProperty("user.dir") + "/src/test/resources/config.json"); } @Test public void testLostGame() { String[][] matrix = new String[][]{ {"A", "B", "C"}, {"E", "B", "5x"}, {"F", "D", "C"} }; long bettingAmount = 100; GameResult gameResult = matrixEvaluationService.evaluateMatrix(matrix, bettingAmount); boolean isLostGameResult = gameResult instanceof LostGameResult; Assertions.assertTrue(isLostGameResult); } @Test public void testWonGame() { String[][] matrix = new String[][]{ {"A", "B", "C"}, {"E", "B", "10x"}, {"F", "D", "B"} }; long bettingAmount = 100; GameResult gameResult = matrixEvaluationService.evaluateMatrix(matrix, bettingAmount); boolean isWonGameResult = gameResult instanceof WonGameResult; Assertions.assertTrue(isWonGameResult); WonGameResult wonGameResult = (WonGameResult) gameResult; Assertions.assertEquals(3000, wonGameResult.getReward()); } @Test public void testWonGameWithExtraBonus() { String[][] matrix = new String[][]{ {"A", "B", "C"}, {"E", "B", "+1000"}, {"F", "D", "B"} }; long bettingAmount = 100; GameResult gameResult = matrixEvaluationService.evaluateMatrix(matrix, bettingAmount); boolean isWonGameResult = gameResult instanceof WonGameResult; Assertions.assertTrue(isWonGameResult); WonGameResult wonGameResult = (WonGameResult) gameResult; Assertions.assertEquals(1300, wonGameResult.getReward()); } @Test public void testWonGameWithMissBonus() { String[][] matrix = new String[][]{ {"A", "B", "C"}, {"E", "B", "MISS"}, {"F", "D", "B"} }; long bettingAmount = 100; GameResult gameResult = matrixEvaluationService.evaluateMatrix(matrix, bettingAmount); boolean isWonGameResult = gameResult instanceof WonGameResult; Assertions.assertTrue(isWonGameResult); WonGameResult wonGameResult = (WonGameResult) gameResult; Assertions.assertEquals(300, wonGameResult.getReward()); } @Test public void testWonGameWithHorizontallyLinearSymbols() { String[][] matrix = new String[][]{ {"A", "A", "C"}, {"E", "B", "MISS"}, {"B", "B", "B"} }; long bettingAmount = 100; GameResult gameResult = matrixEvaluationService.evaluateMatrix(matrix, bettingAmount); boolean isWonGameResult = gameResult instanceof WonGameResult; Assertions.assertTrue(isWonGameResult); WonGameResult wonGameResult = (WonGameResult) gameResult; Assertions.assertEquals(900, wonGameResult.getReward()); } @Test public void testWonGameWithVerticallyLinearSymbols() { String[][] matrix = new String[][]{ {"A", "B", "C"}, {"E", "B", "MISS"}, {"F", "B", "B"} }; long bettingAmount = 100; GameResult gameResult = matrixEvaluationService.evaluateMatrix(matrix, bettingAmount); boolean isWonGameResult = gameResult instanceof WonGameResult; Assertions.assertTrue(isWonGameResult); WonGameResult wonGameResult = (WonGameResult) gameResult; Assertions.assertEquals(900, wonGameResult.getReward()); } @Test public void testWonGameWithDiagonallyLinearSymbols() { String[][] matrix = new String[][]{ {"B", "A", "C"}, {"E", "B", "MISS"}, {"F", "B", "B"} }; long bettingAmount = 100; GameResult gameResult = matrixEvaluationService.evaluateMatrix(matrix, bettingAmount); boolean isWonGameResult = gameResult instanceof WonGameResult; Assertions.assertTrue(isWonGameResult); WonGameResult wonGameResult = (WonGameResult) gameResult; Assertions.assertEquals(2250, wonGameResult.getReward()); } }
package com.example.myandroidapplication import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.typeText import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.rules.ActivityScenarioRule import com.example.myandroidapplication.view.Login import org.junit.Rule import org.junit.Test class LoginEspressoTest { @get:Rule val activityRule = ActivityScenarioRule(Login::class.java) @Test fun testLoginWithValidCredentials() { val email = "francesco@gmail.com" val password = "FrancescoP" // Insert email and password onView(withId(R.id.edit_email)).perform(typeText(email)) onView(withId(R.id.edit_password)).perform(typeText(password)) // Click the login button onView(withId(R.id.btnLogin)).perform(click()) // Sleep for a short while to allow time for the login process to complete Thread.sleep(2000) onView(withId(R.id.bottomNavigationView)).check(matches(isDisplayed())) } @Test fun testLoginFailure() { val email = "invalid@example.com" val password = "invalidPassword" // Insert email and password onView(withId(R.id.edit_email)).perform(typeText(email)) onView(withId(R.id.edit_password)).perform(typeText(password)) // Click the login button onView(withId(R.id.btnLogin)).perform(click()) // Add assertions here to verify the expected behavior // For example, you could use onView(withId(R.id.txtError)).check(matches(isDisplayed())) } }
import { useState, useCallback, useContext } from "react"; import { useRouter } from 'next/router' import Editor from "./Editor"; import Preview from "./Preview"; import Button from "../Button"; import FirebaseService from "../../data/services/FirebaseService"; import { AppContext } from "../contexts/app_context"; import { isAdminUser } from "../../utils/user_utils"; import { undoDepth } from "@codemirror/commands"; const Form = ({ post }) => { const { user } = useContext(AppContext); const router = useRouter(); const [doc, setDoc] = useState(post ? post.content : ""); const [thumbnail, setThumbnail] = useState(post ? post.thumbnail : ""); const [title, setTitle] = useState(post ? post.title : ""); const [isButtonClicked, setIsButtonClicked] = useState(false); const handleDocChange = useCallback((newDoc: string) => { setDoc(newDoc); }, []); if (!user || !isAdminUser(user)) { router.push("/blogs"); return; } const saveToFirebase = async () => { const newPost = { ...(post ? post : {}), id: post ? post.id : title.replace(/\s+/g, '-'), creator_id: post && post.creator_id ? post.creator_id : user.id, thumbnail, title, content: doc, }; if (doc === undefined || doc === null || doc === "") { alert("Markdown content must not be empty") return; } // Edit if (post) { await FirebaseService.updateBlogPost(newPost); } else { // Create await FirebaseService.addBlogPost(newPost); } }; return ( <div className="h-full flex flex-col gap-2 max-w-7xl mx-auto p-4"> <h1 className=""> Markdown Editor </h1> <div className="w-full"> <label htmlFor="title" className="block text-sm font-medium leading-6 text-white"> Title </label> <div className="mt-2"> <input id="title" name="title" type="text" className="block w-full rounded-md border-0 bg-white/5 py-1.5 text-white shadow-sm ring-1 ring-inset ring-white/10 focus:ring-2 focus:ring-inset focus:ring-indigo-500 sm:text-sm sm:leading-6" onChange={event => setTitle(event.target.value)} value={title} /> </div> </div> <div className="mt-2 w-full"> <label htmlFor="thumbnail" className="block text-sm font-medium leading-6 text-white"> Thumbnail URL </label> <div className="mt-2"> <input id="thumbnail" name="thumbnail" type="text" className="block w-full rounded-md border-0 bg-white/5 py-1.5 text-white shadow-sm ring-1 ring-inset ring-white/10 focus:ring-2 focus:ring-inset focus:ring-indigo-500 sm:text-sm sm:leading-6" onChange={event => setThumbnail(event.target.value)} value={thumbnail} /> <img className="h-32 w-32" src={thumbnail} /> </div> </div> <div className="mt-2 flex flex-col sm:flex-row w-full gap-4"> <div className="w-full"> <div>Editor</div> <Editor initialDoc={doc} onChange={handleDocChange} /> </div> <div className="w-full"> <div>Preview</div> <Preview doc={doc} /> </div> </div> <div className="flex flex-row-reverse mt-4"> <Button primary disabled={isButtonClicked} onClick={async () => { setIsButtonClicked(true); await saveToFirebase(); router.push('/blogs') }} > Save </Button> </div> </div> ); } export default Form;
using Commons.Optimization.Evaluator; using ISILab.AI.Optimization.Terminations; using GeneticSharp.Domain; using GeneticSharp.Domain.Chromosomes; using GeneticSharp.Domain.Crossovers; using GeneticSharp.Domain.Mutations; using ISILab.AI.Optimization.Populations; using GeneticSharp.Domain.Reinsertions; using ISILab.AI.Optimization.Selections; using GeneticSharp.Infrastructure.Framework.Texts; using GeneticSharp.Infrastructure.Framework.Threading; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using UnityEngine; namespace ISILab.AI.Optimization { [System.Serializable] public class GeneticAlgorithm : BaseOptimizer { #region FIELDS [SerializeField, SerializeReference] ICrossover crossover; [SerializeField, SerializeReference] IMutation mutation; /// <summary> /// The default crossover probability. /// </summary> [SerializeField, SerializeReference] float crossoverProbability = 1f; /// <summary> /// The default mutation probability. /// </summary> [SerializeField, SerializeReference] float mutationProbability = 0.05f; #endregion #region PROPERTIES /// <summary> /// Gets or sets the task executor which will be used to execute fitness evaluation. /// </summary> public ITaskExecutor TaskExecutor { get; set; } /// <summary> /// Gets or sets the reinsertion operator. /// </summary> public IReinsertion Reinsertion { get; set; } /// <summary> /// Gets the operators strategy /// </summary> public IOperatorsStrategy OperatorsStrategy { get; set; } /// <summary> /// Gets or sets the crossover operator. /// </summary> /// <value>The crossover.</value> public ICrossover Crossover { get => crossover; set => crossover = value; } /// <summary> /// Gets or sets the mutation operator. /// </summary> public IMutation Mutation { get => mutation; set => mutation = value; } /// <summary> /// Gets or sets the crossover probability. /// </summary> public float CrossoverProbability { get => crossoverProbability; set => crossoverProbability = value; } /// <summary> /// Gets or sets the mutation probability. /// </summary> public float MutationProbability { get => mutationProbability; set => mutationProbability = value; } public new IOptimizable Adam { get => adam; set { adam = value; Population.Adam = value; } } #endregion public GeneticAlgorithm() { Reinsertion = new ElitistReinsertion(3); State = Op_State.NotStarted; TaskExecutor = new LinearTaskExecutor(); OperatorsStrategy = new DefaultOperatorsStrategy(); Selection = new TournamentSelection(2); Crossover = new AreaCrossover(); //Crossover = new UniformCrossover(); Population = new Population(); Termination = new GenerationNumberTermination(20); } public override void RunOnce() { var parents = SelectParents(); var p = parents.Select(p => p as ChromosomeBase).ToList(); var offspring = Cross(p); Mutate(offspring); var children = offspring.Select(p => p as IOptimizable).ToList(); EvaluateFitness(children); var newGenerationChromosomes = Reinsert(children, parents); Population.CreateNewGeneration(newGenerationChromosomes); EndCurrentGeneration(); } /// <summary> /// Reinsert the specified offspring and parents. /// </summary> /// <param name="offspring">The offspring chromosomes.</param> /// <param name="parents">The parents chromosomes.</param> /// <returns> /// The reinserted chromosomes. /// </returns> private IList<IOptimizable> Reinsert(IList<IOptimizable> offspring, IList<IOptimizable> parents) { return Reinsertion.SelectChromosomes(Population, offspring, parents); } /// <summary> /// Ends the current generation. /// </summary> /// <returns><c>true</c>, if current generation was ended, <c>false</c> otherwise.</returns> private bool EndCurrentGeneration() { Population.EndCurrentGeneration(); OnGenerationRan?.Invoke(); if (Termination.HasReached(this)) { State = Op_State.TerminationReached; OnTerminationReached?.Invoke(); return true; } if (stopRequested) { TaskExecutor.Stop(); State = Op_State.Stopped; } return false; } /// <summary> /// Crosses the specified parents. /// </summary> /// <param name="parents">The parents.</param> /// <returns>The result chromosomes.</returns> private IList<ChromosomeBase> Cross(IList<ChromosomeBase> parents) { return OperatorsStrategy.Cross(Population, Crossover, CrossoverProbability, parents); } /// <summary> /// Mutate the specified chromosomes. /// </summary> /// <param name="chromosomes">The chromosomes.</param> private void Mutate(IList<ChromosomeBase> chromosomes) { OperatorsStrategy.Mutate(Mutation, MutationProbability, chromosomes); } /// <summary> /// Selects the parents. /// </summary> /// <returns>The parents.</returns> private IList<IOptimizable> SelectParents() { return Selection.SelectEvaluables(Population.MinSize, Population.CurrentGeneration); } /// <summary> /// Evaluates the fitness. /// </summary> public override void EvaluateFitness(IList<IOptimizable> optimizables) { try { for (int i = 0; i < optimizables.Count; i++) { var c = optimizables[i]; TaskExecutor.Add(() => { RunEvaluateFitness(c); }); } if (!TaskExecutor.Start()) { throw new TimeoutException("The fitness evaluation reached the {0} timeout.".With(TaskExecutor.Timeout)); } } finally { TaskExecutor.Stop(); TaskExecutor.Clear(); } optimizables = optimizables.OrderByDescending(c => c.Fitness).ToList(); } /// <summary> /// Runs the evaluate fitness. /// </summary> /// <param name="chromosome">The chromosome.</param> private void RunEvaluateFitness(IOptimizable chromosome) { chromosome.Fitness = Evaluator.Evaluate(chromosome); } public override object Clone() { var ga = new GeneticAlgorithm(); ga.crossoverProbability = CrossoverProbability; ga.mutationProbability = MutationProbability; ga.crossover = Crossover; ga.mutation = Mutation; ga.Evaluator = Evaluator; return ga; } } }
package com.example.gymrattrial4; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.concurrent.TimeoutException; public class ChatDatabaseHelper extends SQLiteOpenHelper { private static final String TAG = "Chat Database Helper"; //Initialization private static final String DATABASE_NAME = "ChatDatabase"; private static final int VERSION = 1; //Chat Logs /* Every text conversation will be stored as a table in this database. It will have five columns: message_id, sender_id, timestamp, message_text, media_path; And it will be sorted by timestamp, in descending order (i.e. oldest messages at the bottom of the table, and top of the chat fragment). */ private ArrayList<String> tableNames = new ArrayList<String>(); private static final String TIME_SENT = "time_sent"; private static final String SENDER_ID = "sender_id"; private static final String MESSAGE_ID = "time_sent"; private static final String MESSAGE_TEXT = "sender_id"; private static final String MEDIA_PATH = "media_path"; private static final String createTable = "CREATE TABLE "; private static final String createTable2 = "(" + TIME_SENT + " DATETIME DEFAULT CURRENT_TIMESTAMP," + SENDER_ID + " VARCHAR(9) NOT NULL," + MESSAGE_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + MESSAGE_TEXT + " TEXT," + MEDIA_PATH + " TEXT;"; public ChatDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { for (String name : tableNames) db.execSQL(createTable + name + createTable2); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { for (String name : tableNames) db.execSQL("DROP TABLE IF EXISTS " + name); onCreate(db); } public void createTable(String tableName) { if (!tableName.equalsIgnoreCase("")) { SQLiteDatabase db = this.getWritableDatabase(); tableNames.add(tableName); db.execSQL(createTable + tableName + createTable2); } } //---------------------------------<Insertion>----------------------------------- public boolean addMessage(String tableName, String message, String mediaPath, String sender_id) { SQLiteDatabase db = this.getWritableDatabase(); String query = "INSERT INTO " + tableName; if (message == null && mediaPath != null) { query += " (" + SENDER_ID + ", " + MEDIA_PATH + ") VALUES ("; query += sender_id + ", " + mediaPath + ");"; } else if (message != null && mediaPath == null) { query += " (" + SENDER_ID + ", " + MESSAGE_TEXT + ") VALUES ("; query += sender_id + ", " + message + ");"; } else if (message == null && mediaPath == null) return false; else { query += " (" + SENDER_ID + ", " + MESSAGE_TEXT + ", " + MEDIA_PATH + ") VALUES ("; query += sender_id + ", " + message + ", " + mediaPath + ");"; } db.execSQL(query); return true; } //---------------------------------<Retrieval>-------------------------------------- public String[][] getFirstFifty(String tableName) { return getFifty(tableName, 0); } public String[][] getFifty(String tableName, int startIndex) { String[][] messages = new String[50][3]; for (int i = startIndex; i < startIndex + 50; i++) { String[][] singleMessage = getMessage(tableName, getTableHeight(tableName) - i); if (singleMessage == null) break; messages[i][0] = singleMessage[0][0]; messages[i][1] = singleMessage[0][1]; messages[i][2] = singleMessage[0][2]; } return messages; } //Tools private String[][] getMessage(String tableName, int row) { String [][] message = null; SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT " + SENDER_ID + ", " + MESSAGE_TEXT + ", " + MEDIA_PATH + " FROM " + tableName + " WHERE message_id=" + row + ";"; Cursor c = db.rawQuery(query, null); if (c.moveToFirst()) { message = new String[1][3]; message[0][0] = c.getInt(c.getColumnIndex(SENDER_ID)) + ""; message[0][1] = c.getString(c.getColumnIndex(MESSAGE_TEXT)); message[0][2] = c.getString(c.getColumnIndex(MEDIA_PATH)); } return message; } private int getTableHeight(String tableName) { SQLiteDatabase db = this.getWritableDatabase(); int h = 0; Cursor c = db.rawQuery("SELECT * FROM " + tableName + ";", null); if (c.moveToFirst()) { h = c.getInt(0); } return h; } //---------------------------------------<DELETION>------------------------- public void deleteRow(String tableName, int row) { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE FROM " + tableName + " WHERE message_id = " + row + ";"); } }
<template> <div class="tabs"> <draggable v-bind="dragOptions" @start="drag = true" @end="drag = false"> <el-tag v-for="(item, index) in tags" :key="item.path" :closable="item.name !== 'home'" :effect="$route.name === item.name ? 'dark' : 'plain'" @click="changeMenu(item, index)" @close="handleClose(item, index)" size="small"> {{ item.label }} </el-tag> </draggable> </div> </template> <script> import { mapState, mapMutations } from 'vuex' import draggable from 'vuedraggable' export default { display: 'Transitions', order: 8, components: { draggable }, name: 'CommonTag', data() { return { list: tags.map((name, index) => { return { name, order: index + 1 } }), drag: false } }, computed: { dragOptions() { return { animation: 200, group: 'description', disabled: false, ghostClass: 'ghost' } }, ...mapState({ tags: state => state.tab.tabList }) }, methods: { // 恢复原始排序 sort() { this.list = this.list.sort((a, b) => a.order - b.order) }, ...mapMutations(['closeTag']), // 点击tag跳转的功能 changeMenu(item) { this.$router.push({ name: item.name }) }, // tag的删除功能 handleClose(item, index) { this.closeTag(item) const length = this.tags.length // 删除之后的跳转逻辑 if (item.name !== this.$route.name) { return } // 表示删除的是最后一项 if (index === length) { this.$router.push({ name: this.tags[index - 1].name }) } else { this.$router.push({ name: this.tags[index].name }) } } } } </script> <style lang="less" scoped> .tabs { padding: 20px; .el-tag { margin-right: 15px; cursor: pointer; } } </style>
package training.v3b.task_38; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; public class Task38tl { private static final int[][] DELTA = new int[][]{ {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1} }; private static int n; private static int m; private static int s; private static int t; public static void main(String[] args) throws IOException { var input = "src/main/java/training/v3b/task_38/input_2.txt"; File file = new File(input); FileReader fileReader = new FileReader(file); try (BufferedReader reader = new BufferedReader(fileReader)) { String line = reader.readLine(); String[] split = line.split("\\s"); n = Integer.parseInt(split[0]); m = Integer.parseInt(split[1]); s = Integer.parseInt(split[2]); t = Integer.parseInt(split[3]); int q = Integer.parseInt(split[4]); Point[] points = new Point[q]; for (int i = 0; i < q; i++) { line = reader.readLine(); split = line.split("\\s"); int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); points[i] = new Point(x, y); } int res = 0; for (Point point : points) { int bfs = bfs(point); if (bfs == -1) { System.out.println(-1); return; } else res += bfs; } System.out.println(res); } } private static int bfs(Point point) { if (point.x == s && point.y == t) return 0; int[][] grid = new int[n + 1][m + 1]; Deque<Point> deque = new ArrayDeque<>(); deque.addLast(point); while (!deque.isEmpty()) { point = deque.pollFirst(); for (int[] vector : DELTA) { int dx = vector[0]; int dy = vector[1]; Point next = new Point(point.x + dx, point.y + dy); if (outOfGrid(next)) continue; if (grid[next.x][next.y] == 0) { grid[next.x][next.y] = grid[point.x][point.y] + 1; deque.addLast(next); } } } return grid[s][t] == 0 ? -1 : grid[s][t]; } private static boolean outOfGrid(Point point) { return point.x < 1 || point.y < 1 || point.x > n || point.y > m; } static class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + ":" + y; } } }
define('lodash/isArguments', ['exports', 'lodash/_baseIsArguments', 'lodash/isObjectLike'], function (exports, _lodash_baseIsArguments, _lodashIsObjectLike) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = (0, _lodash_baseIsArguments['default'])((function () { return arguments; })()) ? _lodash_baseIsArguments['default'] : function (value) { return (0, _lodashIsObjectLike['default'])(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; exports['default'] = isArguments; });
import React, { useRef, useMemo, useState } from 'react'; import JoditEditor from 'jodit-react'; const ReactTextEditor = ({ props }) => { const [desc, setDesc] = useState(''); const editor = useRef(); const config = useMemo( () => ({ placeholder: 'Start Writing here', height: '450px', width: '100%', colorPickerDefaultTab: 'text', enableDragAndDropFileToEditor: true, buttons: [ 'source', 'bold', 'preview', '|', 'italic', 'underline', '|', 'ul', 'ol', '|', 'font', 'fontsize', 'brush', 'paragraph', '|', 'image', 'table', 'link', '|', 'left', 'center', 'right', 'justify', '|', 'undo', 'redo', '|', 'hr', 'lineHeight', 'fullsize' ], autofocus: true, uploader: { insertImageAsBase64URI: true }, removeButtons: ['file', 'eraser'], showXPathInStatusbar: false, showCharsCounter: false, showWordsCounter: false, toolbarAdaptive: true, toolbarSticky: true // style: { // background: '#27272E', // color: '#fff' // } }), [] ); const handleSUbmit = () => { props.setFieldValue('editorContent', editor.current.value); props.setFieldTouched('editorContent', true); }; return <JoditEditor ref={editor} config={config} value={desc} onChange={handleSUbmit} />; }; export default React.memo(ReactTextEditor);
#' @param AggTAD Aggregated TAD object to plot #' @param maxval integer representing the maximum value to plot (essentialy sets the top of the zrange) #' @param cols color palette for plotting #' @param title title of the plot ### Define a function that builds aggregate TADS plotAggTAD <- function(AggTAD,maxval = 10000,cols = RColorBrewer::brewer.pal(6,"YlGnBu"),title="") { # Convert to long format for ggplot AggTAD_long = setNames(melt(AggTAD), c('x', 'y', 'counts')) AggTAD_long$counts = AggTAD_long$counts ggplot(data=AggTAD_long,mapping=aes(x=x,y=y,fill=counts)) + geom_tile() + theme_void() + theme(plot.title = element_text(hjust = 0.5)) + theme(aspect.ratio = 1) + ggtitle(title) + scale_fill_gradientn(colours = cols, na.value=cols[maxval], limits=c(0,maxval), oob = scales::squish) }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('db_user', function (Blueprint $table) { $table->id(); //id $table->string('name'); $table->string('username'); $table->string('password'); $table->string('gender'); $table->string('phone'); $table->string('email'); $table->string('roles'); $table->timestamps(); //created_at, updated_at $table->unsignedInteger('created_by')->default(1); $table->unsignedInteger('updated_by')->nullable(); $table->unsignedTinyInteger('status')->default(2); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('db_user'); } };
import dayjs from "dayjs"; import create from "zustand"; import { tokenList } from "./useSellStore"; import type { PurchaseTime } from "./usePurchaseStore"; import type { Token } from "./useSellStore"; export type TargetToken = Token & { percent: number }; export type Position = { id: number; token: Token; total: number; tokens: TargetToken[]; time: PurchaseTime; totalTime: number; startTime: string; endTime: string; status: "started" | "pending" | "finished"; rate: number; }; export const usePositionStore = create<{ position: Position | null; pendingPositions: Position[]; startedPositions: Position[]; finishedPositions: Position[]; setPosition: (p: Position) => void; addPosition: (p: Position) => void; }>((set, get) => ({ position: null, pendingPositions: [ { id: 0, token: { name: "Wrapped Bitcoin", symbol: "WBTC", slug: "wrapped-bitcoin", icon: "https://static.crypto.com/token/icons/wrapped-bitcoin/color_icon.png", balance: 4000, }, total: 2000, tokens: [ { name: "cronos", symbol: "CRO", slug: "crypto-com-coin", icon: "https://static.crypto.com/token/icons/crypto-com-coin/color_icon.png", balance: 300000, percent: 20, }, { name: "USD Coin", symbol: "USDC", slug: "usd-coin", icon: "https://static.crypto.com/token/icons/usd-coin/color_icon.png", balance: 1000, percent: 30, }, { name: "VVS Finance", symbol: "VVS", slug: "vvs-finance", icon: "https://static.crypto.com/token/icons/vvs-finance/color_icon.png", balance: 100000, percent: 50, }, ], time: "weekly", startTime: "Tue Oct 18 2022", endTime: "Tue Nov 22 2022", totalTime: 5, status: "pending", rate: 400, }, ], startedPositions: [ { id: 5, token: tokenList[0], tokens: tokenList.slice(2, 6).map((token) => ({ ...token, percent: 25 })), total: 10, totalTime: 8, time: "weekly", startTime: dayjs().add(-2, "week").toDate().toDateString(), endTime: dayjs().add(5, "week").toDate().toDateString(), status: "started", rate: 10 / 8, }, ], finishedPositions: [ { id: 2, token: tokenList[1], tokens: tokenList.slice(2, 6).map((token) => ({ ...token, percent: 25 })), total: 110, totalTime: 6, time: "weekly", startTime: dayjs().add(-8, "week").toDate().toDateString(), endTime: dayjs().add(-2, "week").toDate().toDateString(), status: "finished", rate: 110 / 6, }, ], setPosition: (p) => set({ position: p }), addPosition: (p) => set({ pendingPositions: [...get().pendingPositions, p] }), }));
# MathXF [![license](https://badgen.net/github/license/xslasd/mathxf/)](https://github.com/xslasd/mathxf/blob/master/LICENSE) [![release](https://badgen.net/github/release/xslasd/mathxf/stable)](https://github.com/xslasd/mathxf/releases) 这是一个用 Go 语言编写的强大数学计算规则引擎,旨在提供灵活高效的数学表达式计算能力。它支持多种运算符,包括基本的算术运算(如加、减、乘、除)、指数运算、括号分组运算,甚至还包括逻辑条件运算符如 if 语句。该解析器允许用户输入并解析复杂的数学公式,精确计算出表达式的最终结果值。 ## 功能特点: 1. **全面的运算符支持:** 囊括基础算术运算的同时,还融入了指数等高级运算功能。 2. **条件逻辑集成:** 创新性地支持了 if 条件语句,使解析器能够处理含有条件逻辑的数学表达式。 3. **高度可扩展性:** 采用模块化设计,易于扩展,可根据需要轻松添加新的运算符或函数。 4. **准确性保障:** 运用了健壮的解析算法,确保即使是最复杂的公式也能正确解析并计算,同时保持浮点运算的高精度。 5. **易用性佳:** 提供了一套简洁明了、用户友好的API接口,便于无缝集成到各类项目中。 #### 支持操作符: 1. 算术运算符:+(加法)-(减法)*(乘法)/(除法)%(求余数或模运算)**(幂运算) 2. 比较运算符:<(小于)>(大于)<=(小于等于)>=(大于等于)==(等于)!= 或 <>(不等于) 3. 逻辑运算符:&& and(逻辑与)|| or(逻辑或) in (包含) **todo** 还没实现 ! not (逻辑非) #### 支持语法: 1. if条件判断: if<条件>{ }else if<条件>else{ } 2. val定义变量:val a;val a,b,c; val a=1;var a,b,c=1 3. 代码注释: //单行注释; /* */多行注释 4. 赋值操作: a=1; (**常量不能赋值**) #### 支持常量(可动态扩展): 1. pi=math.Pi 2. e=math.E 如添加常量ff ``` tpl.AddFuncOrConst("ff", 100) ``` #### 支持函数(可动态扩展): sum ,avg ,max ,min ,cbrt ,sqrt ,round ,floor ,ceil ,abs ,sin ,cos ,tan ,asin ,acos ,atan ,atan2 ,sinh ,cosh ,tanh ,asinh 函数格式为 func(ctx *mathxf.EvaluatorContext,arg *mathxf.Value)(res1,error) ctx *EvaluatorContext 可以省略 arg *mathxf.Value 可以多个或使用args ...*mathxf.Value 返回参数必须 1-2个,第2个必须为error 如添加函数 DblEquals ``` tpl.AddFuncOrConst("DblEquals", func(a, b *mathxf.Value) bool { return a.Decimal().Cmp(b.Decimal()) == 0 }) ``` #### 支持模板内容替换: 将显示代码转换成可执行代码 ```go package main import ( "fmt" "github.com/xslasd/mathxf" ) func main() { input := ` if 用户显示变量 A > 10 { res.aa=5 } ` tpl, err := mathxf.NewTemplate(input) tpl.ReplaceStrMap(map[string]string{ "用户显示变量 A":"UserA", }) env := map[string]any{ "UserA":100, } res, err := tpl.Execute(env) if err != nil { panic(err) } for k, v := range res { fmt.Printf("--Result.%s---%v\n", k, v) } } ``` ## 用法 go mod github.com/xslasd/mathxf 1. mathxf 默认开启精度计算功能,HighPrecision(false) 关闭。精度库使用:github.com/shopspring/decimal 2. mathxf 计算结果默认放到map[string]map[string]*mathxf.Value中,默认前缀key为”res“,可以使用AddResultKeys(keys ...string)添加返回值前缀Key 3. mathxf 计算结果map中, 前缀key为"env"中,存放着被修改env值。 4. mathxf 支持直接计算,但不能和其它语法混用。 #### 直接计算 ```go package main import ( "fmt" "github.com/xslasd/mathxf" ) func main() { input := `1 + 2 * 6 / 4 + (456 - 8 * 9.2) - (2 + 4 ^ 5)` tpl, err := mathxf.NewTemplate(input) res, err := tpl.Execute(nil) if err != nil { panic(err) } for k, v := range res { fmt.Printf("--Result.%s---%v\n", k, v) } } ``` #### 组合用法 ```go package main import ( "fmt" "github.com/shopspring/decimal" "github.com/xslasd/mathxf" ) func main() { input := ` // 用户优惠劵面值计算规则 if 用户A.总订单数 > 5 && 特价商品区.单价小于10元.订单数<=3 { 优惠劵面值= 优惠算法((用户A.订单总金额-特价商品区.单价小于10元.订单数*10)*优惠比率最大值,用户A.用户等级) } ` tpl, err := mathxf.NewTemplate(input) if err != nil { panic(err) } replaceStrMap := map[string]string{ "用户A.总订单数": "TotalOrders", "用户A.用户等级": "UserLevel", "用户A.订单总金额": "OrderTotalAmount", "特价商品区.单价小于10元.订单数": "SpecialOffer_10_Orders", "优惠比率最大值": "DiscountRatioMax", "优惠劵面值": "CouponFace", "优惠算法": "DiscountAlgorithm", } tpl.ReplaceStrMap(replaceStrMap) tpl.AddFuncOrConst("DiscountAlgorithm", func(a, b *mathxf.Value) decimal.Decimal { level := b.Integer() if level > 5 { return a.Decimal().Mul(decimal.NewFromFloat(0.5)) } else if level > 3 { return a.Decimal().Mul(decimal.NewFromFloat(0.3)) } else if level >= 1 { return a.Decimal().Mul(decimal.NewFromFloat(0.1)) } return decimal.NewFromFloat(0) }) tpl.AddFuncOrConst("DiscountRatioMax", 0.3) env := map[string]any{ "TotalOrders": 10, "UserLevel": 1, "OrderTotalAmount": 100, "SpecialOffer_10_Orders": 3, "DiscountRatioMax": 0.3, "CouponFace": 0, } res, err := tpl.Execute(env) if err != nil { fmt.Println("Execute:", err) return } for k, v := range tpl.PublicValMap() { fmt.Printf("--Public.%s---%v\n", k, v.Val) } for k, v := range res { fmt.Printf("--Result.%s---%v\n", k, v) } } ```
--- title: Recommendations tags: - top clicked - top searched - trending - trending products --- > Look! Those chocolate truffles have a good price! It’s Valentine’s Day, and everybody is already buying them! Recommendations shows the top searched items. That’s to say, the most clicked products on the search results page, based on shopper interaction within a defined period. ![Recommendations](~@assets/media/features/overview-recommendations.svg) Recommendations are relevant product suggestions; they aren’t related to the query, but to products that matched previous searches done by other shoppers, instead. They are useful in numerous situations, especially when there are no search results to show. Whether a shopper lands on your shop and hasn’t written any query yet or if a search doesn’t bring back any product results, Recommendations amaze shoppers with product discovery inspirations. ## Spot the difference Notice that Recommendations guide shoppers to specific products. When clicking on a recommendation, the related product description page displays without any further interaction. No need to search or navigate the results. Try to not confuse it with the [Popular Searches](/explore-empathy-platform/features/popular-searches-overview.md) feature, which presents the top searched queries to trigger a new search. For example, “off-the-shoulder ditsy floral dress” can refer to a top-clicked specific product that redirects to the product description. But “dress”, “floral dress”, or “off-the-shoulder dress” express a currently top searched query, prompting a new search and displaying relevant results such as “off-the-shoulder ditsy floral dress”, among others. You can identify Recommendations mostly under labels like _Top searched items today_. ::: note Remember that other types of suggestions can display hints based on [queries](/explore-empathy-platform/features/query-suggestions-overview.md), [search history](/explore-empathy-platform/features/history-queries-overview.md), or even [product references](/explore-empathy-platform/features/id-results-overview.md). ::: ## Try Recommendations to... - Improve product findability. Guide shoppers to products in your catalogue they don’t know. - Enhance shopper experience. Surprise shoppers with new ideas or alternative products. - Handle shopper frustration. Suggest products when there’s no query to suggest or no results to show. - Speed up the search and discovery process, especially on mobile devices. ## The inner workings of Recommendations Recommendations are generated by shoppers’ actions in the search UI. When shoppers perform different searches and actions, behavioral information (queries, clicks, add to cart, etc.) is collected using the Tagging microservices and processed by the Search microservice. This information is collected by the TopClicked batch process to generate a feed with the final recommended products that are ready to go. :::warning For a correct performance, make sure that your current search service supports this type of feature. ::: ::: interact Explore the [interactive map](/explore-empathy-platform/diagram/interface/recommendations.md) to see how Recommendations relate to the other Empathy Platform features and microservices. :::
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { APP_BOOTSTRAP_LISTENER, ApplicationRef, inject, InjectionToken, makeStateKey, PLATFORM_ID, Provider, StateKey, TransferState, ɵformatRuntimeError as formatRuntimeError, ɵperformanceMarkFeature as performanceMarkFeature, ɵtruncateMiddle as truncateMiddle, ɵwhenStable as whenStable, ɵRuntimeError as RuntimeError, } from '@angular/core'; import {isPlatformServer} from '@angular/common'; import {Observable, of} from 'rxjs'; import {tap} from 'rxjs/operators'; import {RuntimeErrorCode} from './errors'; import {HttpHeaders} from './headers'; import {HTTP_ROOT_INTERCEPTOR_FNS, HttpHandlerFn} from './interceptor'; import {HttpRequest} from './request'; import {HttpEvent, HttpResponse} from './response'; import {HttpParams} from './params'; /** * Options to configure how TransferCache should be used to cache requests made via HttpClient. * * @param includeHeaders Specifies which headers should be included into cached responses. No * headers are included by default. * @param filter A function that receives a request as an argument and returns a boolean to indicate * whether a request should be included into the cache. * @param includePostRequests Enables caching for POST requests. By default, only GET and HEAD * requests are cached. This option can be enabled if POST requests are used to retrieve data * (for example using GraphQL). * @param includeRequestsWithAuthHeaders Enables caching of requests containing either `Authorization` * or `Proxy-Authorization` headers. By default, these requests are excluded from caching. * * @publicApi */ export type HttpTransferCacheOptions = { includeHeaders?: string[]; filter?: (req: HttpRequest<unknown>) => boolean; includePostRequests?: boolean; includeRequestsWithAuthHeaders?: boolean; }; /** * If your application uses different HTTP origins to make API calls (via `HttpClient`) on the server and * on the client, the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token allows you to establish a mapping * between those origins, so that `HttpTransferCache` feature can recognize those requests as the same * ones and reuse the data cached on the server during hydration on the client. * * **Important note**: the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token should *only* be provided in * the *server* code of your application (typically in the `app.server.config.ts` script). Angular throws an * error if it detects that the token is defined while running on the client. * * @usageNotes * * When the same API endpoint is accessed via `http://internal-domain.com:8080` on the server and * via `https://external-domain.com` on the client, you can use the following configuration: * ```typescript * // in app.server.config.ts * { * provide: HTTP_TRANSFER_CACHE_ORIGIN_MAP, * useValue: { * 'http://internal-domain.com:8080': 'https://external-domain.com' * } * } * ``` * * @publicApi */ export const HTTP_TRANSFER_CACHE_ORIGIN_MAP = new InjectionToken<Record<string, string>>( ngDevMode ? 'HTTP_TRANSFER_CACHE_ORIGIN_MAP' : '', ); /** * Keys within cached response data structure. */ export const BODY = 'b'; export const HEADERS = 'h'; export const STATUS = 's'; export const STATUS_TEXT = 'st'; export const REQ_URL = 'u'; export const RESPONSE_TYPE = 'rt'; interface TransferHttpResponse { /** body */ [BODY]: any; /** headers */ [HEADERS]: Record<string, string[]>; /** status */ [STATUS]?: number; /** statusText */ [STATUS_TEXT]?: string; /** url */ [REQ_URL]?: string; /** responseType */ [RESPONSE_TYPE]?: HttpRequest<unknown>['responseType']; } interface CacheOptions extends HttpTransferCacheOptions { isCacheActive: boolean; } const CACHE_OPTIONS = new InjectionToken<CacheOptions>( ngDevMode ? 'HTTP_TRANSFER_STATE_CACHE_OPTIONS' : '', ); /** * A list of allowed HTTP methods to cache. */ const ALLOWED_METHODS = ['GET', 'HEAD']; export function transferCacheInterceptorFn( req: HttpRequest<unknown>, next: HttpHandlerFn, ): Observable<HttpEvent<unknown>> { const {isCacheActive, ...globalOptions} = inject(CACHE_OPTIONS); const {transferCache: requestOptions, method: requestMethod} = req; // In the following situations we do not want to cache the request if ( !isCacheActive || requestOptions === false || // POST requests are allowed either globally or at request level (requestMethod === 'POST' && !globalOptions.includePostRequests && !requestOptions) || (requestMethod !== 'POST' && !ALLOWED_METHODS.includes(requestMethod)) || // Do not cache request that require authorization when includeRequestsWithAuthHeaders is falsey (!globalOptions.includeRequestsWithAuthHeaders && hasAuthHeaders(req)) || globalOptions.filter?.(req) === false ) { return next(req); } const transferState = inject(TransferState); const originMap: Record<string, string> | null = inject(HTTP_TRANSFER_CACHE_ORIGIN_MAP, { optional: true, }); const isServer = isPlatformServer(inject(PLATFORM_ID)); if (originMap && !isServer) { throw new RuntimeError( RuntimeErrorCode.HTTP_ORIGIN_MAP_USED_IN_CLIENT, ngDevMode && 'Angular detected that the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token is configured and ' + 'present in the client side code. Please ensure that this token is only provided in the ' + 'server code of the application.', ); } const requestUrl = isServer && originMap ? mapRequestOriginUrl(req.url, originMap) : req.url; const storeKey = makeCacheKey(req, requestUrl); const response = transferState.get(storeKey, null); let headersToInclude = globalOptions.includeHeaders; if (typeof requestOptions === 'object' && requestOptions.includeHeaders) { // Request-specific config takes precedence over the global config. headersToInclude = requestOptions.includeHeaders; } if (response) { const { [BODY]: undecodedBody, [RESPONSE_TYPE]: responseType, [HEADERS]: httpHeaders, [STATUS]: status, [STATUS_TEXT]: statusText, [REQ_URL]: url, } = response; // Request found in cache. Respond using it. let body: ArrayBuffer | Blob | string | undefined = undecodedBody; switch (responseType) { case 'arraybuffer': body = new TextEncoder().encode(undecodedBody).buffer; break; case 'blob': body = new Blob([undecodedBody]); break; } // We want to warn users accessing a header provided from the cache // That HttpTransferCache alters the headers // The warning will be logged a single time by HttpHeaders instance let headers = new HttpHeaders(httpHeaders); if (typeof ngDevMode === 'undefined' || ngDevMode) { // Append extra logic in dev mode to produce a warning when a header // that was not transferred to the client is accessed in the code via `get` // and `has` calls. headers = appendMissingHeadersDetection(req.url, headers, headersToInclude ?? []); } return of( new HttpResponse({ body, headers, status, statusText, url, }), ); } // Request not found in cache. Make the request and cache it if on the server. return next(req).pipe( tap((event: HttpEvent<unknown>) => { if (event instanceof HttpResponse && isServer) { transferState.set<TransferHttpResponse>(storeKey, { [BODY]: event.body, [HEADERS]: getFilteredHeaders(event.headers, headersToInclude), [STATUS]: event.status, [STATUS_TEXT]: event.statusText, [REQ_URL]: requestUrl, [RESPONSE_TYPE]: req.responseType, }); } }), ); } /** @returns true when the requests contains autorization related headers. */ function hasAuthHeaders(req: HttpRequest<unknown>): boolean { return req.headers.has('authorization') || req.headers.has('proxy-authorization'); } function getFilteredHeaders( headers: HttpHeaders, includeHeaders: string[] | undefined, ): Record<string, string[]> { if (!includeHeaders) { return {}; } const headersMap: Record<string, string[]> = {}; for (const key of includeHeaders) { const values = headers.getAll(key); if (values !== null) { headersMap[key] = values; } } return headersMap; } function sortAndConcatParams(params: HttpParams | URLSearchParams): string { return [...params.keys()] .sort() .map((k) => `${k}=${params.getAll(k)}`) .join('&'); } function makeCacheKey( request: HttpRequest<any>, mappedRequestUrl: string, ): StateKey<TransferHttpResponse> { // make the params encoded same as a url so it's easy to identify const {params, method, responseType} = request; const encodedParams = sortAndConcatParams(params); let serializedBody = request.serializeBody(); if (serializedBody instanceof URLSearchParams) { serializedBody = sortAndConcatParams(serializedBody); } else if (typeof serializedBody !== 'string') { serializedBody = ''; } const key = [method, responseType, mappedRequestUrl, serializedBody, encodedParams].join('|'); const hash = generateHash(key); return makeStateKey(hash); } /** * A method that returns a hash representation of a string using a variant of DJB2 hash * algorithm. * * This is the same hashing logic that is used to generate component ids. */ function generateHash(value: string): string { let hash = 0; for (const char of value) { hash = (Math.imul(31, hash) + char.charCodeAt(0)) << 0; } // Force positive number hash. // 2147483647 = equivalent of Integer.MAX_VALUE. hash += 2147483647 + 1; return hash.toString(); } /** * Returns the DI providers needed to enable HTTP transfer cache. * * By default, when using server rendering, requests are performed twice: once on the server and * other one on the browser. * * When these providers are added, requests performed on the server are cached and reused during the * bootstrapping of the application in the browser thus avoiding duplicate requests and reducing * load time. * */ export function withHttpTransferCache(cacheOptions: HttpTransferCacheOptions): Provider[] { return [ { provide: CACHE_OPTIONS, useFactory: (): CacheOptions => { performanceMarkFeature('NgHttpTransferCache'); return {isCacheActive: true, ...cacheOptions}; }, }, { provide: HTTP_ROOT_INTERCEPTOR_FNS, useValue: transferCacheInterceptorFn, multi: true, deps: [TransferState, CACHE_OPTIONS], }, { provide: APP_BOOTSTRAP_LISTENER, multi: true, useFactory: () => { const appRef = inject(ApplicationRef); const cacheState = inject(CACHE_OPTIONS); return () => { whenStable(appRef).then(() => { cacheState.isCacheActive = false; }); }; }, }, ]; } /** * This function will add a proxy to an HttpHeader to intercept calls to get/has * and log a warning if the header entry requested has been removed */ function appendMissingHeadersDetection( url: string, headers: HttpHeaders, headersToInclude: string[], ): HttpHeaders { const warningProduced = new Set(); return new Proxy<HttpHeaders>(headers, { get(target: HttpHeaders, prop: keyof HttpHeaders): unknown { const value = Reflect.get(target, prop); const methods: Set<keyof HttpHeaders> = new Set(['get', 'has', 'getAll']); if (typeof value !== 'function' || !methods.has(prop)) { return value; } return (headerName: string) => { // We log when the key has been removed and a warning hasn't been produced for the header const key = (prop + ':' + headerName).toLowerCase(); // e.g. `get:cache-control` if (!headersToInclude.includes(headerName) && !warningProduced.has(key)) { warningProduced.add(key); const truncatedUrl = truncateMiddle(url); // TODO: create Error guide for this warning console.warn( formatRuntimeError( RuntimeErrorCode.HEADERS_ALTERED_BY_TRANSFER_CACHE, `Angular detected that the \`${headerName}\` header is accessed, but the value of the header ` + `was not transferred from the server to the client by the HttpTransferCache. ` + `To include the value of the \`${headerName}\` header for the \`${truncatedUrl}\` request, ` + `use the \`includeHeaders\` list. The \`includeHeaders\` can be defined either ` + `on a request level by adding the \`transferCache\` parameter, or on an application ` + `level by adding the \`httpCacheTransfer.includeHeaders\` argument to the ` + `\`provideClientHydration()\` call. `, ), ); } // invoking the original method return (value as Function).apply(target, [headerName]); }; }, }); } function mapRequestOriginUrl(url: string, originMap: Record<string, string>): string { const origin = new URL(url, 'resolve://').origin; const mappedOrigin = originMap[origin]; if (!mappedOrigin) { return url; } if (typeof ngDevMode === 'undefined' || ngDevMode) { verifyMappedOrigin(mappedOrigin); } return url.replace(origin, mappedOrigin); } function verifyMappedOrigin(url: string): void { if (new URL(url, 'resolve://').pathname !== '/') { throw new RuntimeError( RuntimeErrorCode.HTTP_ORIGIN_MAP_CONTAINS_PATH, 'Angular detected a URL with a path segment in the value provided for the ' + `\`HTTP_TRANSFER_CACHE_ORIGIN_MAP\` token: ${url}. The map should only contain origins ` + 'without any other segments.', ); } }
{% extends 'base.html.twig' %} {% block title %}{{ page.title }}{% endblock %} {% block body %} <section class="container{% if not flash %} first-section{% endif %}"> <div class="row"> <div class="col-12"> <div class="row no-gutters border rounded-lg overflow-hidden flex-md-row mb-4 shadow-sm position-relative bg-light featured-border rounded shadow-lg"> <div class="article-detail col-sm-12 p-4"> <div class="col-12 mt-2 mb-4"> {{ page.text | markdown_to_html }} </div> </div> </div> </div> </div> </section> {% if form is defined %} <section id="feedback" class="container"> <div class="row"> <div class="col-sm-12 mb-4"> <div class="row no-gutters border rounded-lg overflow-hidden flex-md-row mb-4 shadow-sm position-relative bg-light featured-border rounded shadow-lg"> <h3><i class="p-4 far fa-comment text-secondary"></i> Отзывов: {{ feedbacks|length }} </h3> <hr id="comment"> {% if app.session.flashBag.peek('flash_comment')|length == 0 and app.session.flashBag.peek('flash_error_comment')|length == 0 and not is_granted('ROLE_BANNED') %} <div class="row mb-4"> <div class="col-sm-12"> <div class="comment-container align-self-start col-sm-12 p-4"> {{ form_start(form) }} <div class="form-group mb-3"> {{ form_row(form.text) }} </div> <button type="submit" class="btn btn-info">Оставить отзыв</button> {{ form_end(form) }} </div> <hr class="col-sm-12"> </div> </div> {% else %} <div class="row justify-content-center"> <div class="col-sm-12"> {% if app.session.flashBag.peek('flash_comment')|length > 0 %} <div class="alert alert-success" role="alert"> {% for message in app.flashes('flash_comment') %} <p>{{ message }}</p> {% endfor %} </div> {% endif %} {% if app.session.flashBag.peek('flash_error_comment')|length > 0 %} <div class="alert alert-danger" role="alert"> <div class="alert alert-danger" role="alert"> {% for message in app.flashes('flash_error_comment') %} <p>{{ message }}</p> {% endfor %} </div> </div> {% endif %} </div> </div> {% endif %} {% for feedback in feedbacks %} <div class="row m-2"> <div class="col-sm-12"> <div class="media"> <div class="media-body align-self-start col-sm-12"> {# <img class="align-self-start comment-img rounded-circle"#} {# src="{{ 'eye.png'|imagine_filter('logo') }}">#} <b class="mx-3"> {% if feedback.otherAuthor is not null %} {{ feedback.otherAuthor }} {% elseif feedback.author is not null %} {{ feedback.author.firstName }} {{ feedback.author.surname }} {% else %} Аноним {% endif %}</b> {# <small class="me-3">{{ feedback.updatedAt|format_date(locale='ru') }}</small>#} {% if not feedback.publishedAt %} <span class="text-danger">Ждет одобрения модератором</span> {% endif %} <br> <p class="comment">{{ feedback.text | markdown_to_html }}</p> </div> <hr class="col-sm-12"> </div> </div> </div> {% endfor %} </div> </div> </div> </section> {% endif %} {% if articles is not empty and articles|length > 0 %} <section class="container mt-4"> <div class="row"> <div class="col-12"> <div class="row no-gutters border overflow-hidden flex-md-row mb-4 position-relative bg-light featured-border rounded shadow-lg"> <div class="media-body d-inline-block align-self-center mx-2"> <div class="mx-3 my-4"> <h3><a href="{{ url('app_articles') }}" title="Смотреть все статьи"><i class="far fa-clipboard fa-lg"> Последние {{ articles|length }} {{ articles|length|format_ru_articles_end }}.</i></a></h3> {% for article in articles %} <hr class="mb-3"> <div class="row mt-2"> <a title="Читать статью" class="text-reset text-decoration-none" href="{{ path('app_article_show', {slug: article.slug}) }}"> <div class="col-sm-12"> <div class="media"> <div class="media-body align-self-start col-sm-12"> <p> <span><b>{{ article.title }}</b></span> </p> </div> <img class="me-3" style="float:left;" src="{{ article.imageFilename|imagine_filter('pict_in_article_preview') }}" alt="Глазной кабинет Валицкого И.С."> <span class="ps-3">{{ article.description }}</span> </div> </div> </a> <p class="mt-3"> <i>Автор: </i><b>{{ article.author.firstname }} {{ article.author.patronymic }} {{ article.author.surname }}</b> </p> <p><small><i>{{ article.publishedAt|format_date(locale='ru', ) }}</i></small> </p> </div> {% endfor %} </div> </div> </div> </div> </div> </section> {% endif %} {% if comments is not empty and comments|length > 0 %} <section class="container mt-4"> <div class="row"> <div class="col-12"> <div class="row no-gutters border overflow-hidden flex-md-row mb-4 position-relative bg-light featured-border rounded shadow-lg"> <div class="media-body d-inline-block align-self-center mx-2"> <div class="m-2"> <h3 class="my-4 ms-3"><i class="far fa-comments fa-lg"> Последние {{ comments|length }} {{ comments|length|format_ru_comments_end }} .</i></h3> <hr class="col-sm-12 m-3"> {% for comment in comments %} <div class="row"> <div class="col-sm-12"> <div class="media"> <div class="media-body align-self-start col-sm-12"> <i class="fas fa-comment fa-lg"></i> <b class="mx-3">{{ comment.author.firstName }} {{ comment.author.surname }}</b> <small class="me-3">{{ comment.updatedAt|format_date(locale='ru') }}</small> <span class="text-primary"><i class="pe-3 fas fa-paste"> Статья:</i><a class="link-unstyled" href="{{ url('app_article_show', {slug: comment.article.slug}) }}">{{ comment.article.title }}</a></span> <br> <p class="comment">{{ comment.text | markdown_to_html }}</p> </div> <hr class="col-sm-12"> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </div> </section> {% endif %} {% endblock %} {% block description %}{{ page.headTitle }}{% endblock %} {% block keywords %}{{ page.keywords }}{% endblock %}
/*É usado para inserir novas linhas de dados na tabela "cursos". Para usar esse comando corretamente, você precisa fornecer os valores correspondentes às colunas da tabela.*/ insert into cursos values ('1', 'HTML4', 'Cursos de HTML5', '40', '37', '2014'), ('2','Algoritimos', 'Lógica de Programação', '20', '15', '2014'), ('3', 'Photoshop', 'Dicas de Photoshop CC', '10', '8', '2014'), ('4', 'PGP', 'Curso de PHP para iniciantes', '40', '20', '2010'), ('5', 'Jarva', 'Introdução à Linguagem Java', '10', '29', '2000'), ('6', 'MYSQL', 'Banco de Dados MYSQL', '30', '15', '2016'), ('7', 'Word', 'Curso completo de Word', '40', '30', '2016'), ('8', 'Sapateiro', 'Danças Rítmicas', '40', '30', '2018'), ('9', 'Cozinha Árabe', 'Aprenda a fazer Kebe', '40', '30', '2018'), ('10', 'YouTube', 'Gerar polêmica e ganhar inscritos', '5', '2', '2018'); /*: Este comando atualiza a coluna "nome" da tabela "cursos" para o valor 'HTML5' onde a coluna "idcursos" é igual a '1'. Isso significa que o nome do curso será alterado para 'HTML5' para o curso com ID '1'.*/ update cursos set nome = 'HTML5' where idcursos = '1'; /*Este comando atualiza as colunas "nome" e "ano" da tabela "cursos" para os valores 'PHP' e '2015', respectivamente, onde a coluna "idcursos" é igual a '4'. Isso significa que o nome do curso será alterado para 'PHP' e o ano do curso será alterado para '2015' para o curso com ID '4'.*/ update cursos set nome = 'PHP', ano = '2015' where idcursos = '4'; /*Este comando atualiza as colunas "nome", "carga" e "ano" da tabela "cursos" para os valores 'Java', '40' e '2015', respectivamente, onde a coluna "idcursos" é igual a '5'. A cláusula LIMIT 1 limita a atualização a apenas uma linha, no caso de existirem várias linhas correspondentes à condição.*/ update cursos set nome = 'Java', carga = '40', ano = '2015' where idcursos = '5' limit 1; /*Este comando atualiza as colunas "ano" e "carga" da tabela "cursos" para os valores '2018' e '0', respectivamente, onde a coluna "ano" é igual a '2050'. A cláusula LIMIT 1 limita a atualização a apenas uma linha, no caso de existirem várias linhas correspondentes à condição.*/ update cursos set ano = '2018', carga = '0' where ano = '2050' limit 1; /* Este comando exclui linhas da tabela "cursos" onde a coluna "idcursos" é igual a '8'. Isso significa que o registro correspondente ao ID '8' será removido da tabela.*/ delete from cursos where idcursos = '8'; /*Este comando exclui até duas linhas da tabela "cursos" onde a coluna "ano" é igual a '2050'. A cláusula LIMIT 2 limita a exclusão a no máximo duas linhas correspondentes à condição.*/ delete from cursos where ano = '2050' limit 2; /*Este comando é uma consulta SQL que recupera todas as linhas e colunas da tabela "cursos". O asterisco (*) é um curinga que representa todas as colunas da tabela. Ao executar esse comando, você verá todos os registros da tabela "cursos" e todas as colunas associadas a esses registros.*/ select * from cursos; drop database cadastro;
1. Vérification des Partitions lsblk (= lister les périphériques de bloc) NAME : Le nom du périphérique ou de la partition. MAJ : Les numéros majeurs et mineurs du périphérique. RM : Indicateur de périphérique amovible (1 pour oui, 0 pour non). SIZE : La taille du périphérique ou de la partition. RO : Indicateur de lecture seule (1 pour oui, 0 pour non). TYPE : Le type de périphérique (disk pour un disque dur, part pour une partition, lvm pour un volume logique, etc.). MOUNTPOINT : Le point de montage où la partition est montée dans le système de fichiers. Options Utiles lsblk -f : Affiche les systèmes de fichiers des partitions. lsblk -l : Affiche la sortie sous forme de liste plutôt que de tableau. lsblk -o NAME,SIZE,FSTYPE,MOUNTPOINT : Affiche des colonnes spécifiques (nom, taille, type de système de fichiers, et point de montage). Commandes Complémentaires df -h : Affiche l'espace disque utilisé et disponible sur les systèmes de fichiers. fdisk -l : Liste les tables de partition. blkid : Affiche les identifiants des systèmes de fichiers et les types de systèmes de fichiers. 2. Configurating Your Virtual Machine 2.1. Installing Sudo su - su = (swich user) changer d'utilisateur dans un terminal. Sans argument, elle change pour l'utilisateur root par défaut. - : L'option - (ou --login) fait que l'environnement de l'utilisateur cible (ici root) est initialisé comme s'il s'agissait d'une nouvelle connexion. Cela inclut la mise à jour des variables d'environnement, le répertoire de travail et les chemins d'accès. => Effectuer des configurations nécessitant des privilèges administratifs (= effectuer des modifications critiques sur le système) Cela peut inclure des tâches comme : Création et gestion de partitions. Configuration des services systèmes comme SSH, UFW (pare-feu), etc. Installation et configuration de logiciels. apt-get update -y apt-get update : Mettre à jour la liste des paquets disponibles (apt = Advanced Package Tool) dans les dépôts logiciels configurés sur votre système Debian. => votre système contacte les dépôts de logiciels configurés pour obtenir la liste actuelle des paquets disponibles. Cette liste est ensuite stockée localement sur votre système pour que le gestionnaire de paquets puisse l'utiliser pour les futures opérations d'installation, de mise à niveau ou de suppression de logiciels. Garantir la Fraîcheur des Informations : M'assure que votre système utilise les informations les plus récentes sur les paquets disponibles. -y : L'option -y permet d'automatiser le processus de MaJ en répondant automatiquement "oui" à toutes les questions posées par la commande. Cela est utile lorsque vous exécutez la commande dans un script ou lorsque vous voulez éviter les interruptions lors de la mise à jour régulière de votre système. apt-get upgrade -y Mettre à niveau tous les paquets installés sur votre système Debian vers leurs versions les plus récentes disponibles dans les dépôts logiciels configurés. => Mise à Jour des Paquets : Lorsque de nouvelles versions de logiciels sont disponibles dans les dépôts, apt-get upgrade met à jour les paquets installés sur votre système avec ces nouvelles versions. Cela permet de garantir que votre système utilise les dernières fonctionnalités, correctifs de bugs et améliorations de sécurité. Sécurité : Les mises à jour de sécurité sont souvent incluses dans les nouvelles versions des logiciels. En exécutant régulièrement apt-get upgrade, vous vous assurez que votre système est protégé contre les vulnérabilités connues. Stabilité : Les mises à jour de logiciels peuvent également inclure des correctifs de bugs qui améliorent la stabilité et les performances de votre système. apt install sudo Installer le programme sudo sur votre système. sudo (abréviation de "SuperUser Do") => permet à un utilisateur d'exécuter des commandes avec les privilèges d'un autre utilisateur, généralement l'utilisateur root. nstaller sudo est généralement une étape importante lors de la configuration d'un nouveau système Linux, car cela permet de mettre en place un système d'administration sécurisé et de limiter l'utilisation directe du compte root, ce qui peut réduire les risques de sécurité. usermod -aG sudo your_username usermod : commande utilisée pour modifier les attributs d'un utilisateur. -aG sudo : option de la commande usermod qui ajoute l'utilisateur spécifié au groupe sudo. -a signifie "append" (ajouter), et -G spécifie le groupe. your_username : C'est le nom de l'utilisateur auquel vous souhaitez accorder des privilèges d'administration avec sudo. => l'utilisateur spécifié pourra utiliser sudo pour exécuter des commandes avec les privilèges d'administration. Cela permet de limiter l'utilisation directe du compte root, ce qui est généralement considéré comme une pratique plus sécurisée. Commandes Complémentaires (pour verif) getent group sudo : Affiche les informations du groupe sudo. groups your_username : Affiche les groupes auxquels appartient un utilisateur spécifique, y compris le groupe sudo s'il y est ajouté.
"use client"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { format } from "date-fns"; import { Calendar as CalendarIcon } from "lucide-react"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { Calendar } from "@/components/ui/calendar"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Textarea } from "@/components/ui/textarea"; const InputForm = ({ onChange, form, setForm, onSubmit, title, method }) => { return ( <form method={method} onSubmit={onSubmit} className="bg-white rounded-md text-black p-4 space-y-6" > <h1 className="text-4xl font-medium text-center">{title}</h1> <div className="text-lg space-y-4"> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8"> <Label htmlFor="name" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0" > Nama Lengkap </Label> <Input required value={form.name} onChange={onChange} type="text" id="name" name="name" placeholder="nama lengkap" className="basis-auto" /> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="name_baptis" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0" > Nama Baptis </Label> <Input required value={form.name_baptis} onChange={onChange} type="text" id="name_baptis" name="name_baptis" placeholder="nama baptis" className="basis-auto" /> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="tempat_lahir" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0" > Tempat Lahir </Label> <Input required value={form.tempat_lahir} onChange={onChange} type="text" id="tempat_lahir" name="tempat_lahir" placeholder="tempat lahir" className="basis-auto" /> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="tanggal_lahir" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0.5" > Tanggal Lahir </Label> <div className="basis-full -ml-0.5"> <Popover> <PopoverTrigger asChild> <Button variant={"outline"} className={cn( "w-[280px] justify-start text-left font-normal", !new Date(form.tanggal_lahir) && "text-muted-foreground" )} > <CalendarIcon className="mr-2 h-4 w-4" /> {form.tanggal_lahir ? ( format(new Date(form.tanggal_lahir), "PPP") ) : ( <span>Pick a date</span> )} </Button> </PopoverTrigger> <PopoverContent className="w-auto p-0"> <Calendar captionLayout="dropdown-buttons" fromYear={1990} toYear={2008} mode="single" selected={new Date(form.tanggal_lahir)} onSelect={(val) => setForm((prev) => ({ ...prev, tanggal_lahir: new Date(val).getTime(), })) } initialFocus /> </PopoverContent> </Popover> </div> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="name_ayah" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0" > Nama ayah </Label> <Input required value={form.name_ayah} onChange={onChange} type="text" id="name_ayah" name="name_ayah" placeholder="nama ayah" className="basis-auto" /> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="name_ibu" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0" > Nama Ibu </Label> <Input required value={form.name_ibu} onChange={onChange} type="text" id="name_ibu" name="name_ibu" placeholder="nama ayah" className="basis-auto" /> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="jenis_kelamin" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0.5" > Jenis Kelamin </Label> <div className="basis-full -ml-0.5"> <Select value={form.jenis_kelamin} onValueChange={(val) => setForm((prev) => ({ ...prev, jenis_kelamin: val, })) } > <SelectTrigger className="w-[180px]"> <SelectValue placeholder="Pilih Jenis Kelamin" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectLabel>Jenis Kelamin</SelectLabel> <SelectItem value="PRIA">Pria</SelectItem> <SelectItem value="WANITA">Wanita</SelectItem> </SelectGroup> </SelectContent> </Select> </div> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="jenis_baptis" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0.5" > Jenis Baptis </Label> <div className="basis-full -ml-0.5"> <Select required value={form.jenis_baptis} onValueChange={(val) => setForm((prev) => ({ ...prev, jenis_baptis: val })) } > <SelectTrigger className="w-[180px]"> <SelectValue placeholder="Pilih Jenis Baptis" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectLabel>Jenis Baptis</SelectLabel> <SelectItem value="ANAK">Anak</SelectItem> <SelectItem value="DEWASA">Dewasa</SelectItem> </SelectGroup> </SelectContent> </Select> </div> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="no_anggota" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0" > No Anggota </Label> <Input required value={form.kode_anggota} onChange={onChange} type="text" id="no_anggota" name="kode_anggota" placeholder="No Anggota" className="basis-auto" /> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="alamat" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0" > Alamat </Label> <Textarea required value={form.alamat} onChange={onChange} type="text" id="alamat" name="alamat" placeholder="Alamat" className="basis-auto" /> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-y-4 gap-x-8 "> <Label htmlFor="no_hp" className="basis-2/5 relative after:content-[''] sm:after:content-[':'] after:absolute after:right-0" > No Telepon </Label> <Input required value={form.no_hp} onChange={onChange} type="number" id="no_hp" name="no_hp" placeholder="No Telepon" className="basis-auto" /> </div> </div> <div className="flex justify-end"> <Button type="submit">Submit Permohonan</Button> </div> </form> ); }; export default InputForm;
import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { BeatLoader } from 'react-spinners'; import './OpdFootfall.css'; import { Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material'; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts'; // import showGraph from '../../Assests/Images/showGraph.svg' function OpdDoctorwise() { // const tokenNo = process.env.REACT_APP_TOKEN_NO; const tokenNo = localStorage.getItem('tokenNo'); const DASHBOARD_URL = process.env.REACT_APP_DASHBOARD_URL; const [loading, setLoading] = useState(true); const [data, setData] = useState([]); const [dates, setDates] = useState([]); const [selectedDoctor, setSelectedDoctor] = useState(null); useEffect(() => { axios .get(`${DASHBOARD_URL}/adhocapi/dashboard/footfall/doctor?type=OP`,{ headers: { Authorization: `Bearer ${tokenNo}`} }) .then(response => { const responseData = response.data.data; const totalDates = Object.keys(responseData[0]).filter(key => key !== 'empId' && key !== 'empName'); setDates(totalDates); const updatedData = responseData.map(doct => { const grandTotal = totalDates.reduce((total, date) => total + (doct[date] || 0), 0); return { ...doct, 'Grand Total': grandTotal }; }); setData(updatedData); setLoading(false); // Data fetching is complete }) .catch(error => { console.error('Error fetching data:', error); setLoading(false); // Stop loader in case of error }); }, []); const handleOpenDialog = (doctor) => { setSelectedDoctor(doctor); }; const handleCloseDialog = () => { setSelectedDoctor(null); }; const renderRows = () => { return data.map((row, index) => { return ( <tr key={index}> <td>{row.empName}</td> {dates.map(date => ( <td key={date}>{row[date] || '0'}</td> ))} <td>{row['Grand Total']}</td> <td> <span style={{cursor:'pointer'}} role="img" aria-label="Show Graph" onClick={() => handleOpenDialog(row)}>📊</span> {/* <img style={{height:'20px', width:'20px'}} src={showGraph} alt="Show Graph" onClick={() => handleOpenDialog(row)} /> */} </td> </tr> ); }); }; const DoctorLineChart = ({ data }) => { return ( <LineChart width={900} height={300} data={data} margin={{ top: 20, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="2 2" /> <XAxis dataKey="date" /> <YAxis /> <Tooltip /> <Legend /> <Line type="monotone" dataKey="count" stroke="#8884d8" activeDot={{ r: 8 }} /> </LineChart> ); }; return ( <div> {loading ? ( <div className="loader-container"> <BeatLoader color="#2190B9" /> </div> ) : ( <div> <table className='MainTable'> <thead> <tr> <th>Doctor Name</th> {dates.map(date => ( <th key={date}>{date}</th> ))} <th>Grand Total</th> <th>Show Graph</th> </tr> </thead> <tbody>{renderRows()}</tbody> </table> <Dialog maxWidth="lg" open={selectedDoctor !== null} onClose={handleCloseDialog}> <DialogTitle className='DialogTitle'>Graph for {selectedDoctor && selectedDoctor.empName}</DialogTitle> <DialogContent> {selectedDoctor && <DoctorLineChart data={dates.map(date => ({ date, count: selectedDoctor[date] || 0 }))} />} </DialogContent> <DialogActions> <Button onClick={handleCloseDialog}>Close</Button> </DialogActions> </Dialog> </div> )} </div> ); } export default OpdDoctorwise;
#!/usr/bin/python # @version : 1.0 # @Create Time : 2023/6/21 10:08 # @File : mian.py # @IDE : PyCharm # @desc : 测试任务 import asyncio import datetime class Test: def __init__(self, name: str, age: int): self.name = name self.age = age async def main(self, *args, **kwargs) -> str: """ 主入口函数 :return: """ now_datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(f"{now_datetime}, 定时任务测试实例,实例参数为: {self.name}, {self.age}") # 增加异步耗时 await asyncio.sleep(2) print(f"{now_datetime}, 定时任务测试实例,方法参数为: {args}, {kwargs}") return "任务执行完成" if __name__ == "__main__": # 调试任务脚本,测试任务脚本功能 # 推荐使用 PyCharm 执行, 执行时需设置工作目录为 kinit-fast-task 为根目录 # 直接执行该脚本, 最方便的调试任务方法: # - 确保执行工作目录为项目根目录:kinit-fast-task task = Test(name="kinit-fast-task", age=2) asyncio.run(task.main())
package gothumb import ( "context" "image" "image/jpeg" "log" "net/http" "os" "strconv" "time" "cloud.google.com/go/storage" "github.com/GoogleCloudPlatform/functions-framework-go/functions" "github.com/cloudevents/sdk-go/v2/event" "github.com/disintegration/imaging" "google.golang.org/api/googleapi" ) const quality = 85 var client *storage.Client var maxSize int var destination string type StorageObjectData struct { Bucket string `json:"bucket,omitempty"` Name string `json:"name,omitempty"` Metageneration int64 `json:"metageneration,string,omitempty"` TimeCreated time.Time `json:"timeCreated,omitempty"` Updated time.Time `json:"updated,omitempty"` ContentType string `json:"content-type,omitempty"` } func init() { var err error var ok bool if client, err = storage.NewClient(context.Background()); err != nil { log.Fatalf("storage.NewClient: %v", err) os.Exit(1) } if size, ok := os.LookupEnv("MAX_SIZE"); !ok { log.Fatalf("No MAX_SIZE given") } else { maxSize, _ = strconv.Atoi(size) } if destination, ok = os.LookupEnv("THUMBNAILS"); !ok { log.Fatalf("No THUMBNAILS given") os.Exit(1) } functions.CloudEvent("Make", make2) functions.CloudEvent("Remove", remove2go) } func eventData(e event.Event) StorageObjectData { log.Printf("Event ID: %s", e.ID()) log.Printf("Event Type: %s", e.Type()) var data StorageObjectData if err := e.DataAs(&data); err != nil { log.Printf("event.DataAs: %v", err) } log.Printf("Bucket: %s", data.Bucket) log.Printf("Name: %s", data.Name) log.Printf("ContentType: %s", data.ContentType) return data } func make2(ctx context.Context, e event.Event) error { data := eventData(e) inputBlob := client.Bucket(data.Bucket).Object(data.Name) outputBlob := client.Bucket(destination).Object(data.Name).If(storage.Conditions{DoesNotExist: true}) attr, err := inputBlob.Attrs(ctx) if err != nil { log.Printf("inputBlob attribute error: %v", err) } _, err = outputBlob.Attrs(ctx) if err != nil { // always returns error with Preconditions switch ee := err.(type) { case *googleapi.Error: if ee.Code == http.StatusPreconditionFailed { log.Printf("Precondition failed, outputBlob exists %v\n", ee.Code) os.Exit(0) } default: log.Printf("continue %v\n", ee) } } r, err := inputBlob.NewReader(ctx) if err != nil { log.Printf("Bucket reader error: %v", err) } defer r.Close() im, _, err := image.DecodeConfig(r) if err != nil { log.Printf("DecodeConfig image: %v", err) } // log.Printf("Width, Height: %v, %v", im.Width, im.Height) r, err = inputBlob.NewReader(ctx) if err != nil { log.Printf("Bucket reader error: %v", err) } defer r.Close() img, _, err := image.Decode(r) if err != nil { log.Printf("Decode image: %v", err) } var newImage image.Image if im.Width >= im.Height { newImage = imaging.Resize(img, maxSize, 0, imaging.Lanczos) } else { newImage = imaging.Resize(img, 0, maxSize, imaging.Lanczos) } var opts jpeg.Options opts.Quality = quality w := outputBlob.NewWriter(ctx) err = jpeg.Encode(w, newImage, &opts) if err != nil { log.Printf("outputBlob writer error %v", err) } objectAttrsToUpdate := storage.ObjectAttrsToUpdate{ Metadata: map[string]string{ "CacheControl": attr.CacheControl, "ContentType": data.ContentType, }, } if _, err := outputBlob.Update(ctx, objectAttrsToUpdate); err != nil { log.Printf("outputBlob attributes update error: %v", err) } if err := w.Close(); err != nil { log.Printf("Writer close error: %v", err) } return nil } func remove2go(ctx context.Context, e event.Event) error { data := eventData(e) blob := client.Bucket(destination).Object(data.Name).If(storage.Conditions{DoesNotExist: false}) if err := blob.Delete(ctx); err != nil { switch ee := err.(type) { case *googleapi.Error: if ee.Code == http.StatusPreconditionFailed { log.Printf("Precondition failed, outputBlob does not exists %v\n", ee.Code) os.Exit(0) } default: // log.Printf("continue %v\n", ee) log.Printf("outputBlob delete error: %v", err) } } return nil } /* cd ~/work/andsnews/functions/thumbnail gcloud functions deploy make2go \ --gen2 \ --runtime=go119 \ --entry-point="make2go" \ --trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \ --trigger-event-filters="bucket=andsnews.appspot.com" \ --set-env-vars="MAX_SIZE=400" \ --set-env-vars="THUMBNAILS=thumbnails400" \ --trigger-location="us" \ --region="us-central1" gcloud functions deploy remove2go \ --gen2 \ --runtime=go119 \ --entry-point="remove2go" \ --trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \ --trigger-event-filters="bucket=andsnews.appspot.com" \ --set-env-vars="THUMBNAILS=thumbnails400" \ --trigger-location="us" \ --region="us-central1" */
//! Helper types for producing stable [`egui::Id`] for the purpose of handling collapsed state of //! various UI elements. use std::hash::Hash; use re_log_types::EntityPath; use crate::{ContainerId, SpaceViewId}; /// The various scopes for which we want to track collapsed state. #[derive(Debug, Clone, Copy, Hash)] pub enum CollapseScope { /// Stream tree from the time panel StreamsTree, /// Blueprint tree from the blueprint panel BlueprintTree, } impl CollapseScope { const ALL: [CollapseScope; 2] = [CollapseScope::StreamsTree, CollapseScope::BlueprintTree]; // convenience functions /// Create a [`CollapsedId`] for a container in this scope. pub fn container(self, container_id: ContainerId) -> CollapsedId { CollapsedId { item: CollapseItem::Container(container_id), scope: self, } } /// Create a [`CollapsedId`] for a space view in this scope. pub fn space_view(self, space_view_id: SpaceViewId) -> CollapsedId { CollapsedId { item: CollapseItem::SpaceView(space_view_id), scope: self, } } /// Create a [`CollapsedId`] for a data result in this scope. pub fn data_result(self, space_view_id: SpaceViewId, entity_path: EntityPath) -> CollapsedId { CollapsedId { item: CollapseItem::DataResult(space_view_id, entity_path), scope: self, } } /// Create a [`CollapsedId`] for an entity in this scope. pub fn entity(self, entity_path: EntityPath) -> CollapsedId { CollapsedId { item: CollapseItem::Entity(entity_path), scope: self, } } } /// The various kinds of items that may be represented and for which we want to track the collapsed /// state. #[derive(Debug, Clone, Hash)] pub enum CollapseItem { Container(ContainerId), SpaceView(SpaceViewId), DataResult(SpaceViewId, EntityPath), Entity(EntityPath), } impl CollapseItem { /// Set the collapsed state for the given item in every available scopes. pub fn set_open_all(&self, ctx: &egui::Context, open: bool) { for scope in CollapseScope::ALL { let id = CollapsedId { item: self.clone(), scope, }; id.set_open(ctx, open); } } } /// A collapsed identifier. /// /// A `CollapsedId` resolves into a stable [`egui::Id`] for a given item and scope. #[derive(Debug, Clone, Hash)] pub struct CollapsedId { item: CollapseItem, scope: CollapseScope, } impl From<CollapsedId> for egui::Id { fn from(id: CollapsedId) -> Self { egui::Id::new(id) } } impl CollapsedId { /// Convert to an [`egui::Id`]. pub fn egui_id(&self) -> egui::Id { self.clone().into() } /// Check the collapsed state for the given [`CollapsedId`]. pub fn is_open(&self, ctx: &egui::Context) -> Option<bool> { egui::collapsing_header::CollapsingState::load(ctx, self.egui_id()) .map(|state| state.is_open()) } /// Set the collapsed state for the given [`CollapsedId`]. pub fn set_open(&self, ctx: &egui::Context, open: bool) { let mut collapsing_state = egui::collapsing_header::CollapsingState::load_with_default_open( ctx, self.egui_id(), false, ); collapsing_state.set_open(open); collapsing_state.store(ctx); } }
<!-- <table> organização de dados, criando tabelas. Prós Visualização de dados via linhas e colunas. Boa acessibilidade para leitura dos dados Contras Pouco flexível Precisa de estilização para melhor visualização Não usar Para criar seu layout --> <!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"> <meta name="description" content="Aqui eu aprendi a fazer uma tabela que usou elementos CSS para melhorar a organização."> <meta name="robots" content="nofollow, index "> <!-- noindex // follow (padrão é index e follow) --> <link rel="icon" href="icon/icon-48x48.png?v=cfca599cb367"/> <title>tabelas</title> </head> <body> <!--Book: tr= Linha (row= linha); th= Cabeçalho; td= Descrição/Conteúdo do tr--> <p> <table> <caption>Pessoas / Idade:</caption> <thead> <tr> <th>Nome</th> <th>Idade</th> </tr> </thead> <tbody> <tr> <td>Rapha</td> <td>18</td> </tr> <tr> <td>Gabriel</td> <td>18</td> </tr> </tbody> <tfoot> <tr> <td>Total:</td> <td>2 pessoas</td> </tr> </tfoot> </table> </p> <!--Tabela Complexa--> <p> <table> <caption>Produtos Produzidos X Vendidos</caption> <colgroup> <col> <col span="2" style="background-color: yellow;"> <col span="2" style="background-color: pink;"> </colgroup> <thead> <tr> <th rowspan="2"></th> <th colspan="2" scope="colgroup">GBarbosa</th> <th colspan="2" scope="colgroup">Magazine Luiza</th> </tr> <tr> <th scope="col">Produzidos</th> <th scope="col">Vendidos</th> <th scope="col">Produzidos</th> <th scope="col">Vendidos</th> </tr> </thead> <tbody> <tr> <th scope="row">Vassouras:</th> <td>50</td> <td>40</td> <td>25</td> <td>10</td> </tr> <tr> <th>Tesouras:</th> <td>100</td> <td>80</td> <td>250</td> <td>180</td> </tr> </tbody> </table> </p> </body> </html>
<?php namespace Database\Factories; use App\Subcategory; use Illuminate\Database\Eloquent\Factories\Factory; class SubcategoryFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Subcategory::class; /** * Define the model's default state. * * @return array */ public function definition() { $title = $this->faker->unique()->randomElement(['Water Purifiers','Refrigerators', 'Washing Machine','Air Conditioners','Vacuum Cleaner','Steam Cleaning','Washer & Dryer', 'Rice Cookers','Fans','Microwave Oven','Tour Drinkware','Hatch Drinkware','Direction Drinkware', 'Crescent Drinkware','Armchairs','Bunk Bed','Mattress','Sideboard','Cookware Brands','Cookware Sets', 'Individual Cookware','Enamel Cookware' ]); return [ 'title'=>ucwords(strtolower($title)), 'category_id'=>$this->faker->numberBetween(1,3), 'slug'=>slugify($title), ]; } }
package it.unibo.mvc; import it.unibo.mvc.api.DrawNumberController; import it.unibo.mvc.api.DrawNumberView; import it.unibo.mvc.controller.DrawNumberControllerImpl; import it.unibo.mvc.model.DrawNumberImpl; import it.unibo.mvc.view.DrawNumberStdoutView; import it.unibo.mvc.view.DrawNumberSwingView; import java.lang.reflect.InvocationTargetException; import java.util.List; /** * Application entry-point. */ public final class LaunchApp { private LaunchApp() { } /** * Runs the application. * * @param args ignored * @throws ClassNotFoundException if the fetches class does not exist * @throws NoSuchMethodException if the 0-ary constructor do not exist * @throws InvocationTargetException if the constructor throws exceptions * @throws InstantiationException if the constructor throws exceptions * @throws IllegalAccessException in case of reflection issues * @throws IllegalArgumentException in case of reflection issues */ public static void main(final String... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { final var model = new DrawNumberImpl(); final DrawNumberController app = new DrawNumberControllerImpl(model); for (final var viewType: List.of("Stdout", "Swing")) { final var classi = Class.forName("it.unibo.mvc.view.DrawNumber" + viewType + "View"); for (int i = 0; i < 3; i++) { final var newView = classi.getConstructor().newInstance(); if (DrawNumberView.class.isAssignableFrom(newView.getClass())) { app.addView((DrawNumberView) newView); } else { throw new IllegalStateException( newView.getClass() + " is not a subclass of " + DrawNumberView.class ); } } } } }
<?php /** * The theme header * * @package bootstrap-basic * Template Name: Halaman Book Detail */ get_header(); $sosmed_url = get_option('social_options','null'); setPostViews(get_the_ID()); $att = get_post(get_the_ID()); $meta = get_post_meta(get_the_ID()); $comments = get_comments( array( 'post_id' => get_the_ID(), 'number' => 100 )); $count_comment = count($comments); $image = get_field('image'); $image_url = $image['url']; $video_meta = get_post_meta(get_the_ID()); // $video_url = $video_meta['url'][0].'?autoplay=0'; setPostViews(get_the_ID()); // $terms = get_the_terms($att->ID,'book_type'); $date = date_create(); $date_now = $date->format('Ymd'); //Article $news = get_field('related_news'); if(is_array($news)){ $article_list = array_splice($news, 0,3); } //Article $palbar = get_field('related_palbar'); if(is_array($palbar)){ $palbar_list = array_splice($palbar, 0,3); } // print_r($article_list);exit(); //Article $banner_image = get_field('banner_image'); $banner_link = get_field('banner_link'); ?> <!-- begin top section --> <header> <div class="top-header"> <div class="container"> <div class="pull-left"> <a href="/" class="logo"><img src="<?php echo get_template_directory_uri() ?>/img/logo.png" /></a> </div> <div class="pull-left"> <ul class="link-social small"> <li> <a href="<?php echo $sosmed_url['facebook']; ?>" class="fb-ico"> <i class="fa fa-facebook"></i> </a> </li> <li> <a href="<?php echo $sosmed_url['youtube']; ?>" class="youtube-ico"> <i class="fa fa-youtube"></i> </a> </li> <li> <a href="<?php echo $sosmed_url['twitter']; ?>" class="twitter-ico"> <i class="fa fa-twitter"></i> </a> </li> <li> <a href="<?php echo $sosmed_url['instagram']; ?>" class="instagram-ico"> <i class="fa fa-instagram"></i> </a> </li> </ul> </div> <div class="pull-right"> <!-- <input type="search" id="form-search-input" class="form-control" placeholder="Search …" value="" name="s" title="Search for:"> --> <form role="search" method="get" class="search-top" action="/"> <input type="search" id="form-search-input" class="form-control" placeholder="Cari..." value="" name="s" title="Search for:" /> <button type="submit"><i class="fa fa-search"></i></button> </form> </div> </div> </div> <div id="sticky-anchor"></div> <nav id="sticky" class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div id="navbar" class="navbar-collapse collapse" aria-expanded="false" style="height: 1px;"> <?php wp_nav_menu( array( 'menu' => 'primary', 'theme_location' => 'primary', 'depth' => 2, 'container' => 'div', // 'container_class' => 'collapse navbar-collapse', // 'container_id' => 'bs-example-navbar-collapse-1', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => 'wp_bootstrap_navwalker::fallback', 'walker' => new wp_bootstrap_navwalker()) ); ?> </div> <!--/.nav-collapse --> </div> <?php // echo wp_nav_menu(array('echo' => false,'theme_location' => 'primary', 'container' => false, 'container_class' => false, 'menu_class' => 'navigation-list list-unstyled', 'walker' => new BootstrapBasicMyWalkerNavMenu())); ?> </nav> </header> <!-- end of top section --> <section id="content"> <div class="container"> <div class="clearfix row"> <div class="col-md-8"> <div class="whitebox berita-box height-auto margintop-min15"> <div class="row"> <div class="col-md-12"> <div class="panel-title left-title"> Dari Palbar </div> <h2 class="main-title"><?php echo $att->post_title; ?></h2> <div class="center"> <h5 class="quote-italic"><?php echo get_field('quote'); ?></h5> </div> <img src="<?php echo $image_url; ?>" class="full-width" /> <p class="center"><?php echo get_field('image_caption'); ?></p> <div class="description"> <p><?php echo $att->post_content; ?></p> <hr> <div class="center"> <h5>Share this Article:</h5> <div class="join-social share-article no-margin"> <a href="" class="fb-btn"><i class="fa fa-facebook" oncontextmenu="return false;" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=<?php echo $_SERVER['HTTP_HOST'].get_permalink(); ?>', 'newwindow', 'width=300, height=250');"></i></a> <a href="" class="twitter-btn"><i class="fa fa-twitter" onclick="window.open('https://twitter.com/share', 'newwindow', 'width=400, height=350');" data-count="none"></i></a> <a href="http://pinterest.com/pin/create/button/?url=<?php echo $_SERVER['HTTP_HOST'].get_permalink(); ?>%2f&description=Static%20social%20media%20%22share%22%20buttons&media=<?php echo $_SERVER['HTTP_HOST'].$front_cover_url; ?>" target="_blank" class="pinterest-btn"><i class="fa fa-pinterest"></i></a> <a href="whatsapp://send?text=You must look this!" class="whatsapp-btn"><i class="fa fa-whatsapp"></i></a> </div> </div> <?php if(is_array($article_list)): ?> <div class="panel-title margintop-50"> Artikel Lainnya </div> <ul class="more-article clearfix row"> <!-- loop --> <?php foreach ($article_list as $key => $value) { ?> <a href="<?php echo get_permalink($value->ID); ?>"> <li class="clearfix berita-list col-md-4"> <div class="clearfix box-img"><?php echo get_the_post_thumbnail($value->ID,'full'); ?></div> <div class="clearfix box-info"> <h2><?php echo $value->post_title; ?></h2> <p> <?php echo strip_tags(wp_trim_words($value->post_content,15,'')); ?> </p> </div> </li> </a> <?php } ?> <!-- loop --> </ul> <?php endif; ?> </div> </div> </div> </div> <div class="whitebox berita-box height-auto"> <div class="panel-title"> Pembicaraan </div> <div class="comment-list text-left margintop-30"> <div class="clearfix"> <h2 class="pull-left"><?php echo $count_comment; ?> Comments</h2> <div class="pull-right"> <span>Urut Berdasarkan:</span> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"> Komentar Terbaru <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="#">HTML</a></li> <li><a href="#">CSS</a></li> <li><a href="#">JavaScript</a></li> </ul> </div> </div> </div> <hr> <ul class="clearfix comments"> <!-- form comment --> <li class="clearfix"> <?php $fields = array(); if(!is_user_logged_in()){ $fields = array( 'author' => '<input type="text" id="author" name="author" class="name-from" placeholder="Your Name..." value="" />', 'email' => '<input type="text" id="email" name="email" class="email-from" placeholder="Your Email..." value="" />', 'url' => '<input id="url" name="url" type="hidden" value=""/>', ); $photo = '<img src="'.get_template_directory_uri().'/img/unknown.png">'; } else{ $current_user = wp_get_current_user(); // echo "<pre>"; print_r();exit(); $photo = get_avatar($current_user->ID,64); } ?> <div class="photo-wrapper"><?php echo $photo; ?></div> <div class="comment-wrapper"> <div class="widget-area no-padding blank"> <div class="status-upload"> <?php $args = array( 'id_form' => 'commentform', 'class_form' => 'comment-form', 'id_submit' => 'submit', 'class_submit' => 'btn btn-yellow', 'name_submit' => 'submit', 'title_reply' => '', 'title_reply_to' => __( 'Leave a Reply to %s' ), 'cancel_reply_link' => __( 'Cancel Reply' ), 'label_submit' => __( 'Comment' ), 'format' => 'xhtml', 'fields' => apply_filters( 'comment_form_default_fields', $fields ), 'comment_field' => '<textarea id="comment" name="comment" placeholder="Add Comment…"></textarea>', 'must_log_in' => '<p class="must-log-in">' . sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink() ) ) ) . '</p>', 'logged_in_as' => '', 'comment_notes_before' => '', 'comment_notes_after' => '', ); comment_form($args, get_the_ID()); ?> </div> </div> </div> </li> <!-- form comment --> <?php foreach ($comments as $key => $value) { $date = date_create($value->comment_date); $formated_date = $date->format('F j').' at '.$date->format('H:i'); ?> <li class="clearfix"> <div class="photo-wrapper"><?php echo get_avatar($value->user_id); ?></div> <div class="comment-wrapper"> <div class="widget-area no-padding blank"> <div class="status-upload"> <div class="panel-body"> <header class="text-left"> <div class="comment-user"><i class="fa fa-user"></i> <?php echo $value->comment_author; ?></div> <time class="comment-date" datetime="16-12-2014 01:05"><i class="fa fa-clock-o"></i> <?php echo $formated_date; ?></time> </header> <div class="comment-post"> <p> <?php echo $value->comment_content; ?> </p> </div> </div> </div> <!-- Status Upload --> </div> <!-- Widget Area --> </div> </li> <?php } ?> </ul> </div> </div> </div> <!-- Righ Content --> <div class="col-md-4"> <?php if(is_array($palbar_list)){ foreach ($palbar_list as $key => $value) { $event_meta = get_post_meta($value->ID); $tags = wp_get_post_tags($value->ID); $image = get_field('image',$value->ID); ?> <a href="<?php echo get_permalink($value->ID); ?>"> <div class="whitebox berita-box height-auto"> <div class="panel-title"> Artikel Lainnya </div> <div class="berita-list"> <span class="image"> <img src="<?php echo $image['url']; ?>"> </span> <h2 class="margintop-20"><?php echo $value->post_title; ?></h2> </div> <hr> </div> </a> <?php }} ?> <?php if(is_array($banner_image)): ?> <div class="whitebox"> <a href="<?php echo $banner_link; ?>" target="_blank"><img class="full-width" src="<?php echo $banner_image['url']; ?>"></a> </div> <?php endif; ?> </div> <!-- Righ Content --> </div> </div> </section> <?php add_action('wp_footer', 'JSforHome'); ?> <?php get_footer(); ?>
<div class="kt-content kt-grid__item kt-grid__item--fluid" id="kt_content"> <div class="row"> <div class="col-md-12"> <!--begin::Portlet--> <div class="kt-portlet"> <div class="kt-portlet__head"> <div class="kt-portlet__head-label"> <h3 class="kt-portlet__head-title"> Add Deal Type </h3> </div> </div> <!--begin::Form--> <form class="kt-form kt-form--label-right" [formGroup]="dealForm"> <div class="kt-portlet__body"> <div class="form-group row"> <div class="col-6"> <label for="example-number-input" class="col-form-label">Deal Type</label> <div> <input class="form-control" type="text" id="example-text-input" formControlName="deal" placeholder="Enter Deal Type" [ngClass]="{ 'is-invalid': submitted && dealForm.controls['deal'].errors }"> <div *ngIf="submitted && dealForm.controls['deal'].errors" class="invalid-feedback"> <div *ngIf="dealForm.controls['deal'].errors.required">Deal Type is required</div> </div> </div> </div> </div> </div> <div class="kt-portlet__foot"> <div class="kt-form__actions"> <div class="row"> <div class="col-2"> </div> <div class="col-10"> <button type="submit" class="btn btn-success" (click)="addDealType()">Add</button> </div> </div> </div> </div> </form> </div> <!--end::Portlet--> </div> </div> </div> <div class="row"> <div class="col-md-12"> <kt-portlet [class]="'kt-portlet--height-fluid'"> <kt-portlet-header [title]="'Deal Type Table'" [class]="'kt-portlet__head--lg kt-portlet__head--noborder kt-portlet__head--break-sm'"> <ng-container ktPortletTools> </ng-container> </kt-portlet-header> <kt-portlet-body [class]="'kt-portlet__body--fit'"> <table mat-table [dataSource]="dataSource" class="mat-elevation-z8" *ngIf="dealLoaded | async"> <!-- Checkbox Column --> <ng-container matColumnDef="select"> <th mat-header-cell *matHeaderCellDef> <mat-checkbox (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()" [indeterminate]="selection.hasValue() && !isAllSelected()" [aria-label]="checkboxLabel()"> </mat-checkbox> </th> <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null" [checked]="selection.isSelected(row)" [aria-label]="checkboxLabel(row)"> </mat-checkbox> </td> </ng-container> <!-- Position Column --> <ng-container matColumnDef="position"> <th mat-header-cell *matHeaderCellDef> No. </th> <td mat-cell *matCellDef="let element; let i = index;"> {{i+1}} </td> </ng-container> <!-- Name Column --> <ng-container matColumnDef="deal"> <th mat-header-cell *matHeaderCellDef> Deal Type </th> <td mat-cell *matCellDef="let element"> {{element.deal_type}} </td> </ng-container> <ng-container matColumnDef="actions"> <th mat-header-cell *matHeaderCellDef width="106px" class="kt-pl-13"> Actions </th> <td mat-cell *matCellDef="let element; let idx = index"> <button mat-icon-button color="primary" matTooltip="Edit item" class="position-static edit-button" (click)="openEditDialog(element)"> <mat-icon>create</mat-icon> </button> <button mat-icon-button color="warn" type="button" matTooltip="Delete item" class="position-static delete-button" (click)="openDeleteDialog(element)"> <mat-icon>delete</mat-icon> </button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"> </tr> </table> <mat-paginator [pageSizeOptions]="[10,25,50]" showFirstLastButtons></mat-paginator> </kt-portlet-body> </kt-portlet> </div> </div> <!-- end:: Content -->
#pragma once #include "Domain.h" #include <vector> #include <sstream> #include <fstream> using std::vector; class Repo { private: vector<Student> list; string FilePath; public: Repo(string FilePath) : FilePath{ FilePath } {}; vector<Student>& getAllRepo(); /* returneaza vectrot<student> = studentii din lista */ void deleteRepo(int matricol); /* functie de stergere sterge din list , student cu nr matricol */ void addRepo(Student s); /* functie adaugare adauga student s in list */ void readAllFromFile(); /* citire din fisier */ void writeAllToFile(); /* afisare modificari in fisier */ void setAgeRepo(bool op); /* incrementeaza sau decrementeaza varsta studentilor in functie de val op true = inc false = dec */ };
package cn.iocoder.yudao.module.ai.controller.admin.app.vo; import io.swagger.v3.oas.annotations.media.Schema; import lombok.*; import java.time.LocalDateTime; import com.alibaba.excel.annotation.*; @Schema(description = "管理后台 - 应用 Response VO") @Data @ExcelIgnoreUnannotated public class AppRespVO { @Schema(description = "自增主键", requiredMode = Schema.RequiredMode.REQUIRED, example = "30871") @ExcelProperty("自增主键") private Long id; @Schema(description = "应用名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "赵六") @ExcelProperty("应用名称") private String name; @Schema(description = "头像地址", requiredMode = Schema.RequiredMode.REQUIRED) @ExcelProperty("头像地址") private String avatar; @Schema(description = "描述", example = "随便") @ExcelProperty("描述") private String description; @Schema(description = "开场介绍") @ExcelProperty("开场介绍") private String prologue; @Schema(description = "相似度") @ExcelProperty("相似度") private String similarity; @Schema(description = "单词检索条数", requiredMode = Schema.RequiredMode.REQUIRED) @ExcelProperty("单词检索条数") private Integer retrievedEntries; @Schema(description = "未命中策略 0--默认知识库 1--固定文案", requiredMode = Schema.RequiredMode.REQUIRED) @ExcelProperty("未命中策略 0--默认知识库 1--固定文案") private String missedPolicies; @Schema(description = "固定文案") @ExcelProperty("固定文案") private String fixedCopy; @Schema(description = "知识库类型,字典值", example = "2") @ExcelProperty("知识库类型,字典值") private String knowledgeBaseType; @Schema(description = "记忆") @ExcelProperty("记忆") private String memory; @Schema(description = "温度") @ExcelProperty("温度") private String temperature; @Schema(description = "应用设定") @ExcelProperty("应用设定") private String appSetting; @Schema(description = "链接") @ExcelProperty("链接") private String link; @Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED) @ExcelProperty("创建时间") private LocalDateTime createTime; }
import React, { useState } from "react"; import { useNavigate, Link } from "react-router-dom"; const Register = ({ setAuth }) => { const [email, setEmail] = useState(""); const [name, setName] = useState(""); const [password, setPassword] = useState(""); const navigate = useNavigate(); const handleRegister = async (e) => { e.preventDefault(); try { const body = { email, password, name }; const response = await fetch("http://localhost:5000/auth/register", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); const parseRes = await response.json(); if (response.ok) { localStorage.setItem("token", parseRes.token); setAuth(true); navigate("/dashboard"); } else { alert(parseRes); // Handle error response } } catch (error) { console.error("Error during registration:", error); alert("Error during registration. Please try again."); } }; return ( <div className="container mt-5"> <div className="row justify-content-center"> <div className="col-md-6"> <div className="card"> <div className="card-body"> <h2 className="card-title text-center">Register</h2> <form onSubmit={handleRegister}> <div className="form-group"> <label htmlFor="name">Name</label> <input type="text" className="form-control" id="name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" required /> </div> <div className="form-group mt-3"> <label htmlFor="email">Email</label> <input type="email" className="form-control" id="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" required /> </div> <div className="form-group mt-3"> <label htmlFor="password">Password</label> <input type="password" className="form-control" id="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" required /> </div> <button type="submit" className="btn btn-primary mt-3"> Register </button> </form> <div className="text-center mt-3"> <p> Already have an account?{" "} <Link to="/login" className="btn btn-link"> Login here </Link> </p> </div> </div> </div> </div> </div> </div> ); }; export default Register;
#include<iostream> using namespace std; struct node { int data; node *left; node *right; }; node *createnode(int x) { node *temp=new node; temp->data=x; temp->left=temp->right=NULL; return temp; } node* insertion(node *root,int value) { if(root==NULL) { root=createnode(value); } else if(value < root->data) root->left=insertion(root->left,value); else if(value > root->data) root->right=insertion(root->right,value); return root; } void inorder(struct node *root) { if (root != NULL) { inorder(root->left); cout<<root->data<<" "; inorder(root->right); } } void preorder(struct node *root) { if (root != NULL) { cout<<root->data<<" "; preorder(root->left); preorder(root->right); } } void postorder(struct node *root) { if (root != NULL) { postorder(root->left); postorder(root->right); cout<<root->data<<" "; } } node* searchnode(node *root,int x) { if(root==NULL){ cout<<"Node not found"; return NULL; } else if(root->data==x) { cout<<"\nNode exists\n"; return NULL; } else if(x < root->data) root->left=searchnode(root->left,x); else root->right=searchnode(root->right,x); } node* delnode(node *root,int x) { if(root==NULL) cout<<"Node not found"; else if(root->data==x && root->right==NULL && root->left==NULL) { delete root; root=NULL; return root; } else if(x < root->data) root->left=delnode(root->left,x); else root->right=delnode(root->right,x); } int findheight(node *root) { int lh,rh; if(root==NULL) return 0; else { lh=findheight(root->left); rh=findheight(root->right); if(lh > rh) return (lh+1); else return (rh+1); } } int findsize(node *root) { if(root==NULL) return 0; else return (findsize(root->left)+1+findsize(root->right)); } int checkbst(node *root) { if(root==NULL) return 1; if(root->left!=NULL && root->left->data > root->data) return 0; if(root->right!=NULL && root->right->data < root->data) return 0; if(!checkbst(root->left) || !checkbst(root->right)) return 0; return 1; } int count=0; int childnodes(node *root) { if(root==NULL) return 0; if(root->left==NULL && root->right==NULL) count++; else{ childnodes(root->left); childnodes(root->right); } return count; } int internalnodes(node *root) { if(root==NULL) return 0; if(root->left!=NULL || root->right!=NULL) count++; childnodes(root->left); childnodes(root->right); return count; } node* heightofnode(node *root,int x) { if(root==NULL){ cout<<"Node not found"; return NULL; } else if(root->data==x) { int x=findheight(root); cout<<"\nHeight of the node is: "<<x-1<<endl; return NULL; } else if(x < root->data) root->left=heightofnode(root->left,x); else root->right=heightofnode(root->right,x); } int main() { node *root = NULL; node *ptr; int x,n,ch; cout<<"Enter choice\n1.Insert\n2.Search\n3.Traverse\n4.Delete\n5.Height or Depth of tree\n6.Size of the tree\n7.BST or not\n8.No of child nodes\n9.No of internal nodes\n10.Height of node\n"; cin>>ch; while(ch) { switch(ch) { case 1: cout<<"Enter the no of nodes: "; cin>>n; for(int i=0;i<n;i++) { cin>>x; root=insertion(root,x); } break; case 2: cout<<"\nEnter an element you want to search: "; cin>>x; ptr=root; ptr=searchnode(ptr,x); break; case 3: ptr=root; cout<<"Inorder: "; inorder(ptr); cout<<"\nPreorder: "; preorder(ptr); cout<<"\nPostorder: "; postorder(ptr); break; case 4: cout<<"\nEnter an element you want to delete: "; cin>>x; ptr=root; delnode(ptr,x); break; case 5: ptr=root; int h; h=findheight(ptr); cout<<"Height of the tree is: "<<h-1<<endl; break; case 6: ptr=root; x=findsize(ptr); cout<<"Size of the tree: "<<x<<endl; break; case 7: ptr=root; x=checkbst(ptr); if(x==0) cout<<"\nTree is not a BST\n"; else cout<<"\nIt is a BST\n"; break; case 8: ptr=root; x=childnodes(ptr); if(x==0) cout<<"\nNo child nodes present\n"; else cout<<"Child nodes are: "<<x<<endl; count=0; break; case 9: ptr=root; x=internalnodes(ptr); if(x==0) cout<<"\nEmpty tree\n"; else cout<<"\nInternal nodes are: "<<x+1<<endl; count=0; break; case 10: cout<<"\nEnter the node you want to find the path for: "; cin>>x; ptr=root; heightofnode(ptr,x); break; } cout<<"\nEnter choice: "; cin>>ch; } return 0; }
package command; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONObject; import dao.PersonDAO; import dto.Person; @WebServlet("/insertPerson.do") public class InsertPersonCommand extends HttpServlet { private static final long serialVersionUID = 1L; public InsertPersonCommand() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("application/json; charset=utf-8"); try { String sno = request.getParameter("sno"); String name = request.getParameter("name"); int age = Integer.parseInt(request.getParameter("age")); // NumFormatException 발생 가능 if (age < 0 || age > 100) { // 유효 범위를 벗어난 나이 입력 // 예외의 강제 발생 throw new RuntimeException(); } String birthday = request.getParameter("birthday"); Person p = new Person(); p.setSno(sno); p.setName(name); p.setAge(age); p.setBirthday(birthday); int count = PersonDAO.getInstance().insertPerson(p); JSONObject obj = new JSONObject(); obj.put("count", count); response.getWriter().println(obj); }catch (NumberFormatException e) { // 나이 : 정수 이외의 값이 입력됨 response.setStatus(3001); // 에러 코드 값을 작성, xhr.status 에러코드 값은 임의로 정한다 response.getWriter().println("나이는 정수만 입력 가능합니다."); }catch (RuntimeException e) { // 나이 : 유효 범위 이외의 값이 입력됨 response.setStatus(3002); response.getWriter().println("나이는 0~100 사이만 입력 가능합니다."); }catch (SQLIntegrityConstraintViolationException e) { // 주민등록번호: 동일한 값을 입력하는 경우 response.setStatus(3003); response.getWriter().println("동일한 주민등록번호는 입력할 수 없습니다."); } catch (SQLException e) { // 이름, 생일 : 칼럼의 크기보다 길이가 긴 값이 입력됨 response.setStatus(3004); response.getWriter().println("입력 데이터의 확인하세요."); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.fundguide.melona.member.service; import com.fundguide.melona.member.entity.MemberEntity; import com.fundguide.melona.member.role.MemberRoleState; import lombok.Getter; import lombok.Setter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.oauth2.core.user.OAuth2User; import java.util.ArrayList; import java.util.Collection; import java.util.Map; @Getter @Setter public class CustomUserDetails implements UserDetails, OAuth2User { private final MemberEntity memberEntity; private Map<String, Object> attributes; private final Collection<MemberRoleState> memberRoleStateCollection; // 일반 로그인용 생성자 public CustomUserDetails(MemberEntity memberEntity, Collection<MemberRoleState> memberRoleStateCollection) { this.memberEntity = memberEntity; this.memberRoleStateCollection = memberRoleStateCollection; } // oauth2용 생성자 public CustomUserDetails(MemberEntity memberEntity, Map<String, Object> attributes, Collection<MemberRoleState> memberRoleStateCollection) { this.memberEntity = memberEntity; this.attributes = attributes; this.memberRoleStateCollection = memberRoleStateCollection; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); grantedAuthorities.add(() ->{ return memberEntity.getMemberRole().toString(); }); return grantedAuthorities; } @Override public String getPassword() { return memberEntity.getMemberPassword(); } @Override public String getUsername() { return memberEntity.getMemberEmail(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } // --------------------- oauth2 @Override public String getName() { return attributes.get("sub").toString(); } @Override public Map<String, Object> getAttributes() { return attributes; } }
import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } export type Transform = { x: number; y: number; }; export function getTransform(el: HTMLElement): Transform { const transform = el.style.transform; if (!transform) { const calcualtedTransform = getComputedStyle(el).transform; // can return "none" https://developer.mozilla.org/en-US/docs/Web/CSS/transform if (calcualtedTransform === "none") { return { x: 0, y: 0 }; } const match = calcualtedTransform.match(/matrix\((.*?)\)/); const split = match![1].split(","); return { x: parseInt(split[4]), y: parseInt(split[5]), }; } const transformMatch = transform.match(/translate(3d)?\((.*?)px, (.*?)px/); return { x: transformMatch ? parseInt(transformMatch[2]) : 0, y: transformMatch ? parseInt(transformMatch[3]) : 0, }; } export function setTransform(el: HTMLElement, transform: Transform) { el.style.setProperty( "transform", `translate3d(${transform.x}px, ${transform.y}px, 0)`, "important", ); } export function formatDateMonthYear(date: Date) { return date.toLocaleDateString("en-GB", { year: "numeric", month: "long", }); } export function formatDateDayMonthYear(date: Date) { return date.toLocaleDateString("en-GB", { year: "numeric", month: "numeric", day: "numeric", }); }
import sys sys.stdin = open("input.txt", "rt") # 해쉬 -> 딕셔너리 # 자바 해쉬맵 -> 딕셔너리 # 어떻게 보면 json이다. word_one = input() word_two = input() dct_one = {} dct_two = {} # for char in word_one: # dct_one[char] = 0 # for char in word_one: # dct_one[char]+=1 # 위 계산이 아래에서 한 방에 해결된다. # char라는 키가 있으면 1을 더하고 없으면 0을 기본값으로 넣어라 for char in word_one: dct_one[char] = dct_one.get(char,0)+1 # for key, val in dct_one.items(): # print(key,val) # print("\n") # for char in word_two: # dct_two[char] = 0 # for char in word_two: # dct_two[char]+=1 # 위 계산이 아래에서 한 방에 해결된다. # char라는 키가 있으면 1을 더하고 없으면 0을 기본값으로 넣어라 for char in word_two: dct_two[char] = dct_two.get(char,0)+1 # for key, val in dct_two.items(): # print(key,val) # 핵심 알고리즘 # 키값만 접근하고 싶다. # 큐도 그렇고 in이라는 함수가 중요하다. # in을 생각하면 어디 어디에 있냐 이게 떠올려진다. for i in dct_one.keys(): # word_one에는 있는데 word_two에는 없으면 안된다. # 아나그램은 모든 원소들이 같이 존재해야하는 것이다. if i in dct_two.keys(): # 갯수 비교 if dct_one[i] != dct_two[i]: print("NO") break else: print("NO") break # 정상 케이스 else: print("YES") # 위랑 아래를 비교해봅시다. print("\n") Hash = {} # 개선 코드 for char in word_one: Hash[char] = Hash.get(char,0)+1 print(Hash) for char in word_two: Hash[char] = Hash.get(char,0)-1 # 이러면 하나의 딕셔너리를 이용해서 풀 수 있다. print(Hash) for x in word_one: if Hash.get(x) != 0: print("NO") break else: print("YES")
import * as React from "react"; import Box from "@mui/material/Box"; import Modal from "@mui/material/Modal"; import { getFirestore, doc, setDoc, getDoc } from "firebase/firestore"; import { getAuth } from "firebase/auth"; import { useAuthContext } from "../../context/AuthContext/AuthContext"; import CircularProgress from "@mui/material/CircularProgress"; import EditIcon from '@mui/icons-material/Edit'; const style = { position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", width: 400, bgcolor: "#101010", border: "1px solid #1e1e1e", p: 4, color: "#F3F5F7", }; const nameField = { width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", }; const btnClose = { border: "none", width: "80px", height: "30px", borderRadius: "10px", background: "#777777", color: "red", cursor: "pointer", }; const btnOpen = { border: "none", width: "80px", height: "30px", borderRadius: "10px", background: "#777777", color: "green", cursor: "pointer", }; const input = { width: "100%", marginTop: "40px", display: "flex", alignItems: "center", justifyContent: "center", }; const inputs = { width: "90%", height: "45px", paddingLeft: "10px", background: "#0A0A0A", border: "1px solid #1e1e1e", borderRadius: "10px", color: "#777777", }; export default function EditModal(props) { const { user, fetchData } = useAuthContext(); const [open, setOpen] = React.useState(false); const handleOpen = () => setOpen(true); const auth = getAuth(); const db = getFirestore(); const uid = auth.currentUser.uid; const userDocRef = doc(db, "users", uid); const [loading, setLoading] = React.useState(false); const handleClose = () => { props.setStateName("Insert Name"); setOpen(false); }; const handleNameChange = (event) => { props.setStateName(event.target.value); }; const handleSubmit = async (e) => { e.preventDefault(); if (props.stateName.length > 12) { window.alert("Name length exceeded 7 characters"); } else if (props.stateName.length <= 12) { props.setStateName(props.stateName); setLoading(true); try { const existingData = (await getDoc(userDocRef)).data(); await setDoc(userDocRef, { ...existingData, initial: props.stateName, }); fetchData(); handleClose(); setLoading(false); } catch (error) { console.error("Error updating user profile: ", error); setLoading(false); } setOpen(false); } }; return ( <div> <p onClick={handleOpen} style={{ cursor:"pointer",display:"flex", alignItems:"center", justifyContent:"space-between", width:"45px", color:"#777777"}}> {" "} {user?.initial ? user.initial : "Insert Initial"} <EditIcon fontSize="small"/> </p> <Modal open={open} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <Box sx={nameField}> <button style={btnClose} onClick={handleClose}> close </button> {props.name} <button style={btnOpen} onClick={handleSubmit}> {!loading ? ( "save" ) : ( <CircularProgress size={20} style={{ color: "#1e1e1e" }} /> )} </button> </Box> <Box sx={input}> <input type="name" placeholder="Insert Name" onChange={handleNameChange} style={inputs} /> </Box> </Box> </Modal> </div> ); }
package hat.auth.utils import com.google.gson.JsonObject import com.google.gson.annotations.SerializedName import hat.auth.data.TapAccount import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.Request import okhttp3.Response val TapUrlRegex = Regex("https://www\\.taptap\\.com/qrcode/to\\?url=https%3A%2F%2Fwww\\.taptap\\.com%2Fdevice%3Fqrcode%3D1%26user_code%3D\\w{5}") data class Profile(val name: String, val avatar: String) @JvmInline value class ConfirmPage(private val s: String) { val param get() = PARAM_REGEX.findValue(s).substringAfter('"') val token get() = TOKEN_REGEX.findValue(s).substringAfter('"') fun getBasicProfile() = Profile( name = NAME_REGEX.findValue(s).dropLast(1), avatar = AVATAR_REGEX.findValue(s) ) private companion object { val NAME_REGEX = Regex("(?<=auth__user-name\">)\\S+<") val PARAM_REGEX = Regex("(?<=name=\"params\")\\s+value=\"[a-zA-z0-9]+(?=\">)") val TOKEN_REGEX = Regex("(?<=name=\"_token\")\\s+value=\"[a-zA-z0-9]+(?=\">)") val AVATAR_REGEX = Regex("https://img3\\.tapimg\\.com/default_avatars/[a-z0-9]+\\.jpg") } } private fun Regex.findValue(s: String) = find(s)!!.value object TapAPI { suspend fun getCode() = getJson( url = "https://www.taptap.com/oauth2/v1/device/code", headers = mapOf( "User-Agent" to "TapTapUnitySDK/1.0 UnityPlayer/2017.4.30f1", "Content-Type" to "application/x-www-form-urlencoded", "X-Unity-Version" to "2017.4.30f1" ), postBody = buildFormBody { add("version","1.0.1") add("platform","unity") add("scope","public_profile") add("response_type","device_code") add("client_id","WT6NfH8PsSmZtyXNFb") add("info","{\"device_id\":\"Windows PC\"}") } ).checkSuccess().toDataClass(TapOAuthCode::class.java) suspend fun getPage(url: String,u: TapAccount) = withContext(Dispatchers.IO) { buildHttpRequest { url(url) addCookie(u) }.execute().run { u.copy( sid = getCookieMap().getValue("ACCOUNT_SID") ) to ConfirmPage(getStringBody()) } } suspend fun TapOAuthCode.getPage(u: TapAccount) = getPage(url,u) suspend fun ConfirmPage.confirm( u: TapAccount, cUrl: String = "https://www.taptap.com/device" ) = withContext(Dispatchers.IO) { buildHttpRequest { url(cUrl) addCookie(u) postFormBody { add("params",param) add("_token",token) add("scope","public_profile+") add("approve","1") } }.execute(OkClients.NO_REDIRECT).code == 302 } data class TapOAuthCode( @SerializedName("device_code") val deviceCode: String = "", @SerializedName("user_code") val user: String = "", @SerializedName("verification_url") val verificationUrl: String = "", @SerializedName("qrcode_url") private val qrcodeUrl: String = "" ) { val url get() = checkNotNull(qrcodeUrl.toHttpUrl().queryParameterValue(0)) } private fun Request.Builder.addCookie(u: TapAccount) = addHeader("Cookie",u.toString()) private fun Response.getCookieMap() = headers("set-cookie").associate { s -> s.split(";")[0].split("=").let { it[0] to it[1] } } private fun Response.getStringBody() = notNullBody.string() private fun JsonObject.checkSuccess(): JsonObject = getAsJsonObject("data").apply { if (!this@checkSuccess.get("success").asBoolean) { throw IllegalStateException(get("msg").asString) } } }
N.B: I tried to simulate the network only with docker containers, so that people working on Windows and Mac can follow, but unknowingly I used the namespace features, which is only available on linux. * The Problem :PROPERTIES: :heading: 3 :END: Meena and Raju have got new computers to play around. They played a lot of solo mission based based games. Their favorite game is Call of Duty MW3. They have finished all the campaign and now looking forward to the special ops challenges. They have successfully completed the first five special ops missions but the sixth one is *Firewall* a *co-op* mission. [[https://i.ytimg.com/vi/ATwQ64qLN2g/maxresdefault.jpg]] Let's took at Meena and Raju's room [[../assets/image_1695215839229_0.png]] Now they have to find a way to connect the two computers together and finish the *coop mission*. How will they do it? * We need a network! :PROPERTIES: :heading: 3 :END: Network is a group of interconnected computers sharing resources. Here we need a network to share Meena and Raju's location, actions and the overall world state within the game. For creating a network: - Firstly we need nodes(computers) that follows the `same language`(protocol) when sharing data between them. - We need to connect the computers * Simulating Nodes :PROPERTIES: :heading: 3 :END: We will be used docker containers to simulate nodes. #+BEGIN_SRC Dockerfile # nfd-node.dockerfile FROM fedora:latest RUN dnf update -y RUN dnf install -y tcpdump iproute iputils bind-utils net-tools iptables ENTRYPOINT sleep infinity #+END_SRC To build the image, #+BEGIN_SRC bash docker build --tag nfd-node --file nfd-node.dockerfile . #+END_SRC * Creating the nodes :PROPERTIES: :heading: 3 :END: We will create the nodes by running two docker containers of the ~nfd-node~ image #+BEGIN_SRC sh docker run -d --rm --name nfd-node-meena --network none --privileged --hostname nfd-node-meena nfd-node:latest docker run -d --rm --name nfd-node-raju --network none --privileged --hostname nfd-node-raju nfd-node:latest #+END_SRC * Accessing the nodes :PROPERTIES: :heading: 3 :END: I am using tmux for accessing all the nodes in a single screen. (I have not setup wm yet 😔). For getting into the nodes execute the following commands in different terminals. #+BEGIN_SRC sh docker exec -it nfd-node-meena bash docker exec -it nfd-node-raju bash #+END_SRC After that you will have access to nodes. And it will look something like the following [[../assets/image_1695912258299_0.png]] * Connecting the computers (phase0) :PROPERTIES: :heading: 2 :END: In this phase, we are going to connect the nodes directly with ethernet cable and interfaces. Of course, we dont have any cables within the virtual space, so we have to use virtual ethernet cables and interfaces. Each of the interface will get its own device address(mac address) and a network address(ip address) to talk to other computers on the network. * What is a network interface? :PROPERTIES: :heading: 3 :END: It is usually a hardware component that is used to connect the computer. It is the peripheral device that acts as a junction point. Network interfaces are generally physical devices, but doesn't have to be; it can also be a software simulating the network device. And that's what we will be using today to simulate our network. The first device we will use to simulate the connection between two nodes are virtual ethernet devices (veth) * Network Interfaces: :PROPERTIES: :heading: 3 :END: ** LOOPBACK :PROPERTIES: :heading: 4 :END: By default all nodes have loopback interfaces installed on them by default. If we execute the ~ip addr~ command on meena and raju's computer we will see, that they have only loopback interfaces. [[../assets/image_1695915428748_0.png]] The loopback interface, which is a virtual interface used for internal communication within the same device. It has IPV4 address of ~127.0.0.1~ which is local only to host (localhost), and its MAC address is typically set to all zeros. ** VETH :PROPERTIES: :heading: 4 :END: Veth acts as tunnel through which devices on one network can talk to devices on another network. Veth devices are always created in interconnected pairs. Packets transmitted on one device in the pair are immediately received on the other device. A pair can be created using the command: #+BEGIN_SRC sh ip link add <p1-name> type veth peer name <p2-name> #+END_SRC In the above, p1-name and p2-name are the names assigned to the two connected end points. * Connecting the computers...continued :PROPERTIES: :heading: 3 :END: And now we will try to create a pair of veth devices that connects meena and raju's computers together. [[../assets/image_1695913755287_0.png]] #+BEGIN_SRC sh sudo ip link add veth-meena type veth peer name veth-raju ip addr | grep veth -A1 #+END_SRC After running this command we will have a pair of virtual ethernet devices in our own machine. Now the state looks something like this. [[../assets/image_1695914059672_0.png]] Notice that the newly created veth interfaces have unique MAC addresses associated associated with them. MAC addresses are unique identifiers assigned to network devices. They still don't have any IP address associated with them. Now let's associate the interfaces to the nodes. #+BEGIN_SRC sh sudo ip link set netns $(docker container inspect --format '{{.State.Pid}}' nfd-node-meena) dev veth-meena sudo ip link set netns $(docker container inspect --format '{{.State.Pid}}' nfd-node-raju) dev veth-raju #+END_SRC I promise I will explain what these complex commands do when its time. For now just hang with me. Roughly speaking we set the veth-meena interface to nfd-node-meena and vice versa. Now lets see the interfaces in the nodes. [[../assets/image_1695917713076_0.png]] Notice that meena's computer have now interface named veth-meena and the same for raju. Upto now, the interfaces only have device addresses. Which means they are layer 2 interfaces. * Network Layers :PROPERTIES: :heading: 3 :END: Let's look into the layers that makes up the network. [[https://media.fs.com/images/community/upload/kindEditor/202107/29/original-seven-layers-of-osi-model-1627523878-JYjV8oybcC.png]] The first layer is the physical layer and we don't see it in our network, because, well its virtual network, we don't need physical wires to connect them. When we created the veth pairs the physical and data link layers are taken as granted by default and we didn't have to worry about them. What we do need to worry about is layer 3, the network layer. In this layer we need logical addresses for the devices, for if we want them to communicate. These addresses are called IP addresses. And now we will assign IP addresses to our virtual network interfaces. Before assigning IP addresses, lets talk a little bit more about IP addresses. * Network (IP) Address :PROPERTIES: :heading: 3 :END: Every IP address has two parts, the first part is same and the second part is unique for all the devices in the network. Let's look at how we can identify these two parts. The first part is also called the network address. As obvious it is, the network address for all the devices in the same network is same. Let's take a look at an IP address example ~192.168.0.5/24~ Here the ip address is comprised of 4 segments of 8 bits. ~00000000.00000000.00000000.00000000~ So the lowest value is ~0.0.0.0~ and the highest value is ~255.255.255.255~ And the /X part identifies the network address also known as network mask. Here 24 means first 24 bits will be taken as network address and the remaining bits will be allocated to the devices. So in this network, ~192.168.0~ is the network part, and the last 8 bits are allocated to devices. So that means the network has addresses from ~192.168.0.0~ to ~192.168.0.255~. This means this network can have 256 devices connected to each other. But there is a catch, there are two special reserved addresses for a network, the first and the last one. The first one is called network address and the last one is called broadcast address. So, here the addresses ~192.168.0.0~ is the network address and ~192.168.0.255~ is the broadcast address. Broadcast address is a little bit special in the sense that, any message sent to the broadcast address will be delivered to all of the devices in the network. And thus, we have 254 unique addresses in the network ~192.168.0.0/24~. Now let's do a little exercise, if the network address is ~192.168.0.0/18~, what will be the broadcast address of the network? How many devices can this network contain? Let's convert the address in bits. ~11000000.10101000.00000000.00000000~ Here the first 18 bits are untouchable, since it's the network address, and its same for everybody. The two separated parts are: ~11000000.10101000.00~ ~000000.00000000~ So here the network mask is: ~11111111.11111111.11~ ~000000.00000000~ or ~255.255.192.0~ And the highest address will be: ~11000000.10101000.00~ ~111111.11111111~ So the network address is ~192.168.0.0/18~ and the broadcast address is ~192.168.63.255/18~ And the network can contain ~2^14 = 16384 - 2 = 16382~ devices. Following this procedure, we can break a large network into smaller networks, which is called subnetting. * Connecting the computers...continued... :PROPERTIES: :heading: 3 :END: Let's create a new network with address 10.2.3.0/24. Note that this network doesn't overlap with any other networks in my machine. [[../assets/Screenshot_from_2023-09-28_22-44-18_1696043036103_0.png]] Now we will assign IP address 10.2.3.2 to meena and 10.2.3.3 to raju. #+BEGIN_SRC shell ip addr add 10.2.3.2/24 dev veth-meena ip addr add 10.2.3.3/24 dev veth-raju #+END_SRC After that it will look something like this. [[../assets/image_1695918847119_0.png]] Note that the state is still down. [[../assets/Screenshot_from_2023-09-30_09-09-07-mh_1696043574852_0.png]] We need to turn them UP. #+BEGIN_SRC shell sudo ip link set dev veth-meena up sudo ip link set dev veth-raju up #+END_SRC And then we can communicate with the computers in the network. #+BEGIN_SRC shell ping -c 2 10.2.3.3 ping -c 2 10.2.3.2 #+END_SRC [[../assets/image_1696043882398_0.png]] And with that we are done with phase 1. We have successfully connected two computers with a virtual ethernet pair and established network within themselves. Now meena and raju can complete the ~coop~ missions in Call of Duty. * Network Protocols :PROPERTIES: :heading: 3 :END: We haven't talked about the ping command and what it does, lets learn a little bit about the language of the communication, i.e. the protocols of the network. ** ICMP :PROPERTIES: :heading: 4 :END: The Internet Control Message Protocol (ICMP) is a network layer protocol used by network devices to diagnose network communication issues. ICMP is mainly used to determine whether or not data is reaching its intended destination in a timely manner. Here we used the ping command to send an ICMP message to the other computer in the network and if everythingis OK, then they reply with a response and the communication between the two computers is established successfully. We will talk about other network protocols as we progress on. * Connecting the computers (phase-1) :PROPERTIES: :heading: 2 :END: It's going all well, but recently meetu has been gifted a new laptop on his birthday and now, he also wants to play along with them. [[../assets/image_1696061356581_0.png]] How do we connect all of their computers in the same network? One solution would be connecting all of the computers with each other. Although it is a solution, it's a bad one. The solution doesn't scale if we need to add more computers. Lot's of connections makes it harder to maintain and debug. The better solution is to bring in a *Router* If we want to mentally visualize, the network will look something like below: [[../assets/image_1696097354631_0.png]] Here the number of connections scale linearly as the no of devices grow. Now we will create an additional node to emulate meetu's computer. #+BEGIN_SRC shell docker run -d --rm --name nfd-node-meetu --network none --privileged --hostname nfd-node-meetu nfd-node:latest docker exec -it nfd-node-meetu bash #+END_SRC Then we will delete the old veth interface pair on meena and raju's computer. #+BEGIN_SRC shell ip link delete veth-meena #+END_SRC If we delete one of the interface, the other one will be automatically deleted. [[../assets/image_1696185719575_0.png]] Now we will create a virtual interface of type *bridge* that will actually act as a router for our network. #+BEGIN_SRC shell sudo ip link add nfd-rtr type bridge ip addr | grep nfd-rtr -A1 #+END_SRC [[../assets/image_1696186776785_0.png]] Now we will create the veth pairs for the connections. #+BEGIN_SRC shell sudo ip link add veth-meena-rtr type veth peer name veth-rtr-meena sudo ip link add veth-raju-rtr type veth peer name veth-rtr-raju sudo ip link add veth-meetu-rtr type veth peer name veth-rtr-meetu ip addr | grep veth -A1 #+END_SRC [[../assets/image_1696187040059_0.png]] Now we will associate the interfaces to the machines like before. #+BEGIN_SRC shell sudo ip link set netns $(docker container inspect --format '{{.State.Pid}}' nfd-node-meena) dev veth-meena-rtr sudo ip link set netns $(docker container inspect --format '{{.State.Pid}}' nfd-node-raju) dev veth-raju-rtr sudo ip link set netns $(docker container inspect --format '{{.State.Pid}}' nfd-node-meetu) dev veth-meetu-rtr #+END_SRC And assign ip addresses to the interfaces. #+BEGIN_SRC shell sudo ip addr add 10.2.3.2/24 dev veth-meena-rtr sudo ip addr add 10.2.3.3/24 dev veth-raju-rtr sudo ip addr add 10.2.3.4/24 dev veth-meetu-rtr #+END_SRC And now, if we see the interfaces, it will look something like below. [[../assets/image_1696188956498_0.png]] After that we need to connect the other end of the veth pair with the router. #+BEGIN_SRC shell sudo ip link set veth-rtr-meena master nfd-rtr sudo ip link set veth-rtr-raju master nfd-rtr sudo ip link set veth-rtr-meetu master nfd-rtr brctl show nfd-rtr #+END_SRC [[../assets/image_1696190483136_0.png]] Now it's time to bring up all the connections. #+BEGIN_SRC shell sudo ip link set nfd-rtr up sudo ip link set veth-rtr-meena up sudo ip link set veth-rtr-raju up sudo ip link set veth-rtr-meetu up ip link set veth-meena-rtr up ip link set veth-raju-rtr up ip link set veth-meetu-rtr up #+END_SRC [[../assets/image_1696190922391_0.png]] Now if we ping the other devices in the network, [[../assets/image_1696226945994_0.png]] We can see, from the host machine(upper left hand corner), we can ping all four of the devices. But on the other machines, we can only ping the router and the machine itself. Now there are two questions: - How is the host machine communicating with all the devices in different network? - The other machines can't communicate with each other. But the router is supposed to forward the packets to the destined ip addresses, why isn't it doing so? In this phase, we will learn about debugging network communications. Stay hydrated, it's gonna be a walk through the Sahara. * TCPDUMP :PROPERTIES: :heading: 3 :END: Firstly we will run a tcpdump command on meena's machine and get all the information we want. #+BEGIN_SRC shell tcpdump -n -vvv -e -i veth-meena-rtr host 10.2.3.3 #+END_SRC The following *tcpdump* command captures network traffic on the specified network interface (*veth-meena-rtr*) and filters it to display packets involving the host with the IP address 10.2.3.3. Here's a breakdown of the command and what it does: - *tcpdump*: This is the command used for packet capture and analysis. - *-n*: The *-n* option prevents *tcpdump* from performing hostname resolution, so it displays IP addresses and port numbers instead of resolving them to hostnames and service names. - *-vvv*: The *-vvv* option increases the verbosity level, providing more detailed information about each captured packet. In this case, it's set to a high verbosity level, which means you'll get extensive packet details. - *-e*: The *-e* option instructs *tcpdump* to display the link-level header (Ethernet frame header) information, including source and destination MAC addresses. - *-i veth-meena-rtr*: The *-i* option specifies the network interface (*veth-meena-rtr*) on which *tcpdump* should capture packets. - *host 10.2.3.3*: This filter specifies that you want to capture packets where the source or destination IP address is 10.2.3.3. This filter helps you focus on traffic involving this specific IP address. When you run this command, *tcpdump* will capture network packets on the *veth-meena-rtr* interface and display detailed information for each packet that matches the specified filter (packets involving the IP address 10.2.3.3). The output will include source and destination IP addresses, source and destination MAC addresses, and other packet details. This is useful for monitoring or troubleshooting network traffic to or from the specified host. Now we see that, 3 packets are captured, and 3 are received by the filter. [[../assets/image_1696766242406_0.png]] We see that the meena tries to send a ICMP echo request which originated from her machine(10.2.3.2) to raju's machine(10.2.3.3) Then we see a followup ARP request asking whoever has the ip address 10.2.3.3 please tell meena that you are the one. We see that the ARP request is received by both raju and meetu, but only raju responds with an ARP reply. The reply of the ARP request is the MAC address of the interface on raju's machine that is connected to the router. And then meena is also supposed to receive an ICMP echo reply packet. But it never receives so. * Debugging Firewall :PROPERTIES: :heading: 3 :END: The first thing that should come to your mind, when packets are not being received is the cursed *FIREWALL* [[https://i.imgflip.com/81up6d.jpg]] You inspect all the firewall rules in your machine by running the command #+BEGIN_SRC shell sudo iptables --list --verbose --numeric #+END_SRC [[../assets/image_1696767902761_0.png]] By default, it has three chains, (INPUT, FORWARD, OUTPUT)* - Chain INPUT*: This chain is responsible for filtering packets that are destined for the local system (i.e., incoming packets). As the policy is set to ACCEPT, it means that all incoming packets are allowed unless there are specific rules that match and modify this behavior.* - Chain FORWARD*: This chain is responsible for filtering packets that are being forwarded through the system (i.e., packets that are not destined for the local system but are being routed through it). Again, the policy is set to ACCEPT, so all forwarding is allowed by default unless there are specific rules in place.* - Chain OUTPUT*: This chain is responsible for filtering packets generated by the local system and going out to other destinations (i.e., outgoing packets). Like the other chains, the policy is set to ACCEPT, so all outgoing packets are allowed by default. But if you execute the same command on the host machine, then, we will a lot of rules in the chains [[../assets/image_1696768246403_0.png]] And we also see that, the default forwarding rule is dropping packets if it doesn't match any rules. Now if you want to see the motion of which rule is stopping us from forwarding our packets, we observe the iptables #+BEGIN_SRC shell sudo watch --difference --interval 1 iptables --list FORWARD --verbose #+END_SRC [[../assets/ping-dropping_1696768685923_0.gif]] We see packets dropped by the firewall rule *DOCKER-ISOLATION-STAGE-1* and *DOCKER-USER* [[../assets/image_1696769381581_0.png]] These rules say, whatever the input or output interface, source or destination address, drop all the packets. So that's why our packets were not travelling. We can just disable the firewall and everything will work correctly. But we will not do so. Instead, we will add a rule to the top of the firewall table, that says, any thing going in or coming out of the interface *nfd-rtr* will be *ACCEPTED*. #+BEGIN_SRC shell sudo iptables --insert FORWARD --in-interface nfd-rtr --jump ACCEPT sudo iptables --insert FORWARD --out-interface nfd-rtr --jump ACCEPT #+END_SRC Here we add the rule that - ~sudo iptables --insert FORWARD --in-interface nfd-rtr --jump ACCEPT~: This command inserts a rule into the FORWARD chain that allows incoming traffic on the ~nfd-rtr~ network interface. In other words, it permits traffic coming into your system through the ~nfd-rtr~ interface to be forwarded.~ - ~sudo iptables --insert FORWARD --out-interface nfd-rtr --jump ACCEPT~: This command inserts a rule into the FORWARD chain that allows outgoing traffic on the ~nfd-rtr~ network interface. It permits traffic leaving your system through the ~nfd-rtr~ interface to be forwarded. Since the rules are evaluated in order, we ask the firewall not to drop any packets for the interface ~nfd-rtr~, other packets will be evaluated as before. [[../assets/image_1696770111881_0.png]] Now if we ping from the machines, we will see all the pings, succeeded. *
------------------------------------------------ AutoBouquets E2 for satellite 28.2E Version date - 1st March 2013 Created by LraiZer - www.ukcvs.org ------------------------------------------------ Plugin Usage ---------------- first perform a scan on 28.2e satellite so that you have the latest lamedb service file for 28.2 East. next zap to an active channel on 28.2e so that we can get dvbsnoop to read the bouquet data from the stream. now its time to select AutoBouquets E2 Plugin from the plugins menu and choose your nearest localized region. generated bouquets are prepended to any existing bouquets so your current bouquets are not overwritten. sit back and watch for a few minutes as your regional bouquets are read and generated direct from the stream. Menus ---------------- - Local Area Selection generate selected bouquets for your SD/HD local region. - Use HD First Bouquet puts the HD channels starting at position 6 immediately after 1-5 (BBC1, BBC2, ITV1, C4, C5 for your region). yes = placeholder channels are put in category bouquets. no = placeholder channels are put in first bouquet only. - Show Channel Numbers puts epg position number in front of the channel names. - Use Internal NIT Scan updates the lamedb with latest transponders and services by scanning Network Information Table via script instead of running standard 28.2e engima2 automatic service scan. - Use Pli Placeholders yes = allows placeholder skipping on openpli based images. allows placeholder hiding if supported by engima2 version. no = uses normal services for placeholder channels as none pli based images do not assign correct positions using pli. - Create Child Friendly dont generate the adult or the gaming and dating bouquets. - Make Default Bouquets this will force default bouquet categories to be generated. if you wish to remove any bouquets from future generations, delete the bouquets you dont want and disable this option. - Custom Channel Order this allows you to change the generated channel ordering. edit the example custom.txt file in /AutoBouquets/ folder by changing the second channel number 101-999 accordingly. - Scan Free To Air Only this will generate services with free to air flag detection. - Scheduled Update Scan this allows you to set a daily, weekly, monthly update timer. Tips ---------------- if you want 1, 2, 3 button presses for BBC1, BBC2, ITV1. simply remove your "28.2E ---- UK Bouquets ---" bouquet. this will remove the official epg numbering and set your Entertainment bouquet channels to starting with 1, 2, 3. the Plugin does not re-create any bouquets that have been previously removed by the user. if for example you remove the adult bouquet, it will remain removed the next time you run the plugin and so remain child friendly updatable. you will need to turn the default bouquets option to "off" you can set default option to create first bouquets again. changing the order of the bouquets also remains static and does not get re-ordered on subsequent runs. this will have to be done while not using the HD Bouquet settings option, or your offical numbering with not be correct and match up. when creating a custom.txt file for personal channel order, enter the two channel you wish to switch with each other. 101=143 103=178 104=230 105=171 when using the supplement.txt file to manually add channels, its best to add your channel with a channel number that puts the new channel into an empty slot in the "other" bouquet. current empty slots are 975 < 995. you can then simply add a switch entry in the custom.txt file to swap with another one. Prerequisites ---------------- dvbsnoop binary is required in /usr/bin/ folder. frontend GUI should work on systems using Enigma2, backend script should work on most linux systems. script requires all the common busybox functions: grep, sed, cat, printf, wget, echo, mv, rm, date. plus busybox math support for arithmetic $((1+1)) all these should be standard in your linux image. Manual Installation - AutoBouquets_E2.rar (archive) --------------- 1) make sure you have dvbsnoop in your /usr/bin/ 2) place files onto engima2 box in relevant folders. make autobouquets_e2.sh executable (chmod 755) 3) restart Enigma2 to reload AutoBouquets E2 plugin HOW TO: install required dvbsnoop on openpli image? telnet to your box and type the following command: opkg update && opkg install dvbsnoop Version infos --------------- 10-08-2012 first version released to public for testing, this is totaly untested, so backup your files first! :) 13-08-2012 current bouquets are no longer overwritten. if not detected as already present in user bouquets, they are written to front to preserve official numbering. various other code fixes and imporvements also done. 19-08-2012 new GUI with help button for onbox readme.txt viewing. error checks added to stop box lockup on none active. added special handling of the sbo channels namespace. other file and error checking and various code fixes. 21-08-2012 added checks to make sure we only process 28.2E sat. also .ipk installer for mipsel with dvbsnoop depend. 24-09-2012 LraiZer:- auto update lamedb services using script NIT scanning. option to parentally control and make child friendly. option to add official channel numbering with names. option to use channel placeholder on none PLi images. option to be able to create the default bouquet set. option to be able to create free to air only bouquets. option to create customized channel ordered bouquets, use example custom.txt in plugin folder to customize. AndyBlac:- OE-Alliance: https://github.com/oe-alliance/ oe-alliance-plugins/tree/master/AutoBouquets new GUI, which will now remember and save your settings. option to keep official numbering with HD first bouquet. auto schedule for Daily, Weekly, Monthly at chosen time. perform a service scan before running script (optional). compatible with PLi based image placeholder skipping. compatible with iDreamX Bouquet Editor for Apple MAC. Thanks to ViX TEAM members for feedback and beta testing. 27-09-2012 auto detect correct transponder modulation with NIT scan. adds full list of active channels to interactive bouquet. removed needsRestart paramater, feedback crashes on some. 30-09-2012 fix unassigned option crash in scheduled service scanning. remove duplicated channel epg numbering list in custom.txt 9-10-2012 now also detects and parses the hidden data channel names. add autobouquets selection menu to service searching menu. also adds the channel epg numbers to the official bouquet. 13-10-2012 now also auto initializes systems for first run of plugin. 21-02-2013 AutoBouquets E2 code has been 90% rewritten and optimized for speed. main coding has now been moved into binaries. script checking can be disabled for none comaptible boxes. run AutoBouquets Downloader in background via blue button. custom.txt channel swap file has be slightly simplified. now just enter channels to swap with each other. 105=171 01-03-2013 fixed missing channels bug. added bouquet style options. added supplement.txt file for manual service additions. ------------------------------------------------------ www.ukcvs.org thanks you for using AutoBouquets E2 thanks to PaphosAL for plugin icon. HAVE FUN! ------------------------------------------------------
using System.ComponentModel.DataAnnotations; namespace AspLoginCore.Models { public class Cliente { [Display(Name = "Código",Description ="Código.")] public int Id { get; set; } [Display(Name = "Nome completo", Description = "Nome e Sobrenome.")] [Required(ErrorMessage = "O nome Completo é obrigatorio!")] public string Name { get; set; } [Display(Name = "Nascimento")] [Required(ErrorMessage = "A data é obrigatorio!")] public DateTime Nascimento { get; set; } [Display(Name = "Sexo")] [Required(ErrorMessage = "O Sexo é obrigatorio!")] [StringLength(1,ErrorMessage ="Deve conter 1 char!")] public string Sexo { get; set; } [Display(Name = "CPF")] [Required(ErrorMessage = "O CPF é obrigatorio!")] public string CPF { get; set; } [Display(Name = "Celular")] [Required(ErrorMessage = "O Celular é obrigatorio!")] public string Telefone { get; set; } [Display(Name = "E-mail")] [Required(ErrorMessage = "O E-mail é obrigatorio!")] [RegularExpression(".+\\@.+\\..+",ErrorMessage = "Informe um email valido...")] public string Email { get; set; } [Display(Name = "Senha")] [Required(ErrorMessage = "A senha é obrigatorio!")] [StringLength(6,MinimumLength = 6,ErrorMessage ="A senha dever ter 6 digitos")] public string Senha { get; set; } [Display(Name = "Situação")] [Required(ErrorMessage = "A situação é obrigatorio!")] public string Situação { get; set; } } }
<template> <h2>{{ customTitle }}</h2> <p> {{ counter }} <sup>2</sup> = {{squareCounter}} </p> <p data-testid="counter"> {{counter}} </p> <div class="buttons-container"> <button @click="increase">+1</button> <button @click="decrease">-1</button> </div> </template> <script> export default { props: { title: String, start: { type: Number, // require: true default: 100, validator(value) { return value > 10 } } }, data() { return { counter: this.start } }, methods: { getSqureValue() { return this.counter * this.counter }, increase() { this.counter++ }, decrease() { this.counter-- } }, computed: { squareCounter() { return this.counter * this.counter }, customTitle() { // return this.title !== undefined ? this.title : 'Counter' return this.title || 'Counter' } } } </script> <style> button{ background-color: #64bb87; border-radius: 5px; border: 1px solid white; color: white; cursor: pointer; margin: 0 5px; padding: 5px 15px; transition: 0.3s ease-in-out; } button:hover { background-color: #5aa67b; transition: 0.3s ease-in-out; } </style>
import React, { useEffect, useState } from 'react' import Card from './CardNumber' import Grid from '@material-ui/core/Grid' import ToggleButton from '@material-ui/lab/ToggleButton' import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup' import { makeStyles, createStyles, Theme } from '@material-ui/core/styles' import Paper from '@material-ui/core/Paper' import UserGraph from './UserGraph' import ActivityGraph from './ActivityGraph' import { useDispatch } from '../../../store' import { useAuthState } from '../../../user/state/AuthState' import { useAnalyticsState } from '../../state/AnalyticsState' import { AnalyticsService } from '../../state/AnalyticsService' interface Props { adminGroupState?: any fetchAdminGroup?: any } const useStyles = makeStyles((theme: Theme) => createStyles({ root: { flexGrow: 1 }, paper: { padding: theme.spacing(2), textAlign: 'center', color: theme.palette.text.secondary, height: '35rem', width: '99.9%' }, mtopp: { marginTop: '20px' }, btn: { fontSize: '0.875rem', [theme.breakpoints.down('xs')]: { fontSize: '0.6rem' } } }) ) /** * Function for analytics on admin dashboard * * @returns @ReactDomElements * @author Kevin KIMENYI <kimenyikevin@gmail.com> */ const Analytics = (props: Props) => { const dispatch = useDispatch() const [refetch, setRefetch] = useState(false) const [graphSelector, setGraphSelector] = useState('activity') let isDataAvailable = false const analyticsState = useAnalyticsState() const activeLocations = analyticsState.activeLocations.value const activeParties = analyticsState.activeParties.value const activeScenes = analyticsState.activeScenes.value const activeInstances = analyticsState.activeInstances.value const instanceUsers = analyticsState.instanceUsers.value const channelUsers = analyticsState.channelUsers.value const dailyUsers = analyticsState.dailyUsers.value const dailyNewUsers = analyticsState.dailyNewUsers.value const fetchTick = () => { setTimeout(() => { setRefetch(true) fetchTick() }, 5000) } const activityGraphData = [ { name: 'Active Parties', data: activeParties }, { name: 'Active Locations', data: activeLocations }, { name: 'Active Instances', data: activeInstances }, { name: 'Active Scenes', data: activeScenes }, { name: 'Instance Users', data: instanceUsers }, { name: 'Channel Users', data: channelUsers } ] const userGraphData = [ { name: 'Daily Users', data: dailyUsers }, { name: 'Daily New Users', data: dailyNewUsers } ] if ( activityGraphData[0].data.length && activityGraphData[1].data.length && activityGraphData[2].data.length && activityGraphData[3].data.length && activityGraphData[4].data.length && activityGraphData[5].data.length ) isDataAvailable = true useEffect(() => { if (refetch === true) { AnalyticsService.fetchActiveParties() AnalyticsService.fetchInstanceUsers() AnalyticsService.fetchChannelUsers() AnalyticsService.fetchActiveLocations() AnalyticsService.fetchActiveScenes() AnalyticsService.fetchActiveInstances() AnalyticsService.fetchDailyUsers() AnalyticsService.fetchDailyNewUsers() } setRefetch(false) }, [refetch]) const authState = useAuthState() useEffect(() => { if (authState.isLoggedIn.value) setRefetch(true) }, [authState.isLoggedIn.value]) useEffect(() => { fetchTick() }, []) const classes = useStyles() const data = [ { number: activeParties[activeParties.length - 1] ? activeParties[activeParties.length - 1][1] : 0, label: 'Active Parties' }, { number: activeLocations[activeLocations.length - 1] ? activeLocations[activeLocations.length - 1][1] : 0, label: 'Active Locations' }, { number: activeScenes[activeScenes.length - 1] ? activeScenes[activeScenes.length - 1][1] : 0, label: 'Active Scenes' }, { number: activeInstances[activeInstances.length - 1] ? activeInstances[activeInstances.length - 1][1] : 0, label: 'Active Instances' }, { number: dailyUsers[dailyUsers.length - 1] ? dailyUsers[dailyUsers.length - 1][1] : 0, label: 'Users Today' }, { number: dailyNewUsers[dailyNewUsers.length - 1] ? dailyNewUsers[dailyNewUsers.length - 1][1] : 0, label: 'New Users Today' } ] return ( <div> <Grid container spacing={3}> {data.map((el) => { return ( <Grid item xs={12} sm={6} lg={3} key={el.label}> <Card data={el} /> </Grid> ) })} </Grid> <div className={classes.mtopp}> <Paper className={classes.paper}> <ToggleButtonGroup value={graphSelector} exclusive color="primary" aria-label="outlined primary button group"> <ToggleButton className={classes.btn} value="activity" onClick={() => setGraphSelector('activity')}> Activity </ToggleButton> <ToggleButton className={classes.btn} value="users" onClick={() => setGraphSelector('users')}> Users </ToggleButton> </ToggleButtonGroup> {graphSelector === 'activity' && isDataAvailable && <ActivityGraph data={activityGraphData} />} {graphSelector === 'users' && <UserGraph data={userGraphData} />} </Paper> </div> {/*<div className={classes.mtopp}>*/} {/* <ApiLinks />*/} {/*</div>*/} </div> ) } export default Analytics
/** * Filename: TestTask.java * Copyright: Copyright (c)2016 * Company: Yves * @version: 1.0 * Create at: 2017-3-28 下午7:54:29 * Description: * * Author Yves He */ package cn.com.yves.thread.threadpoolexecutor; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class TestTask { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); Task task = new Task(); Future<Integer> result = executor.submit(task); executor.shutdown(); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.println("主线程在执行任务"); try { System.out.println("task运行结果" + result.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println("所有任务执行完毕"); } } class Task implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("子线程在进行计算"); Thread.sleep(3000); int sum = 0; for (int i = 0; i < 100; i++) sum += i; return sum; } }
import 'package:flutter/material.dart'; import 'package:food_shop/item.dart'; import 'package:food_shop/homePage.dart'; List<Item> favItems = []; List<Item> cartItems = []; class ItemDescription extends StatelessWidget { final Item item; int _counter =0; ItemDescription({@required this.item}); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: item.color, body: Container( width: double.infinity, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only(left: 24.0, right: 24.0, bottom: 24.0, top: 48.0), child: Row( children: <Widget>[ GestureDetector( onTap: () { Navigator.pop(context); }, child: Container( width: 45, height: 45, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular(15), ), ), child: Icon( Icons.keyboard_arrow_left, color: Colors.black, size: 28, ) ), ), ], ), ), Center( child: SizedBox( height: 120, child: Hero( tag: item.title, child: Image.asset( item.imageUrl, ), ), ), ), SizedBox( height: 32.0, ), Expanded( child: Container( width: double.infinity, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(50), ), ), child: Padding( padding: EdgeInsets.all(32.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( item.title, style: TextStyle( fontSize: 32, fontWeight: FontWeight.bold, color: Colors.black, ), ), SizedBox( height: 24.0, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Container( child: Row( children: <Widget>[ Container( width: 0, height: 48, /* decoration: BoxDecoration( color: Colors.grey[200], borderRadius: BorderRadius.only( topLeft: Radius.circular(15), bottomLeft: Radius.circular(15), ), ), child: Icon( Icons.remove, color: Colors.black, )*/ ), Container( /*color: Colors.grey[200], width: 48, height: 48,*/ child: Center( child: MyStatefulWidget(), ), /*"2", style: TextStyle( color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold, ), ), ),*/ ), Container( width: 0, height: 48, /*decoration: BoxDecoration( color: Colors.grey[200], borderRadius: BorderRadius.only( topRight: Radius.circular(15), bottomRight: Radius.circular(15), ), ), child: Icon( Icons.add, color: Colors.black, )*/ ), ], ) ), Container( child: Text( r"$ " + item.price, style: TextStyle( fontSize: 36, fontWeight: FontWeight.bold, color: Colors.black, ), ) ), ], ), SizedBox( height: 24.0, ), Expanded( child: SingleChildScrollView( physics: BouncingScrollPhysics(), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text( "Product description", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black, ), ), Text( item.description, style: TextStyle( fontSize: 18, color: Colors.black, ), ), ], ), ), ), SizedBox( height: 24.0, ), Row( children: <Widget>[ Container( child: Container( height: 72, width: 72, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular(20), ), border: Border.all( color: item.color, width: 2, ), ), child: IconButton( icon: const Icon(Icons.favorite), color: item.color, onPressed:() { favItems.add(item); getFavItems(favItems); } ), ), ), SizedBox( width: 16, ), Expanded( child: Container( height: 72, decoration: BoxDecoration( color: item.color, borderRadius: BorderRadius.all( Radius.circular(20), ), ), child: Center( child: TextButton( onPressed: () { cartItems.add(item); getCartItems(cartItems); }, child: Text( "Add to cart", style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 18, ) ), ) ), ), ) ], ) ], ), ), ), ), ], ), ), ); } } int counter = 0; class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({Key key}) : super(key: key); @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { final Item item; _MyStatefulWidgetState({@required this.item}); @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ IconButton( icon: const Icon(Icons.add), // tooltip: 'Increase volume by 10', onPressed: () { setState(() { counter += 1; }); }, ), Text(' $counter'), IconButton( icon: const Icon(Icons.remove), // tooltip: 'Increase volume by 10', onPressed: () { setState(() { counter -= 1; if(counter <= 0) counter = 0; }); }, ), // Text(' $_counter') ], ); } }
(function () { // Add event listeners const chatInput = document.getElementById('chat-input'); const chatSubmit = document.getElementById('chat-submit'); const chatMessages = document.getElementById('chat-messages'); //get project id const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const projectId = urlParams.get('projectId') const API_URL = `${window.location.origin}/api/v1/chat-stream`; var histories = []; //get chat interface const chatbotName = document.getElementById('chatbot_name'); const chatbotAvatar = document.getElementById('chatbot_avatar'); const chatHeader = document.getElementById('chat-header'); const chatInitial = document.getElementById('chat_initial'); const suggestMessage = document.getElementById('suggest_mess'); const API_CHAT_INTERFACE = `${window.location.origin}/api/v1/chat_interface/${projectId}`; var xhr = new XMLHttpRequest(); xhr.open("GET", API_CHAT_INTERFACE, true); xhr.onload = function() { if (xhr.status === 200) { var chatInterface = JSON.parse(xhr.responseText); if (chatInterface) { //Chatbot name if (chatInterface.data.chatbot_name) { chatbotName.innerHTML = chatInterface.data.chatbot_name; } //avatar if (chatInterface.data.chatbot_picture) { chatbotAvatar.src = `${window.location.origin}/${chatInterface.data.chatbot_picture}`; if (chatInterface.data.chatbot_picture_active == 0) { chatbotAvatar.style.display = 'block'; } } //Chatbot color if (chatInterface.data.theme_color) { chatHeader.style.backgroundColor = chatInterface.data.theme_color; const backgroundColor = getComputedStyle(chatHeader).backgroundColor; const rgb = backgroundColor.match(/\d+/g); const brightness = (parseInt(rgb[0]) * 299 + parseInt(rgb[1]) * 587 + parseInt(rgb[2]) * 114) / 1000; if (brightness < 128) { chatbotName.style.color = "#fff"; } else { chatbotName.style.color = "#000000"; } } //Chatbot initial message if (chatInterface.data.initial_message) { chatInitial.innerHTML = chatInterface.data.initial_message; } //Chatbot suggest message if (chatInterface.data.suggest_message) { const currentValue = chatInterface.data.suggest_message; contentArray = currentValue.split("\n"); suggestMessage.innerHTML = ""; contentArray.forEach((content, index) => { if (content !== "") { const buttonSuggest = document.createElement("button"); buttonSuggest.setAttribute("type", "button"); buttonSuggest.classList = "rounded-xl border-0 whitespace-nowrap mx-1 mt-1 py-2 px-3 text-sm text-nowrap bg-zinc-100"; buttonSuggest.textContent = content; buttonSuggest.addEventListener("click", function() { suggestFunction(content); }); suggestMessage.appendChild(buttonSuggest); } }); } } } else { console.error("Request failed with status: " + xhr.status); } }; xhr.onerror = function() { console.error("Network error occurred"); }; xhr.send(); function suggestFunction(content) { onUserRequest(content); } chatSubmit.addEventListener('click', function () { const message = chatInput.value.trim(); if (!message) return; chatMessages.scrollTop = chatMessages.scrollHeight; chatInput.value = ''; onUserRequest(message); }); chatInput.addEventListener('keyup', function (event) { if (event.key === 'Enter') { chatSubmit.click(); } }); async function onUserRequest(message) { if (chatSubmit.disabled == true) { return; } chatSubmit.disabled = true; // Handle user request here const chatMessages = document.getElementById('chat-messages'); // Display user message const messageElement = document.createElement('div'); messageElement.className = 'flex justify-end mb-3'; messageElement.innerHTML = ` <div class="bg-gray-800 text-white rounded-lg py-2 px-4 max-w-[70%]" style="background-color: rgb(111, 68, 252); color: white;"> ${message} </div> `; chatMessages.appendChild(messageElement); chatMessages.scrollTop = chatMessages.scrollHeight; chatInput.value = ''; const replyElement = document.createElement('div'); replyElement.className = 'flex mb-3'; replyElement.innerHTML = ` <div class="reply text-black rounded-lg py-2 px-4 max-w-[70%] typing"> <span></span> <span></span> <span></span> </div>`; chatMessages.appendChild(replyElement); // Create a new AbortController instance controller = new AbortController(); const signal = controller.signal; try { // Fetch the response from the OpenAI API with the signal from AbortController const response = await fetch(API_URL, { method: "POST", mode: "cors", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ 'project_id': projectId, 'question': message, 'histories': histories.slice(-6) }), signal // Pass the signal to the fetch request }); // Read the response as a stream of data const reader = response.body.getReader(); const decoder = new TextDecoder("utf-8"); // replyElement.innerText = ""; while (true) { const { done, value } = await reader.read(); if (done) { break; } // Massage and parse the chunk of data const content = decoder.decode(value); replyElement.getElementsByTagName('div')[0].classList.add('bg-gray-200'); replyElement.getElementsByTagName('div')[0].innerText += content; answer = replyElement.getElementsByTagName('div')[0].innerText; chatMessages.scrollTop = chatMessages.scrollHeight } histories.push( { role: "user", content: message }, { role: "assistant", content: answer } ); chatSubmit.disabled = false; } catch (error) { // Handle fetch request errors if (signal.aborted) { replyElement.innerText = "Request aborted."; } else { replyElement.innerText = "Error occurred while generating."; return true; } chatSubmit.disabled = false; } finally { chatSubmit.disabled = false; // Enable the generate button and disable the stop button controller = null; // Reset the AbortController instance } } })();
<?php /** * @package Joomla.Administrator * @subpackage com_newsfeeds * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('JPATH_BASE') or die; use Joomla\CMS\Language\LanguageHelper; /** * Supports a modal newsfeeds picker. * * @since 1.6 */ class JFormFieldModal_Newsfeed extends JFormField { /** * The form field type. * * @var string * @since 1.6 */ protected $type = 'Modal_Newsfeed'; /** * Method to get the field input markup. * * @return string The field input markup. * * @since 1.6 */ protected function getInput() { $allowNew = ((string) $this->element['new'] == 'true'); $allowEdit = ((string) $this->element['edit'] == 'true'); $allowClear = ((string) $this->element['clear'] != 'false'); $allowSelect = ((string) $this->element['select'] != 'false'); $allowPropagate = ((string) $this->element['propagate'] == 'true'); $languages = LanguageHelper::getContentLanguages(array(0, 1)); // Load language JFactory::getLanguage()->load('com_newsfeeds', JPATH_ADMINISTRATOR); // The active newsfeed id field. $value = (int) $this->value > 0 ? (int) $this->value : ''; // Create the modal id. $modalId = 'Newsfeed_' . $this->id; // Add the modal field script to the document head. JHtml::_('jquery.framework'); JHtml::_('script', 'system/modal-fields.js', array('version' => 'auto', 'relative' => true)); // Script to proxy the select modal function to the modal-fields.js file. if ($allowSelect) { static $scriptSelect = null; if (is_null($scriptSelect)) { $scriptSelect = array(); } if (!isset($scriptSelect[$this->id])) { JFactory::getDocument()->addScriptDeclaration(" function jSelectNewsfeed_" . $this->id . "(id, title, object) { window.processModalSelect('Newsfeed', '" . $this->id . "', id, title, '', object); } " ); JText::script('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED'); $scriptSelect[$this->id] = true; } } // Setup variables for display. $linkNewsfeeds = 'index.php?option=com_newsfeeds&amp;view=newsfeeds&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1'; $linkNewsfeed = 'index.php?option=com_newsfeeds&amp;view=newsfeed&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1'; $modalTitle = JText::_('COM_NEWSFEEDS_CHANGE_FEED'); if (isset($this->element['language'])) { $linkNewsfeeds .= '&amp;forcedLanguage=' . $this->element['language']; $linkNewsfeed .= '&amp;forcedLanguage=' . $this->element['language']; $modalTitle .= ' &#8212; ' . $this->element['label']; } $urlSelect = $linkNewsfeeds . '&amp;function=jSelectNewsfeed_' . $this->id; $urlEdit = $linkNewsfeed . '&amp;task=newsfeed.edit&amp;id=\' + document.getElementById("' . $this->id . '_id").value + \''; $urlNew = $linkNewsfeed . '&amp;task=newsfeed.add'; if ($value) { $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select($db->quoteName('name')) ->from($db->quoteName('#__newsfeeds')) ->where($db->quoteName('id') . ' = ' . (int) $value); $db->setQuery($query); try { $title = $db->loadResult(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } } $title = empty($title) ? JText::_('COM_NEWSFEEDS_SELECT_A_FEED') : htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); // The current newsfeed display field. $html = '<span class="input-append">'; $html .= '<input class="input-medium" id="' . $this->id . '_name" type="text" value="' . $title . '" disabled="disabled" size="35" />'; // Select newsfeed button if ($allowSelect) { $html .= '<button' . ' type="button"' . ' class="btn hasTooltip' . ($value ? ' hidden' : '') . '"' . ' id="' . $this->id . '_select"' . ' data-toggle="modal"' . ' data-target="#ModalSelect' . $modalId . '"' . ' title="' . JHtml::tooltipText('COM_NEWSFEEDS_CHANGE_FEED') . '">' . '<span class="icon-file" aria-hidden="true"></span> ' . JText::_('JSELECT') . '</button>'; } // New newsfeed button if ($allowNew) { $html .= '<button' . ' type="button"' . ' class="btn hasTooltip' . ($value ? ' hidden' : '') . '"' . ' id="' . $this->id . '_new"' . ' data-toggle="modal"' . ' data-target="#ModalNew' . $modalId . '"' . ' title="' . JHtml::tooltipText('COM_NEWSFEEDS_NEW_NEWSFEED') . '">' . '<span class="icon-new" aria-hidden="true"></span> ' . JText::_('JACTION_CREATE') . '</button>'; } // Edit newsfeed button if ($allowEdit) { $html .= '<button' . ' type="button"' . ' class="btn hasTooltip' . ($value ? '' : ' hidden') . '"' . ' id="' . $this->id . '_edit"' . ' data-toggle="modal"' . ' data-target="#ModalEdit' . $modalId . '"' . ' title="' . JHtml::tooltipText('COM_NEWSFEEDS_EDIT_NEWSFEED') . '">' . '<span class="icon-edit" aria-hidden="true"></span> ' . JText::_('JACTION_EDIT') . '</button>'; } // Clear newsfeed button if ($allowClear) { $html .= '<button' . ' type="button"' . ' class="btn' . ($value ? '' : ' hidden') . '"' . ' id="' . $this->id . '_clear"' . ' onclick="window.processModalParent(\'' . $this->id . '\'); return false;">' . '<span class="icon-remove" aria-hidden="true"></span>' . JText::_('JCLEAR') . '</button>'; } // Propagate newsfeed button if ($allowPropagate && count($languages) > 2) { // Strip off language tag at the end $tagLength = (int) strlen($this->element['language']); $callbackFunctionStem = substr("jSelectNewsfeed_" . $this->id, 0, -$tagLength); $html .= '<a' . ' class="btn hasTooltip' . ($value ? '' : ' hidden') . '"' . ' id="' . $this->id . '_propagate"' . ' href="#"' . ' title="' . JHtml::tooltipText('JGLOBAL_ASSOCIATIONS_PROPAGATE_TIP') . '"' . ' onclick="Joomla.propagateAssociation(\'' . $this->id . '\', \'' . $callbackFunctionStem . '\');">' . '<span class="icon-refresh" aria-hidden="true"></span>' . JText::_('JGLOBAL_ASSOCIATIONS_PROPAGATE_BUTTON') . '</a>'; } $html .= '</span>'; // Select newsfeed modal if ($allowSelect) { $html .= JHtml::_( 'bootstrap.renderModal', 'ModalSelect' . $modalId, array( 'title' => $modalTitle, 'url' => $urlSelect, 'height' => '400px', 'width' => '800px', 'bodyHeight' => '70', 'modalWidth' => '80', 'footer' => '<button type="button" class="btn" data-dismiss="modal">' . JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>', ) ); } // New newsfeed modal if ($allowNew) { $html .= JHtml::_( 'bootstrap.renderModal', 'ModalNew' . $modalId, array( 'title' => JText::_('COM_NEWSFEEDS_NEW_NEWSFEED'), 'backdrop' => 'static', 'keyboard' => false, 'closeButton' => false, 'url' => $urlNew, 'height' => '400px', 'width' => '800px', 'bodyHeight' => '70', 'modalWidth' => '80', 'footer' => '<button type="button" class="btn"' . ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'add\', \'newsfeed\', \'cancel\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">' . JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>' . '<button type="button" class="btn btn-primary"' . ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'add\', \'newsfeed\', \'save\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">' . JText::_('JSAVE') . '</button>' . '<button type="button" class="btn btn-success"' . ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'add\', \'newsfeed\', \'apply\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">' . JText::_('JAPPLY') . '</button>', ) ); } // Edit newsfeed modal. if ($allowEdit) { $html .= JHtml::_( 'bootstrap.renderModal', 'ModalEdit' . $modalId, array( 'title' => JText::_('COM_NEWSFEEDS_EDIT_NEWSFEED'), 'backdrop' => 'static', 'keyboard' => false, 'closeButton' => false, 'url' => $urlEdit, 'height' => '400px', 'width' => '800px', 'bodyHeight' => '70', 'modalWidth' => '80', 'footer' => '<button type="button" class="btn"' . ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'edit\', \'newsfeed\', \'cancel\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">' . JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>' . '<button type="button" class="btn btn-primary"' . ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'edit\', \'newsfeed\', \'save\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">' . JText::_('JSAVE') . '</button>' . '<button type="button" class="btn btn-success"' . ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'edit\', \'newsfeed\', \'apply\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">' . JText::_('JAPPLY') . '</button>', ) ); } // Add class='required' for client side validation $class = $this->required ? ' class="required modal-value"' : ''; $html .= '<input type="hidden" id="' . $this->id . '_id"' . $class . ' data-required="' . (int) $this->required . '" name="' . $this->name . '" data-text="' . htmlspecialchars(JText::_('COM_NEWSFEEDS_SELECT_A_FEED', true), ENT_COMPAT, 'UTF-8') . '" value="' . $value . '" />'; return $html; } /** * Method to get the field label markup. * * @return string The field label markup. * * @since 3.4 */ protected function getLabel() { return str_replace($this->id, $this->id . '_id', parent::getLabel()); } }
// // Network.swift // AutoChek // // Created by mac on 12/5/21. // import UIKit import SVGKit import Kingfisher class Network { //MARK: - Method to get data for make and logo func getMakeAndLogo(completionHandler: @escaping (MakeAndLogoModel) -> ()) { let url = "https://api-prod.autochek.africa/v1/inventory/make?popular=true" if let url = URL(string: url) { URLSession.shared.dataTask(with: url) { data, response, error in if let data = data { do { let json = try JSONDecoder().decode(MakeAndLogoModel.self, from: data) completionHandler(json) } catch { } } }.resume() } } //MARK: - Method to load imageview with image from url using svg dependency func loadImage(_ urlString: String, _ imageView: UIImageView){ guard let url = URL(string: urlString) else { return } URLSession.shared.dataTask(with: url) { data, _, error in guard error == nil, let image: SVGKImage = SVGKImage(contentsOf: url) else { return } DispatchQueue.main.async { imageView.image = image.uiImage } }.resume() } func getCarDetails(completionHandler: @escaping (CarDetailsModel) -> ()) { let url = "https://api-prod.autochek.africa/v1/inventory/car/search" if let url = URL(string: url) { URLSession.shared.dataTask(with: url) { data, response, error in if let data = data { do { let json = try JSONDecoder().decode(CarDetailsModel.self, from: data) completionHandler(json) } catch { } } }.resume() } } func getCarFeatures(_ carID: String, completionHandler: @escaping (CarFeature) -> ()) { let url = "https://api-prod.autochek.africa/v1/inventory/car/\(carID)" if let url = URL(string: url) { URLSession.shared.dataTask(with: url) { data, response, error in if let data = data { do { let json = try JSONDecoder().decode(CarFeature.self, from: data) completionHandler(json) } catch { } } }.resume() } } }
package remove import ( "github.com/BenjuhminStewart/stew/types" "github.com/spf13/cobra" "github.com/spf13/viper" ) // RemoveCmd represents the delete command var RemoveCmd = &cobra.Command{ Use: "remove <name_of_stew>", Short: "Remove a stew", Long: `stew remove <name_of_stew> [flags]`, Run: func(cmd *cobra.Command, args []string) { s := types.Stews{} err := s.Load(viper.GetString("stewsPath")) if err != nil { cmd.Println(err) return } if len(args) == 0 { cmd.Help() return } name := args[0] _, err = s.GetByName(name) if err != nil { cmd.Println(err) return } err = s.RemoveByName(name) if err != nil { cmd.Println(err) return } err = s.Save(viper.GetString("stewsPath")) if err != nil { cmd.Println(err) return } }, } func flags() { RemoveCmd.Flags().IntP("id", "i", -1, "The id of the stew you want to remove") RemoveCmd.Flags().StringP("name", "n", "", "The name of the stew you want to remove") } func init() { // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // deleteCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // deleteCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") flags() }
--- title: In 2024, How To Remove Flashlight From iPhone X Lock Screen | Dr.fone date: 2024-05-19T07:27:20.163Z updated: 2024-05-20T07:27:20.163Z tags: - unlock - remove screen lock categories: - ios - iphone description: This article describes How To Remove Flashlight From iPhone X Lock Screen excerpt: This article describes How To Remove Flashlight From iPhone X Lock Screen keywords: remove flashlight from iphone lock screen,iphone locked to owner,unlock iphone screen passcode,iphone passcode not working after update ios 13,forgot iphone pin,unlock iphone passcode without computer,iphone lost mode unlock,forgot passcode on iphone,unlock iphone 5 passcode without itunes,unlock iphone without passcode,iphone 15 unlock thumbnail: https://www.lifewire.com/thmb/wAMAGSxPA1Fx2QobaiyABiSggJ4=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/GettyImages-753288077-5bb0f9b2cff47e00261aa8fc.jpg --- ## How To Remove Flashlight From Apple iPhone X Lock Screen Ever wonder why the flashlight shows up on your Apple iPhone X lock screen? Especially when it happens in your pocket or while you're holding it. If you, like many, accidentally turn it on and drain your battery, no need to worry. While you can't remove it, figuring out **how to remove flashlight from iPhone lock screens** is a common question. This guide shares several ways to prevent accidental activations and save your device's battery. Keep reading for easy solutions to take charge of your Apple iPhone X's lock screen and make it work better for you. ![iphone lock screen](https://images.wondershare.com/drfone/article/2024/01/remove-flashlight-from-lock-screen-01.jpg) ## Part 1: How To Remove Flashlight From iPhone Lock Screens? You can't remove the shortcuts like the flashlight icon from an iPhone lock screen. These are built-in features, and Apple doesn't currently offer an option to disable them. However, there are some workarounds to make the flashlights less accessible and avoid turning them on accidentally. You can turn off Tap to Wake, Raise to Wake, remove the flashlight icon from the control center, and turn off the Back Tap shortcut. Find out the steps below. Quick Fix No. 1: Turn Off Tap To Wake Tap to Wake lets you light up your Apple iPhone X screen with a simple tap. It's handy, but there's a catch – tapping near the bottom right corner might accidentally turn on the flashlight icon. The Tap to Wake feature can be troublesome, especially in the dark, when you don't want any unexpected brightness. Turning off the Tap to Wake feature is not directly related to the issue of iPhone users wanting to **remove the flashlight from lock screens**. However, adjusting settings like Tap to Wake can be part of customizing the overall user experience on an iPhone. When turned off, the screen won't light up with a tap, reducing the likelihood of accidentally triggering the flashlight. Here is how to turn off the Tap to Wake feature: - **Step 1:** Go to **Settings** or **General** > **Accessibility** on your Apple iPhone X device. - **Step 2:** Toggle off **Tap to Wake**. ![iphone turn off tap to wake](https://images.wondershare.com/drfone/article/2024/01/remove-flashlight-from-lock-screen-02.jpg) Quick Fix No. 2: Turn Off Raise To Wake With "Raise to Wake" enabled, simply picking up your phone can activate the lock screen. Consequently, the flashlight icon becomes more susceptible to accidental touches. To address this, turning off this feature stops the screen from waking when you lift your Apple iPhone X. By doing so, it becomes less likely that you'll accidentally turn on the flashlight when you pick up your iOS device. Here is **how to remove flashlights from iPhone lock screens** when not needed: - **Step 1:** Head to **Settings** > **Display & Brightness** on your iOS device. - **Step 2:** Toggle off the **Raise to Wake** option. ![iphone turn off raise to wake](https://images.wondershare.com/drfone/article/2024/01/remove-flashlight-from-lock-screen-03.jpg) Quick Fix No. 3: Remove the Flashlight From the Control Center The Control Center on iPhones is a quick-access panel. You can access it by swiping down from the top right corner of your screen. There, you can control various settings, like the flashlight. If you remove it, the flashlight becomes less accessible from the lock screen. Follow these steps to remove the flashlight from the control center: - **Step 1:** Open the **Settings** app and navigate to **Control Center**. - **Step 2:** Tap on **Customize Controls**, then find the **Flashlight** icon. - **Step 3:** Tap the red minus (**\-**) sign next to the **Flashlight** icon. - **Step 4:** Tap **Remove** to confirm deleting the **Flashlight** icon from the **Control Center**. ![remove flashlight from iphone control center](https://images.wondershare.com/drfone/article/2024/01/remove-flashlight-from-lock-screen-04.jpg) Quick Fix No. 4: Turn Off Back Tap Shortcut Back Tap on the Apple iPhone X lets you set actions for double or triple taps on the back. One of these actions is turning on the flashlight. If you often tap your phone's back, you might accidentally activate the flashlight. Turning off the Back Tap for the flashlight prevents these accidental activations. Although the flashlight icon remains on the lock screen, you won't accidentally turn it on by hitting the back of your phone. Here's how to disable the Back Tap for the flashlight shortcut: - **Step 1**: Go to **Settings** > **Accessibility** > **Touch** > **Back Tap**. - **Step 2:** Select the **Double Tap** or **Triple Tap** option you're using for the flashlight shortcut. - **Step 3:** Choose **None** instead of the currently assigned action, which might be ****Flashlight****. ![setup iphone back tap to none](https://images.wondershare.com/drfone/article/2024/01/remove-flashlight-from-lock-screen-05.jpg) ## Part 2: How To Turn Off the Flashlight on iPhone? Now, let's address turning off the flashlight on your Apple iPhone X. Even if you've applied Part 1's solutions, knowing how to switch off the flashlight is crucial. In this section, you'll learn **how to turn the light off on iPhone** devices. Method No. 1: Turn Off the Flashlight in the Control Center You can't remove the flashlight icon from the lock screen, but you can still turn it off easily. Just swipe down from the upper-right corner or swipe up from the bottom (for iPhones with a Home button). Then, follow these steps to discover **how to turn off the flashlight** on your Apple iPhone X: Here's how to do it. - **Step 1:** Find the flashlight icon in the **Control Center**. It's usually located in the bottom left corner. - **Step 2:** Tap on the flashlight icon once to turn it off. The icon will turn gray, indicating the flashlight is deactivated. ![turn off flashlight from control center](https://images.wondershare.com/drfone/article/2024/01/remove-flashlight-from-lock-screen-06.jpg) This method is fast and convenient, especially if you've kept the flashlight icon in the Control Center. Plus, it works regardless of how the flashlight was activated, even if it was an accidental tap on the lock screen. Method No. 2: Use Siri To Turn Off Flashlight To go hands-free and avoid accidental taps, you can use Siri to turn off the flashlight. For those who favor a hands-free approach, it offers an alternative method, particularly if you haven't customized the Control Center. Here's **how to turn off the flashlight** with Siri on your Apple iPhone X: - **Step 1:** Say **"Hey Siri"** or press and hold the power button (or Home button on older iPhones) to activate Siri. - **Step 2:** Give the commands saying, **"Turn off the flashlight."** - **Step 3:** Siri will confirm your request and turn off the flashlight. You'll hear a voice cue and see the flashlight icon on your screen dim. ![use siri to turn off flashlight](https://images.wondershare.com/drfone/article/2024/01/remove-flashlight-from-lock-screen-07.jpg) Remember, even with Siri, ensure your Apple iPhone X's microphone isn't covered or blocked for successful voice recognition. ## Bonus Part: Easily Unlock Your Apple iPhone X Without a Password Removing the flashlight shortcut avoids accidentally activating the Apple iPhone X flashlight. But what if you forget your lock screen passcode and need to access your Apple iPhone X? That's where [<u>Wondershare Dr.Fone</u>](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/) Screen Unlock (iOS) comes in, offering a powerful toolkit for regaining access to your locked iOS device. This software effortlessly [<u>bypasses any lock screen</u>](https://drfone.wondershare.com/unlock/bypass-android-lock-screen.html), so you can access your data in a few steps. Dr.Fone works seamlessly with the latest iOS versions and devices, providing a dependable safety net for iPhone users. **Key Features:** - If you've forgotten your phone's password or bought a second-hand device, here's how Dr.Fone can help you: - Bypasses various lock screen types like [<u>pattern</u>](https://drfone.wondershare.com/unlock/pattern-lock.html), 4 or 6-digit passcode, Touch ID, and Face ID without the original passcode. - [<u>Removes iCloud Activation Lock</u>](https://drfone.wondershare.com/icloud/bypass-iphone-11-12-icloud-activation-lock.html)on a used or lost iPhone/iPad, allowing it to be set up with a new Apple ID. - Offers a simple, intuitive interface with clear instructions. Forgotten passcodes and iCloud Activation Lock can leave you feeling shut out. To address this issue, here's a step-by-step guide using Dr.Fone Screen Unlock (iOS): - **Step 1:** Download and install Dr. Fone's desktop app on your computer. Make sure you get the latest version for optimal compatibility. Launch the app and select the **Screen Unlock** option from the **Toolbox** homepage. ![dr.fone homepage desktop interface](https://images.wondershare.com/drfone/guide/drfone-home.png) - **Step 2:** Select **iOS** as the Apple iPhone X device type. Then, within the **Screen Unlock** window, select **Unlock iOS Screen** to begin the process. ![dr.fone screen unlock tools](https://images.wondershare.com/drfone/guide/unlock-ios-screen-1.png) - **Step 3:** Click **Start** to remove the iOS screen lock. ![start to remove ios screen lock](https://images.wondershare.com/drfone/guide/unlock-ios-screen-2.png) - **Step 4:** Get your Apple iPhone X and a USB cable. Connect the phone to your computer and wait for Dr.Fone to recognize it. Next, put your Apple iPhone X into Recovery Mode using specific button combinations for your model. ![on screen instructions for recovery mode](https://images.wondershare.com/drfone/guide/unlock-ios-screen-3.png) - **Step 5:** Check your **Device Model**, select the **System Version** you need from the dropdown list, then click **Start**. ![dr.fone select system version](https://images.wondershare.com/drfone/guide/unlock-ios-screen-4.png) - **Step 6:** Dr.Fone will download and install the latest iOS firmware on your device. Then, click **Unlock Now** once the firmware is ready. Follow the on-screen instructions to continue unlocking your device. ![dr.fone downloading ios firmware](https://images.wondershare.com/drfone/guide/unlock-ios-screen-5.png) - **Step 7:** Once the process is complete, Dr.Fone will notify you. Your Apple iPhone X should be unlocked and ready for you to set it up again with your preferred settings and Apple ID. ![dr.fone removed ios lock screen](https://images.wondershare.com/drfone/guide/unlock-ios-screen-9.png) ## Conclusion Resolving the issue of **how to remove flashlight from iPhone lock screens** is attainable with these workarounds. Turning off Tap to Wake and Raise to Wake reduces accidental activations. Customizing the Control Center and Back Tap allows precise accessibility adjustments. Additionally, learn **how to turn off the flashlight** using straightforward methods: either through the Control Center or by instructing Siri to do so. These solutions ensure a personalized lock screen experience, minimizing unwanted light disruptions. And if ever locked out with the flashlight on, consider Dr.Fone Screen Unlock. This powerful tool bypasses various screen locks, including passcodes, Face IDs, and Touch IDs. Dr.Fone remains a valuable safety net for unexpected moments while fixing your iOS device. Customize your Apple iPhone X lock screen settings with these tips for a seamless experience. _**Tips:** Are you searching for a powerful Screen Unlock tool? No worries as [Dr.Fone](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) is here to help you. Download it and start a seamless unlock experience!_ ## Complete Guide For Apple iPhone X Lock Screen Like most iPhone users, you rely on your lock screen to keep your data safe and protected. But with the release of iOS 17, there are a few new features and changes that you need to know about. This complete guide will clarify everything you need to know about the iOS 17 lock screen. We'll explain to you how to use the new features, protect your data, and more. So don't waste any time - read on for all the details! ## How to Have a Customized iOS 17 Lock Screen? Before we get started, you should know that there are three ways to have a customized lock screen in iOS 17. Let's get to know more about them. ![ios 17 lock screen](https://images.wondershare.com/drfone/article/2022/11/ios-15-lock-screen-1.jpg) ### 1\. How to select your favorite wallpaper The first way is to use a pre-made wallpaper from the Apple Wallpaper Gallery. To do this, go to Settings > Wallpapers & Brightness > Choose a New Wallpaper. Then, select the Apple Wallpaper Gallery and choose the image you want to use. ![select favorite wallpaper](https://images.wondershare.com/drfone/article/2022/11/ios-15-lock-screen-2.jpg) The second way to have a customized lock screen is to use a Live Photo. To do this, go to Settings > Wallpapers & Brightness > Choose a New Wallpaper. Then, select the Live Photo option and choose the image you want to use. **Note:** You can only use Live Photos for your lock screen if your Apple iPhone X is unlocked. ### 2\. How to manage notifications If you want to manage notifications on the iOS 17 lock screen, there are two ways to do it. At first, you can go to Settings > Notifications. Here, you can choose how many notifications you want to see on your lock screen and which apps can send you notifications. ![lock screen notification setting](https://images.wondershare.com/drfone/article/2022/11/ios-15-lock-screen-3.jpg) The Do Not Disturb feature is the second way to manage notifications. To do this, go to Settings > Do Not Disturb and enable the feature. You can also schedule when Do Not should turn on and off. This feature work like a charm if you want to silence all notifications at night. ### 3\. How to set Auto-Lock time If you want to set the Auto-Lock time, go to Settings > Display & Brightness > Auto-Lock. Here, you can choose how long it should take for your Apple iPhone X to lock automatically. ![set auto lock on ios 17 lock screen](https://images.wondershare.com/drfone/article/2022/11/ios-15-lock-screen-4.jpg) By default, the Auto-Lock time is set to 30 seconds. But you can choose to lock it immediately, after 1 minute, 5 minutes, or never. ## How to Turn Off/On Lock Screen in iOS 17? If you want to turn off the lock screen, go to Settings > Touch ID & Passcode (or Face ID & Passcode). Then, scroll down and disable the Unlock with Passcode (or Unlock with Face ID) option. Enable the Unlock with Passcode (or Unlock with Face ID) to turn ON the lock screen. ![ios 17 lock screen](https://images.wondershare.com/drfone/article/2022/11/ios-15-lock-screen-5.jpg) But if you have forgotten your passcode, don't worry. The next section will show you how to bypass the lock screen. ## How to Bypass the iOS 17 Lock Screen Passcode? Different methods can help you bypass the iOS 17 lock screen passcode. Let's discuss them in detail. ### 1\. Use Emergency call The first method to bypass the passcode is to use the emergency call feature. To do this, access your device with five wrong passcodes attempts. This will trigger the emergency call feature. All you need to do is, dial an emergency number and then tap on the cancel button, and you'll be taken to the home screen. That's how you bypass the lock screen without losing any data. ![emergency dial](https://images.wondershare.com/drfone/article/2022/11/ios-15-lock-screen-6.jpg) ### 2\. Bypass passcode with iTunes restore If your Apple iPhone X needs to be backed up with iTunes sync feature, you can use this method to bypass the passcode. To do this, connect your Apple iPhone X to a computer and open iTunes. Then, click the Restore button and follow the on-screen instructions to restore your Apple iPhone X. It will take some time, but you can use your Apple iPhone X without a passcode once it's done. ![recovery mode on itunes](https://images.wondershare.com/drfone/article/2022/11/ios-15-lock-screen-7.jpg) ### 3\. Use Find My in iCloud If you have synced your Apple iPhone X with iCloud, you can try the Find My feature to bypass the lock screen. To do this, go to icloud.com/#find and sign in with your Apple ID. Then, select your device from the list of devices and click on the Erase button. To do this, go to icloud.com/#find and sign in with your Apple ID. Then, select your device from the list of devices and click on the Erase button. All the data will disappear on your Apple iPhone X, and you'll be able to access it without a passcode. This process can also take some time, so be patient. ![find My Apple iPhone X feature](https://images.wondershare.com/drfone/article/2022/11/ios-15-lock-screen-8.jpg) ### 4\. Dr.Fone-Screen Unlock If all mentioned methods don't work for you, the ultimate solution is to use Wondershare Dr.Fone-Screen Unlock and bypass the passcode. To finish it, you can follow the steps given below carefully. **Step #1: Download/Install Dr.Fone on your Computer or MacBook** A third-party tool named Dr.Fone-Screen Unlock can help you in this regard. The wonderful part is that you don't have to learn any technical knowledge. First, download/install Dr.Fone-Screen Unlock on your computer or MacBook. You can get it from here: After downloading the tool, install launch it on your PC. **Step #2: Launch the Application and Go for Screen Unlock** Once you have installed the tool, launch it and go to its main window. Here, you will see different features. Select the Screen Unlock feature from the list. ![ios 17 passcode bypass](https://images.wondershare.com/drfone/guide/drfone-home.png) **Step #3: Connect your Apple iPhone X and Activate DFU Mode** Now, you need to connect your Apple iPhone X to the computer using an Apple original cable. Once done, you need to put your Apple iPhone X into DFU mode. To do this, you need to press and hold the Home button and Sleep/Wake button simultaneously for 10 seconds. After that, release the Sleep/Wake button but keep holding the Home button until Dr.Fone detects your device in DFU mode. ![recovery mode to bypass ios 17 lock screen](https://images.wondershare.com/drfone/guide/unlock-ios-screen-3.png) **Step #4: Download the Appropriate Firmware** Once Dr.Fone detects your Apple iPhone X, it will ask you to continue. So, proceed to the next, and here you will be asked to download the correct firmware package for your device. So, choose the firmware carefully and hit the download button. Depending on your internet connection, you may have to wait for a longer time. But once the firmware is downloaded successfully, you can proceed to the next step. ![ios 17 lock screen](https://images.wondershare.com/drfone/guide/unlock-ios-screen-4.png) **Step #5: Unlock your Apple iPhone X** After the firmware is downloaded, you need to press the Unlock Now button, and Dr.Fone will start to unlock your Apple iPhone X without a passcode. Once it is done, you can get into your device without any restriction. ![ios 17 lock screen without passcode](https://images.wondershare.com/drfone/guide/unlock-ios-screen-6.png) ## FAQs ### Why iOS 17 Lock Screen is not working? There could be many reasons for the malfunction of the Lock Screen in iOS 17. The most common reason is the installation of incompatible jailbreak tweaks. Therefore, it is recommended to remove all the jailbreak tweaks and check whether the problem persists. You can try resetting your device to factory settings if the problem still exists. But make sure to back up your data before doing so, as it will erase all your data. ### How do I fix my iOS 17 lock screen bugs? There are various ways to fix the lock screen bugs in iOS 17. You can try resetting your device to factory settings, or you can also try restoring your device from a previous backup. If none of these methods work, you can try using a third-party tool like Dr.Fone-Screen Unlock to bypass the lock screen. ### How do you unlock a locked iPhone iOS 17? There are various ways to unlock a locked iPhone running on iOS 17. You can try the feature of Find My iPhone, or you can also use a third-party tool like Dr.Fone-Screen Unlock. ### How do you fix an unresponsive lock screen on iPhone running on iOS 17? If your lock screen is unresponsive on iPhone running on iOS 17, you can try force restarting your device. To do this, you need to press and hold the Home button and Sleep/Wake button simultaneously for 10 seconds. After that, release the Sleep/Wake button but keep holding the Home button until you see the Apple logo. Once your device is restarted, check if the problem persists or not. If the problem still bothers you, you can try using a third-party tool like Dr.Fone-Screen Unlock to reset the phone, eventually fixing the issue. ### The Bottom Line So this is what we want to talk about the iOS 17 Lock Screen with you. We have tried to cover everything in this article, including the new features, lock screen bugs, and how to fix them. All the fixes mentioned above are tested and proven to be working. So you can try them without any hesitation. But if you are still facing problems with your lock screen, then the greatest thing you can do is to use a third-party tool like Dr.Fone-Screen Unlock. This tool is very easy to use and will unlock your device within minutes. So, if you are looking for a hassle-free solution to fix your lock screen issues, then this is the best one you should never miss. ## Easy Steps on How To Create a New Apple ID Account On Apple iPhone X Your Apple ID is your gateway to a world of apps and services, making it an essential part of your Apple experience. Whether you're a new Apple user or simply looking to start fresh, **creating a new Apple ID** can open the doors to endless possibilities. This guide will walk you through creating a new account for Apple devices in an easy-to-understand manner. From setting up your email address to securing your account, this article covered you every step of the way. Embark on this journey and learn **how to create a new Apple ID account** effortlessly. ![create a free apple id](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-01.jpg) ## Part 1: Why Create a New Apple ID? You might need to create a new Apple ID to enhance your Apple experience. Let's dive into why it's a good idea: ### A. Reasons for Creating a New Apple ID Account Here's a breakdown of the reasons why you should **create a new Apple ID for your Apple iPhone X**: - Your Apple ID is like your digital identity. Creating a new one lets you choose a unique email address that suits you, adding a personal touch to your Apple journey. - Maybe you've been using an email for your Apple ID that you don't want to use anymore. Creating a new one helps keep your personal and Apple-related emails separate. - **Switching Devices.**When you switch to a new Apple device, like getting a new iPhone or iPad, creating a unique Apple ID ensures a fresh start tailored to your new gadget. - **Separation of Accounts.**Sometimes, you may want to keep your work-related apps and data separate from your ones. Creating a new Apple ID helps you achieve this separation. - If you're using Apple services for different purposes, such as work and personal use, having separate Apple IDs can help keep everything organized and distinct. ![create a free apple id account](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-02.jpg) ### B. Scenarios Where a New ID Is Needed Below are the common scenarios where a new Apple ID might be needed: - **New Apple Device.**When you purchase a new Apple device, like an iPhone or iPad, you'll need a new Apple ID to set it up and make it truly yours. - **Shared Device.**If multiple people use the same device, creating a new Apple ID for each user ensures that everyone has their own personalized experience. - **Change of Email.**If your current email address associated with your Apple ID is changed or you prefer a new one, creating a unique Apple ID with the updated email is the solution. - **Work and Personal.**To keep your work-related apps and data separate from your personal ones, having separate Apple IDs for each purpose is practical and organized. - **Starting Fresh.**Sometimes, you might want a fresh start with your Apple experience, and creating a new Apple ID provides a clean slate. **Creating a new Apple ID** isn't just about getting a new email; it's about tailoring your Apple experience to your needs, whether for personalization, privacy, or organization. Now that you know why it's essential, let's explore how to create it in the next section. ## Part 2: Step-by-Step Guide: How To Create a New Apple ID Account **Creating a new Apple ID for free** is a straightforward process. Let's break it down into simple steps: ### A. Registering a New Apple ID These are the steps for registering a new Apple ID: - **Step 1:** Open your web browser and visit the [<u>Apple ID account management page</u>](http://appleid.apple.com/). Click the **Create Your Apple ID** button to begin. ![apple id account management page](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-03.jpg) - **Step 2:** On the registration page, you'll be asked to provide your **First name** and **Last name**. Make sure to use the name associated with your new Apple ID. Next, you'll need to enter your preferred email address. This one will be your new Apple ID. **Tip:** Choose an email that's easy to remember and access. ![create your apple id step 1](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-04.jpg) - **Step 3:** Create a strong password that combines letters, numbers, and symbols. This password is essential for the security of your account, so make it unique and hard to guess. Confirm your password by entering it again in the designated field. ### B. Verifying Your Identity The next step is verifying your identity. Check out the steps below: - **Step 4:** Apple takes your security seriously. You may be asked to provide a phone number to verify your identity. This number can be used for account recovery or two-factor authentication. The phone number you provided will receive a verification code. Enter this code in the space provided to confirm your identity. **Note:** It's crucial to ensure that your phone number is accurate and accessible. This number will help you recover your account in case you forget your password or encounter any issues. Apple may use this phone number for two-factor authentication, adding an extra layer of security to your account. ![create your apple id step 2](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-05.jpg) - **Step 5:** Apple may sometimes ask you to complete a **CAPTCHA** or verify your identity to prevent automated account creation. ### C. Setting Up Security Questions The next process will be setting up security questions for your account: - **Step 6:** Apple asks you to choose and answer security questions. These questions provide an additional layer of protection for your account. Select questions that you can easily remember and that others can't guess. ### D. Finalizing the Process To finalize the creation process, refer to the steps given below: - **Step 7:** Read through Apple's Terms and Conditions and Privacy Policy. Once you've understood them, tick the box to confirm that you've read and agree to the iCloud and Apple Media Services Terms and Conditions. Then click **Agree** to proceed. Remember that it's essential to be familiar with Apple's policies to ensure a secure and smooth experience. ![create your apple id step 3](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-06.jpg) - **Step 8:** After completing these steps, Apple will send a confirmation email to the address you provided. Go to your email and open the verification link to confirm your new Apple ID. Congratulations! You've successfully **created a new Apple ID**. With this account, you can now access Apple's services, including the App Store, iCloud, and more. Remember to keep your login credentials secure and use them to personalize your Apple experience fully. ## Part 3: Effortlessly Remove Your Apple ID Using [<u>Wondershare Dr.Fone - Screen Unlock (iOS)</u>](https://drfone.wondershare.com/guide/ios-unlock.html) You can embark on an enhanced Apple experience after successfully **creating your new Apple ID**. Removing the previous one is essential when you create it, especially if you've acquired a second-hand device or no longer want the previous user's associated credentials. This step ensures that your new Apple ID takes center stage, granting you full control over your device and its associated services. But if you encounter difficulties when removing the previous Apple ID from your device, Dr.Fone - Screen Unlock (iOS) is a reliable and user-friendly solution. ![drfone unlock ios screen](https://images.wondershare.com/drfone/guide/remove-apple-id-1.png) ### Key Features of Dr.Fone - Screen Unlock (iOS) This versatile tool offers the following key features in the context of Apple ID issues: - **User-Friendly Interface.**Fone - Screen Unlock (iOS) is designed to be straightforward, making it accessible to users of all levels of technical expertise. - It is usable with a wide range of iOS devices, ensuring you can [<u>remove the previous Apple ID from your device</u>](https://drfone.wondershare.com/apple-account/how-to-remove-apple-id-from-iphone-without-password.html), regardless of the model. - **Multiple Unlock Modes.**Fone offers various unlock modes to cater to different scenarios, including removing the previous Apple ID. This flexibility ensures that you have the right solution for your specific situation. - **Data Security.**Fone - Screen Unlock (iOS) prioritizes data security, ensuring that your personal information and content remain intact during the Apple ID removal process. ### Step-by-Step Guide on Using Dr.Fone Screen Unlock (iOS) Check out the steps on how to remove an Apple ID account using Dr.Fone below: - **Step 1:** Launch Wondershare Dr.Fone on your PC to use the **Screen Unlock** function and then navigate to **Toolbox**. Click the **Screen Unlock** section, then choose **iOS**. ![drfone v13 homepage](https://images.wondershare.com/drfone/guide/drfone-home.png) - **Step 2:** If you want to proceed with deleting your Apple ID, you'll need to go to the next window and select the **Remove AppleID** option from the menu. - **Step 3:** When you hook up your iOS device to a computer, the next screen will report on its connectivity. Select the **Unlock Now** button to proceed. ![remove apple id unlock now](https://images.wondershare.com/drfone/guide/remove-apple-id-2.png) - **Step 4:** Before the Apple ID can be unlocked, the next step is for the platform to ask a series of questions. Verify that a screen lock is active on your iOS device. However, please lock your iOS device before proceeding with the **Yes** option. ![set up screen lock](https://images.wondershare.com/drfone/guide/remove-apple-id-3.png) - **Step 5:** Check if **Two-Factor Authentication** is set up on all your iOS devices. If not, switch it on before confirming your decision to unlock your Apple ID. ![confirm two-factor authentication](https://images.wondershare.com/drfone/guide/remove-apple-id-4.png) - **Step 6:** After you have confirmed these settings, you will be taken to a screen with on-screen instructions for entering **Recovery Mode** on your iDevice. If the steps for your specific iOS device don't work, try tapping **Try DFU Mode** in the app's bottom left corner. To continue with the unlocking process, this will [<u>launch the DFU Mode</u>](https://drfone.wondershare.com/dfu-mode/tools-for-iphone-to-enter-dfu-mode.html) instructions. ![try dfu mode](https://images.wondershare.com/drfone/guide/remove-apple-id-5.png) - **Step 7:** Once **Recovery Mode** has been activated, the Apple iPhone X device's information will be shown on the subsequent screen. Once the **Device Model** has been identified, all that remains is to choose the appropriate **System Version** and click **Start**. However, if there are disagreements in recognition, pick the details by hand and move forward. ![choose device model](https://images.wondershare.com/drfone/guide/unlock-ios-screen-4.png) - **Step 8:** The appropriate iOS firmware begins downloading, showing its status on the following screen. Click the **Copy** button to copy the direct URL to [<u>download iOS firmware</u>](https://drfone.wondershare.com/ios-upgrade/how-to-upgrade-with-firmware-files.html) for systems with sluggish firmware download speeds. - **Step 9:** The platform checks the downloaded firmware and displays its details on the following screen. To proceed with unlocking your Apple ID, click the **Unlock Now** button. To proceed, you will be prompted to input a code into a confirmation window. Enter the code and then click the **Unlock** button. ![firmware complete](https://images.wondershare.com/drfone/guide/remove-apple-id-6.png) - **Step 10:** The following screen shows the unlocking status of your Apple ID. Don't let the Apple iPhone X device lose its connection under any circumstances. The screen prompts the process of completing the Apple ID once the ID has been unlocked. If the Apple ID has been unlocked, click **Done** to proceed. If that fails, click the **Try Again** button and give it another shot. ![apple id completely unlocked](https://images.wondershare.com/drfone/guide/remove-apple-id-8.png) ## Conclusion This guide has simplified the process of **creating a new Apple ID**, ensuring you can effortlessly personalize, secure, and organize your digital experience. **Creating a new Apple ID** is easy, and it allows you to tailor your Apple journey to your preferences. Remember, it's all about you, your privacy, and your convenience. Should you encounter any challenges while managing your Apple ID, such as removing a previous one, consider Dr.Fone - iOS Screen Unlock tool. This user-friendly resource stands ready to assist, ensuring a seamless and secure Apple experience. Explore the possibilities and make the most of your Apple adventure! <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://iphone-unlock.techidaily.com/in-2024-forgot-apple-iphone-13-backup-password-heres-what-to-do-drfone-by-drfone-ios/"><u>In 2024, Forgot Apple iPhone 13 Backup Password? Heres What to Do | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-many-attempts-to-unlock-iphone-xr-drfone-by-drfone-ios/"><u>How Many Attempts To Unlock iPhone XR | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-disabling-apple-iphone-x-parental-restrictions-withwithout-password-drfone-by-drfone-ios/"><u>In 2024, Disabling Apple iPhone X Parental Restrictions With/Without Password | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-easy-steps-on-how-to-create-a-new-apple-id-account-on-iphone-15-pro-drfone-by-drfone-ios/"><u>In 2024, Easy Steps on How To Create a New Apple ID Account On iPhone 15 Pro | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-locked-out-of-iphone-6-plus-5-ways-to-get-into-a-locked-iphone-6-plus-drfone-by-drfone-ios/"><u>In 2024, Locked Out of iPhone 6 Plus? 5 Ways to get into a Locked iPhone 6 Plus | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-can-i-unlock-my-iphone-14-plus-after-forgetting-my-pin-code-drfone-by-drfone-ios/"><u>How Can I Unlock My iPhone 14 Plus After Forgetting my PIN Code? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-apple-iphone-15-plus-apples-new-iphone-drfone-by-drfone-ios/"><u>In 2024, How to Unlock Apple iPhone 15 Plus, Apples New iPhone | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-complete-fixes-to-solve-apple-iphone-11-pro-max-randomly-asking-for-apple-id-password-drfone-by-drfone-ios/"><u>In 2024, Complete Fixes To Solve Apple iPhone 11 Pro Max Randomly Asking for Apple ID Password | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/what-does-jailbreaking-iphone-xr-i-do-get-answers-here-drfone-by-drfone-ios/"><u>What Does Jailbreaking iPhone XR i Do? Get Answers here | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-4-ways-to-unlock-apple-iphone-6-plus-to-use-usb-accessories-without-passcode-drfone-by-drfone-ios/"><u>In 2024, 4 Ways to Unlock Apple iPhone 6 Plus to Use USB Accessories Without Passcode | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-change-country-on-app-store-for-apple-iphone-15-pro-with-7-methods-drfone-by-drfone-ios/"><u>In 2024, How To Change Country on App Store for Apple iPhone 15 Pro With 7 Methods | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-change-country-on-app-store-for-apple-iphone-se-2022-with-7-methods-drfone-by-drfone-ios/"><u>In 2024, How To Change Country on App Store for Apple iPhone SE (2022) With 7 Methods | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/guide-on-how-to-change-your-apple-id-email-address-on-iphone-se-2020-drfone-by-drfone-ios/"><u>Guide on How To Change Your Apple ID Email Address On iPhone SE (2020) | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-bypass-apple-iphone-11-pro-passcode-easily-video-inside-drfone-by-drfone-ios/"><u>How to Bypass Apple iPhone 11 Pro Passcode Easily Video Inside | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/trouble-with-apple-iphone-x-swipe-up-try-these-11-solutions-drfone-by-drfone-ios/"><u>Trouble with Apple iPhone X Swipe-Up? Try These 11 Solutions | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-apple-iphone-7-plus-with-an-apple-watch-and-what-to-do-if-it-doesnt-work-drfone-by-drfone-ios/"><u>In 2024, How to Unlock Apple iPhone 7 Plus With an Apple Watch & What to Do if It Doesnt Work | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-what-does-jailbreaking-apple-iphone-11-pro-max-i-do-get-answers-here-drfone-by-drfone-ios/"><u>In 2024, What Does Jailbreaking Apple iPhone 11 Pro Max i Do? Get Answers here | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-remove-and-reset-face-id-on-iphone-se-drfone-by-drfone-ios/"><u>How to Remove and Reset Face ID on iPhone SE | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/3-ways-to-unlock-iphone-se-2020-without-passcode-or-face-id-drfone-by-drfone-ios/"><u>3 Ways to Unlock iPhone SE (2020) without Passcode or Face ID | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-unlock-iphone-8-with-an-apple-watch-and-what-to-do-if-it-doesnt-work-drfone-by-drfone-ios/"><u>How to Unlock iPhone 8 With an Apple Watch & What to Do if It Doesnt Work | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/disabling-apple-iphone-14-pro-max-parental-restrictions-withwithout-password-drfone-by-drfone-ios/"><u>Disabling Apple iPhone 14 Pro Max Parental Restrictions With/Without Password | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-complete-guide-for-iphone-6-lock-screen-drfone-by-drfone-ios/"><u>In 2024, Complete Guide For iPhone 6 Lock Screen | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-do-you-unlock-your-apple-iphone-se-2022-learn-all-4-methods-drfone-by-drfone-ios/"><u>How Do You Unlock your Apple iPhone SE (2022)? Learn All 4 Methods | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/iphone-is-disabled-here-is-the-way-to-unlock-disabled-apple-iphone-11-drfone-by-drfone-ios/"><u>iPhone Is Disabled? Here Is The Way To Unlock Disabled Apple iPhone 11 | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-unlock-apple-iphone-15-plus-passcode-screen-drfone-by-drfone-ios/"><u>How to Unlock Apple iPhone 15 Plus Passcode Screen? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-fix-apple-iphone-se-unavailable-issue-with-ease-drfone-by-drfone-ios/"><u>In 2024, How To Fix Apple iPhone SE Unavailable Issue With Ease | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-fix-apple-iphone-13-mini-passcode-not-working-drfone-by-drfone-ios/"><u>In 2024, How to Fix Apple iPhone 13 mini Passcode not Working? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/locked-out-of-iphone-7-5-ways-to-get-into-a-locked-iphone-7-drfone-by-drfone-ios/"><u>Locked Out of iPhone 7? 5 Ways to get into a Locked iPhone 7 | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-forgot-iphone-passcode-again-unlock-iphone-12-without-passcode-now-drfone-by-drfone-ios/"><u>In 2024, Forgot iPhone Passcode Again? Unlock iPhone 12 Without Passcode Now | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-change-country-on-app-store-for-apple-iphone-xr-with-7-methods-drfone-by-drfone-ios/"><u>In 2024, How To Change Country on App Store for Apple iPhone XR With 7 Methods | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-remove-flashlight-from-iphone-11-pro-max-lock-screen-drfone-by-drfone-ios/"><u>How To Remove Flashlight From iPhone 11 Pro Max Lock Screen | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-iphone-11-pro-max-without-passcode-drfone-by-drfone-ios/"><u>In 2024, How to Unlock iPhone 11 Pro Max Without Passcode? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/unlock-your-disabled-iphone-7-plus-without-itunes-in-5-ways-drfone-by-drfone-ios/"><u>Unlock Your Disabled iPhone 7 Plus Without iTunes in 5 Ways | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/detailed-review-of-doctorsim-unlock-service-for-apple-iphone-xs-max-drfone-by-drfone-ios/"><u>Detailed Review of doctorSIM Unlock Service For Apple iPhone XS Max | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-passfab-iphone-13-backup-unlocker-top-4-alternatives-drfone-by-drfone-ios/"><u>In 2024, PassFab iPhone 13 Backup Unlocker Top 4 Alternatives | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-a-found-apple-iphone-6s-plus-drfone-by-drfone-ios/"><u>In 2024, How To Unlock A Found Apple iPhone 6s Plus? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/7-top-ways-to-resolve-apple-id-not-active-issue-for-apple-iphone-13-drfone-by-drfone-ios/"><u>7 Top Ways To Resolve Apple ID Not Active Issue For Apple iPhone 13 | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-everything-you-need-to-know-about-unlocked-iphone-6s-drfone-by-drfone-ios/"><u>In 2024, Everything You Need To Know About Unlocked iPhone 6s | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-reset-itunes-backup-password-of-apple-iphone-14-pro-prevention-and-solution-drfone-by-drfone-ios/"><u>In 2024, Reset iTunes Backup Password Of Apple iPhone 14 Pro Prevention & Solution | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-apple-iphone-xr-without-passcode-drfone-by-drfone-ios/"><u>In 2024, How to Unlock Apple iPhone XR Without Passcode? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/trouble-with-iphone-13-pro-max-swipe-up-try-these-11-solutions-drfone-by-drfone-ios/"><u>Trouble with iPhone 13 Pro Max Swipe-Up? Try These 11 Solutions | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-remove-flashlight-from-apple-iphone-8-lock-screen-drfone-by-drfone-ios/"><u>How To Remove Flashlight From Apple iPhone 8 Lock Screen | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-access-your-iphone-6s-when-you-forget-the-passcode-drfone-by-drfone-ios/"><u>In 2024, How to Access Your iPhone 6s When You Forget the Passcode? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-can-i-unlock-my-iphone-11-after-forgetting-my-pin-code-drfone-by-drfone-ios/"><u>How Can I Unlock My iPhone 11 After Forgetting my PIN Code? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-turn-off-find-my-iphone-8-plus-when-phone-is-broken-drfone-by-drfone-ios/"><u>In 2024, How to Turn Off Find My iPhone 8 Plus when Phone is Broken? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-can-you-unlock-apple-iphone-11-pro-after-forgetting-the-passcode-drfone-by-drfone-ios/"><u>In 2024, Can You Unlock Apple iPhone 11 Pro After Forgetting the Passcode? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/unlock-apple-iphone-14-with-forgotten-passcode-different-methods-you-can-try-drfone-by-drfone-ios/"><u>Unlock Apple iPhone 14 With Forgotten Passcode Different Methods You Can Try | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/trouble-with-iphone-14-pro-max-swipe-up-try-these-11-solutions-drfone-by-drfone-ios/"><u>Trouble with iPhone 14 Pro Max Swipe-Up? Try These 11 Solutions | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-unlock-iphone-13-without-passcode-or-face-id-drfone-by-drfone-ios/"><u>How to Unlock iPhone 13 without Passcode or Face ID | Dr.fone</u></a></li> <li><a href="https://android-location-track.techidaily.com/3-solutions-to-find-your-samsung-galaxy-a05-current-location-of-a-mobile-number-drfone-by-drfone-virtual-android/"><u>3 Solutions to Find Your Samsung Galaxy A05 Current Location of a Mobile Number | Dr.fone</u></a></li> <li><a href="https://change-location.techidaily.com/how-to-get-the-dragon-scale-and-evolution-enabled-pokemon-on-vivo-s17e-drfone-by-drfone-virtual-android/"><u>How to get the dragon scale and evolution-enabled pokemon On Vivo S17e? | Dr.fone</u></a></li> <li><a href="https://location-social.techidaily.com/4-feasible-ways-to-fake-location-on-facebook-for-your-honor-x8b-drfone-by-drfone-virtual-android/"><u>4 Feasible Ways to Fake Location on Facebook For your Honor X8b | Dr.fone</u></a></li> <li><a href="https://fake-location.techidaily.com/complete-tutorial-to-use-gps-joystick-to-fake-gps-location-on-vivo-y27-5g-drfone-by-drfone-virtual-android/"><u>Complete Tutorial to Use GPS Joystick to Fake GPS Location On Vivo Y27 5G | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/how-to-transfer-everything-from-apple-iphone-se-2022-to-iphone-8x11-drfone-by-drfone-transfer-from-ios/"><u>How to Transfer Everything from Apple iPhone SE (2022) to iPhone 8/X/11 | Dr.fone</u></a></li> <li><a href="https://apple-account.techidaily.com/how-to-remove-apple-iphone-11-device-from-icloud-by-drfone-ios/"><u>How to Remove Apple iPhone 11 Device from iCloud</u></a></li> <li><a href="https://animation-videos.techidaily.com/10-great-apps-to-turn-funny-animated-images-into-comics-for-2024/"><u>10 Great Apps to Turn Funny Animated Images Into Comics for 2024</u></a></li> <li><a href="https://android-transfer.techidaily.com/in-2024-4-ways-to-transfer-music-from-zte-blade-a73-5g-to-iphone-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>In 2024, 4 Ways to Transfer Music from ZTE Blade A73 5G to iPhone | Dr.fone</u></a></li> <li><a href="https://location-social.techidaily.com/in-2024-does-find-my-friends-work-on-vivo-y27-4g-drfone-by-drfone-virtual-android/"><u>In 2024, Does find my friends work on Vivo Y27 4G | Dr.fone</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/in-2024-how-to-use-pokemon-go-joystick-on-tecno-pop-7-pro-drfone-by-drfone-virtual-android/"><u>In 2024, How to use Pokemon Go Joystick on Tecno Pop 7 Pro? | Dr.fone</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/having-trouble-with-black-backgrounds-in-after-effects-land-in-here-to-know-how-you-can-quickly-escape-this-glitch-in-the-simplest-ever-way-possible/"><u>Having Trouble with Black Backgrounds in After Effects? Land in Here to Know How You Can Quickly Escape This Glitch in the Simplest Ever Way Possible</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/in-2024-ipogo-will-be-the-new-ispoofer-on-motorola-edge-2023-drfone-by-drfone-virtual-android/"><u>In 2024, iPogo will be the new iSpoofer On Motorola Edge 2023? | Dr.fone</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-how-to-unlock-nubia-z50-ultra-pin-codepattern-lockpassword-by-drfone-android/"><u>In 2024, How to Unlock Nubia Z50 Ultra PIN Code/Pattern Lock/Password</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/new-2024-approved-how-to-make-a-slow-motion-video-complete-guide/"><u>New 2024 Approved How to Make a Slow Motion Video Complete Guide</u></a></li> <li><a href="https://techidaily.com/how-to-reset-oppo-f23-5g-without-losing-data-drfone-by-drfone-reset-android-reset-android/"><u>How to Reset Oppo F23 5G without Losing Data | Dr.fone</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-how-to-stream-anything-from-realme-v30-to-apple-tv-drfone-by-drfone-android/"><u>In 2024, How To Stream Anything From Realme V30 to Apple TV | Dr.fone</u></a></li> <li><a href="https://bypass-frp.techidaily.com/is-gsm-flasher-adb-legit-full-review-to-bypass-your-tecno-pop-7-profrp-lock-by-drfone-android/"><u>Is GSM Flasher ADB Legit? Full Review To Bypass Your Tecno Pop 7 ProFRP Lock</u></a></li> <li><a href="https://phone-solutions.techidaily.com/how-to-bypass-google-frp-on-honor-magic5-ultimate-by-drfone-android-unlock-remove-google-frp/"><u>How To Bypass Google FRP on Honor Magic5 Ultimate</u></a></li> <li><a href="https://location-social.techidaily.com/in-2024-how-to-send-and-fake-live-location-on-facebook-messenger-of-your-apple-iphone-12-pro-drfone-by-drfone-virtual-ios/"><u>In 2024, How to Send and Fake Live Location on Facebook Messenger Of your Apple iPhone 12 Pro | Dr.fone</u></a></li> </ul></div>
import React from "react"; import Image from "next/image"; import Link from "next/link"; interface MetricProps { imgUrl: string; alt: string; value: string | number; title: string; textStyles?: string; href?: string; isAuther?: boolean; } const Metric = ({ imgUrl, alt, value, title, textStyles, isAuther, href, }: MetricProps) => { const metricContent = ( <> <Image src={imgUrl} alt={alt} height={16} width={16} className={`object-contain ${href ? "rounded-full" : ""}`} /> <p className={`${textStyles} flex items-center gap-1`}> {value} <span className={`small-regular line-clamp-1 ${isAuther ? "max-sm:hidden" : ""}`} > {title} </span> </p> </> ); if (href) { return ( <Link href={href} className="flex-center gap-1"> {metricContent} </Link> ); } return <div className="flex-center flex-wrap gap-1">{metricContent}</div>; }; export default Metric;
#ifndef ROBOTOMYREQUESTFORM_HPP # define ROBOTOMYREQUESTFORM_HPP #include "AForm.hpp" #include <cstdlib> #include <ctime> class RobotomyRequestForm : public AForm { private : const std::string name; bool sign; const int signGrade; const int execGrade; std::string target; public : RobotomyRequestForm(); RobotomyRequestForm(std::string target); ~RobotomyRequestForm(); RobotomyRequestForm(const RobotomyRequestForm &robotomyRequestForm); RobotomyRequestForm &operator=(const RobotomyRequestForm &robotomyRequestForm); std::string getName() const; int getSignGrade() const; int getExecGrade() const; bool getSign() const; void beSigned(Bureaucrat &bureaucrat); int execute(Bureaucrat const & executor) const; void randomNumber() const; }; #endif
/* * Copyright 2003-2021 The Music Player Daemon Project * http://www.musicpd.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef MPD_TIMER_HXX #define MPD_TIMER_HXX #include <chrono> struct AudioFormat; class Timer { typedef std::chrono::microseconds Time; Time time; bool started = false; const int rate; public: explicit Timer(AudioFormat af); bool IsStarted() const { return started; } void Start(); void Reset(); void Add(size_t size); /** * Returns the duration to sleep to get back to sync. */ std::chrono::steady_clock::duration GetDelay() const; private: static Time Now() { return std::chrono::duration_cast<Time>(std::chrono::steady_clock::now().time_since_epoch()); } }; #endif
import { PropsWithChildren, useMemo } from "react"; import { StyleProp, StyleSheet, Text, TextStyle } from "react-native"; import { useTheme } from "./Themed"; interface Props { variant?: "title" | "subtitle" | "text"; align?: "left" | "center" | "right"; color?: string; style?: StyleProp<TextStyle>; } const Typography: React.FC<PropsWithChildren<Props>> = ({ variant = "text", align = "left", color, children, style, }) => { const theme = useTheme(); const s = useMemo( () => ({ ..._styles.common, ..._styles[variant], color: color ?? theme.colors.typography.primary, textAlign: align, ...(typeof style === "object" ? style : {}), }), [], ); return <Text style={s}>{children}</Text>; }; const _styles = StyleSheet.create({ title: { fontSize: 24, fontWeight: "bold", }, subtitle: { fontSize: 19, fontWeight: "bold", }, text: { fontSize: 14, }, common: {}, }); export default Typography;
import { React, useMemo, useState, useEffect } from "react"; import { MaterialReactTable, useMaterialReactTable, } from 'material-react-table'; import axios from 'axios' import "./Scoreboard.css" export const Scoreboard = () => { const [scoreboardData, setScoreboardData] = useState([]); useEffect(() => { axios.get(`/api/user/scoreboard`) .then(responseScores => { console.log("Response Scores ", responseScores); setScoreboardData(responseScores.data.data); }) .catch(error => { console.error('Error fetching user score:', error); }); }, []); // Empty dependency array means this effect runs only once const columns = useMemo( //column definitions... () => [ { accessorKey: 'userName', header: 'User', footer: '', }, { accessorKey: 'scoresLevel1', header: 'Highest Score Level 1', footer: '', }, { accessorKey: 'scoresLevel2', header: 'Highest Score Level 2', footer: '', }, { accessorKey: 'totalScore', header: 'Total Score', footer: '', }, ], [], //end ); let data = null if ((scoreboardData || []).length === 0) { data = [] } else { data = scoreboardData data.forEach(userScore => { userScore.totalScore = userScore.scoresLevel1 + userScore.scoresLevel2 }) } const table = useMaterialReactTable({ columns, data, enableBottomToolbar: false, enableStickyHeader: true, enableStickyFooter: true, enablePagination: false, muiTableContainerProps: { sx: { maxHeight: '400px' } }, muiTableBodyCellProps: { sx: (theme) => ({ backgroundColor: theme.palette.mode === 'dark' ? theme.palette.grey[900] : theme.palette.grey[50], }), }, }); if (data.length === 0) { return <><div className="title"><h1>Scoreboard</h1></div><MaterialReactTable table={table} /></>; } else { return <><div className="title"><h1>Scoreboard</h1></div><MaterialReactTable table={table} /></>; } };
import React from 'react'; import { format } from 'date-fns'; export const Booking = ({ booking }) => { return ( <div className="mb-2 rounded-xl border border-neutral-300 p-2"> <div className="sm:flex sm:items-center sm:justify-around"> <div className="sm:flex sm:items-center sm:gap-4 "> <div className=" size-20 rounded-lg"> <img src={booking?.customer.avatar.url} alt={booking?.customer.avatar.alt} className="h-full w-full rounded-lg object-cover" /> </div> <div className="mt-3"> <div> <p className="text-sm font-semibold">Name</p> <p className="text-sm font-light">{booking?.customer.name}</p> </div> <div> <p className="text-sm font-semibold">Email address</p> <p className="text-sm font-light">{booking?.customer.email}</p> </div> </div> </div> <div className="mt-4 sm:mt-0"> <h3 className="font-semibold">Booking Information</h3> <div className="flex gap-2"> <p className="text-sm font-semibold">Check In:</p> <p className="text-sm font-light"> {format(booking?.dateFrom, 'MMM dd yyyy')} </p> </div> <div className="flex gap-2"> <p className="text-sm font-semibold">Check Out:</p> <p className="text-sm font-light"> {format(booking?.dateTo, 'MMM dd yyyy')} </p> </div> <div className="flex gap-2"> <p className="text-sm font-semibold">Guests:</p> <p className="text-sm font-light">{booking?.guests}</p> </div> </div> </div> </div> ); };
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { CoursesComponent } from './courses.component'; import { CourseComponent } from './course/course.component'; import { CoursesService } from './courses.service'; import { HttpClientModule } from '@angular/common/http'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ declarations: [ AppComponent, CoursesComponent, CourseComponent ], imports: [ BrowserModule, //import http after browser HttpClientModule, NgbModule, ], providers: [ CoursesService ], bootstrap: [AppComponent] }) export class AppModule { }
import Foundation extension ExportChatMessagesRepository { static let `default` = ExportChatMessagesRepository(sdk: MEGASdkManager.sharedMEGASdk(), chatSdk: MEGASdkManager.sharedMEGAChatSdk(), store: MEGAStore.shareInstance()) } class ExportChatMessagesRepository: ExportChatMessagesRepositoryProtocol { private let sdk: MEGASdk private let chatSdk: MEGAChatSdk private let store: MEGAStore init(sdk: MEGASdk, chatSdk: MEGAChatSdk, store: MEGAStore) { self.sdk = sdk self.chatSdk = chatSdk self.store = store } func exportText(message: MEGAChatMessage) -> URL? { let userName = chatSdk.userFullnameFromCache(byUserHandle: message.userHandle) ?? "" let messageTimestamp = message.timestamp?.string(withDateFormat: "dd/MM/yyyy HH:mm") let messageContent = message.content ?? "" let content = "[\(messageTimestamp ?? "")]#\(userName): \(messageContent)\n" let messageFilePath = NSTemporaryDirectory() + "Message \(message.messageId).txt" if (FileManager.default.createFile(atPath: messageFilePath, contents: content.data(using: .utf8), attributes: nil)) { return URL(fileURLWithPath: messageFilePath) } else { return nil } } func exportContact(message: MEGAChatMessage, contactAvatarImage: String?) -> URL? { let cnMutableContact = CNMutableContact() let userHandle = message.userHandle(at: 0) if let moUser = store.fetchUser(withUserHandle: userHandle), let firstname = moUser.firstname, let lastname = moUser.lastname { cnMutableContact.givenName = firstname cnMutableContact.familyName = lastname } else { cnMutableContact.givenName = message.userName(at: 0) ?? "" } let userEmail1 = (message.userEmail(at: 0) ?? "")as NSString cnMutableContact.emailAddresses = [CNLabeledValue.init(label: CNLabelHome, value: userEmail1)] if let avatarFilePath = contactAvatarImage, let avatarImage = UIImage(contentsOfFile: avatarFilePath) { cnMutableContact.imageData = avatarImage.jpegData(compressionQuality: 1) } do { var vCardData = try CNContactVCardSerialization.data(with: [cnMutableContact]) var vCardString = String(data: vCardData, encoding: .utf8) if let base64Image = cnMutableContact.imageData?.base64EncodedString(), !base64Image.isEmpty { let vCardImageString = "PHOTO;TYPE=JPEG;ENCODING=BASE64:" + base64Image + "\n" let endvCardString = vCardImageString + "END:VCARD" vCardString = vCardString?.replacingOccurrences(of: "END:VCARD", with: endvCardString) } vCardData = vCardString?.data(using: .utf8) ?? vCardData do { if let fullName = message.userName(at: 0) { let vCardFilename = fullName + ".vcf" let vCardPath = NSTemporaryDirectory() + vCardFilename let vCardURL = URL(fileURLWithPath: vCardPath) try vCardData.write(to: vCardURL, options: Data.WritingOptions.atomic) return vCardURL } } catch let error as NSError { MEGALogError("Could not write to vCard with error \(error)") } } catch let error as NSError { MEGALogError("Could not create vCard representation of the specified contacts with error \(error)") } return nil } }
import ee import tensorflow as tf import os import numpy as np outputBucket = "/home/burn/Downloads/ee-docs-demos-berlin" # Names for output files. trainFilePrefix = 'Training_demo_' testFilePrefix = 'Testing_demo_' fileNameSuffix = 'ee_export.tfrecord.gz' trainFilePath = outputBucket + '/' + trainFilePrefix + fileNameSuffix testFilePath = outputBucket + '/' + testFilePrefix + fileNameSuffix # Check existence of the exported files print('Found training file.' if tf.gfile.Exists(trainFilePath) else 'No training file found.') print('Found testing file.' if tf.gfile.Exists(testFilePath) else 'No testing file found.') # Create a dataset from the TFRecord file in Cloud Storage. trainDataset = tf.data.TFRecordDataset(trainFilePath, compression_type='GZIP') # Print the first record to check. # print(iter(trainDataset).next()) # Use these bands for prediction. bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'] label = 'landcover' # This is list of all the properties we want to export. featureNames = list(bands) featureNames.append(label) # List of fixed-length features, all of which are float32. columns = [ tf.io.FixedLenFeature(shape=[1], dtype=tf.float32) for k in featureNames ] # Dictionary with names as keys, features as values. featuresDict = dict(zip(featureNames, columns)) def parse_tfrecord(example_proto): """The parsing function. Read a serialized example into the structure defined by featuresDict. Args: example_proto: a serialized Example. Returns: A tuple of the predictors dictionary and the label, cast to an `int32`. """ parsed_features = tf.io.parse_single_example(example_proto, featuresDict) labels = parsed_features.pop(label) return parsed_features, tf.cast(labels, tf.int32) # Map the function over the dataset. parsedDataset = trainDataset.map(parse_tfrecord, num_parallel_calls=5) def normalizedDifference(a, b): """Compute normalized difference of two inputs. Compute (a - b) / (a + b). If the denomenator is zero, add a small delta. Args: a: an input tensor with shape=[1] b: an input tensor with shape=[1] Returns: The normalized difference as a tensor. """ nd = (a - b) / (a + b) nd_inf = (a - b) / (a + b + 0.000001) return tf.where(tf.is_finite(nd), nd, nd_inf) def addNDVI(features, label): """Add NDVI to the dataset. Args: features: a dictionary of input tensors keyed by feature name. label: the target label Returns: A tuple of the input dictionary with an NDVI tensor added and the label. """ features['NDVI'] = normalizedDifference(features['B5'], features['B4']) return features, label from tensorflow import keras # How many classes there are in the model. nClasses = 3 # Add NDVI. inputDataset = parsedDataset.map(addNDVI) # Keras requires inputs as a tuple. Note that the inputs must be in the # right shape. Also note that to use the categorical_crossentropy loss, # the label needs to be turned into a one-hot vector. def toTuple(dict, label): return tf.transpose(list(dict.values())), tf.one_hot(indices=label, depth=nClasses) # Repeat the input dataset as many times as necessary in batches of 10. inputDataset = inputDataset.map(toTuple).repeat().batch(10) # Define the layers in the model. model = tf.keras.models.Sequential([ tf.keras.layers.Dense(64, activation=tf.nn.relu), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(nClasses, activation=tf.nn.softmax) ]) # Compile the model with the specified loss function. model.compile(optimizer=tf.train.AdamOptimizer(), loss='categorical_crossentropy', metrics=['accuracy']) # Fit the model to the training data. # Don't forget to specify `steps_per_epoch` when calling `fit` on a dataset. model.fit(x=inputDataset, epochs=3, steps_per_epoch=100) # Save the model to disk # tf.keras.models.save_model(model, "./model_path", overwrite=True) model.save("./model_path")
<template> <el-form-item :prop="`tableArr.${rowIndex}.${field}`" :rules="buildRules(rowIndex, field)" > <!-- // -important- 这里必须用v-show,让slot组件必渲染,使slot组件能用updateShowText方法,更新当前显示的文本 (如:下拉选项组件实际值可能是数字,但实际需要显示数字代表的文本) // -important- 为了能让slot组件能进行最大的性能优化,因此传递了renderDom,用于告知slot组件,实际是否需要渲染具体的dom节点 (如: select组件,如果选项较多,那会创建大量dom节点,但v-show为false时,这些dom节点虽然看不到,但还是被渲染出来了,因此slot组件应该仅在renderDom为true时,才渲染实际dom节点) // -important- 为什么v-show写在了div标签之上,因为slot标签不允许使用v-show, 因为v-show需要动态更新css的display属性 --> <div v-show="editable"> <slot ref="itemRef" :update-show-text="updateShowText" :render-dom="editable" ></slot> </div> <MarkErrorPopover v-if="!editable" :val="showText" :mark-error="getRowFieldErrorMsg(rowIndex, field)" :disabled="true" @on-clear-mark-error="onClearMarkError" @on-save-mark-error="onSaveMarkError" ></MarkErrorPopover> </el-form-item> </template> <script setup lang="ts"> import MarkErrorPopover from '../MarkErrorPopover.vue' import { SaveMarkErrorCallback } from '../typing' import { toRefs } from 'vue' import { FormItemRule } from 'element-plus' import { computed } from 'vue' import { watch } from 'vue' import { ref } from 'vue' const props = defineProps<{ field: string value: string | number rowIndex: number editRowIndex: number buildRules: (rowIndex: number, field: string) => FormItemRule[] | undefined getRowFieldErrorMsg: (rowIndex: number, field: string) => string | undefined }>() const $emits = defineEmits<{ onClearMarkError: [rowIndex: number, field: string] onSaveMarkError: [ rowIndex: number, errorMsg: string, field: string, callback: SaveMarkErrorCallback ] }>() const itemRef = ref() const showText = ref<string>('') const { value, rowIndex, field, editRowIndex } = toRefs(props) const editable = computed(() => rowIndex.value === editRowIndex.value) watch( value, newValue => { showText.value = `${newValue ? newValue : ''}` }, { immediate: true } ) function updateShowText(content: string) { showText.value = content } function onClearMarkError() { $emits('onClearMarkError', rowIndex.value, field.value) } function onSaveMarkError(errorMsg: string, callback: SaveMarkErrorCallback) { $emits('onSaveMarkError', rowIndex.value, errorMsg, field.value, callback) } </script> <style scoped></style>
import torch import numpy as np from matplotlib import pyplot as plt from sklearn.metrics import r2_score from sklearn.preprocessing import MinMaxScaler, StandardScaler from torch.utils.data import DataLoader, Dataset def evaluate_model(m, data_loader: DataLoader, y_scaler: MinMaxScaler): """ 模型评价函数 :param m: 回归模型 :param data_loader: 数据集 :param y_scaler: y数据归一化方法 :return: None """ model = m.cpu() model.eval() with torch.no_grad(): all_predictions = [] all_targets = [] for data in data_loader: x, y = data y_pred = model(x) all_predictions.append(y_pred.numpy()) all_targets.append(y.numpy()) all_predictions = np.concatenate(all_predictions) all_targets = np.concatenate(all_targets) all_predictions = y_scaler.inverse_transform(all_predictions.reshape(-1, 1)) all_targets = y_scaler.inverse_transform(all_targets.reshape(-1, 1)) return all_predictions, all_targets def plot_loss_and_lr(train_losses, test_losses, learning_rate): plt.plot(learning_rate, label='Learning Rate') plot_loss(train_losses, test_losses) def plot_loss(train_losses, test_losses): plt.plot(train_losses, label='Train Loss') plt.plot(test_losses, label='Test Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend() plt.title('Training and Test Loss') plt.show() def plot_predictions(predictions, targets): # 绘制散点图 plt.scatter(targets, predictions, alpha=0.5) # 添加对角线 plt.plot(targets, targets, color='red', linestyle='--') # 计算 R^2 r2 = r2_score(targets, predictions) # 计算 RMSE rmse = np.sqrt(np.mean((predictions - targets) ** 2)) print("R2 {:.2f}, RMSE {:.2f}".format(r2, rmse)) # 添加标题和标签 plt.xlabel('True values') plt.ylabel('Predicted values') plt.title('True vs Predicted values\nRMSE: {:.2f}, R^2: {:.2f}'.format(rmse, r2)) # 显示图例 plt.legend(['Diagonal', 'Data Points']) # 显示图形 plt.show(block=False) return r2, rmse def plot_tests(predictions, targets, test_predictions, test_targets): plt.scatter(targets, predictions) plt.scatter(test_targets, test_predictions, color='green') plt.plot(np.append(targets, test_targets), np.append(targets, test_targets), color='red', linestyle='--') plt.legend(['Validation points', 'Test points']) # 计算 R^2 r2 = r2_score(test_targets, test_predictions) # 计算 RMSE rmse = np.sqrt(np.mean((test_predictions - test_targets) ** 2)) print("R2 {:.2f}, RMSE {:.2f}".format(r2, rmse)) # 添加标题和标签 plt.xlabel('True values') plt.ylabel('Predicted values') plt.title('True vs Predicted values\nRMSE: {:.2f}, R^2: {:.2f}'.format(rmse, r2)) plt.show() def plot_residuals(predictions, targets): residuals = targets - predictions plt.scatter(predictions, residuals, alpha=0.5) plt.axhline(y=0, color='red', linestyle='--') plt.xlabel('Predicted values') plt.ylabel('Residuals') plt.title('Residuals vs Predicted values') plt.show()
using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using MyGame.Engine.Rendering.Shaders; using Silk.NET.Maths; using Silk.NET.OpenGL; namespace MyGame.Engine.Rendering; public static class Renderer { /// <summary> /// The meshes we need to draw, grouped by their material so we won't /// need to set the uniforms too much /// </summary> private static Dictionary<Material, List<(Matrix4x4, MeshPrimitive)>> _meshes = new(); /// <summary> /// The default material that we are using when rendering /// </summary> public static readonly Material DefaultMaterial = new(); /// <summary> /// The shader we are using for everything /// </summary> private static MainShader _shader = null!; /// <summary> /// The debug callback for opengl, keep a global reference to make /// sure the GC won't collect this delegate /// </summary> private static readonly DebugProc GlDebugProc = (sourceInt, typeInt, id, severityInt, length, message, param) => { var source = (DebugSource)sourceInt; var severity = (DebugSeverity)severityInt; var type = (DebugType)typeInt; var sourceStr = source switch { DebugSource.DebugSourceApi => "API", DebugSource.DebugSourceWindowSystem => "Window System", DebugSource.DebugSourceShaderCompiler => "Shader Compiler", DebugSource.DebugSourceThirdParty => "Third Party", DebugSource.DebugSourceApplication => "Application", DebugSource.DebugSourceOther => "Other", _ => source.ToString() }; var severityStr = severity switch { DebugSeverity.DebugSeverityNotification => "Notification", DebugSeverity.DebugSeverityHigh => "High", DebugSeverity.DebugSeverityMedium => "Medium", DebugSeverity.DebugSeverityLow => "Low", _ => severity.ToString() }; var typeStr = type switch { DebugType.DebugTypeError => "Error", DebugType.DebugTypeDeprecatedBehavior => "Deprecated Behavior", DebugType.DebugTypeUndefinedBehavior => "Undefined Behavior", DebugType.DebugTypePortability => "Portability", DebugType.DebugTypePerformance => "Performance", DebugType.DebugTypeOther => "Other", DebugType.DebugTypeMarker => "Marker", DebugType.DebugTypePushGroup => "Push Group", DebugType.DebugTypePopGroup => "Pop Group", _ => type.ToString() }; var messageStr = Marshal.PtrToStringUTF8(message, length); var fullMsg = $"OpenGL[{sourceStr}/{typeStr}] ({severityStr}): {messageStr}"; Console.WriteLine(fullMsg); if (type == DebugType.DebugTypeError) { throw new Exception(fullMsg); } // if (severity != DebugSeverity.DebugSeverityNotification) // { // Console.WriteLine(new StackTrace().ToString()); // } }; /// <summary> /// Initialize the rendering subsystem /// </summary> public static void Init() { // Make sure we got the correct information Console.WriteLine($"Version: {GL.Gl.GetStringS(StringName.Version)}"); Console.WriteLine($"Vendor/Renderer: {GL.Gl.GetStringS(StringName.Vendor)}/{GL.Gl.GetStringS(StringName.Renderer)}"); // enable debugging if we have a debug context GL.Gl.GetInteger(GetPName.ContextFlags, out var flags); if ((flags & (int)ContextFlagMask.DebugBit) != 0) { GL.Gl.Enable(EnableCap.DebugOutput); GL.Gl.Enable(EnableCap.DebugOutputSynchronous); unsafe { GL.Gl.DebugMessageCallback(GlDebugProc, null); GL.Gl.DebugMessageControl(DebugSource.DontCare, DebugType.DontCare, DebugSeverity.DontCare, 0, null, true); } } // set depth testing properly GL.Gl.Enable(EnableCap.DepthTest); GL.Gl.DepthFunc(DepthFunction.Lequal); // enable back-face culling GL.Gl.Enable(EnableCap.CullFace); GL.Gl.CullFace(TriangleFace.Back); // enable multi-sampling GL.Gl.Enable(EnableCap.Multisample); // compile and use the shader _shader = new MainShader(); } public static void SubmitLight(in Vector3 position, in Vector3 color) { var shader = _shader; GL.Gl.Uniform3(shader.UniformLightPosition, position); GL.Gl.Uniform3(shader.UniformLightColor, color); } public static void SubmitMesh(Mesh mesh, in Matrix4x4 transform) { foreach (var primitive in mesh.Primitives) { if (!_meshes.TryGetValue(primitive.Material, out var list)) { list = new List<(Matrix4x4, MeshPrimitive)>(); _meshes[primitive.Material] = list; } list.Add((transform, primitive)); } } /// <summary> /// Perform the full render cycle with the given camera /// </summary> public static void Render(Matrix4x4 projection, Matrix4x4 view) { var shader = _shader; GL.Gl.UseProgram(shader.Id); // clear everything GL.Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); // Update the camera in the shader unsafe { GL.Gl.UniformMatrix4(shader.UniformProjection, 1, false, (float*)&projection); GL.Gl.UniformMatrix4(shader.UniformView, 1, false, (float*)&view); } // camera position GL.Gl.Uniform3(shader.UniformViewPosition, view.Translation); // Go over all the materials var materialsToRemove = new List<Material>(); foreach (var (material, list) in _meshes) { if (list.Count == 0) { materialsToRemove.Add(material); continue; } var pbr = material.PbrMetallicRoughness; // // Set all the base material parameters // GL.Gl.Uniform4(shader.UniformBaseColorFactor, pbr.BaseColorFactor); GL.Gl.Uniform1(shader.UniformMetallicFactor, pbr.MetallicFactor); GL.Gl.Uniform1(shader.UniformRoughnessFactor, pbr.RoughnessFactor); // // Set all the textures of the material // var textureSlot = 0; ShaderAttributes attributes = 0; if (pbr.BaseColorTexture != null) { attributes |= ShaderAttributes.BaseColorTexture; GL.Gl.ActiveTexture(TextureUnit.Texture0 + textureSlot); GL.Gl.BindTexture(GLEnum.Texture2D, pbr.BaseColorTexture.Id); GL.Gl.Uniform1(shader.UniformBaseColorTexture, textureSlot); textureSlot += 1; } if (pbr.MetallicRoughnessTexture != null) { attributes |= ShaderAttributes.MetallicRoughnessTexture; GL.Gl.ActiveTexture(TextureUnit.Texture0 + textureSlot); GL.Gl.BindTexture(GLEnum.Texture2D, pbr.MetallicRoughnessTexture.Id); GL.Gl.Uniform1(shader.UniformMetallicRoughnessTexture, textureSlot); textureSlot += 1; } if (material.NormalTexture != null) { attributes |= ShaderAttributes.NormalTexture; GL.Gl.ActiveTexture(TextureUnit.Texture0 + textureSlot); GL.Gl.BindTexture(GLEnum.Texture2D, material.NormalTexture.Id); GL.Gl.Uniform1(shader.UniformNormalTexture, textureSlot); GL.Gl.Uniform1(shader.UniformNormalScale, material.NormalScale); textureSlot += 1; } // alpha mode if (material.AlphaMode == AlphaMode.Mask) { attributes |= ShaderAttributes.AlphaMask; GL.Gl.Uniform1(shader.UniformAlphaCutoff, material.AlphaCutoff); } // // Update the attributes // GL.Gl.Uniform1(shader.UniformAttributes, (int)attributes); // disable culling if double sided // we assume most materials are not double sided if (material.DoubleSided) { GL.Gl.Disable(EnableCap.CullFace); } // and now over all the meshes that use that material // and render them one by one foreach (var (transform, primitive) in list) { // // Update the vertex attributes // ShaderVertexAttributes vertexAttributes = 0; if (primitive.Tangent != null) { vertexAttributes |= ShaderVertexAttributes.Tangents; } GL.Gl.Uniform1(shader.UniformVertexAttributes, (int)vertexAttributes); // set the transform of the mesh unsafe { GL.Gl.UniformMatrix4(shader.UniformModel, 1, false, (float*)&transform); } // bind the vertex array that we are going to draw GL.Gl.BindVertexArray(primitive.Id); // actually draw it now var type = (DrawElementsType)primitive.Indices.ComponentType; unsafe { GL.Gl.DrawElements(primitive.Mode, primitive.Indices.Count, type, (void*)primitive.Indices.ByteOffset); } } // enable it again if (material.DoubleSided) { GL.Gl.Enable(EnableCap.CullFace); } // clear the list to save on space list.Clear(); } // remove materials that had no items in this iteration foreach (var material in materialsToRemove) { _meshes.Remove(material); } } }
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:pillatickets/View/ticket.dart'; import 'home.dart'; import 'logout.dart'; class SuccessPage extends StatelessWidget { final String name; final String surname; final String ticketId; final String zone; final String email; final String phone; final String createdAt; const SuccessPage({ required this.name, required this.surname, required this.ticketId, required this.zone, required this.email, required this.phone, required this.createdAt, }); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xFF24292E), body: SafeArea( child: Stack( children: [ Container( height: 55.h, width: MediaQuery.of(context).size.width, color: Color(0xFF002E3D), child: Padding( padding: EdgeInsets.only(left: 16.w), child: Align( alignment: Alignment.center, child: Text( " ESCANEAR TICKET", style: TextStyle( color: Color(0xFFF4F4F4), fontSize: 22.sp, fontWeight: FontWeight.bold, ), ), ), ), ), //Column Bar Container( height: MediaQuery.of(context).size.height, width: 70.w, color: Color.fromRGBO(0, 0, 0, 0.15), ), //Column icons Positioned( top: 0.h, left: 10.w, child: Container( height: 55.h, width: 50.w, child: Image.asset( 'assets/images/thunder.png', width: 200.w, height: 200.h, fit: BoxFit.cover, color: Colors.white, ), ), ), SizedBox( height: 15.h, ), Positioned( top: 70.h, left: 0.w, child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => Home( eventId: '', ))); }, child: Container( height: 70.h, width: 70.w, color: Colors.white, child: Image.asset( 'assets/images/home.png', width: 150.w, height: 150.h, fit: BoxFit.cover, ), ), ), ), SizedBox( height: 15.h, ), Positioned( top: 160.h, left: 0.w, child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => Home( eventId: '', ))); }, child: Container( height: 70.h, width: 70.w, color: Color(0xFFB0C756), child: Image.asset( 'assets/images/scan.png', width: 150.w, height: 150.h, fit: BoxFit.cover, ), ), ), ), SizedBox( height: 15.h, ), Positioned( top: 250.h, left: 0.w, child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => Ticket( eventId: '', ))); }, child: Container( height: 70.h, width: 70.w, color: Colors.white, child: Image.asset( 'assets/images/ticket.png', width: 150.w, height: 150.h, fit: BoxFit.cover, ), ), ), ), SizedBox( height: 15.h, ), Positioned( top: 340.h, left: 0.w, child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => Logout( eventId: '', zoneId: '', ))); }, child: Container( height: 70.h, width: 70.w, color: Colors.white, child: Image.asset( 'assets/images/logout.png', width: 150.w, height: 150.h, fit: BoxFit.cover, ), ), ), ), Positioned( top: 120.h, left: 80.w, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: 200.h, width: 220.w, decoration: BoxDecoration( color: Color(0xFF4CCD38), shape: BoxShape.circle, ), child: Stack( children: [ Positioned.fill( child: Center( child: ClipRRect( borderRadius: BorderRadius.circular(150.h), child: Icon( Icons.check, color: Color(0xFF24292E), size: 150.0.h, ), ), ), ), ], ), ), Container( margin: EdgeInsets.symmetric(vertical: 20.h), child: Text( 'Status: VÁLIDO', style: TextStyle( color: Colors.white, fontSize: 25.sp, fontWeight: FontWeight.bold, ), ), ), Row( children: [ Text( 'Name: $name ', style: TextStyle( fontSize: 22.sp, fontWeight: FontWeight.bold, color: Colors.white, ), ), Text( 'Surname: $surname', style: TextStyle( fontSize: 22.sp, fontWeight: FontWeight.bold, color: Colors.white, ), ), ], ), Text( 'Ticket ID: $ticketId', style: TextStyle( fontSize: 16.sp, color: Colors.white, fontWeight: FontWeight.bold, ), ), Text( '$createdAt', style: TextStyle( fontSize: 22.sp, fontWeight: FontWeight.bold, color: Colors.white, ), ), Container( margin: EdgeInsets.symmetric(vertical: 20.h), child: Text( '$zone Ticket', style: TextStyle( color: Colors.white, fontSize: 25.sp, fontWeight: FontWeight.bold, ), ), ), Text( 'Email: $email', style: TextStyle( fontSize: 22.sp, fontWeight: FontWeight.bold, color: Colors.white, ), ), Text( 'Phone: $phone', style: TextStyle( fontSize: 22.sp, fontWeight: FontWeight.bold, color: Colors.white, ), ), ], ), ) ], ), ), ); } } // import 'package:flutter/cupertino.dart'; // import 'package:flutter/material.dart'; // import 'package:flutter_screenutil/flutter_screenutil.dart'; // // class SuccessPage extends StatelessWidget { // final String name; // final String surname; // final String ticketId; // final String createdAt; // final String email; // final String mobile; // final String type; // final List<String> zones; // // SuccessPage({ // required this.name, // required this.surname, // required this.ticketId, // required this.createdAt, // required this.email, // required this.mobile, // required this.type, // required this.zones, // }); // // @override // Widget build(BuildContext context) { // return Scaffold( // backgroundColor: Color(0xFF24292E), // body: SafeArea( // child: SingleChildScrollView( // child: Padding( // padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 24.h), // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Text( // 'Ticket Scanned Successfully', // style: TextStyle( // color: Colors.white, // fontSize: 22.sp, // fontWeight: FontWeight.bold, // ), // ), // SizedBox(height: 24.h), // Text( // 'Name: $name $surname', // style: TextStyle( // color: Colors.white, // fontSize: 16.sp, // ), // ), // SizedBox(height: 8.h), // Text( // 'Ticket ID: $ticketId', // style: TextStyle( // color: Colors.white, // fontSize: 16.sp, // ), // ), // SizedBox(height: 8.h), // Text( // 'Created At: $createdAt', // style: TextStyle( // color: Colors.white, // fontSize: 16.sp, // ), // ), // SizedBox(height: 8.h), // Text( // 'Email: $email', // style: TextStyle( // color: Colors.white, // fontSize: 16.sp, // ), // ), // SizedBox(height: 8.h), // Text( // 'Mobile: $mobile', // style: TextStyle( // color: Colors.white, // fontSize: 16.sp, // ), // ), // SizedBox(height: 8.h), // Text( // 'Type: $type', // style: TextStyle( // color: Colors.white, // fontSize: 16.sp, // ), // ), // SizedBox(height: 8.h), // Text( // 'Zones:', // style: TextStyle( // color: Colors.white, // fontSize: 16.sp, // ), // ), // SizedBox(height: 8.h), // ListView.builder( // shrinkWrap: true, // physics: NeverScrollableScrollPhysics(), // itemCount: zones.length, // itemBuilder: (context, index) { // final zone = zones[index]; // return Text( // '- $zone', // style: TextStyle( // color: Colors.white, // fontSize: 16.sp, // ), // ); // }, // ), // ], // ), // ), // ), // ), // ); // } // }
package com.example.colorsound.ui.screens.splash import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import com.example.colorsound.R import com.example.colorsound.ui.theme.ColorSoundTheme @Composable fun SplashScreen() { Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center ) { Image( painter = painterResource(id = R.drawable.ic_launcher_color_sound_foreground), contentDescription = null, modifier = Modifier.scale(2f) ) } } @Preview @Composable fun SplashScreenPreview() { ColorSoundTheme { SplashScreen() } }
import { Injectable } from '@angular/core'; import {HttpClient} from "@angular/common/http"; import {Observable} from "rxjs"; import {Customer} from "../model/customer"; import {CustomerType} from "../model/customerType"; @Injectable({ providedIn: 'root' }) export class CustomerServiceService { private API_URL = 'http://localhost:3000/'; constructor(private httpClient: HttpClient) { } findAllCustomerSearch(nameSearch: string, typeSearch: string): Observable<Customer[]> { return this.httpClient.get<Customer[]>(this.API_URL + 'customers?customerName_like=' + nameSearch + '&customerType.customerTypeName_like=' + typeSearch); } findCustomerSearchPaging(numberRecord: number, curPage: number, nameSearch: string, typeSearch: string): Observable<Customer[]> { return this.httpClient.get<Customer[]>(this.API_URL + 'customers?_page=' + curPage + '&_limit=' + numberRecord + '&customerName_like=' + nameSearch + '&customerType.customerTypeName_like=' + typeSearch); } deleteCustomer(id: number): Observable<Customer> { return this.httpClient.delete<Customer>(this.API_URL + 'customers/' + id); } findAllCustomerType(): Observable<CustomerType[]> { return this.httpClient.get<CustomerType[]>(this.API_URL + 'customerTypes'); } addCustomer(customer): Observable<Customer> { return this.httpClient.post<Customer>(this.API_URL + 'customers', customer); } getById(id: number): Observable<Customer> { return this.httpClient.get<Customer>(this.API_URL + 'customers/' + id); } updateCustomer(id: number, customer: Customer): Observable<Customer> { return this.httpClient.put<Customer>(this.API_URL + 'customers/' + id, customer); } }
/* * bernoulli_synapse.h * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * NEST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NEST. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef BERNOULLI_SYNAPSE_H #define BERNOULLI_SYNAPSE_H // Includes from nestkernel: #include "connection.h" #include "kernel_manager.h" namespace nest { /* BeginUserDocs: synapse, static Short description +++++++++++++++++ Static synapse with stochastic transmission Description +++++++++++ Spikes are transmitted by ``bernoulli_synapse`` following a Bernoulli trial with success probability ``p_transmit``. This synaptic mechanism was inspired by the results described in [1]_ of greater transmission probability for stronger excitatory connections and it was previously applied in [2]_ and [3]_. ``bernoulli_synapse`` does not support any kind of plasticity. It simply stores the parameters target, weight, transmission probability, delay and receiver port for each connection. Parameters ++++++++++ p_transmit real Transmission probability, must be between 0 and 1 Transmits +++++++++ SpikeEvent, RateEvent, CurrentEvent, ConductanceEvent, DoubleDataEvent, DataLoggingRequest References ++++++++++ .. [1] Lefort S, Tomm C, Sarria J-C F, Petersen CCH (2009). The excitatory neuronal network of the C2 barrel column in mouse primary somatosensory cortex. Neuron, 61(2):301-316. DOI: https://doi.org/10.1016/j.neuron.2008.12.020. .. [2] Teramae J, Tsubo Y, Fukai T (2012). Optimal spike-based communication in excitable networks with strong-sparse and weak-dense links, Scientific Reports 2,485. DOI: https://doi.org/10.1038/srep00485 .. [3] Omura Y, Carvalho MM, Inokuchi K, Fukai T (2015). A lognormal recurrent network model for burst generation during hippocampal sharp waves. Journal of Neuroscience, 35(43):14585-14601. DOI: https://doi.org/10.1523/JNEUROSCI.4944-14.2015 See also ++++++++ static_synapse, static_synapse_hom_w Examples using this model +++++++++++++++++++++++++ .. listexamples:: bernoulli_synapse EndUserDocs */ template < typename targetidentifierT > class bernoulli_synapse : public Connection< targetidentifierT > { public: // this line determines which common properties to use typedef CommonSynapseProperties CommonPropertiesType; typedef Connection< targetidentifierT > ConnectionBase; static constexpr ConnectionModelProperties properties = ConnectionModelProperties::HAS_DELAY | ConnectionModelProperties::IS_PRIMARY | ConnectionModelProperties::SUPPORTS_HPC | ConnectionModelProperties::SUPPORTS_LBL; /** * Default Constructor. * Sets default values for all parameters. Needed by GenericConnectorModel. */ bernoulli_synapse() : ConnectionBase() , weight_( 1.0 ) , p_transmit_( 1.0 ) { } /** * Copy constructor from a property object. * Needs to be defined properly in order for GenericConnector to work. */ bernoulli_synapse( const bernoulli_synapse& rhs ) = default; bernoulli_synapse& operator=( const bernoulli_synapse& rhs ) = default; // Explicitly declare all methods inherited from the dependent base // ConnectionBase. This avoids explicit name prefixes in all places these // functions are used. Since ConnectionBase depends on the template parameter, // they are not automatically found in the base class. using ConnectionBase::get_delay_steps; using ConnectionBase::get_rport; using ConnectionBase::get_target; class ConnTestDummyNode : public ConnTestDummyNodeBase { public: // Ensure proper overriding of overloaded virtual functions. // Return values from functions are ignored. using ConnTestDummyNodeBase::handles_test_event; size_t handles_test_event( SpikeEvent&, size_t ) override { return invalid_port; } }; void check_connection( Node& s, Node& t, size_t receptor_type, const CommonPropertiesType& ) { ConnTestDummyNode dummy_target; ConnectionBase::check_connection_( dummy_target, s, t, receptor_type ); } void send( Event& e, size_t t, const CommonSynapseProperties& ) { SpikeEvent e_spike = static_cast< SpikeEvent& >( e ); const unsigned long n_spikes_in = e_spike.get_multiplicity(); unsigned long n_spikes_out = 0; for ( unsigned long n = 0; n < n_spikes_in; ++n ) { if ( get_vp_specific_rng( t )->drand() < p_transmit_ ) { ++n_spikes_out; } } if ( n_spikes_out > 0 ) { e_spike.set_multiplicity( n_spikes_out ); e.set_weight( weight_ ); e.set_delay_steps( get_delay_steps() ); e.set_receiver( *get_target( t ) ); e.set_rport( get_rport() ); e(); } // Resets multiplicity for consistency e_spike.set_multiplicity( n_spikes_in ); } void get_status( DictionaryDatum& d ) const; void set_status( const DictionaryDatum& d, ConnectorModel& cm ); void set_weight( double w ) { weight_ = w; } private: double weight_; double p_transmit_; }; template < typename targetidentifierT > constexpr ConnectionModelProperties bernoulli_synapse< targetidentifierT >::properties; template < typename targetidentifierT > void bernoulli_synapse< targetidentifierT >::get_status( DictionaryDatum& d ) const { ConnectionBase::get_status( d ); def< double >( d, names::weight, weight_ ); def< double >( d, names::p_transmit, p_transmit_ ); def< long >( d, names::size_of, sizeof( *this ) ); } template < typename targetidentifierT > void bernoulli_synapse< targetidentifierT >::set_status( const DictionaryDatum& d, ConnectorModel& cm ) { ConnectionBase::set_status( d, cm ); updateValue< double >( d, names::weight, weight_ ); updateValue< double >( d, names::p_transmit, p_transmit_ ); if ( p_transmit_ < 0 or p_transmit_ > 1 ) { throw BadProperty( "Spike transmission probability must be in [0, 1]." ); } } } // namespace #endif /* #ifndef BERNOULLI_SYNAPSE_H */
import { useState, useEffect } from 'react' import { Button } from '../components/Button' import { Client } from '../components/Client' import { getAllClients, createClient, deleteClient } from '../services' export const ClientsPage = () => { const [clients, setClients] = useState([]) const [name, setName] = useState('') const [phone, setPhone] = useState('') const [gold, setGold] = useState(false) console.log({ clients }) useEffect(() => { getAllClients() .then(client => { setClients(client) }) }, []) const handleNameChange = (e) => { const listener = e.target.value setName(listener) } const handlePhoneChange = (e) => { const listener = e.target.value setPhone(listener) } const handleGoldChange = (e) => { const listener = e.target.checked setGold(listener) } const addClient = (e) => { e.preventDefault() const noteObject = { name, phone, isGold: gold } createClient(noteObject) .then(newClient => { setClients(clients.concat(newClient)) }) setName('') setPhone('') } const handleDelete = (id) => { deleteClient(id) .then(data => { const filter = clients.filter(client => client._id !== data.customer._id) const filterRepeat = clients.filter(client => client._id === data.customer._id) console.log({ filterRepeat }) setClients(filter) }) } return ( <div className='p-10 space-y-7'> <h1 className='text-3xl'>Clients</h1> <ul className='space-y-3'> {clients.map(({ _id, name, phone, isGold }) => ( <Client key={_id} name={name} phone={phone} isGold={isGold} buttonClick={() => handleDelete(_id)} /> ))} </ul> <form onSubmit={addClient}> {/* Name input */} <div className='space-y-5'> <input type='text' placeholder='Name' value={name} onChange={handleNameChange} className='appearance-none border border-[#161b22] rounded-2xl p-4 bg-secondary text-gray-200 leading-tight focus:outline-none focus:border-purple-600 flex-1 w-full' /> {/* Phone input */} <input type='text' placeholder='Phone' value={phone} onChange={handlePhoneChange} className='appearance-none border border-[#161b22] rounded-2xl p-4 bg-secondary text-gray-200 leading-tight focus:outline-none focus:border-purple-600 flex-1 w-full' /> {/* isGold */} <label htmlFor='default-toggle' className='inline-flex relative items-center cursor-pointer'> <input type='checkbox' value={gold} onChange={handleGoldChange} id='default-toggle' className='sr-only peer' /> <div className="w-11 h-6 bg-red-600 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-green-600" /> <span className='ml-3 text-sm font-medium text-gray-200 dark:text-gray-300'>Gold membership</span> </label> <Button bgcolor='bg-purple-600' hover='bg-blue-800' textcolor='text-white' width='w-full' > Send </Button> </div> </form> </div> ) }
#' Illustrative code for building a mesh in 2d domain. #' #' Creates a mesh object. #' #' @param loc a two column matrix with location coordinates. #' @param domain a two column matrix defining the domain. #' @param max.edge the maximun edge length. #' @param offset the length of the outer extension. #' @param SP logical indicating if the output will include the SpatialPolygons. #' @section Warning: #' This is just for illustration purpose and one should consider the #' efficient function available a the INLA package. #' @return a mesh object. #' @export mesh2d <- function(loc, domain, max.edge, offset, SP = TRUE) { ### arguments check if (missing(loc)) { if (missing(domain)) { stop("please provide 'loc' or domain'!") } xy <- domain } else { if (missing(domain)) { xy <- loc } else { xy <- rbind(loc, domain) } } if (!is.logical(SP)) { stop("'SP' must be logical") } ### define rectangle around xyl <- unique(apply(xy, 2, range, na.rm = TRUE)) if (!missing(offset)) { ro <- which(offset < 0) if (length(ro) > 0) { offset[ro] <- -(xyl[2, ro] - xyl[1, ro]) * offset[ro] } xyl[1, ] <- xyl[1, ] - offset xyl[2, ] <- xyl[2, ] + offset } ### define triangle coordinates xyr <- apply(xyl, 2, diff) transpose <- (xyr[1] < xyr[2]) if (transpose) { xyl <- xyl[, 2:1] xyr <- rev(xyr) } k0 <- trunc(xyr[1] / max.edge) + ((xyr[1] %% max.edge) > 0) + 1 edgelen <- xyr[1] / (k0 - 1) h <- edgelen / sqrt(2) k <- trunc(xyr[2] / h) + ((xyr[2] %% h) > 0) + 1 xu <- seq(xyl[1, 1], xyl[2, 1], edgelen) nxu <- length(xu) if (length(xu) != k0) { stop(paste0("length(xu)=", nxu, ", k0=", k0, " and k=", k)) } xx <- list(c( xu[1] - edgelen / 2, (xu[-nxu] + xu[-1]) / 2, xu[nxu] + edgelen / 2 ), xu) k.a <- 0 refine <- TRUE if (refine) { xx <- xx[2:1] } else { while (length(xx[[k.a + 2]]) > 1) { k.a <- k.a + 1 xx[[k.a + 2]] <- xx[[k.a]][2:length(xx[[k.a + 1]])] } xx <- xx[(k.a + 2):1] } y0 <- ((-(k - 1)):k.a) * h + xyl[2, 2] y0 <- y0 + abs(min(y0) - xyl[1, 2]) / 2 k <- k + k.a if (k > length(xx)) { for (j in (length(xx) + 1):k) { turn <- refine && ((j - 1) > trunc(k / 2)) if (turn) { if (length(xx[[j - 1]]) > length(xx[[j - 2]])) { xj <- xx[[j - 2]] } else { xj <- xx[[j - 2]][-c(1, length(xx[[j - 2]]))] } } else { xj <- c( xx[[j - 2]][1] - edgelen, xx[[j - 2]], xx[[j - 2]][length(xx[[j - 2]])] + edgelen ) } xx[[j]] <- xj } } xx <- xx[length(xx):1] triang <- list(loc = cbind( unlist(xx), rep(y0, sapply(xx, length)) )) if (transpose) { triang$loc <- triang$loc[, 2:1] } triang$manifold <- "R2" triang$meta$is.refined <- refine ### triangle identification tv <- list() a <- length(xx[[1]]) i.b <- list() if (a == 2) { i.b[[1]] <- cbind(1, 2) } if (a > 2) { i.b[[1]] <- matrix(c(1, rep(2:(a - 1), each = 2), a), ncol = 2, byrow = TRUE ) } a0 <- 0 for (j in 1:(length(xx) - 1)) { a <- length(xx[[j]]) turn <- refine && (a < length(xx[[j + 1]])) if (turn) { tv[[j]] <- rbind( cbind(1:(a - 1), 2:a, (2:a) + a), cbind(1:a, 1:a + a + 1, 1:a + a)[a:1, ] ) + a0 i.b[[j + 1]] <- rbind(c(1, a + 1), c(a, 2 * a + 1)) + a0 } else { tv[[j]] <- cbind(1:(a - 1), 2:a, 1:(a - 1) + a) + a0 if (nrow(tv[[j]]) > 1) { add <- cbind(2:(a - 1), 2:(a - 1) + a, 1:(a - 2) + a) + a0 tv[[j]] <- rbind( tv[[j]], add[nrow(add):1, , drop = FALSE] ) } i.b[[j + 1]] <- rbind(c(1, a + 1), c(a, 2 * a - 1)) + a0 } a0 <- a0 + a } if (refine) { a <- length(xx[[length(xx)]]) if (a > 1) { i.b[[length(i.b) + 1]] <- cbind(1:(a - 1), 2:a) + a0 } } triang$graph <- list(tv = Reduce("rbind", tv)) triang$n <- nrow(triang$loc) triang$segm <- list(bnd = list( loc = NULL, idx = Reduce("rbind", i.b) )) triang$segm$bnd$grp <- matrix(0, nrow(triang$segm$bnd$idx), 1) triang$segm$bnd$is.bnd <- TRUE attr(triang$segm$bnd, "class") <- "inla.mesh.segment" if (SP) { triang$SP <- sp::SpatialPolygons( lapply(1:nrow(triang$graph$tv), function(j) { jj <- triang$graph$tv[j, ] p <- sp::Polygon(triang$loc[c(jj, jj[1]), ]) sp::Polygons(list(p), paste(j)) }) ) triang$centroids <- sp::coordinates(triang$SP) } triang$loc <- cbind(triang$loc, 0) attr(triang, "class") <- "inla.mesh" return(triang) }
function sum(a = 0, b = 0) { return a + b; } test('adds 1+2 to equal 3', () => { expect(sum(1,2)).toBe(3); }); test('adds only one parameter to equal 1', () => { expect(sum(1)).toBe(1); }); test('object assignment', () => { const data = {one: 1}; data['two'] = 2; expect(data).toEqual({one: 1, two: 2}); }); test('adding positive numbers is not zero', () => { for (let a = 1; a < 10; a++) { for (let b = 1; b < 10; b++) { expect(a + b).not.toBe(0); } } }); test('null', () => { const n = null; expect(n).toBeNull(); expect(n).toBeDefined(); expect(n).not.toBeUndefined(); expect(n).not.toBeTruthy(); expect(n).toBeFalsy(); }); const shoppingList = [ 'diapers', 'kleenex', 'trash bags', 'paper towels', 'milk', ]; test('the shopping list has milk on it', () => { expect(shoppingList).toContain('milk'); expect(new Set(shoppingList)).toContain('milk'); });
/* Comparison with the Strict Equality Operator Strict equality (===) is the counterpart to the equality operator (==). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion. If the values being compared have different types, they are considered unequal, and the strict equality operator will return false. Examples 3 === 3 // true 3 === '3' // false */ // Setup function testStrict(val) { if (val===7) { // Change this line return "Equal"; } return "Not Equal"; } testStrict(10);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://unpkg.com/vue/dist/vue.js" ></script> <script src="https://unpkg.com/vue-router" ></script> <title>Rotas</title> <style> nav{ padding: 20px; background-color: lightgray; } a{ text-decoration: none; color:black; } div{ color: white; width: 40vw; height:10vh; padding: 10px; display: flex; justify-content: center; align-items: center; border:none; box-shadow: 0px 0px 30px black; border-radius: 5px; font-size: 36px; } .red{ background-color: darkred; } .green{ background-color: darkgreen; } .purple{ background-color: purple; } .links{ padding: 20px; background-color: rgba(0,255,255,.3); } .links:hover{ background-color:blue; color:white; } #proibido{ background-color: red; color:white; } </style> </head> <body> <main> <nav> <router-link to="/" class="links">HOME</router-link> <strong> | </strong> <router-link to="/comp" class="links">Componente 1</router-link> <strong> | </strong> <router-link :to="number" class="links">Componente 2</router-link> <strong> | </strong> <router-link to="/proibido" class="links" id="proibido">Rota Proibida (Bloqueada)</router-link> <strong> | </strong> </nav> <hr> <router-view></router-view> </main> <script> const home = { template:'<div class="purple">HOME</div>' } const Comp1 = { template:'<div class="red">Componente</div>' } const routes = [ {path:"/comp",component:Comp1}, { path:"/proibido",component:null, beforeEnter:function(to,from,next){ next(false); } }, { path:"/comp/:parametro", component: { template:` <div class='green'> Parametro {{$route.params.parametro}} </div>` } }, {path:'/',component:home} ]; const router = new VueRouter({routes:routes}); router.beforeEach( function(to,from,next){ console.clear(); console.log("To: ",to); console.log("from: ",from); console.log("next: ",next); next(true); } ); const vue = new Vue( { el:"main", computed:{ number:function(){ return '/comp/'+parseInt(Math.random() * 10); } }, router:router } ); </script> </body> </html>
<html> <head> {% load static %} <!-- Bootstrap --> <link href="{% static 'ProyectoWebApp/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css2?family=Bree+Serif&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Lora:400,400i,700,700i" rel="stylesheet"> <!-- Styles --> <link href="{% static 'ProyectoWebApp/css/gestion.css' %}" rel="stylesheet"> </head> <body> <h1 class="site-heading text-center text-gold d-none d-lg-block" > <span class="site-heading-lower">Gestión de Pedidos</span> </h1> <div style="color: #EABE3F; text-align: right; margin-right: 100px;"> {% if user.is_authenticated %} Hola {{request.user}} &nbsp;&nbsp; <button type="button" class="btn btn-default"> <a href="{% url 'cerrar_sesion' %} ">Cerrar Sesión</a> </button> &nbsp;&nbsp; <button type="button" class="btn btn-default"> <a href="{% url 'editar_perfil' %}">Editar Perfil</a> </button> {% else %} No estas logueado<br> <button type="button" class="btn btn-default"> <a href="{% url 'loguear' %}">Login</a> </button> &nbsp;&nbsp; <button type="button" class="btn btn-default"> <a href="{% url 'autenticacion' %}">Regístrate</a> </button> {% endif %} </div> <!-- Navbar --> <nav class="navbar navbar-expand-lg navbar-dark py-lg-4" id="mainNav"> <div class="container"> <a class="navbar-brand text-uppercase text-expanded font-weight-bold d-lg-none" href="{% url 'home' %}">Gestión de Pedidos</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav mx-auto"> <li class="nav-item {% if request.path == '/' %}active{% endif %} px-lg-4"> <a class="nav-link text-uppercase text-expanded" href="{% url 'home' %}">Inicio</a> </li> <li class="nav-item {% if request.path == '/servicios/' %}active{% endif %} px-lg-4"> <a class="nav-link text-uppercase text-expanded" href="{% url 'servicios' %}">Servicios</a> </li> <li class="nav-item {% if request.path == '/tienda/' %}active{% endif %} px-lg-4"> <a class="nav-link text-uppercase text-expanded" href="{% url 'tienda' %}">Tienda</a> </li> <li class="nav-item {% if request.path == '/contacto/' %}active{% endif %} px-lg-4"> <a class="nav-link text-uppercase text-expanded" href="{% url 'contacto' %}">Contacto</a> </li> <li class="nav-item {% if request.path|slice:':6' == '/blog/' %}active{% endif %} px-lg-4"> <a class="nav-link text-uppercase text-expanded" href="{% url 'blog:blog' %}">Blog</a> </li> <li class="nav-item {% if request.path == '/pedidos/lista_pedidos/' %}active{% endif %} px-lg-4"> <a class="nav-link text-uppercase text-expanded" href="{% url 'lista_pedidos' %}">Pedidos</a> </li> </ul> </div> </div> </nav> <!-- Contenido Cambiante --> {% block content %} {% endblock %} <!-- Footer --> <footer class="footer text-faded text-center py-5"> <div class="container"> <p class="m-0"> <a href="#" class="link"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-twitter fa-stack-1x fa-inverse"></i> </span> </a> <a href="https://www.facebook.com/" class="link"> <img src="{% static 'ProyectoWebApp/img/facebook.jpg' %}" alt="" style="width:50px"> </a> <a href="https://www.instagram.com/" class="link"> <img src="{% static 'ProyectoWebApp/img/instagram.jpg' %}" alt="" style="width:50px"> </a> <a href="https://www.whatsapp.com/" class="link"> <img src="{% static 'ProyectoWebApp/img/whatsapp.jpg' %}" alt="" style="width:50px"> </a> </p> <p class="m-0 mbt"> <a href="sample.html" class="link">Política de privacidad</a> · <a href="sample.html" class="link">Aviso legal</a> · <a href="sample.html" class="link">Cookies</a> </p> <p class="m-0 mbt1">&copy; Gestión de Pedidos 2020</p> </div> </footer> <!-- Bootstrap --> <script src="{% static 'ProyectoWebApp/vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'ProyectoWebApp/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> </body> </html>
/** * @file kick command * @author Sankarsan Kampa (a.k.a k3rn31p4nic) * @license GPL-3.0 */ exports.exec = async (ThotPatrol, message, args) => { let user; if (message.mentions.users.size) { user = message.mentions.users.first(); } else if (args.id) { user = await ThotPatrol.fetchUser(args.id); } if (!user) { return ThotPatrol.emit('commandUsage', message, this.help); } let member = await ThotPatrol.utils.fetchMember(message.guild, user.id); if (message.author.id !== message.guild.ownerID && message.member.highestRole.comparePositionTo(member.highestRole) <= 0) return ThotPatrol.log.info(ThotPatrol.i18n.error(message.guild.language, 'lowerRole')); if (!member.kickable) { return ThotPatrol.emit('error', '', ThotPatrol.i18n.error(message.guild.language, 'noPermission', 'kick', user), message.channel); } await member.kick(args.reason); args.reason = args.reason.join(' '); await message.channel.send({ embed: { color: ThotPatrol.colors.RED, description: ThotPatrol.i18n.info(message.guild.language, 'kick', message.author.tag, user.tag, args.reason), footer: { text: `ID ${user.id}` } } }).catch(e => { ThotPatrol.log.error(e); }); ThotPatrol.emit('moderationLog', message, this.help.name, member, args.reason); await member.send({ embed: { color: ThotPatrol.colors.RED, description: ThotPatrol.i18n.info(message.guild.language, 'kickDM', message.author.tag, message.guild.name, args.reason) } }).catch(e => { ThotPatrol.log.error(e); }); }; exports.config = { aliases: [ 'k' ], enabled: true, argsDefinitions: [ { name: 'id', type: String, defaultOption: true }, { name: 'reason', alias: 'r', type: String, multiple: true, defaultValue: [ 'No reason given.' ] } ] }; exports.help = { name: 'kick', description: 'Kicks the specified user from your Discord server.', botPermission: 'KICK_MEMBERS', userTextPermission: 'KICK_MEMBERS', userVoicePermission: '', usage: 'kick <@USER_MENTION | USER_ID> -r [Reason]', example: [ 'kick @user#001 -r Being rude to everyone.', 'kick 167147569575323761 -r Spamming' ] };
import { Body, Controller,Get, Param, Post } from '@nestjs/common'; import { MemberService } from './member.service'; import { Member } from './schemas/member.schema'; @Controller('members') // route export class MemberController { constructor(private memberService:MemberService){} @Get() async getAllMembers():Promise<Member[]>{ return this.memberService.findAll(); } @Get(':id') async getMember( @Param('id') id:string, ):Promise<Member>{ return this.memberService.findById(id); } @Post() async createMember( @Body() member, ): Promise<Member>{ return this.memberService.create(member); } }
require('dotenv').config(); const express = require('express'); const helmet = require('helmet'); const cookieParser = require('cookie-parser'); const { celebrate, errors } = require('celebrate'); const app = express(); const mongoose = require('mongoose'); const limiter = require('./limiter'); const { userRouter, cardRouter } = require('./routes/index'); const { userValidationSchema } = require('./routes/validationSchema'); const { login, createUser, logOut } = require('./controllers/users'); const auth = require('./middlewares/auth'); const config = require('./config'); const NotFoundError = require('./errors/NotFoundError'); const errorsHandler = require('./middlewares/errorsHandler'); const { requestLogger, errorLogger } = require('./middlewares/logger'); const { handleCors } = require('./middlewares/cors'); mongoose.connect('mongodb://127.0.0.1:27017/mestodb '); app.use(express.json()); app.use(helmet()); app.use(limiter); app.use(cookieParser()); app.use(handleCors); app.use(requestLogger); app.get('/crash-test', () => { setTimeout(() => { throw new Error('Сервер сейчас упадёт'); }, 0); }); app.post('/signup', celebrate({ body: userValidationSchema, }), createUser); app.post('/signin', celebrate({ body: userValidationSchema, }), login); app.get('/signout', logOut); app.use(auth); app.use('/users', userRouter); app.use('/cards', cardRouter); app.use((req, res, next) => { next(new NotFoundError('Запрашиваемый ресурс не найден')); }); app.use(errorLogger); app.use(errors()); app.use(errorsHandler); app.listen(config.port, () => { // eslint-disable-next-line no-console console.log(`Server started at port ${config.port}`); });
import 'package:flutter/material.dart'; import 'package:hive/hive.dart'; import 'extensions.dart'; import 'location_searcher.dart'; import 'main.dart'; import 'network/planera_resa.dart'; import 'utils.dart'; abstract class BoxOption { late Box box; } abstract class TripOptions with ChangeMarginGetter, ServicesGetter, IncludeNearbyStopsGetter, ViaGetter, WalkDistanceGetter, OptionsSummary {} abstract class DepartureBoardOptions with IncludeArrivalGetter, OptionsSummary {} abstract mixin class ChangeMarginGetter { int? get changeMarginMinutes; } abstract mixin class ServicesGetter { List<bool> get services; } abstract mixin class IncludeNearbyStopsGetter { bool get includeNearbyStops; } abstract mixin class ViaGetter { StopLocation? get via; } abstract mixin class IncludeArrivalGetter { bool get includeArrivals; } abstract mixin class WalkDistanceGetter { int? get maxWalkDistance; } abstract mixin class OptionsSummary { String? get summary; } class BoxTripOptions extends BoxOption with ChangeMarginOption, ServicesOption, IncludeNearbyStopsOption, WalkDistanceOption, TripOptionsSummary implements TripOptions { BoxTripOptions() { box = tripBox; } LocationFieldController viaFieldController = LocationFieldController('via', tripBox); final TextEditingController viaInput = RichTextEditingController(); @override StopLocation? get via => viaFieldController.location as StopLocation?; } class ParamTripOptions extends TripOptions with TripOptionsSummary { Map<String, String> params; ParamTripOptions(this.params); @override int? get changeMarginMinutes => parseInt(params['changeMargin']); @override List<bool> get services => params['services']?.split('').map((s) => s == '1').toList(growable: false) ?? List.filled(serviceButtons.length, true); @override StopLocation? get via => parseLocation(params, 'via') as StopLocation?; @override bool get includeNearbyStops => params['includeNearbyStops'] != 'false'; @override int? get maxWalkDistance => parseInt(params['maxWalkDistance']); } mixin TripOptionsSummary implements TripOptions { @override String? get summary { List<String> changes = []; if (via != null) changes.add('Via ${via!.name.firstPart()}'); if (changeMarginMinutes == 2) { changes.add('Kort bytesmarginal (2 min)'); } else if (changeMarginMinutes != null) { var durationString = _TripOptionsPanelState.customChangeMarginDurationString(changeMarginMinutes!); changes.add('Bytesmarginal ($durationString)'); } if (!services.all()) changes.add('Färdmedelsfilter'); if (!includeNearbyStops) changes.add('Gå inte till närliggande hållplatser'); if (maxWalkDistance != null && includeNearbyStops) changes.add('Gå max ${getDistanceString(maxWalkDistance!)}'); return changes.isNotEmpty ? changes.join(', ') : null; } } class BoxDepartureBoardOptions extends BoxOption with IncludeArrivalOption, ServicesOption, DepartureBoardOptionsSummary implements DepartureBoardOptions { BoxDepartureBoardOptions() { box = departureBoardBox; } } class ParamDepartureBoardOptions extends DepartureBoardOptions with DepartureBoardOptionsSummary { Map<String, String> params; ParamDepartureBoardOptions(this.params); @override bool get includeArrivals => params['includeArrivals'] == 'true'; } mixin DepartureBoardOptionsSummary implements DepartureBoardOptions { @override String? get summary { List<String> changes = []; if (includeArrivals) changes.add('Inkluderar ankomster'); return changes.isNotEmpty ? changes.join(', ') : null; } } mixin IncludeArrivalOption on BoxOption implements IncludeArrivalGetter { @override bool get includeArrivals => box.get('includeArrivals', defaultValue: false); set includeArrivals(bool value) => box.put('includeArrivals', value); } mixin ServicesOption on BoxOption implements ServicesGetter { @override List<bool> get services => box.get('toggleVehicle', defaultValue: List.filled(serviceButtons.length, true)); void toggle(int index) { var temp = services; temp[index] = !temp[index]; box.put('toggleVehicle', temp); } } class ServiceButtons extends StatefulWidget { final ServicesOption servicesOption; const ServiceButtons(this.servicesOption, {super.key}); @override State<ServiceButtons> createState() => _ServiceButtonsState(); } class _ServiceButtonsState extends State<ServiceButtons> { @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) => ToggleButtons( color: Theme.of(context).hintColor, constraints: BoxConstraints.expand( width: (constraints.maxWidth - widget.servicesOption.services.length - 1) / widget.servicesOption.services.length), onPressed: (int index) { setState(() { widget.servicesOption.toggle(index); }); }, isSelected: widget.servicesOption.services, children: serviceButtons .map((v) => Padding( padding: const EdgeInsets.symmetric(horizontal: 2, vertical: 10), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(v.icon), Text(v.name, textAlign: TextAlign.center), ], ), )) .toList(growable: false), ), ); } } mixin ChangeMarginOption on BoxOption implements ChangeMarginGetter { ChangeMargin get changeMarginDropdownValue => ChangeMargin.values[box.get('changeMargin', defaultValue: ChangeMargin.normal.index)]; set changeMarginDropdownValue(ChangeMargin value) => box.put('changeMargin', value.index); @override int? get changeMarginMinutes { if (changeMarginDropdownValue == ChangeMargin.custom) return box.get('changeMarginMinutes'); return changeMarginDropdownValue == ChangeMargin.short ? 2 : null; } set changeMarginMinutes(int? value) => box.put('changeMarginMinutes', value); } mixin IncludeNearbyStopsOption on BoxOption implements IncludeNearbyStopsGetter { @override bool get includeNearbyStops => box.get('includeNearbyStops', defaultValue: true); set includeNearbyStops(bool value) => box.put('includeNearbyStops', value); } mixin WalkDistanceOption on BoxOption implements WalkDistanceGetter { WalkDistance get walkDistanceDropdownValue => WalkDistance.values[box.get('maxWalkDistance', defaultValue: WalkDistance.max2km.index)]; set walkDistanceDropdownValue(WalkDistance value) => box.put('maxWalkDistance', value.index); @override int? get maxWalkDistance { if (walkDistanceDropdownValue == WalkDistance.custom) return box.get('maxWalkDistanceMeters'); return walkDistanceDropdownValue.meters; } set maxWalkDistance(int? value) => box.put('maxWalkDistanceMeters', value); } enum WalkDistance { max500m, max1km, max2km, max5km, custom } extension WalkDistanceExt on WalkDistance { int? get meters => switch (this) { WalkDistance.max500m => 500, WalkDistance.max1km => 1000, WalkDistance.max2km => null, WalkDistance.max5km => 5000, WalkDistance.custom => null }; } enum ChangeMargin { short, normal, custom } class Service { final IconData icon; final String name; const Service(this.icon, this.name); } List<Service> serviceButtons = const [ Service(Icons.tram, 'Spårvagn'), Service(Icons.directions_bus, 'Buss'), Service(Icons.train, 'Västtåg'), Service(Icons.directions_railway, 'Övriga tåg'), Service(Icons.directions_boat, 'Båt'), ]; class TripOptionsPanel extends StatefulWidget implements OptionsPanel { final BoxTripOptions tripOptions; const TripOptionsPanel(this.tripOptions, {super.key}); @override State<TripOptionsPanel> createState() => _TripOptionsPanelState(); @override String? get summary => tripOptions.summary; } class _TripOptionsPanelState extends _OptionsPanelState<TripOptionsPanel> { static String customChangeMarginDurationString(int minutes) => '${getDurationString(Duration(minutes: minutes))}${minutes >= 5 ? ' extra marginal' : ''}'; String get customChangeMarginText { var minutes = widget.tripOptions.changeMarginMinutes; return widget.tripOptions.changeMarginDropdownValue != ChangeMargin.custom || minutes == null ? 'Anpassad' : 'Anpassad (${customChangeMarginDurationString(minutes)})'; } String get customWalkDistanceText { var meters = widget.tripOptions.maxWalkDistance; return widget.tripOptions.walkDistanceDropdownValue != WalkDistance.custom || meters == null ? 'Anpassad' : 'Anpassad (${getDistanceString(meters)})'; } _TripOptionsPanelState(); @override List<Widget> children() { var changeMargins = [ const DropdownMenuItem(value: ChangeMargin.short, child: Text('Kort (2 min)')), const DropdownMenuItem(value: ChangeMargin.normal, child: Text('Normal (oftast 5 min)')), DropdownMenuItem(value: ChangeMargin.custom, child: Text(customChangeMarginText)), ]; var walkDistances = [ const DropdownMenuItem(value: WalkDistance.max500m, child: Text('Max 500 m')), const DropdownMenuItem(value: WalkDistance.max1km, child: Text('Max 1 km')), const DropdownMenuItem(value: WalkDistance.max2km, child: Text('Max 2 km')), const DropdownMenuItem(value: WalkDistance.max5km, child: Text('Max 5 km')), DropdownMenuItem(value: WalkDistance.custom, child: Text(customWalkDistanceText)), ]; return [ const Text('Res via hållplats'), LocationField(widget.tripOptions.viaFieldController, widget.tripOptions.viaInput, 'Via', onlyStops: true, suffixIcon: IconButton( onPressed: widget.tripOptions.viaFieldController.clearLocation, icon: const Icon(Icons.clear))), const SizedBox(height: 16), const Text('Bytesmarginal'), DropdownButton<ChangeMargin>( value: widget.tripOptions.changeMarginDropdownValue, onChanged: (ChangeMargin? newValue) { if (newValue == ChangeMargin.custom) { _customChangeMargin().then((minutes) { if (minutes == null) return; widget.tripOptions.changeMarginMinutes = minutes; setState(() => widget.tripOptions.changeMarginDropdownValue = ChangeMargin.custom); }); } else { widget.tripOptions.changeMarginMinutes = newValue == ChangeMargin.short ? 2 : null; setState(() => widget.tripOptions.changeMarginDropdownValue = newValue!); } }, items: changeMargins), if (widget.tripOptions.changeMarginDropdownValue == ChangeMargin.short || (widget.tripOptions.changeMarginMinutes ?? 5) < 5) Text('Med kort bytesmarginal gäller inte längre rätten till förseningsersättning', style: TextStyle(color: Theme.of(context).hintColor)), const SizedBox(height: 16), const Text('Färdmedel'), const SizedBox(height: 5), ServiceButtons(widget.tripOptions), CheckboxListTile( value: widget.tripOptions.includeNearbyStops, onChanged: (newValue) => setState(() => widget.tripOptions.includeNearbyStops = newValue ?? true), title: const Text('Jag kan gå till närliggande hållplatser'), ), if (widget.tripOptions.includeNearbyStops) const SizedBox(height: 5), if (widget.tripOptions.includeNearbyStops) const Text('Maximal gångsträcka'), if (widget.tripOptions.includeNearbyStops) const SizedBox(height: 5), if (widget.tripOptions.includeNearbyStops) DropdownButton<WalkDistance>( value: widget.tripOptions.walkDistanceDropdownValue, onChanged: (WalkDistance? newValue) { if (newValue == WalkDistance.custom) { _customMaxWalkDistance().then((meters) { if (meters == null) return; widget.tripOptions.maxWalkDistance = meters; setState(() => widget.tripOptions.walkDistanceDropdownValue = WalkDistance.custom); }); } else { widget.tripOptions.maxWalkDistance = newValue?.meters; setState(() => widget.tripOptions.walkDistanceDropdownValue = newValue!); } }, items: walkDistances), ]; } int? _parseChangeMargin(String text) { int? minutes = int.tryParse(text); return minutes != null && minutes > 0 && minutes <= 600 ? minutes : null; } int? _parseWalkDistance(String text) { int? meters = int.tryParse(text); return meters != null && meters >= 0 && meters <= 10000 ? meters : null; } Future<int?> _customChangeMargin() async { return _customValueDialog('Ange bytesmarginal', 'Ange antal minuter', _parseChangeMargin); } Future<int?> _customMaxWalkDistance() async { return _customValueDialog('Ange maximala gångsträcka', 'Ange antal meter', _parseWalkDistance); } Future<int?> _customValueDialog(String title, String hintText, int? Function(String) parseValue) async { var textController = TextEditingController(); var valid = ValueNotifier<bool>(false); return showDialog<int?>( context: context, builder: (context) { return AlertDialog( title: Text(title), content: TextField( autofocus: true, keyboardType: const TextInputType.numberWithOptions(signed: false, decimal: false), onChanged: (value) => valid.value = parseValue(value) != null, onSubmitted: (value) { var parsed = parseValue(value); if (parsed == null) return; Navigator.pop(context, parsed); }, controller: textController, decoration: InputDecoration(hintText: hintText), ), actions: [ TextButton( child: Text(MaterialLocalizations.of(context).cancelButtonLabel), onPressed: () => Navigator.pop(context), ), ValueListenableBuilder( valueListenable: valid, builder: (BuildContext context, bool value, Widget? child) => TextButton( onPressed: value ? () => Navigator.pop(context, parseValue(textController.text)) : null, child: Text(MaterialLocalizations.of(context).okButtonLabel), ), ), ], ); }); } } class DepartureBoardOptionsPanel extends StatefulWidget implements OptionsPanel { final BoxDepartureBoardOptions departureBoardOptions; const DepartureBoardOptionsPanel(this.departureBoardOptions, {super.key}); @override State<DepartureBoardOptionsPanel> createState() => _DepartureBoardOptionsPanel(); @override String? get summary => departureBoardOptions.summary; } class _DepartureBoardOptionsPanel extends _OptionsPanelState<DepartureBoardOptionsPanel> { _DepartureBoardOptionsPanel(); @override List<Widget> children() { return [ CheckboxListTile( value: widget.departureBoardOptions.includeArrivals, onChanged: (newValue) { setState(() { widget.departureBoardOptions.includeArrivals = newValue ?? false; }); }, title: const Text('Inkludera ankomster'), ) ]; } } abstract class OptionsPanel extends StatefulWidget implements OptionsSummary { const OptionsPanel({super.key}); } abstract class _OptionsPanelState<T extends OptionsPanel> extends State<T> { bool expanded = false; List<Widget> children(); @override Widget build(BuildContext context) { return ExpansionPanelList( elevation: expanded ? 2 : 0, expandedHeaderPadding: EdgeInsets.zero, expansionCallback: (int index, bool isExpanded) { setState(() { expanded = isExpanded; }); }, children: [ ExpansionPanel( backgroundColor: expanded ? null : Theme.of(context).canvasColor, canTapOnHeader: true, headerBuilder: (BuildContext context, bool isExpanded) { var summaryText = widget.summary; return AnimatedSize( duration: kThemeAnimationDuration, curve: Curves.easeInOut, child: ListTile( title: Text('Alternativ', style: TextStyle(color: Theme.of(context).hintColor)), subtitle: !expanded && summaryText != null ? Text(summaryText) : null, ), ); }, body: Padding( padding: const EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: children(), ), ), isExpanded: expanded, ), ], ); } }
package org.example.service; import org.example.bom.*; import org.example.converter.Converter; import org.example.dto.db.*; import org.example.repository.DealRepository; import org.example.service.DealService.DealService; import org.example.service.DealService.DealServiceImpl; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.sql.Timestamp; import java.time.LocalDateTime; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class DealServiceTest { @Mock private Converter<DealDTO, Deal> dealConverter; @Mock private DealRepository dealRepository; private DealService dealService; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); dealService = new DealServiceImpl(dealConverter, dealRepository); } @Test void save() { Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); Country country = new Country(1L, "country"); Manufacturer manufacturer = new Manufacturer(1L, "manufacturer", country); Model model = new Model(1L, "ModelA", manufacturer); Color color = new Color(1L, "Red"); Vehicle vehicle = new PassengerCar(1L, 5000, model, color, 6000, 2022, false); Client client = new Client(1L, "John", "Address", "+380984785740", "UA023948274", 3); Employee employee = new Employee(1L, "Alex", "+38097847567", "Sales manages"); Deal deal = new Deal(1L, vehicle, client, employee, timestamp, 10000F, PaymentType.CASH, 100F, 0F); CountryDTO countryDTO = new CountryDTO(1L, "country"); ManufacturerDTO manufacturerDTO = new ManufacturerDTO(1L, "manufacturer", countryDTO); ModelDTO modelDTO = new ModelDTO(1L, "ModelA", manufacturerDTO); ColorDTO colorDTO = new ColorDTO(1L, "Red"); VehicleDTO vehicleDTO = new VehicleDTO(1L, 5000, modelDTO, Type.PASSENGER_CAR.toString(), colorDTO, 6000F, 2022, false); ClientDTO clientDTO = new ClientDTO(1L, "John", "Address", "+380984785740", "UA023948274", 3); EmployeeDTO employeeDTO = new EmployeeDTO(1L, "Alex", "+38097847567", "Sales manages"); DealDTO dealDTO = new DealDTO(1L, vehicleDTO, clientDTO, employeeDTO, timestamp, 10000F, PaymentType.CASH.toString(), 100F, 0F); when(dealConverter.toDTO(deal)).thenReturn(dealDTO); when(dealRepository.save(dealDTO)).thenReturn(dealDTO); when(dealConverter.fromDTO(dealDTO)).thenReturn(deal); Deal actualDeal = dealService.save(deal); assertEquals(deal, actualDeal); verify(dealConverter).toDTO(deal); verify(dealRepository).save(dealDTO); verify(dealConverter).fromDTO(dealDTO); } }
from django.conf import settings from django_elasticsearch_dsl import Document, Index, fields from elasticsearch_dsl import analyzer, normalizer, token_filter from api.models import ECTSCard INDEX = Index(settings.ELASTICSEARCH_INDEX_NAMES[__name__]) # See Elasticsearch Indices API reference for available settings INDEX.settings( number_of_shards=1, number_of_replicas=1 ) edge_ngram_completion_filter = token_filter( 'edge_ngram_completion_filter', type="edge_ngram", min_gram=3, max_gram=6 ) edge_ngram_completion = analyzer( "edge_ngram_completion", tokenizer="standard", filter=["lowercase", edge_ngram_completion_filter], char_filter=["html_strip"], ) lowercase_normalizer = normalizer( 'lowercase_normalizer', filter=['lowercase'] ) @INDEX.doc_type class ECTSCardDocument(Document): """Elasticsearch document.""" id = fields.IntegerField(attr='id') field_of_study = fields.NestedField(properties={ 'id': fields.IntegerField(attr='id'), 'name': fields.TextField( analyzer=edge_ngram_completion, fields={'raw': fields.KeywordField(normalizer=lowercase_normalizer)} ), 'study_type': fields.TextField(), 'start_date': fields.DateField(), 'field_groups': fields.NestedField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField() }) }) semester = fields.NestedField(properties={ 'id': fields.IntegerField(attr='id'), 'semester': fields.IntegerField(), 'year': fields.IntegerField(), 'students': fields.NestedField(properties={ 'id': fields.IntegerField(attr='id'), 'index': fields.IntegerField(), 'email': fields.TextField(), 'name': fields.TextField(), 'surname': fields.TextField(), }), 'field_of_study': fields.NestedField(properties={ 'id': fields.IntegerField(attr='id'), 'name': fields.TextField( analyzer=edge_ngram_completion, fields={'raw': fields.KeywordField(normalizer=lowercase_normalizer)} ), 'study_type': fields.TextField(), 'start_date': fields.DateField(), 'end_date': fields.DateField(), 'field_groups': fields.NestedField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField() }) }), 'courses': fields.NestedField(properties={ 'id': fields.IntegerField(attr='id'), 'name': fields.TextField( analyzer=edge_ngram_completion, fields={'raw': fields.KeywordField(normalizer=lowercase_normalizer)} ), 'points_value': fields.IntegerField(), 'prerequisites': fields.TextField(), 'purposes': fields.TextField(), 'subject_learning_outcomes': fields.TextField(), 'methods_of_verification_of_learning_outcomes_and_criteria': fields.TextField(), 'content_of_the_subject': fields.TextField(), 'didactic_methods': fields.TextField(), 'literature': fields.TextField(), 'balance_of_work_of_an_avg_student': fields.TextField() }), 'semester_start_date': fields.DateField(), 'semester_end_date': fields.DateField() }) class Django(object): """Inner nested class Django.""" model = ECTSCard # The model associate with this Document
import React from 'react'; import { BrowserRouter, Route, Routes } from 'react-router-dom'; import LayoutContainer from '../componets/layout'; import Home from '../pages/home'; import Login from '../pages/login'; import Register from '../pages/register'; import Products from '../pages/products'; import DetailProduct from '../pages/detail-product'; import Checkout from '../pages/checkout'; import { ROOT_PAGE_PATH, LOGIN_PATH, REGISTER_PATH, PRODUCTS_PATH, CHECKOUT_PATH, DETAIL_PRODUCT_PATH, } from './path'; const routes = [ { path: LOGIN_PATH, component: <Login /> }, { path: ROOT_PAGE_PATH, component: <Home /> }, { path: REGISTER_PATH, component: <Register /> }, { path: PRODUCTS_PATH, component: <Products /> }, { path: `${DETAIL_PRODUCT_PATH}/:id`, component: <DetailProduct /> }, { path: CHECKOUT_PATH, component: <Checkout /> }, ]; const getRoutes = () => routes.map(({ path, component }) => ( <Route path={path} element={component} key={path} /> )); const RouteApp = () => ( <BrowserRouter> <LayoutContainer> <Routes> {getRoutes()} </Routes> </LayoutContainer> </BrowserRouter> ); export default RouteApp;
import scss from "./carousel.module.scss"; import { useDispatch } from "react-redux"; import { userActions } from "../../redux/reducers/slice"; import React from "react"; import { useSelector } from "react-redux"; function SliderCard({ img, id, price, descriptionA, descriptionB, descriptionUnder, imgLikeT, imgLike, descriptionC, descriptionD, descriptionF, imgDesk }) { const dataLocalStorage = { img, id, price, descriptionA, descriptionB, descriptionUnder, imgLikeT, imgLike, descriptionC, descriptionD, descriptionF, imgDesk }; const likeSelector = useSelector((getRedux) => getRedux.user.data); const isLiked = likeSelector.filter((item) => item.id === id).length; const dispatch = useDispatch(); const onDelete = () => { dispatch(userActions.removeLike(id)); }; const handleReduxLike = () => { if (isLiked) { onDelete(); } else { dispatch(userActions.handleLike(dataLocalStorage)); } }; return ( <div> <div className={scss.button} onClick={handleReduxLike}> <img className={scss.imgLike} src={isLiked ? imgLikeT : imgLike} alt="like" /> </div> <div id={scss.square} className={scss.wrapper}> {imgDesk ? ( <div className={scss.imgDesk}> <div className={scss.imgDeskWord}>{imgDesk}</div> </div> ) : ( "" )} <img className={scss.imgSlider} src={img} key={id} alt="slider" /> <div className={scss.title}> <div className={scss.price}>{price}</div> <div className={scss.whiteBlock}> <div>{descriptionA}</div> <div className={scss.opacity}>|</div> <div>{descriptionB}</div> <div className={scss.opacity}>|</div> <div>{descriptionC}</div> <div className={scss.opacity}>|</div> <div>{descriptionD}</div> </div> <div className={scss.descriptionUnder}>{descriptionUnder}</div> <div className={scss.descriptionF}>{descriptionF}</div> </div> </div> </div> ); } export default SliderCard;
<?xml version="1.0" encoding="utf-8"?> <layout 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"> <data> <variable name="promo" type="com.ubaya.uas_anmp.model.Promo" /> <variable name="listener" type="com.ubaya.uas_anmp.view.ButtonDetailPromoClickListener" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:layout_marginTop="8dp" android:layout_marginBottom="8dp" app:cardCornerRadius="24dp" app:cardElevation="5dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imageViewPromo" android:layout_width="80dp" android:layout_height="80dp" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:scaleType="centerCrop" app:imageUrl="@{promo.photoUrl}" app:progressBar="@{progressLoadPromoList}" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:srcCompat="@tools:sample/avatars" /> <TextView android:id="@+id/textValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{promo.value}" android:textSize="24sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@+id/imageViewPromo" app:layout_constraintStart_toStartOf="@+id/textNamaVoucher" app:layout_constraintTop_toBottomOf="@+id/textNamaVoucher" app:layout_constraintVertical_bias="0.0" /> <TextView android:id="@+id/textNamaVoucher" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="4dp" android:text="Discount" app:layout_constraintStart_toEndOf="@+id/imageViewPromo" app:layout_constraintTop_toTopOf="@+id/imageViewPromo" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Valid until" android:textSize="12sp" app:layout_constraintStart_toStartOf="@+id/imageViewPromo" app:layout_constraintTop_toBottomOf="@+id/imageViewPromo" /> <TextView android:id="@+id/textValidUntil" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:text="@{promo.validUntil}" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="@+id/textView5" app:layout_constraintTop_toBottomOf="@+id/textView5" app:layout_constraintVertical_bias="0.0" /> <Button android:id="@+id/buttonRedeem" style="@style/Widget.MaterialComponents.Button.TextButton" android:layout_width="wrap_content" android:layout_height="48dp" android:layout_marginEnd="16dp" android:layout_marginBottom="4dp" android:onClick="@{listener::onButtonDetailPromoClick}" android:tag="@{promo.idPromo}" android:text="Terms and conditions" android:textColor="@color/secondary" app:cornerRadius="20dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" /> <ProgressBar android:id="@+id/progressLoadPromoList" style="?android:attr/progressBarStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="@+id/imageViewPromo" app:layout_constraintEnd_toEndOf="@+id/imageViewPromo" app:layout_constraintStart_toStartOf="@+id/imageViewPromo" app:layout_constraintTop_toTopOf="@+id/imageViewPromo" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.cardview.widget.CardView> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
package com.example.naejango.global.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; @Aspect @Component public class NPlus1DetectorAop { private final ThreadLocal<LoggingForm> currentLoggingForm; private final Logger logger = LoggerFactory.getLogger("N+1 detector Log"); public NPlus1DetectorAop() { this.currentLoggingForm = new ThreadLocal<>(); } @Around("execution( * javax.sql.DataSource.getConnection())") public Object captureConnection(final ProceedingJoinPoint joinPoint) throws Throwable { final Object connection = joinPoint.proceed(); return new ConnectionProxyHandler(connection, getCurrentLoggingForm()).getProxy(); } private LoggingForm getCurrentLoggingForm() { if (currentLoggingForm.get() == null) { currentLoggingForm.set(new LoggingForm()); } return currentLoggingForm.get(); } @After("within(@org.springframework.web.bind.annotation.RestController *) && !@annotation(com.example.naejango.global.aop.NoLogging)") public void loggingAfterApiFinish() { final LoggingForm loggingForm = getCurrentLoggingForm(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (isInRequestScope(attributes)) { HttpServletRequest request = attributes.getRequest(); loggingForm.setApiMethod(request.getMethod()); loggingForm.setApiUrl(request.getRequestURI()); } logger.info("{}", getCurrentLoggingForm()); currentLoggingForm.remove(); } private boolean isInRequestScope(final ServletRequestAttributes attributes) { return attributes != null; } }
import React from 'react'; // eslint-disable-line no-unused-vars import PropTypes from 'prop-types'; function Typography({ variant = 'body1', className, children, ...otherProps }) { const variantMapping = { h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', subtitle1: 'h6', subtitle2: 'h6', body1: 'p', body2: 'p', caption: 'span', overline: 'span', button: 'span', srOnly: 'span', }; const ComponentProp = variantMapping[variant] || 'p'; return ( <ComponentProp className={className} {...otherProps}> {children} </ComponentProp> ) } Typography.propTypes = { variant: PropTypes.oneOf([ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1', 'subtitle2', 'body1', 'body2', 'caption', 'overline', 'button', 'srOnly', ]), className: PropTypes.string, children: PropTypes.node } export default Typography;
import Vex from "vexflow"; import { ClefEnum } from "../../VoiceData/Instructions/ClefInstruction"; import { ClefInstruction } from "../../VoiceData/Instructions/ClefInstruction"; import { Pitch } from "../../../Common/DataObjects/Pitch"; import { Fraction } from "../../../Common/DataObjects/Fraction"; import { RhythmInstruction } from "../../VoiceData/Instructions/RhythmInstruction"; import { KeyInstruction } from "../../VoiceData/Instructions/KeyInstruction"; import { SystemLinesEnum } from "../SystemLinesEnum"; import { FontStyles } from "../../../Common/Enums/FontStyles"; import { Fonts } from "../../../Common/Enums/Fonts"; import { OutlineAndFillStyleEnum } from "../DrawingEnums"; import { SystemLinePosition } from "../SystemLinePosition"; import { GraphicalVoiceEntry } from "../GraphicalVoiceEntry"; import { OrnamentContainer } from "../../VoiceData/OrnamentContainer"; import { Notehead } from "../../VoiceData/Notehead"; import { EngravingRules } from "../EngravingRules"; import { ArpeggioType } from "../../VoiceData/Arpeggio"; import { Articulation } from "../../VoiceData/Articulation"; /** * Helper class, which contains static methods which actually convert * from OSMD objects to VexFlow objects. */ export declare class VexFlowConverter { /** * Mapping from numbers of alterations on the key signature to major keys * @type {[alterationsNo: number]: string; } */ private static majorMap; /** * Mapping from numbers of alterations on the key signature to minor keys * @type {[alterationsNo: number]: string; } */ private static minorMap; /** * Convert a fraction to Vexflow string durations. * A duration like 5/16 (5 16th notes) can't be represented by a single (dotted) note, * so we need to return multiple durations (e.g. for 5/16th ghost notes). * Currently, for a dotted quarter ghost note, we return a quarter and an eighth ghost note. * We could return a dotted quarter instead, but then the code would need to distinguish between * notes that can be represented as dotted notes and notes that can't, which would complicate things. * We could e.g. add a parameter "allowSingleDottedNote" which makes it possible to return single dotted notes instead. * But currently, this is only really used for Ghost notes, so it doesn't make a difference visually. * (for other uses like StaveNotes, we calculate the dots separately) * @param fraction a fraction representing the duration of a note * @returns {string[]} Vexflow note type strings (e.g. "h" = half note) */ static durations(fraction: Fraction, isTuplet: boolean): string[]; /** * Takes a Pitch and returns a string representing a VexFlow pitch, * which has the form "b/4", plus its alteration (accidental) * @param pitch * @returns {string[]} */ static pitch(pitch: Pitch, isRest: boolean, clef: ClefInstruction, notehead?: Notehead, octaveOffsetGiven?: number): [string, string, ClefInstruction]; static restToNotePitch(pitch: Pitch, clefType: ClefEnum): Pitch; /** returns the Vexflow code for a note head. Some are still unsupported, see Vexflow/tables.js */ static NoteHeadCode(notehead: Notehead): string; static GhostNotes(frac: Fraction): Vex.Flow.GhostNote[]; /** * Convert a GraphicalVoiceEntry to a VexFlow StaveNote * @param gve the GraphicalVoiceEntry which can hold a note or a chord on the staff belonging to one voice * @returns {Vex.Flow.StaveNote} */ static StaveNote(gve: GraphicalVoiceEntry): Vex.Flow.StaveNote; static generateArticulations(vfnote: Vex.Flow.StemmableNote, articulations: Articulation[], rules: EngravingRules): void; static generateOrnaments(vfnote: Vex.Flow.StemmableNote, oContainer: OrnamentContainer): void; static StrokeTypeFromArpeggioType(arpeggioType: ArpeggioType): Vex.Flow.Stroke.Type; /** * Convert a set of GraphicalNotes to a VexFlow StaveNote * @param notes form a chord on the staff * @returns {Vex.Flow.StaveNote} */ static CreateTabNote(gve: GraphicalVoiceEntry): Vex.Flow.TabNote; /** * Convert a ClefInstruction to a string represention of a clef type in VexFlow. * * @param clef The OSMD object to be converted representing the clef * @param size The VexFlow size to be used. Can be `default` or `small`. * As soon as #118 is done, this parameter will be dispensable. * @returns A string representation of a VexFlow clef * @see https://github.com/0xfe/vexflow/blob/master/src/clef.js * @see https://github.com/0xfe/vexflow/blob/master/tests/clef_tests.js */ static Clef(clef: ClefInstruction, size?: string): { type: string; size: string; annotation: string; }; /** * Convert a RhythmInstruction to a VexFlow TimeSignature object * @param rhythm * @returns {Vex.Flow.TimeSignature} * @constructor */ static TimeSignature(rhythm: RhythmInstruction): Vex.Flow.TimeSignature; /** * Convert a KeyInstruction to a string representing in VexFlow a key * @param key * @returns {string} */ static keySignature(key: KeyInstruction): string; /** * Converts a lineType to a VexFlow StaveConnector type * @param lineType * @returns {any} */ static line(lineType: SystemLinesEnum, linePosition: SystemLinePosition): any; /** * Construct a string which can be used in a CSS font property * @param fontSize * @param fontStyle * @param font * @returns {string} */ static font(fontSize: number, fontStyle: FontStyles, font: Fonts, rules: EngravingRules, fontFamily?: string): string; /** * Converts the style into a string that VexFlow RenderContext can understand * as the weight of the font */ static fontStyle(style: FontStyles): string; /** * Convert OutlineAndFillStyle to CSS properties * @param styleId * @returns {string} */ static style(styleId: OutlineAndFillStyleEnum): string; }
package com.example.coverviewer; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.util.Callback; import java.net.URL; public class CoverViewerController { // instance variables for interacting with GUI @FXML private ListView<Book> booksListView; @FXML private ImageView coverImageView; // stores the list of Book Objects private final ObservableList<Book> books = FXCollections.observableArrayList(); // initialize controller public void initialize() { // populate the ObservableList<Book> books.add(new Book("Android How to Program", "images/small/androidhtp.jpg", "images/large/androidhtp.jpg")); books.add(new Book("C How to Program", "images/small/chtp.jpg", "images/large/chtp.jpg")); books.add(new Book("C++ How to Program", "images/small/cpphtp.jpg", "images/large/cpphtp.jpg")); books.add(new Book("Visual C# How to Program", "images/small/vcshtp.jpg", "images/large/vcshtp.jpg")); books.add(new Book("Visual Basic How to Program", "images/small/vbhtp.jpg", "images/large/vbhtp.jpg")); books.add(new Book("Internet and World Wide Web How to Program", "images/small/iw3htp.jpg", "images/large/iw3htp.jpg")); booksListView.setItems(books); // bind bookListView to books // when ListView selection changes, show large cover in ImageView booksListView.getSelectionModel().selectedItemProperty(). addListener( new ChangeListener<Book>() { @Override public void changed(ObservableValue<? extends Book> ov, Book oldValue, Book newValue) { if (newValue != null) { URL imageUrl = getClass().getResource(newValue.getLargeImage()); if (imageUrl == null) { System.out.println("Resource not found: " + newValue.getLargeImage()); } else { Image image = new Image(imageUrl.toExternalForm()); coverImageView.setImage(image); } } } } ); // booksListView.setCellFactory( // new Callback<ListView<Book>, ListCell<Book>>() { // @Override // public ListCell<Book> call(ListView<Book> listView) { // return new ImageTextCell(); // } // } // ); } }
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js"; import { FieldType } from "../Enums"; import { IPageViewPerfData } from "../Interfaces/Contracts/IPageViewPerfData"; import { IPageViewPerformanceTelemetry } from "../Interfaces/IPageViewPerformanceTelemetry"; import { ISerializable } from "../Interfaces/Telemetry/ISerializable"; export declare class PageViewPerformance implements IPageViewPerfData, ISerializable { static envelopeType: string; static dataType: string; aiDataContract: { ver: FieldType; name: FieldType; url: FieldType; duration: FieldType; perfTotal: FieldType; networkConnect: FieldType; sentRequest: FieldType; receivedResponse: FieldType; domProcessing: FieldType; properties: FieldType; measurements: FieldType; }; /** * Schema version */ ver: number; /** * Event name. Keep it low cardinality to allow proper grouping and useful metrics. */ name: string; /** * Collection of custom properties. */ properties: any; /** * Collection of custom measurements. */ measurements: any; /** * Request URL with all query string parameters */ url: string; /** * Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */ duration: string; /** * Identifier of a page view instance. Used for correlation between page view and other telemetry items. */ id: string; /** * Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ perfTotal: string; /** * Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ networkConnect: string; /** * Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ sentRequest: string; /** * Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ receivedResponse: string; /** * DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */ domProcessing: string; /** * Constructs a new instance of the PageEventTelemetry object */ constructor(logger: IDiagnosticLogger, name: string, url: string, unused: number, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }, cs4BaseData?: IPageViewPerformanceTelemetry); }
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.protect = exports.signIn = exports.signUpCompany = exports.signUpUser = void 0; const user_schema_1 = require("../models/user.schema"); const company_schema_1 = require("../models/company.schema"); const business_entity_schema_1 = require("../models/business-entity.schema"); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const config_1 = __importDefault(require("../config")); const signUpUser = (req, res) => __awaiter(void 0, void 0, void 0, function* () { try { const user = new user_schema_1.User(req.body); const entity = yield business_entity_schema_1.BusinessEntity.findOne({ email: req.body.email }).exec(); if (entity) { return res.status(400).send({ 'msg': 'El correo ya esta en uso' }); } yield user.save().then((result) => { res.send(result); res.end(); }).catch((error) => { res.send({ message: 'Hubo un error al guardar', error }); res.end(); }); } catch (error) { return res.status(400).send({ 'msg': 'Algo salio mal' }); } }); exports.signUpUser = signUpUser; const signUpCompany = (req, res) => __awaiter(void 0, void 0, void 0, function* () { try { const company = new company_schema_1.Company(req.body); const entity = yield business_entity_schema_1.BusinessEntity.findOne({ email: req.body.email }).exec(); if (entity) { return res.status(400).send({ 'msg': 'El correo ya esta en uso' }); } yield company.save().then((result) => { res.send(result); res.end(); }).catch((error) => { res.send({ message: 'Hubo un error al guardar', error }); res.end(); }); } catch (error) { return res.status(400).send({ 'msg': 'Algo salio mal' }); } }); exports.signUpCompany = signUpCompany; const signIn = (req, res) => __awaiter(void 0, void 0, void 0, function* () { const { email, password } = req.body; try { const entity = yield business_entity_schema_1.BusinessEntity.findOne({ email: email }).exec(); if (!entity) { return res.status(400).json({ message: "User or company not found" }); } if (!(yield entity.comparePassword(password))) { return res.status(400).json({ message: "Password is incorrect" }); } const token = yield entity.generateToken(); return res.status(201).send({ access_token: token }); } catch (error) { return res.status(400).send({ "msg": "Hubo un error al iniciar sesion" }); } }); exports.signIn = signIn; const protect = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { if (!req.headers.authorization) { return res.status(400).send({ 'msg': 'Not auth' }); } try { const token = req.headers.authorization.split(' ')[1]; if (!token) { return res.status(403).send({ 'msg': 'Not found token' }); } const entity = yield jsonwebtoken_1.default.verify(token, config_1.default.jwt_secret); req.entity = entity; next(); } catch (error) { return res.status(400).send({ 'msg': 'Not auth' }); } }); exports.protect = protect; //# sourceMappingURL=auth.controller.js.map
import styled from "styled-components"; import LocIcon from '../assets/icon-location.svg'; import TwitterIcon from '../assets/icon-twitter.svg'; import WebsiteIcon from '../assets/icon-website.svg'; import CompanyIcon from '../assets/icon-company.svg'; import React from "react"; const InfoBox = function ({ fetchedData, error, isLoading }) { const createTime = new Date(fetchedData.created_at); const day = createTime.getUTCDate(); const year = createTime.getUTCFullYear(); const month = createTime.toLocaleString('default', { month: 'long' }); const content = <> <div className="grid-box-1"> <img className="user-pic" src={fetchedData.avatar_url} alt="User profile picture" /> </div> <div className="grid-box-2"> <div className="name-date-box"> <span className="username">{fetchedData.name ?? ''}</span> <span className="GHname">@{fetchedData.login}</span> </div> <span className="join-date">Joined {day} {month} {year}</span> </div> <div className="grid-box-3"> <p className="bio">{fetchedData.bio ?? 'This profile has no bio'}</p> </div> <div className="grid-box-4"> <div className="statistics"> <span className="statistics-span-texts">Repos</span> <span className="statistics-span-numbers">{fetchedData.public_repos}</span> </div> <div className="statistics"> <span className="statistics-span-texts">Followers</span> <span className="statistics-span-numbers">{fetchedData.followers}</span> </div> <div className="statistics"> <span className="statistics-span-texts">Following</span> <span className="statistics-span-numbers">{fetchedData.following}</span> </div> </div> <div className="grid-box-5"> <div className="contact-info-div"> <img className="contact-icon fix" src={LocIcon} alt="Location icon" /> <span className="contact-text extra-space">{fetchedData.location ?? <span className="op">Not available</span>}</span> </div> <div className="contact-info-div"> <img className="contact-icon" src={TwitterIcon} alt="Twitter icon" /> <a className="contact-text" target={fetchedData.twitter_username === null ? '' : '_blank'} href={fetchedData.twitter_username === null ? '#' : `https://twitter.com/${fetchedData.twitter_username}`}><span>{fetchedData.twitter_username ?? <span className="op">Not available</span>}</span></a> </div> <div className="contact-info-div"> <img className="contact-icon" src={WebsiteIcon} alt="Website icon" /> <a className="contact-text" target="_blank" href={fetchedData.blog === '' ? '#' : `${fetchedData.blog}`}><span>{fetchedData.blog === '' ? <span className="op">Not available</span> : fetchedData.blog}</span></a> </div> <div className="contact-info-div"> <img className="contact-icon" src={CompanyIcon} alt="Company icon" /> <span className="contact-text">{fetchedData.company ?? <span className="op">Not available</span>}</span> </div> </div> </> const LoadingContent = <InfoContainer> <ErrLoadingBox> <Loader /> </ErrLoadingBox> </InfoContainer> const ErrorContent = <ErrLoadingBox> {error} </ErrLoadingBox> const handledContent = <InfoContainer> {error ? ErrorContent : content} </InfoContainer> return ( <React.Fragment> {isLoading ? LoadingContent : handledContent} </React.Fragment> ) } export default InfoBox; const InfoContainer = styled.div` width: 100%; height: 27.75rem; background: ${props => props.theme.containersBackground}; box-shadow: 0px 16px 30px -10px rgba(70, 96, 187, 0.198567); border-radius: 0.93rem; display: grid; padding: 3rem; grid-template-columns: 10rem 1fr; transition: all 0.3s; position: relative; overflow: hidden; //Below 768px// @media (max-width: 48em) { padding: 2.5rem; height: 30rem; }; //Below 550px // @media (max-width: 34.375em) { grid-template-columns: 5rem 1fr; padding: 2rem 1.5rem 3rem 1.5rem; height: 32.31rem; } } .grid-box-1 { grid-row: 1/span 4; //Below 768px// @media (max-width: 48em) { grid-row: 1/span 1; } .user-pic { width: 7.31rem; height: 7.31rem; border-radius: 50%; //Below 550px // @media (max-width: 34.375em) { height: 4.375rem; width: 4.375rem; margin-top: 0.8rem; } } } .grid-box-2 { display: flex; justify-content: space-between; align-items: center; @media (max-width: 48em) { flex-direction: column; justify-content: center; align-items: start; } .name-date-box { display: flex; flex-direction: column; } .username { font-weight 700; font-size: 1.62rem; line-height: 2.4rem; color: ${props => props.theme.username}; transition: all 0.3s; //Below 550px // @media (max-width: 34.375em) { font-size: 1rem; margin-bottom: -0.5rem; } } .join-date { color: ${props => props.theme.moon}; font-weight: 400; font-size: 0.9rem; line-height: 1.37rem; transition: all 0.3s; //Below 550px // @media (max-width: 34.375em) { font-size: 0.8rem; } } .GHname { color: #0079FF; font-weight: 400; font-size: 1rem; line-height: 1.37rem; transition: all 0.3s; //Below 550px // @media (max-width: 34.375em) { font-size: 0.8rem; } } } .grid-box-3 { @media (max-width: 48em) { grid-column: 1/ span 2; } .bio { color: ${props => props.theme.moon}; font-size: 0.9rem; font-weight: 400; line-height: 1.37rem; transition: all 0.3s; //Below 550px // @media (max-width: 34.375em) { font-size: 0.8rem; } } } .grid-box-4 { height: 5.3rem; display: grid; grid-template-columns: repeat(3, 1fr); background: ${props => props.theme.primaryBackground}; border-radius: 0.6rem; padding: 1rem 2rem; transition: all 0.3s; @media (max-width: 48em) { grid-column: 1/ span 2; } .statistics { display: flex; flex-direction: column; } .statistics-span-texts { color: ${props => props.theme.moon}; font-weight: 400; font-size: 0.8rem; line-height: 1.2rem; transition: all 0.3s; //Below 550px // @media (max-width: 34.375em) { font-size: 0.69rem; } } .statistics-span-numbers { color: ${props => props.theme.boldText}; font-weight: 700; font-size: 1.4rem; line-height: 2rem; transition: all 0.3s; //Below 550px // @media (max-width: 34.375em) { font-size: 1rem; } } } .grid-box-5 { display: grid; grid-template-columns: 1fr 1fr; column-gap: 3rem; //Below 550px // @media (max-width: 34.375em) { grid-template-columns: 1fr; row-gap: 1rem; } .extra-space { margin-left: 0.35rem; } .contact-info-div { display: flex; gap: 1rem; max-width: 11rem; @media(max-width: 768px) { max-width: 15rem; } } .contact-icon { width: 1.2rem; height: 1.2rem; } .fix { height: 1.25rem; width: 0.85rem; } .contact-text { color: ${props => props.theme.commonTextAndIcons}; font-weight: 400; font-size: 1rem; white-space: nowrap; transition: all 0.3s; text-decoration: none; cursor: pointer; //Below 550px // @media (max-width: 34.375em) { font-size: 0.8rem; } } } .op { opacity: 0.7; } ` const ErrLoadingBox = styled.div` position: absolute; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; color: #F74646; font-size: 1.5rem; font-weight: 700; ` const Loader = styled.span` height: 8rem; width: 8rem; border-radius: 50%; border: 1rem dashed #0079FF; animation-name: rotate; animation-duration: 1s; animation-iteration-count: infinite; @keyframes rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } `
package com.infosharing.project.service.impl; import com.infosharing.project.mapper.UserPrecautionMapper; import com.infosharing.project.pojo.UserPrecaution; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.infosharing.project.pojo.Precaution; import com.infosharing.project.service.PrecautionService; import com.infosharing.project.mapper.PrecautionMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.List; /** * @author Quanle * @description 针对表【precaution】的数据库操作Service实现 * @createDate 2023-12-01 16:44:14 */ @Service public class PrecautionServiceImpl extends ServiceImpl<PrecautionMapper, Precaution> implements PrecautionService{ private static final Logger logger = LoggerFactory.getLogger(PrecautionService.class); @Autowired UserPrecautionMapper userPrecautionMapper; @Autowired PrecautionMapper precautionMapper; @Override public void saveUserAndPrecautions(Integer userId, List<Integer> precautions) { for (Integer precaution : precautions) { try { UserPrecaution userPrecaution = new UserPrecaution(); userPrecaution.setUserId(userId); userPrecaution.setPrecautionId(precaution); userPrecautionMapper.insert(userPrecaution); } catch (Exception e) { logger.error("Error occurred while saving user precaution for user ID " + userId + " and precaution ID " + precaution, e); } } } @Override public List<Integer> getPrecautionsIDsByUserId(Integer id) { try { return precautionMapper.getPrecautionsIDsByUserId(id); } catch (Exception e) { logger.error("Error occurred while fetching precautions for user ID " + id, e); return Collections.emptyList(); } } @Override public List<Precaution> getPrecautionsByUserId(Integer id) { try { return precautionMapper.getPrecautionsByUserId(id); } catch (Exception e) { logger.error("Error occurred while fetching precautions for user ID " + id, e); return Collections.emptyList(); } } @Override public List<Precaution> getPrecautionByDiseaseId(Integer diseaseId) { try { return precautionMapper.getPrecautionByDiseaseId(diseaseId); } catch (Exception e) { logger.error("Error occurred while fetching precautions for disease ID " + diseaseId, e); return Collections.emptyList(); } } @Override public List<Precaution> getPrecautionByDiseaseName(String diseaseName) { try { return precautionMapper.getPrecautionByDiseaseName(diseaseName); } catch (Exception e) { logger.error("Error occurred while fetching precautions for disease named " + diseaseName, e); return Collections.emptyList(); } } @Override public void deletePrecautionsByUserId(Integer id) { precautionMapper.deletePrecautionsByUserId(id); } }
import { createEntityAdapter, createSlice, PayloadAction, } from "@reduxjs/toolkit"; import { TTrack } from "anghami-bot/src/types"; import { chunk, omit } from "lodash"; import { AppThunk, RootState } from "../store"; import { PageState, setPage } from "./pageSlice"; import { selectSettings } from "./profileSlice"; export interface Track extends TTrack { filePath: string; state: "downloaded" | "error" | "waiting" | "downloading" | null; selected: boolean; progress?: { percent: number; type: string; }; } export interface PlaylistState { coverArt: string | null; id: string | null; title: string | null; active: boolean; } const tracksAdapter = createEntityAdapter<Track>({ selectId: (track) => track.id, sortComparer: (a, b) => a.title.localeCompare(b.title), }); const initialState = tracksAdapter.getInitialState({} as PlaylistState); export const playlistSlice = createSlice({ name: "playlist", initialState, reducers: { add: tracksAdapter.upsertOne, addMany: tracksAdapter.upsertMany, update: tracksAdapter.updateOne, updateMany: tracksAdapter.updateMany, remove: tracksAdapter.removeOne, removeAll: tracksAdapter.removeAll, reset: (state) => { tracksAdapter.setAll(state, []); state.active = false; state.coverArt = null; state.id = null; state.title = null; }, setPlaylist: (state, action: PayloadAction<Partial<PlaylistState>>) => { return Object.assign({}, state, action.payload); }, }, }); export const playlistActions = playlistSlice.actions; export const selectTrackById = (id: string, selected: boolean = true): AppThunk => (dispatch) => { dispatch( playlistActions.update({ id, changes: { selected, }, }) ); }; export const selectAllTracks = (value: boolean = true): AppThunk => (dispatch, getState) => { const state = getState(); const tracks = tracksSelectors.selectAll(state); return dispatch( playlistActions.updateMany( tracks .filter(({ state }) => state !== "downloaded") .filter(({ selected }) => selected != value) .map(({ id }) => ({ id, changes: { selected: value, }, })) ) ); }; export const loadPlaylist = (url: string, title?: string): AppThunk => async (dispatch, getState) => { const state = getState(); const errors: PageState["errors"] = []; try { if (!state.profile.loggedIn) { errors.push({ type: "login", massage: "Please login to Anghami first", }); throw new Error(); } if (!url || !url.includes("anghami")) { errors.push({ type: "form.url", massage: "Please enter a valid URL", }); throw new Error(); } dispatch(playlistActions.reset()); dispatch( setPage({ type: "playlist", title, loading: true, errors: [], }) ); const playlist = await window.getTracksDetails(url); console.log({ playlist }); if (!playlist) { throw new Error(); } dispatch( playlistActions.setPlaylist({ coverArt: playlist.coverArt, id: playlist.id, title: playlist.title, active: false, }) ); dispatch(playlistActions.addMany(Object.values(playlist.tracks))); return dispatch( setPage({ loading: false, type: "playlist", title: playlist.title, errors: [], }) ); } catch (error) { console.error(error); if (!errors.length) { errors.push({ type: "load-playlist", massage: "Error loading playlist", }); } return dispatch( setPage({ loading: false, errors, }) ); } }; export const loadMyLikesPlaylist = (): AppThunk => (dispatch, getState) => { dispatch( loadPlaylist( `'https://play.anghami.com/playlist/${ getState().profile.playlists?.likes.id || "" }'`, "My Likes" ) ); }; export const downloadTrack = (id: string): AppThunk => (dispatch, getState) => { const state = getState(); const playlist = state.playlist!; const convert = selectSettings(state).convert; const track = tracksSelectors.selectById(state, id)!; dispatch( playlistActions.update({ id, changes: { state: "downloading", }, }) ); return window .downloadTrack(track, playlist.title || "", convert) .then((result: null | typeof track) => { if (!result) { throw new Error(); } dispatch( playlistActions.update({ id, changes: omit(result, ["sections", "buttons"]), }) ); }) .catch((error) => { console.error(error); dispatch( playlistActions.update({ id, changes: { state: "error", }, }) ); }); }; window["downloadTrack2"] = downloadTrack; export const downloadProgress = ( id: string, { progress, type }: { progress: number; type: string } ): AppThunk => (dispatch, getState) => { dispatch( playlistActions.update({ id, changes: { progress: { percent: progress, type, }, }, }) ); }; export const downloadPlaylist = (): AppThunk => async (dispatch, getState) => { const state = getState(); const playlist = state.playlist; const tracks = selectSelectedTracks(state); if (!playlist.id || !tracks.length) { return; } dispatch( playlistActions.setPlaylist({ active: true, }) ); // window.setProgressBar(0, { mode: "indeterminate" }); dispatch( playlistActions.updateMany( tracks.map(({ id }) => ({ id, changes: { state: "waiting", }, })) ) ); const tracksChunk = chunk(tracks, 2); for (const trackChunk of tracksChunk) { const state = getState(); const active = selectIsActive(state); if (!active) { dispatch( playlistActions.updateMany( tracksSelectors .selectAll(state) .filter(({ state }) => state == "waiting") .map(({ id }) => ({ id, changes: { state: null, }, })) ) ); break; } await Promise.all( trackChunk.map(async (_track) => { console.log("downloading", { _track }); await dispatch(downloadTrack(_track.id)); }) ); } dispatch( playlistActions.setPlaylist({ active: false, }) ); dispatch( playlistActions.updateMany( tracksSelectors.selectIds(state).map((id) => ({ id, changes: { selected: false, }, })) ) ); }; export const stopDownloadingPlaylist = (): AppThunk => (dispatch, getState) => { return dispatch( playlistActions.setPlaylist({ active: false, }) ); }; export const tracksSelectors = tracksAdapter.getSelectors( (state: RootState) => state.playlist ); export const selectSelectedTracks = (state: RootState) => tracksSelectors.selectAll(state).filter(({ selected }) => selected); export const selectSelectedTracksCount = (state: RootState) => selectSelectedTracks(state).length; export const selectDownloadCount = (state: RootState) => selectSelectedTracks(state).filter( ({ state }) => state == "downloaded" || state == "error" ).length; export const selectIsActive = (state: RootState) => !!state.playlist.active; export const selectIsStopping = (state: RootState) => { return ( tracksSelectors .selectAll(state) .some(({ state }) => state == "waiting" || state == "downloading") && !selectIsActive(state) ); }; export default playlistSlice.reducer;
import { ApiProperty } from '@nestjs/swagger'; import { IsNotEmpty, IsNotEmptyObject, IsObject, IsOptional, IsString, } from 'class-validator'; import { UpdateStallionProfileDto } from 'src/stallions/dto/update-stallion-profile.dto'; import { StallionGalleryImageDto } from 'src/stallion-gallery-images/dto/stallion-gallery-image.dto'; export class UpdateMarketingStallionDto { @ApiProperty() @IsOptional() @IsObject() @IsNotEmptyObject() profile?: UpdateStallionProfileDto; @ApiProperty({ type: [StallionGalleryImageDto], }) @IsOptional() @IsNotEmpty() galleryImages?: StallionGalleryImageDto[]; @ApiProperty({ example: 'Sample Overview' }) @IsOptional() @IsString() overview?: string; }
--- class: ember --- # AuthDialog ```hbs preview-template <AuthDialog @dc={{'dc-1'}} @nspace={{'default'}} @onchange={{action (noop)}} as |api components|> {{#let components.AuthForm components.AuthProfile as |AuthForm AuthProfile|}} <BlockSlot @name="unauthorized"> Here's the login form: <AuthForm /> </BlockSlot> <BlockSlot @name="authorized"> Here's your profile: <AuthProfile /> <button onclick={{action api.logout}}>Logout</button> </BlockSlot> {{/let}} </AuthDialog> ``` ### Arguments A component to help orchestrate a login/logout flow. | Argument | Type | Default | Description | | --- | --- | --- | --- | | `dc` | `String` | | The name of the current datacenter | | `nspace` | `String` | | The name of the current namespace | | `onchange` | `Function` | | An action to fire when the users token has changed (logged in/logged out/token changed) | ### Methods/Actions/api | Method/Action | Description | | --- | --- | | `login` | Login with a specified token | | `logout` | Logout (delete token) | | `token` | The current token itself (as a property not a method) | ### Components | Name | Description | | --- | --- | | [`AuthForm`](../auth-form/README.mdx) | Renders an Authorization form | | [`AuthProfile`](../auth-profile/README.mdx) | Renders a User Profile | ### Slots | Name | Description | | --- | --- | | `unauthorized` | This slot is only rendered when the user doesn't have a token | | `authorized` | This slot is only rendered whtn the user has a token.| ### See - [Component Source Code](./index.js) - [Template Source Code](./index.hbs) ---
package com.atguigu.springcloud.feign; import com.atguigu.springcloud.entities.CommonResult; import com.atguigu.springcloud.entities.Payment; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient(value = "cloud-payment-service",fallback = PaymentFallback.class) public interface PaymentClient { @GetMapping("/payment/get/{id}") CommonResult getPaymentById(@PathVariable("id") Long id); @GetMapping("/payment/create") CommonResult create(Payment payment); @GetMapping("/payment/test1/{id}") String test1(@PathVariable("id") Long id); @GetMapping("/payment/test2/{id}") String test2(@PathVariable("id") Long id); }
import type { Metadata } from "next"; import { Inter as FontSans } from "next/font/google" import NextTopLoader from 'nextjs-toploader'; import { Toaster as ReactHotToast } from 'react-hot-toast'; import "./globals.css"; import { cn } from "@/lib/utils"; import { ThemeProvider } from "@/providers/theme-provider"; import AuthProvider from "@/providers/auth-provider" import { Toaster } from "@/components/ui/sonner" import { QueryProvider } from "@/providers/query-provider" import { AppKnockProviders } from "@/providers/knock-provider"; import { ModalProvider } from "@/providers/modal-provider"; import { ConfettiProvider } from "@/providers/confetti-provider"; const fontSans = FontSans({ subsets: ["latin"], variable: "--font-sans", }) export const metadata: Metadata = { title: "E-Shop | E-commerce platform", description: "Best E-commerce platform of Bangladesh", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <AuthProvider> <html lang="en"> <body className={cn( "min-h-screen bg-background font-sans antialiased", fontSans.variable )} > <ThemeProvider attribute="class" defaultTheme="light" disableTransitionOnChange > <QueryProvider> <AppKnockProviders> {children} <NextTopLoader showSpinner={false} color="#16A34A" /> <Toaster /> <ReactHotToast /> <ConfettiProvider /> <ModalProvider /> </AppKnockProviders> </QueryProvider> </ThemeProvider> </body> </html> </AuthProvider> ); }