Reading view

There are new articles available, click to refresh the page.

Weekly notes 16-17 2025

Last two weeks went super busy with office work, reading, library visits and few events.

Reading:

Completed reading the original book and rewritten version of “பெண் ஏன் அடிமையானாள்?” “Why women became slave?” by originally written by Periyar. That book describes why Indian women are still slaves of family, society due to various reasons like marriage, childcare etc.

The sad part is, even though that book was written few decades ago, it is still relevant.

Like any other devotional books/stories are retold for every generation, this book should also be rewritten,
once in every 10-20 years and it should be told on all modern formats like audio books, drama, shortfilms, shorts etc.

Reviewing and editing that rewritten version is one of the most satisfying action I did this year.
Hope we can release this as a print edition and free ebook edition. Checking with few contacts to publish this. Will share the progress soon.

Still reading the book “Attention Span”. May take few weeks to complete.

Easter:
Kids got some 4 days holidays due to Easter. They all went for a Easter egg hunting event.

HeartComonos:
At HeartComonos, a social non profit organization, is conducting many free events here. Participated on a Bollywood dance event with family. Celebrated its lead Hardy’s birthday, along with fun filled dancing.
Helped to capture the wonderful moments with Camera.

Library visit:

On the weekend, we visited Mississauga Central Library. It is one of the best places, as a family, we like to go anytime. Just being surrounded by million books itself a great feeling. Viyan is reading a lot. Iyal is still trying to read. Paari is yet to learn reading, but he can turn pages of books one by one for many hours. There are good comics books available. Both Iyal and Paari are creating their own stories, just by seeing and turning the pages. What else we need for kid’s mind to be filled with imagination?

Upcoming talk on Open Licensed Tamil dataset collection:
On May 05 2025, I will be giving an online talk on curation of open licensed tamil dataset.
Preparing for the talk along with collecting open data in Tamil.

KanchiLUG meets:
Every sunday IST evening hours, ( my mornings) are going useful with interesting discussions on Linux,
Free/Open Source software etc.

check https://kaniyam.com/events and subscribe to the calendar there for more interesting events.

Tamil Skills contest for kids:
Last saturday, attended a contest for kids with viyan. Good to see that around 100+ kids participated on the contest on Skills for Tamil reading,writing and speaking. viyan participated with last min preparation.
Next year, hope all three kids will attend. Happy to see many friends like Natkeeran, Suba, Kent, Selvanayaki madam.Took care of capturing some wonderful moments of the events.

After the event, spent few hours in a library at Toronto Downtown. I skimmed on few books on black/white photography, Instagram posting, video making and Toronto Photographers collection etc. Discussing many things with viyan is one of my favourite things. When we travel along, we talk about many things like world history, war, mythology, comics, manga, atheism, Tamilnadu political history etc.

ComicCon Mississauga:
Sunday, attended an event for Comics and Toy Collections. Around 100 sellers were selling old comics books, unopened hero toys. There were many kids buying those stuffs. I was wondering to see, there were many adults standing in line, exploring the old comics and toys, and buying them with wide open eyes.

First they create a cha rector, then bring as comic books, then toys, then computer games, then graphic novel, then text novel, then movies. This is how all the childhood characters are becoming immortal. The business behind this is very huge. Thinking why we the Indians can not bring such huge cycle of business, even though we have tons of stories. Among all the mythological stories, there are very little for children. We have to create more stories and do business with them.

Nithya’s Video series on GenAI

Nithya started text series on GenAI at Kaniyam.com and a video series on her youtube channel, in Tamil. We had some good outdoor shooting for the intro video. Released the first video here

Task 6: Tuple

1.Create a tuple containing the names of three fruits. Print the tuple and its type.

Image description

2.Given a tuple t = ("apple", "banana", "cherry"), access and print the second element.

Image description

3.Unpack the tuple t = (1, 2, 3) into variables a, b, and c, and print the variables.

Image description

4.Concatenate two tuples t1 = (1, 2) and t2 = (3, 4) and print the result.

Image description

5.Create a tuple t = ("repeat",) and repeat it three times. Print the resulting tuple.

Image description

6.Given a tuple t = (1, 2, 3, 2, 2, 4), count the number of times the number 2 appears.

Image description

7.Given a tuple t = ("a", "b", "c", "d"), find the index of the element "c".

Image description

8.Check if the element 5 is present in the tuple t = (1, 2, 3, 4)

Image description

9.Find and print the length of the tuple t = ("one", "two", "three").

Image description

10.Slice the tuple t = (0, 1, 2, 3, 4, 5) to obtain a sub-tuple containing only the elements from index 2 to 4.

Image description

11.Create a nested tuple representing a 2D point (x, y) = ((1, 2), (3,
4)). Access and print the second coordinate of the second point.

