Normal view
Yesterday — 3 June 2025IRC mates
3 June 2025 at 00:00
Before yesterdayIRC mates
Spring boot annotation used in entity class
17 April 2025 at 16:54
Class based Annotation:
- @Entity – used to indicates the class is below to JPA entites.
- @Table – is used to indicates the table name.
- @MappedSuperClass – is used to parent entity, which can be inherited by many entities, but it won’t be mapped to its own table. we cannot use @Entity annotation on this class.
@MappedSuperclass public abstract class BaseEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // Getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } } @Entity @Table(name = "employees") public class Employee extends BaseEntity { private String firstName; private String lastName; // Constructors, getters, setters, other fields... }
- In this example, the
BaseEntity
class is annotated with@MappedSuperclass
. It contains the common fields that you want to share across multiple entity classes. - The
Employee
class inherits fromBaseEntity
, effectively inheriting theid
field from the superclass. - By using
@MappedSuperclass
, you’re able to create a common base class for your entity hierarchy while allowing each subclass to include additional fields and annotations specific to their needs. - This promotes code reusability and maintains a clean and structured entity hierarchy.
Primary Keys
- Define a primary key using @Id.
- Use @GeneratedValue with appropriate strategy for generating primary key values (e.g., GenerationType.IDENTITY, GenerationType.SEQUENCE)
@Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // other fields, getters, setters }
Associations
It says the relationship between two entity class.
- Use @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships between entities.
- Use fetch attribute to control loading behavior (e.g., LAZY or EAGER).
- Utilize mappedBy to define the owning side of bidirectional relationships.
@Entity public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "department",cascade=CascadeType.ALL) private List<Employee> employees; // Constructors, getters, setters, other fields... } @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String lastName; @ManyToOne @JoinColumn(name = "department_id") private Department department; // Constructors, getters, setters, other fields... }
Cascading Operations
- Use cascade attribute to specify cascading operations (e.g., CascadeType.ALL, CascadeType.PERSIST).
- Be cautious with cascading DELETE to avoid unintentional data loss.
import javax.persistence.*; import java.util.List; @Entity public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true) private List<Book> books; // Constructors, getters, setters, other fields... } @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; @ManyToOne @JoinColumn(name = "author_id") private Author author; // Constructors, getters, setters, other fields... }
- CascadeType.ALL: This option specifies that all operations (e.g., persist, merge, remove) should be cascaded from the parent entity (
Author
) to the child entity (Book
). - orphanRemoval = true: This option specifies that when an
Author
entity’s reference to aBook
entity is removed from thebooks
collection, the orphanedBook
entity should also be removed from the database
When you perform a cascading operation on the Author entity, the corresponding operation will cascade to the associated Book entities. For instance.
Author author = new Author(); author.setName("J.K. Rowling"); Book book1 = new Book(); book1.setTitle("Harry Potter and the Sorcerer's Stone"); book1.setAuthor(author); Book book2 = new Book(); book2.setTitle("Harry Potter and the Chamber of Secrets"); book2.setAuthor(author); author.setBooks(Arrays.asList(book1, book2)); // Cascading persist: Saving the author will also save both associated books. entityManager.persist(author);
Likewise, cascading operations work for merge, remove, and other entity operations, reducing the need for explicitly managing related entities persistence.
Validation
Use validation annotations (@NotNull, @Size, etc.) to enforce data integrity constraints directly in the entity class.
Combine JPA validation with Spring’s @Valid annotation to automatically validate incoming data.
@Entity public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank(message = "Title is required") @Size(max = 100, message = "Title must be at most 100 characters") private String title; @OneToMany(mappedBy = "post", cascade = CascadeType.ALL) private List<Comment> comments; // Constructors, getters, setters, other fields... } @Entity public class Comment { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank(message = "Text is required") @Size(max = 500, message = "Text must be at most 500 characters") private String text; @ManyToOne @JoinColumn(name = "post_id") private Post post; // Constructors, getters, setters, other fields... }
Auditing
- Implement entity auditing by adding fields like @CreatedBy, @CreatedDate, @LastModifiedBy, and @LastModifiedDate for tracking who created or modified an entity and when.
- Utilize Spring’s @EntityListeners to manage the auditing behavior.
@EntityListeners(AuditingEntityListener.class) @MappedSuperclass public abstract class Auditable { @CreatedBy protected String createdBy; @CreatedDate @Column(nullable = false, updatable = false) protected LocalDateTime createdDate; @LastModifiedBy protected String lastModifiedBy; @LastModifiedDate protected LocalDateTime lastModifiedDate; // Getters and setters... }
- @EntityListeners(AuditingEntityListener.class): This annotation specifies that this entity should be audited using the provided entity listener class. Spring Data JPA will automatically update the auditing fields before persisting or updating the entity.
- @MappedSuperclass: This annotation indicates that this class is not an entity itself but serves as a base class for other entities. It allows attributes and behaviors to be inherited by other entities.
- @CreatedBy: This annotation specifies the field to store the username of the user who created the entity.
- @CreatedDate: This annotation marks the field to store the timestamp when the entity was created. The nullable and updatable properties are set to false to ensure that this field is populated during creation and not updated afterwards.
- @LastModifiedBy: This annotation specifies the field to store the username of the user who last modified the entity.
- @LastModifiedDate: This annotation marks the field to store the timestamp when the entity was last modified.
By implementing auditing, you can track who created or modified entities and when those actions occurred. This information can be invaluable for monitoring and maintaining your application’s data.
Enums and Enumerated Types
- Use Java enums for fields with predefined values.
- Annotate enum fields with @Enumerated(EnumType.STRING) to store enum values as strings in the database.
@Entity public class Task { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Enumerated(EnumType.STRING) private TaskStatus status; // other fields, getters, setters } public enum TaskStatus { TODO, IN_PROGRESS, DONE }
Reference:
- https://medium.com/@bubu.tripathy/best-practices-entity-class-design-with-jpa-and-spring-boot-6f703339ab3d
- https://medium.com/@bubu.tripathy/best-practices-entity-class-design-with-jpa-and-spring-boot-6f703339ab3d
Warpd - Keyboard driven virtual pointer
15 April 2025 at 00:00
25th Build2Learn Hackathon project
22 March 2025 at 00:00
Trying out floorp browser
14 March 2025 at 00:00
To-Do Application on Spring boot
14 April 2025 at 20:13
I am going to create To-do list.
Spring boot dependencies.
- spring boot web
- jdbc postgreSQl driver
- spring- JPA
- Thyme-leaf
Entities
I am going to create two entities. They are task and Todo. It has one to many, It means todo has many task. Create the field and getter and setter methods.
TodoList class
It has id, name and List<Task>. Create getter and setter method.
Then we create bidirectional relationship between todo have task. so we create mappedBy the todo object on task. so task can create foreign key for todo list.
@Entity public class TodoList { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; @OneToMany(mappedBy = "todoList", cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.EAGER) private List<Task> taskList= new ArrayList<>(); @ManyToOne @JoinColumn(name = "user_idn") private Users users; // no-arg constructor and getter and setter }
Task class
It has id and name and todo object. Then we create getter and setter method.
The foreign key create in this table, because we mapped this todo object is mapped on that class. joinColumn name is the foreign key name.
@Entity public class Task { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private boolean status; // private Locale locale; // date and time @ManyToOne @JoinColumn(name = "todo_list_id") private TodoList todoList; }
Repository Interface
Simple that create two interface one for task and todo which can extend the JPARepository.
public interface TaskRepository extends JpaRepository<Task, Long> { } public interface TaskRepository extends JpaRepository<Task, Long> { }
DB and JPA configuations
spring.datasource.url=jdbc:postgresql://localhost:5432/login spring.datasource.username=progres spring.datasource.password=1234 spring.datasource.driver-class-name=org.postgresql.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect
Controller class with html
We are going to create 7 task with frontend html with thyme leaf. Map the class with “/todos” using @RequestMapping.
Click the arrow or triange (|>) to see full details.
1. show all todo list
It method is used to default page of /todos page. It have List of Todo and newlist which can return to html page.
@GetMapping public String listTodoLists(Model model) { model.addAttribute("todoLists", todoListRepository.findAll()); model.addAttribute("newTodoList", new TodoList()); return "todo-lists"; }
2. create the todo list
Then we press create list button on html. we got newlist from getMapping that List pass through @modelAttribute. That list can save in repository.
@PostMapping public String createTodoList(@ModelAttribute TodoList todoList) { todoListRepository.save(todoList); return "redirect:/todos"; }
3. show tasks from todo list
Then we enter into the a list, it have many task. That can be shown by this method. we get the list by id and we pass that list of task and new task to html.
@GetMapping("/{listId}") public String viewTodoList(@PathVariable Long listId, Model model) { TodoList todoList = todoListRepository.findById(listId) .orElseThrow(() -> new IllegalArgumentException("Invalid list id")); model.addAttribute("todoList", todoList); model.addAttribute("newTask", new Task()); return "tasks"; }
4. create the task from todo list
Then we press create task button on html. we got new task from getMapping that task pass through @modelAttribute. That list can save in repository.
// Add task to a todo list @PostMapping("/{listId}/tasks") public String addTask(@PathVariable Long listId, @ModelAttribute Task task) { TodoList todoList = todoListRepository.findById(listId) .orElseThrow(() -> new IllegalArgumentException("Invalid list id")); task.setTodoList(todoList); taskRepository.save(task); return "redirect:/todos/" + listId; }
5. Toggle the task or not
Then we press todo checkbox it can be tick. Same find the task by taskId. That task setCompleted and save it again in task. Return redirect://todos/+listId, it redirect to getMapping or this Todo List.
// Toggle task completion status @PostMapping("/{listId}/tasks/{taskId}/toggle") public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) { Task task = taskRepository.findById(taskId) .orElseThrow(() -> new IllegalArgumentException("Invalid task id")); task.setCompleted(!task.isCompleted()); taskRepository.save(task); return "redirect:/todos/" + listId; }
6. delete the todo list
Then we press delete button from list on html. we remove from repository. Return the getMapping of current list.
@PostMapping("/{listId}/delete") public String deleteTask(@PathVariable Long listId) { taskRepository.deleteById(taskId); return "redirect:/todos/" + listId; }
7. delete the task from task list
Then we press delete button on html. We delete task from task repository. We return and redirect to getmapping of current task list.
@PostMapping("/{listId}/delete") public String deleteTodoList(@PathVariable Long listId) { todoListRepository.deleteById(listId); return "redirect:/todos"; }
Controller full code
@Controller @RequestMapping("/todos") public class TodoController { @Autowired private TodoListRepository todoListRepository; @Autowired private TaskRepository taskRepository; // Show all todo lists @GetMapping public String listTodoLists(Model model) { model.addAttribute("todoLists", todoListRepository.findAll()); model.addAttribute("newTodoList", new TodoList()); return "todo-lists"; } // Create new todo list @PostMapping public String createTodoList(@ModelAttribute TodoList todoList) { todoListRepository.save(todoList); return "redirect:/todos"; } // Show tasks from todo list @GetMapping("/{listId}") public String viewTodoList(@PathVariable Long listId, Model model) { TodoList todoList = todoListRepository.findById(listId) .orElseThrow(() -> new IllegalArgumentException("Invalid list id")); model.addAttribute("todoList", todoList); model.addAttribute("newTask", new Task()); return "tasks"; } // Add task to a todo list @PostMapping("/{listId}/tasks") public String addTask(@PathVariable Long listId, @ModelAttribute Task task) { TodoList todoList = todoListRepository.findById(listId) .orElseThrow(() -> new IllegalArgumentException("Invalid list id")); task.setTodoList(todoList); taskRepository.save(task); return "redirect:/todos/" + listId; } // Toggle task completion status @PostMapping("/{listId}/tasks/{taskId}/toggle") public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) { Task task = taskRepository.findById(taskId) .orElseThrow(() -> new IllegalArgumentException("Invalid task id")); task.setCompleted(!task.isCompleted()); taskRepository.save(task); return "redirect:/todos/" + listId; } // Delete a task @PostMapping("/{listId}/tasks/{taskId}/delete") public String deleteTask(@PathVariable Long listId, @PathVariable Long taskId) { taskRepository.deleteById(taskId); return "redirect:/todos/" + listId; } // Delete a todo list @PostMapping("/{listId}/delete") public String deleteTodoList(@PathVariable Long listId) { todoListRepository.deleteById(listId); return "redirect:/todos"; } }
Html code
Html has two page one for todo list and another for task list.
Todo list.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Todo Lists</title> <link rel="icon" type="image/x-icon" href="/aaeranLogo.ico" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-4"> <h1>My Todo Lists</h1> <!-- Form to create new todo list --> <form th:action="@{/todos}" th:object="${newTodoList}" method="post" class="mb-4"> <div class="input-group"> <input type="text" th:field="*{name}" class="form-control" placeholder="New list name" required> <button type="submit" class="btn btn-primary">Create List</button> </div> </form> <!-- display the todo list --> <div th:each="todoList : ${todoLists}" class="card mb-3"> <div class="card-body"> <h2 class="card-title"> <a th:href="@{/todos/{id}(id=${todoList.id})}" th:text="${todoList.name}">List Name</a> <span class="badge bg-secondary" th:text="${todoList.taskList.size()}">0</span> </h2> <form th:action="@{/todos/{id}/delete(id=${todoList.id})}" method="post" class="d-inline"> <button type="submit" class="btn btn-sm btn-danger">Delete List</button> </form> </div> </div> </div> </body> </html>
Task.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Tasks</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-4"> <h1>Tasks for <span th:text="${todoList.name}">List Name</span></h1> <a href="/todos" class="btn btn-secondary mb-3">Back to Lists</a> <!-- Form to add new task --> <form th:action="@{/todos/{id}/tasks(id=${todoList.id})}" th:object="${newTask}" method="post" class="mb-4"> <div class="input-group"> <input type="text" th:field="*{name}" class="form-control" placeholder="New task description" required> <button type="submit" class="btn btn-primary">Add Task</button> </div> </form> <div th:each="task : ${todoList.taskList}" class="card mb-2"> <div class="card-body d-flex align-items-center"> <form th:action="@{/todos/{listId}/tasks/{taskId}/toggle(listId=${todoList.id}, taskId=${task.id})}" method="post" class="me-3"> <input type="checkbox" th:checked="${task.status}" onChange="this.form.submit()" class="form-check-input" style="transform: scale(1.5);"> </form> <span th:class="${task.status} ? 'text-decoration-line-through text-muted' : ''" th:text="${task.name}" class="flex-grow-1">Task description</span> <form th:action="@{/todos/{listId}/tasks/{taskId}/delete(listId=${todoList.id}, taskId=${task.id})}" method="post" class="ms-2"> <button type="submit" class="btn btn-sm btn-danger">Delete</button> </form> </div> </div> </div> </body> </html>
Reference :
- https://www.javaguides.net/2018/09/mini-todo-management-project-using-spring-boot-springmvc-springsecurity-jsp-hibernate-mysql.html
- https://www.javaguides.net/2018/09/mini-todo-management-project-using-spring-boot-springmvc-springsecurity-jsp-hibernate-mysql.html
Deploy our Spring boot application for free.
14 April 2025 at 18:46
In this blog, we are going to deploy out spring boot application with PostgreSQL using to
- Web site on render.com
- PostgreSQl on neon.com
Create an Application
We can create application that can interact with html and controller layer of our application. Then, service layer that can interact with Repository layer.
Frontent (Thyme Leaf)
I am going to create html that can integrate with thyme leaf.
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title> first page </title> </head> <body> <div> <h1>Heading name</h1> <p><span th:text="${word}"></span></p> </div> <div> <h1>list</h1> <p><span th:text="${word}"></span></p> </div> </body> </html>
Create a html in spring boot
Go to template and create our html pages and Go to static from create js and CSS files. I paste above code on the index.html.
Spring boot Controller layer
I create controller class which can map the html with java class.
@Controller public class ControllerClass { @GetMapping public String getInitialisePage(Model model) { String p = "ravana"; model.addAttribute("word",p); return "index"; } }
Create a Repository Interface
we are going to do dataBase configuaration and spring JPA here.
Configuration of Database and JPA
Configure the Database and JPA on Application.Properties.
spring.datasource.url = ${DATASOURCE_URL} spring.datasource.username= ${DATASOURCE_USERNAME} spring.datasource.password= ${DATASOURCE_PASSWORD} spring.datasource.driver-class-name=org.postgresql.Driver spring.jpa.hibernate.ddl-auto = update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect
Now, the database url, userName, password are assigned as Environment variables. So, now we want to assign as in different approach by IDE.
Using Eclipse or Spring tool suit IDE
- Right click on our project.
- Run as -> run configurations
- click the environment and set the name and value.
- Eg. name = DATASOURCE_URL and value = our jbdc url
- Eg. name = DATASOURCE_USERNAME and value = our username
- Eg. name = DATASOURCE_PASSWORD and value = our Password
Create jar file from our project
When we create Spring boot project we have .mvn file. Delete the test related dependency and class.
./mvnw clean package
If not work copy this below code. This is work on linux only
export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/login" export SPRING_USERNAME="postgres" export DATASOURCE_PASSWORD="1234" //don't be panic as run again to run ./mvnw clean package // else give this command // remove the test depandancy and delete src/main/test. // ./mvnw clean package
Create a docker file
Download docker and docker desktop on our system. Create a file on our project, named as Dockerfile.
# Use an official Maven image to build the Spring Boot app FROM maven:3.8.4-openjdk-17 AS build # Set the working working directory WORKDIR /app # Copy the pom.xml and install dependencies COPY pom.xml . RUN mvn dependency:go-offline # Copy the source code and build the application COPY src ./src RUN mvn clean package -DskipTests # This will download the all depandencies # Use an official OpenJDK image to run the application FROM openjdk:17-jdk-slim #Set the working directory WORKDIR /app # Copy the built JAR file from the build stage COPY --from=build /app/target/file-name.jar . # my fileName is demo-0.0.1-SNAPSHOT so COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar # Expose port 8080 EXPOSE 8080 # Specify the command to run the application ENTRYPOINT ["java", "-jar", "/app/notes-0.0.1-SNAPSHOT.jar"] # change the notes-0.0.1-SNAPSHOT.jar into fileName demo-0.0.1-SNAPSHOT # ENTRYPOINT ["java", "-jar", "/app/demo-0.0.1-SNAPSHOT.jar"]
Create Docker image
After create docker file. Then run the below command on terminal. It will generate a docker image. Check the image on your docker or not.
docker build -t demo_deployment . docker tag demo-deployment kalaiarasan23/demo-deployment:latest docker push kalaiarasan23/demo-deployment:latest
Host our Database
Go to neon.tech, create account we got free 500MB space DB. Now create project and add.
Important is to get the configutation because we will use in application part.
postgresql://username:password2@ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require Select the environmental variable on render.com DATASOURCE_URL=jdbc:postgresql://ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require DATASOURCE_USERNAME=username DATASOURCE_PASSWORD=password
Host the Web application
Go to render.com and open dashboard -> Click new web services ->click image. Enter the environment variable at last. Deploy our web site and verify the server online or not.
Reference :
Place button on wiki Page.
10 January 2025 at 14:14
I got a task, that to add a cody in wiktionary side. For do this we have knowledge of Wiki Gadget.
Create an Account on wiki page:
- If we want to change in wiki page. First we want to create account in wiki.
- Then we create a own javascript page for make change.
- The changes can be seen in our page only.
- If we want to change globally, i have a knowledge of Gadget_kitchen in wiki.
Find the place that have to change
- Go to wiktionary site and seach any word it.
- open F12 to view inspect and find the place heading usi.
- I found in
- body -> div(mw-page-container) -> div(mw-page-container-inner) -> div(mw-content-container) ->main -> header.
- header contains nav, h1, div(title-shortlink-container), div(vector-dropdown.
- h1 must be copy and button place near to h1 or div(title-shortlink-container).

Create common.js page and paste the code
- After create account on Wiktionary.
- Type this url :https://en.wiktionary.org/wiki/User:UserName/common.js.
- Re-place the UserName with your userName.
- Paste the below code on the editor.
Code:
const observer = new MutationObserver(() => { const heading = document.querySelector(".title-shortlink-container"); if (heading) { // Create the button element const button = document.createElement("button"); button.textContent = "Copy Text"; button.style.marginLeft = "10px"; // Add some spacing from the container // Insert the button next to the .title-shortlink-container heading.insertAdjacentElement("afterend", button); // Add an event listener to copy the text button.addEventListener("click", () => { const textToCopy = heading.textContent.trim(); // Get only the container's text navigator.clipboard.writeText(textToCopy).then(() => { alert("Text copied: " + textToCopy); }).catch(err => { console.error("Failed to copy text: ", err); }); }); observer.disconnect(); // Stop observing once the element is found } }); // Observe the document for dynamic changes observer.observe(document.body, { childList: true, subtree: true });
Code Explanation :
- Use Document. querySelector for get the element of the .title-shortlink-container class. This class is for shortURL className and assign to variable Heading.
- If the Heading is not null. Then we create the button and styles.
- The Button is placed next to link. Use heading.insertAdjacentElement(“afterend”, button);
- Button action create a function in addEventListener.
- Get the link by heading.textContent and store in textToCopy
- For copy the text use navigator.clipboard.writeText(textToCopy)
- Then pop alert for the event.
- if error catch throw error message.
Problem faced (dynamically loaded content)
- First i use DOMContentLoaded. It cannot work in wiki.
- Then i use Polling (Setintervel for a Certain time). It works partcially.
- Then i use MutationObserver. I works perfectly to all pages.
Reference:
https://ta.wikipedia.org/wiki/Special:MyPage/common.js
https://stackoverflow.com/questions/24344022/how-to-use-mutationobserver
https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript
136. Single Number
5 January 2025 at 13:42
Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1] Output: 1
Example 2:
Input: nums = [4,1,2,1,2] Output: 4
Example 3:
Input: nums = [1] Output: 1
Constraints:
1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
- Each element in the array appears twice except for one element which appears only once.
package ArrayExecise; /* * result=1 => 0001 * result=2 => 0010 ^ 0001 = 0011 * result=2 => 0011 ^ 0010 = 0001 * result=3 => 0001 ^ * */ public class SingleElement { public static void main(String[] args) { int nums[]= {1,2,2,3,3,4,4,5,5}; int result=0; for(int i=0; i<nums.length; i++) { result = result^nums[i]; } System.out.println(result); } }
Table and List
5 January 2025 at 13:39
HTML table tag is used to display data in tabular form (row * column). There can be many columns in a row.
We can create a table to display data in tabular form, using <table> element, with the help of <tr> , <td>, and <th> elements.
In Each table, table row is defined by <tr> tag, table header is defined by <th>, and table data is defined by <td> tags.
Tag | Description |
---|---|
<table> | It defines a table. |
<tr> | It defines a row in a table. |
<th> | It defines a header cell in a table. |
<td> | It defines a cell in a table. |
<caption> | It defines the table caption. |
<colgroup> | It specifies a group of one or more columns in a table for formatting. |
<col> | It is used with <colgroup> element to specify column properties for each column. |
<tbody> | It is used to group the body content in a table. |
<thead> | It is used to group the header content in a table. |
<tfooter> | It is used to group the footer content in a table. |
Update data on table
18 May 2024 at 19:50
UPDATE
statement allows you to update data in one or more columns of one or more rows in a table.
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
In this syntax:
- First, specify the name of the table that you want to update data after the
UPDATE
keyword. - Second, specify columns and their new values after
SET
keyword. The columns that do not appear in theSET
clause retain their original values. - Third, determine which rows to update in the condition of the
WHERE
clause
Code:
UPDATE company SET salary = salary * 2 WHERE salary = 150000;
The WHERE
clause is optional. If you omit the WHERE
clause, the UPDATE
statement will update all the column values in the table.
Code:
UPDATE company SET salary = salary * 2
Summary :
- Use the
UPDATE
statement to update data in one or more columns of a table. - Specify a condition in a WHERE clause to determine which rows to update data.
- Use the
RETURNING
clause to return the updated rows from theUPDATE
statement
Reference :
Insert data on table
18 May 2024 at 19:32
INSERT
statement to insert a new row into a table.
INSERT INTO table1(column1, column2, …) VALUES (value1, value2, …);
In this syntax:
- First, specify the name of the table (
table1
) that you want to insert data after theINSERT INTO
keywords and a list of comma-separated columns (colum1, column2, ....
). - Second, supply a list of comma-separated values in parentheses
(value1, value2, ...)
after theVALUES
keyword. The column and value lists must be in the same order.

RETURNING clause
- The
INSERT
statement has an optionalRETURNING
clause - returns the information of the inserted row.
INSERT INTO table1(column1, column2, …) VALUES (value1, value2, …) RETURNING *;

It return the inside table
We can return by any parameters.

Summary
- Use PostgreSQL
INSERT
statement to insert a new row into a table. - Use the
RETURNING
clause to get the inserted rows.
Reference:
how to install PGAdmin in Linux-mint
18 May 2024 at 18:56
Use jammy ubuntu version, for install the PGAdmin on linux-mint.
1) Install the public key for the repository (if not done previously):
sudo curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add
2) Create the repository configuration file: (jammy is important)
sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/jammy pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update
3) Install pgAdmin
sudo apt install pgadmin4
4) Install for desktop mode only
sudo apt install pgadmin4-desktop
5) If you need, also install for web mode only:
sudo apt install pgadmin4-web
6) After install pgadmin4. Configure the webserver, (if you installed pgadmin4-web)
sudo /usr/pgadmin4/bin/setup-web.sh
Reference :
- https://stackoverflow.com/questions/68777587/linux-mint-20-x-ubuntu-based-cant-install-pgadmin4
- https://www.pgadmin.org/download/pgadmin-4-apt/
67. Add Binary
7 May 2024 at 16:20
This problem is like add String number in String.
Description :
Given two binary strings a
and b
, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
Algorithm:
- Add numbers from end to start so, initials i =a.length() -1 and j=a.length()-1.
- Intialize the carry =0 as the remaining number.
- use Stringbuffer for the mutable property in string.
- Now Add the continuously,
- carry += num1.charAt(i) and i– upto i>=0.
- carry += num2.charAt(j) and j– upto j>=0.
- stringBuffer. append(carry%10).
- carry /= 10.
- then reverse the stringBuffer by st.reverse().
Code :
int carry =0,i=a.length()-1,j=b.length()-1; StringBuffer sb =new StringBuffer(); while(i>=0 || j>=0 || carry > 0) { if(i>=0) carry += a.charAt(i--)-'0'; if(j>=0) carry += b.charAt(j--)-'0'; sb.append(carry%2); carry /=2; } return sb.reverse().toString();
Reference :
415. Add Strings
7 May 2024 at 16:03
LeetCode number 415, String.
This problem is like add binary number in String.
Description:
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Input / Ouput :
Example 1:
Input: num1 = "11", num2 = "123" Output: "134"
Example 2:
Input: num1 = "456", num2 = "77" Output: "533"
Example 3:
Input: num1 = "0", num2 = "0"
Output: "0"
Algorithm:
- Add numbers from end to start so, initials i =num1.length() -1 and j=num2.length()-1.
- Intialize the carry =0 as the remaining number.
- use Stringbuffer for the mutable property in string.
- Now Add the continuously,
- carry += num1.charAt(i) and i– upto i>=0.
- carry += num2.charAt(j) and j– upto j>=0.
- stringBuffer. append(carry%10).
- carry /= 10.
- then reverse the stringBuffer by st.reverse().
code :
int i=num1.length()-1, j=num2.length()-1, carry=0; StringBuffer sb = new StringBuffer(); while(i>=0 || j>=0 || carry > 0) { // condtion for string out of boundary i.e means i should less then 0 if(i>=0) carry += num1.charAt(i--) - '0'; if(j>=0) carry += num2.charAt(j--) - '0'; sb.append(carry%10); carry /= 10; } return sb.reverse().toString();
Reference :
https://leetcode.com/problems/add-strings
Digital library using calibre
14 March 2025 at 00:00
Mako and Ednc Notifcation daemon
12 March 2025 at 00:00
Simple Live reload server
22 February 2025 at 00:00
Not able to comprehend eSIM
19 February 2025 at 00:00