Image description

12.Try to change the value of the first element in the tuple t = (1, 2, 3) and observe what happens.

Image description

13.Convert a list l = [1, 2, 3] to a tuple and print the result. Then convert a tuple t = (4, 5, 6) to a list and print the result.

Image description

14.Create a tuple with a single item 5 and verify its type is a tuple.

Image description

15.Iterate over the tuple t = ("ParottaSalna", "is", "good") and print each element.
16.Convert the string "hello" into a tuple of characters.
17.Convert a dictionary d = {"one": 1, "two": 2} into a tuple of its items.
18.Write a function that takes a tuple of numbers and returns the sum of the numbers.
19.Use tuples as keys in a dictionary to represent points on a grid. For example, grid = {(0, 0): "origin", (1, 2): "point A"}.

Task 5: Python Function

1.Write a function greet that takes a name as an argument and prints a greeting message.

Image description

2.Write a function sum_two that takes two numbers as arguments and returns their sum.

Image description

3.Write a function is_even that takes a number as an argument and returns True if the number is even, and False if it is odd.

Image description

4.Write a function find_max that takes two numbers as arguments and returns the larger one.

Image description

5.Write a function multiplication_table that takes a number n and prints the multiplication table for n from 1 to 10.

Image description

Image description

6.Write a function celsius_to_fahrenheit that takes a temperature in Celsius and returns the temperature in Fahrenheit.

Image description

7.Write a function power that takes two arguments, a number and an exponent, and returns the number raised to the given exponent. The exponent should have a default value of 2.

Image description

TASK 4: Python Lists

1.Create a list of five delivery items and print the third item in the list. eg: [“Notebook”, “Pencil”, “Eraser”, “Ruler”, “Marker”]

Image description

2.A new delivery item “Glue Stick” needs to be added to the list. Add it to the end of the list and print the updated list.

Image description

3.Insert “Highlighter” between the second and third items and print the updated list.

Image description

4.One delivery was canceled. Remove “Ruler” from the list and print the updated list.

Image description

5.The delivery man needs to deliver only the first three items. Print a sublist containing only these items.

Image description

6.The delivery man has finished his deliveries. Convert all item names to uppercase using a list comprehension and print the new list.

Image description

7.Check if “Marker” is still in the list and print a message indicating whether it is found.

Image description

8.Print the number of delivery items in the list.

Image description

9.Sort the list of items in alphabetical order and print the sorted list.

Image description

10.The delivery man decides to reverse the order of his deliveries. Reverse the list and print it.

Image description

11.Create a list where each item is a list containing a delivery item and its delivery time. Print the first item and its time.

12.Count how many times “Ruler” appears in the list and print the count.

Image description

13.Find the index of “Pencil” in the list and print it.

Image description

14.Extend the list items with another list of new delivery items and print the updated list.

Image description

15.Clear the list of all delivery items and print the list.

Image description

16.Create a list with the item “Notebook” repeated three times and print the list.

Image description

17.Using a nested list comprehension, create a list of lists where each sublist contains an item and its length, then print the new list.

Image description

18.Filter the list to include only items that contain the letter “e” and print the filtered list.

Image description

19.Remove duplicate items from the list and print the list of unique items.

Image description

TamilKavi: Release of Python Package & Dataset

Hi guys 👋

Today, I want to share something unexpected. To be honest, if someone had told me a month ago that I could do this, I wouldn’t have believed them. But here we are — I’ve finally released a Python package and dataset called TamilKavi. I still can’t believe I pulled it off, but it’s real!

I’d love to share the whole story with you. Many of you already know me — I write Tamil poetry and have even published two books. However, I faced font issues when trying to release them on Amazon and Kindle. Frustrated, I reached out to my community friend, Hari, and I asked them:
“Bro, I want to release my Tamil poetry book on Amazon, but I’m stuck with font issues. Do you know anyone who can solve it?”

Hari referred me to Ayyanar Bro, and to me it’s a surprise, he was from Madurai — what a coincidence! We spoke almost four times a week for different reasons. I had already written about him and his portfolio website, which he built using Emacs & Org, so I won’t go into more details — you guys might find it repetitive.

Through Ayyanar Bro, I learned about the Tamil Kanchilung community and FreeTamilBooks, where I finally found a solution to my font issue. But here’s another twist — FreeTamilBooks required more poetry for my book release. Because I like to release that in FreeTamilBooks.Then another book on Amazon. That was another headache because, with my tight schedule, I barely had time to write.

While navigating all this, I discovered Tamilrulepy, a Python package with Tamil grammar rules. I was eager to learn more, and unexpectedly, I got an opportunity to contribute to it! That’s when I met Boopalan — another passionate tech enthusiast like me. He helped me write code for TamilRulePy and even invited me to contribute to TamilString, a Python package for documentation. I accepted his invitation and started working on it.

Then, during one of our conversations, I got an idea: why not develop my own Python package? And that’s how TamilKavi was born.

I shared my idea with Boopalan and invited him to build it as a team because, honestly, I’m no expert. But it wasn’t easy — we had to overcome countless challenges, especially since we were both preparing for our model exams and semester exams (he’s an MSc student, and I’m a BSc student). It was a tough time, but I didn’t give up. I studied, understood, and gradually started coding — not entirely on my own, of course.

Now, you might wonder — why build a website? Simple: to collect data from authors. But due to financial constraints, the data collected through the website idea transformed into a Google Form, and now it is a navigation button. It’s another story altogether. Since I had no time, I built a basic structure using Lovable.dev and handed it over to my juniors, Gagan & Rohith, who took care of the website.

The final result? Release of the Python package & website!

I must especially thank Praveen Bro — my community brother and mentor. Without hesitation, he offered me a subdomain. For me, that’s a huge deal, and I’m incredibly grateful!

“Okay thambi, enough of this English talk — why did you release the dataset?” When you ask me likewise.

Well, there’s a reason for that, too. I’ve seen Selvakumar Duraipandian Bro on LinkedIn about their post of numerous Tamil datasets on Hugging Face, including Thirukkural, Tholkappiyam, and more. I was truly inspired by his work. So, I release that as a Dataset.

Now, you might ask, “So, thambi, after all this talk, what does your package actually do?”

It’s simple — TamilKavi helps discover new Tamil poems. That’s all. Now your mind is

Edhuka evalo seenu?

Well, I’m not just a developer. The person who is are Tamil poet & tech enthusiast, it’s a crazy project. Through this journey, I’ve learned so much, especially about GitHub workflows.

When you feel this content is valuable, follow me for more upcoming Blogs.

Connect with Me:

TASK 3: Slicing & Indexing

1.Write a function that takes a string and returns a new string consisting of its first and last character.

Image description

2.Write a function that reverses a given string.

Image description

3.Given a string, extract and return a substring from the 3rd to the 8th character (inclusive).

Image description

4.Write a function that returns every second character from a given string.

Image description

5.Write a function that replaces the middle third of a string with asterisks. If the length of the string is not divisible by 3, adjust the middle third accordingly.

6.Write a function that checks if a given string is a palindrome (reads the same backward as forward).

7.Given an email address, extract and return the domain.
Ans: How to find incase there are multiple occurrences? Loop?
Image description

Image description

8.Write a function that returns every third character from a given string.

Image description

9.Write a function that extracts and returns characters at even indices from a given string.

Image description

10.Write a function that skips every second character and then reverses the resulting string.

Image description

TASK 2: Constants and Variables

1.Create a variable named name and assign your name to it. Then print the value of the variable.

Image description

2.Create a variable age and assign your age to it. Later, reassign the variable with a new value and print the new value.

Image description

3.Assign the values 5, 10, and 15 to three variables a, b, and c in a single line. Print their values.
Ans:TypeError on 4th statement, because we're trying to concatenate integers (a, b, c) with strings

Image description

4.Swap the values of two variables x and y without using a third variable. Print their values before and after swapping.

Image description

5.Define constants PI with appropriate values and print them.
Ans: constants are typically written in all uppercase letters with underscores separating words. However, Python does not enforce this, so constants are not truly immutable. You can still override.

Image description

6.Write a program that calculates the area of a circle using the constant PI and a variable radius. Print the area.
Ans: ** is Squared

Image description

7.Define constants for the length and width of a rectangle. Calculate and print the area.

Image description

8.Define a constant for π (pi) and a variable for the radius. Calculate and print the circumference of the circle.

Image description

TASK 1: Python – Print exercises

1.How do you print the string “Hello, world!” to the screen?
Ans: Using sep and end Parameters is preferred way.
Image description

2.How do you print the value of a variable name which is set to “Syed Jafer” or Your name?
Ans: Note the Variable is case sensitive

Image description

3.How do you print the variables name, age, and city with labels “Name:”, “Age:”, and “City:”?
Ans: Using keyword sep="," brings in , between the Variable Name and Value itself, so avoid

Image description

4.How do you use an f-string to print name, age, and city in the format “Name: …, Age: …, City: …”?
Ans: To insert variables directly into the string used f-string
Also, you can assign values to multiple variables in a single line as seen in 1st line

Image description

5.How do you concatenate and print the strings greeting (“Hello”) and target (“world”) with a space between them?
Ans: + is used to concat the items

Image description

6.How do you print three lines of text with the strings “Line1”, “Line2”, and “Line3” on separate lines?****

Image description

7.How do you print the string He said, "Hello, world!" including the double quotes?
Ans: To print quotes inside a string, you can use either single or double quotes to enclose the string and the other type of quotes inside it.

Image description

8.How do you print the string C:\Users\Name without escaping the backslashes?
Ans: you can also use a literal backslash "\" when using Concat or Try with 'r' to treat backslashes as literal characters

Image description

9.How do you print the result of the expression 5 + 3?

Image description

10.How do you print the strings “Hello” and “world” separated by a hyphen -?

Image description

11.How do you print the string “Hello” followed by a space, and then print “world!” on the same line?

Image description

12.How do you print the value of a boolean variable is_active which is set to True?

Image description

13.How do you print the string “Hello ” three times in a row?

Image description

14.How do you print the sentence The temperature is 22.5 degrees Celsius. using the variable temperature?

Image description

15.How do you print name, age, and city using the .format() method in the format “Name: …, Age: …, City: …”?

Image description

16.How do you print the value of pi (3.14159) rounded to two decimal places in the format The value of pi is approximately 3.14?
Ans: pi is the variable & .2f formats it as a floating-point number with 2 digits after the decimal

Image description

17.How do you print the words “left” and “right” with “left” left-aligned and “right” right-aligned within a width of 10 characters each?

Image description

Spring boot annotation used in entity class

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...
}
  1. In this example, the BaseEntity class is annotated with @MappedSuperclass. It contains the common fields that you want to share across multiple entity classes.
  2. The Employee class inherits from BaseEntity, effectively inheriting the id field from the superclass.
  3. 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.
  4. 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.

  1. Use @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships between entities.
  2. Use fetch attribute to control loading behavior (e.g., LAZY or EAGER).
  3. 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...
}
  1. 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).
  2. orphanRemoval = true: This option specifies that when an Author entity’s reference to a Book entity is removed from the books collection, the orphaned Book 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...
}
  1. @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.
  2. @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.
  3. @CreatedBy: This annotation specifies the field to store the username of the user who created the entity.
  4. @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.
  5. @LastModifiedBy: This annotation specifies the field to store the username of the user who last modified the entity.
  6. @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:

Spring boot annotation used in entity class

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...
}
  1. In this example, the BaseEntity class is annotated with @MappedSuperclass. It contains the common fields that you want to share across multiple entity classes.
  2. The Employee class inherits from BaseEntity, effectively inheriting the id field from the superclass.
  3. 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.
  4. 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.

  1. Use @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships between entities.
  2. Use fetch attribute to control loading behavior (e.g., LAZY or EAGER).
  3. 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...
}
  1. 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).
  2. orphanRemoval = true: This option specifies that when an Author entity’s reference to a Book entity is removed from the books collection, the orphaned Book 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...
}
  1. @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.
  2. @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.
  3. @CreatedBy: This annotation specifies the field to store the username of the user who created the entity.
  4. @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.
  5. @LastModifiedBy: This annotation specifies the field to store the username of the user who last modified the entity.
  6. @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:

To-Do Application on Spring boot

I am going to create To-do list.

Spring boot dependencies.

  1. spring boot web
  2. jdbc postgreSQl driver
  3. spring- JPA
  4. 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 :

Deploy our Spring boot application for free.

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.

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

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 :

  1. Use Document. querySelector for get the element of the .title-shortlink-container class. This class is for shortURL className and assign to variable Heading.
  2. If the Heading is not null. Then we create the button and styles.
  3. The Button is placed next to link. Use heading.insertAdjacentElement(“afterend”, button);
  4. Button action create a function in addEventListener.
  5. Get the link by heading.textContent and store in textToCopy
  6. For copy the text use navigator.clipboard.writeText(textToCopy)
  7. Then pop alert for the event.
  8. if error catch throw error message.
Problem faced (dynamically loaded content)
  1. First i use DOMContentLoaded. It cannot work in wiki.
  2. Then i use Polling (Setintervel for a Certain time). It works partcially.
  3. 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

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

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.

TagDescription
<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.
Table tags

Update data on table

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 the SET 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 the UPDATE statement

Reference :

Insert data on table

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 the INSERT INTO keywords and a list of comma-separated columns (colum1, column2, ....).
  • Second, supply a list of comma-separated values in parentheses (value1, value2, ...) after the VALUES keyword. The column and value lists must be in the same order.

RETURNING clause

  • The INSERT statement has an optional RETURNING 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

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 :

67. Add Binary

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:

  1. Add numbers from end to start so, initials i =a.length() -1 and j=a.length()-1.
  2. Intialize the carry =0 as the remaining number.
  3. use Stringbuffer for the mutable property in string.
  4. 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.
  5. 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 :

  1. https://leetcode.com/problems/add-binary/description/

❌