<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Justgiveacar on Medium]]></title>
        <description><![CDATA[Stories by Justgiveacar on Medium]]></description>
        <link>https://medium.com/@justgiveacar?source=rss-bd4ace02d0ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vzsUU40eLe4pjj6_MKE8UA.jpeg</url>
            <title>Stories by Justgiveacar on Medium</title>
            <link>https://medium.com/@justgiveacar?source=rss-bd4ace02d0ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:39:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@justgiveacar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Row-Oriented vs Column-Oriented Databases]]></title>
            <link>https://justgiveacar.medium.com/row-oriented-vs-column-oriented-databases-85c17d86f517?source=rss-bd4ace02d0ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/85c17d86f517</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Justgiveacar]]></dc:creator>
            <pubDate>Fri, 03 Sep 2021 15:06:03 GMT</pubDate>
            <atom:updated>2021-09-03T15:06:03.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*n8W8vJHtFzY9THz9.png" /></figure><p>There are two types of data storage databases one is a <strong>row-oriented</strong> database and another one is a <strong>column-oriented</strong> database.</p><p><strong>Row-Oriented (ACID Transactions)</strong>: They are databases that organize data by the record, keeping all of the data associated with a record next to each other in memory. Row-oriented databases are the traditional way of organizing data and still provide some key benefits for storing data quickly. They are optimized for reading and writing rows efficiently.</p><p>Common row-oriented databases:</p><ul><li>PostgreSQL</li><li>MySQL</li></ul><p><strong>Column-Oriented (Analytics)</strong>: They are databases that organize data by field, keeping all of the data associated with a field next to each other in memory. Columnar databases have grown in popularity and provide performance advantages to querying data. They are optimized for reading and computing on columns efficiently.</p><p>Common column-oriented databases:</p><ul><li>AWS RedShift</li><li>Google BigQuery</li><li>HBase</li></ul><h3>Row-Oriented Databases</h3><p>Traditional Database Management Systems (DBMS) were created to store data. They are optimized to read and write a single row of data which leads to a series of design choices including having a row store architecture.</p><p>In a row store or row-oriented database, the data is stored row by row, such that the first column of a row will be next to the last column of the previous row.</p><p>For instance, let’s take this example data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tM6yft1AdDUn0MDP_PBlyA.png" /></figure><p>This data would be stored on a disk in a row-oriented database in order row by row like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*WuE1zSPTkJNg4BPXKmEAyg.png" /></figure><p>This allows the database to write a row quickly because all that needs to be done to write to it is to tack on another row to the end of the data.</p><p>Row-oriented databases are still commonly used for Online Transactional Processing (OLTP) style applications since they can manage writes to the database well. However, another use case for databases is to analyze the data within them. This Online Analytical Processing (OLAP) use cases need a database that can support ad hoc querying of the data. This is where row-oriented databases are slower than column-oriented databases.</p><h3>Reading from Row-Oriented Databases</h3><p>Row-oriented databases are fast at <strong>retrieving</strong> a row or a set of rows but when performing an aggregation it brings extra data (columns) into memory which is slower than only selecting the columns that you are performing the aggregation on. In addition, the number of disks the row-oriented database might need to access is usually larger.</p><h4>Number of Disks accessed</h4><p>Let’s assume a Disk can only hold enough bytes of data for three columns to be stored on each disk. In a row-oriented database, the table above would be stored as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*j7jVJnnbIVmfVmfJFEgo0A.png" /></figure><p>So we can see that while adding data to a row-oriented database is quick and easy, getting data out of it can require extra memory to be used and multiple disks to be accessed.</p><h3>Column-Oriented Databases</h3><p>Data Warehouses were created in order to support <strong>analyzing</strong> data. These types of databases are read optimized.</p><p>In a column-oriented database, the data is stored such that each row of a column will be next to other rows from that same column.</p><p>Let’s look at the same data set again and see how it would be stored in a column-oriented database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tM6yft1AdDUn0MDP_PBlyA.png" /></figure><p>A table is stored one column at a time in order row by row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*N3FJaTH6mtCiSjtmBRfU9g.png" /></figure><h3>Writing to a Column-Oriented Databases</h3><p>If we want to add a new record, we have to navigate around the data to plug each column into where it should be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*U6QYFhfgya_t_a2SiXhRHQ.png" /></figure><p>If the data was stored on a single disk it would have the same extra memory problem as a row-oriented database, since it would need to bring everything into memory. However, column-oriented databases will have significant benefits when stored on separate disks.</p><p>If we placed the table above into the similarly restricted three columns of data disk they would be stored like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*BIwWWpFEqhHmQJz1KqTCXQ.png" /></figure><h3>Reading from a Column-Oriented Database</h3><p>To get the sum of the name the computer only needs to go to one disk where stores the name and sum all the values inside of it. No extra memory needs to be pulled in, and it accesses a minimal number of disks.</p><h3>Summary</h3><p>We can build better services by weighing the tradeoffs between response latency and data volume and understanding the difference between column-oriented and row-oriented databases. When clients rely on services for data and analytics to their company, choosing the right database can save a lot of headaches.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85c17d86f517" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Volumes can help you code smoothly]]></title>
            <link>https://justgiveacar.medium.com/docker-volumes-can-help-you-code-smoothly-39afa207af19?source=rss-bd4ace02d0ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/39afa207af19</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Justgiveacar]]></dc:creator>
            <pubDate>Sun, 22 Aug 2021 17:14:36 GMT</pubDate>
            <atom:updated>2021-08-22T17:14:36.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqoDWDyixbpZUpSnf9RIaw.png" /></figure><p>Hello there, today I want to introduce Docker Volume to you if you are recently using Docker and feeling very painful while synchronizing your local code inside the Docker container.</p><p>Maybe you have already heard that we can use volumes to maintain and persist state for the containers in production. But do you know that volumes can also be an excellent tool for speeding up your development workflow?</p><h3><strong>What is a Volume?</strong></h3><p><strong>Docker’s official documentation</strong>: Volumes are the preferred mechanism for persisting data generated by and used by Docker containers. While bind-mounts are dependent on the directory structure and OS of the host machine, volumes are completely managed by Docker.</p><p><strong>My unofficial documentation: </strong>Volumes are a special type of folder that is accessible by a Docker container. Unlike regular folders, volumes have a life cycle independent of the containers in which they’re mounted. Because they are stored outside of a container. As a result, volumes can persist data even when containers die to and share data between containers and the host.</p><p>In this article, we’re going to focus on a type of volume known as <strong>host volumes</strong>, which can be used to make it easier and faster to work with code inside of the container.</p><h3>Host Volumes</h3><p>Host volumes allow you to mount a folder on your own computer into a container. It synchronizes file changes between your local folder and a container’s folder. So if you use a host volume to mount code you are working on into a container, any edits you make to code on your local folder will automatically appear in the container.</p><p>Without this approach, every time you want to test your new code, you have to rebuild the container’s image. Conversely, if you mount your code as a host volume, you can configure that container to synchronize code changes as you make them.</p><p>Let&#39;s take a look at a Docker-compose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cffd765b86775508fabfdb9b2795c3b/href">https://medium.com/media/3cffd765b86775508fabfdb9b2795c3b/href</a></iframe><p>This file tells Docker to boot a container and the application. It also tells Docker to mount a host volume:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67d221405d194ad4b5d9b2df8755cc66/href">https://medium.com/media/67d221405d194ad4b5d9b2df8755cc66/href</a></iframe><p>As a result, Docker will mount the ./app directory on local machine, which contains your code, into the container at /usr/src/app/app.</p><p>Now what we need to do is ensure that the node process will restart whenever you’ve edited your code.</p><p>How to configure your container to sync your code automatically.</p><ol><li>Find the folder in your Docker container that has your code. The easiest way to figure out where your code is located in your container is to look at the COPY commands in your Dockerfile.</li></ol><pre>COPY . /user/src/app</pre><p>2. Find the path to the folder on your local machine that has the same code.</p><p>3. Add a host volume to your Docker-compose file. Find the container in your Docker-compose file that you want to sync with, and add a ‘volume’ instruction underneath that container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9abae4f920243618851636fc0c3121b8/href">https://medium.com/media/9abae4f920243618851636fc0c3121b8/href</a></iframe><p>4. Run Docker Compose</p><pre>docker-compose up</pre><p>Docker will overwrite the code that was built into the container with the code you’ve got running locally on your local machine.</p><p>And you’re all set. By modifying your project so it uses a host volume, any changes you make to the code on your local machine will now automatically appear in the container.</p><h3>Conclusion</h3><p>Docker volumes were originally designed to make it easier to work with local files. But as we’ve seen in this article, they’re also a great way to make development easier and faster. It may take you a little time to get comfortable using volumes as part of your development process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39afa207af19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot micro-services deployement on Kubernetes]]></title>
            <link>https://justgiveacar.medium.com/spring-boot-micro-services-deployement-on-kubernetes-76c1d298c1f?source=rss-bd4ace02d0ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c1d298c1f</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Justgiveacar]]></dc:creator>
            <pubDate>Wed, 21 Jul 2021 18:26:58 GMT</pubDate>
            <atom:updated>2021-07-21T18:29:49.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwUk9eJGncne7DU2PROS3g.jpeg" /></figure><p>Hello, I would like to guide you how to launch a local Kubernetes cluster (minikube), develop an app using the Spring Boot framework and deploy it as a container in Kubernetes.</p><p>The app can let you do so:</p><ul><li>Find customer’s information (GET)</li><li>Add customer’s information (POST)</li><li>Update customer’s information (PUT)</li><li>Remove customer’s information (DELETE)</li></ul><h3>Get started with the initialisation of Spring Boot</h3><p>You will build a simple web application with Spring Boot and add some useful services to it.</p><p>First we need to create a Spring Boot application, which can be done in a number of ways.</p><h4>Using the Initialiser Website</h4><ol><li>Visit <a href="https://start.spring.io/">https://start.spring.io</a> and choose the Java language and Maven project.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yKzoSm7G6mgWjMIEZH2Hw.png" /></figure><p>2. Enter the following coordinates:</p><ul><li><strong>Artifact</strong>: jpa_project</li><li><strong>Packaging</strong>: Jar</li><li><strong>Java</strong>: 8</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*FQMKkT6QH4aJRwgCR1_lEg.png" /></figure><p>3. Add the following dependencies:</p><ul><li><strong>Spring Web</strong>: Build web, including RESTful, applications using Spring MVC. Uses Apache Tomcat as the default embedded container.</li><li><strong>Spring Boot DevTools</strong>: Provides fast application restarts, LiveReload, and configurations for enhanced development experience.</li><li><strong>Spring Data JPA</strong>: Persist data in SQL stores with Java Persistence API using Spring Data and Hibernate.</li><li><strong>Lombok</strong>: Java annotation library which helps to reduce boilerplate code.</li><li><strong>MySQL Driver</strong>: MySQL JDBC and R2DBC driver.</li><li><strong>H2 Database</strong>: Provides a fast in-memory database that supports JDBC API and R2DBC access. Supports embedded and server modes as well as a browser based console application.</li></ul><p>4. Click “Generate project”</p><ul><li>The .zip file contains a standard project in the root directory, so you might want to create an empty directory before you unpack it.</li></ul><h4>Using IntelliJ IDEA</h4><p>Spring Initialiser is also integrated in IntelliJ IDEA and allows you to create and import a new project without having to leave the IDE for the command-line or the web UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSHfWZnZpnOiwuZiP-csGQ.png" /></figure><h3>Saving and retrieving data</h3><p>When the main page of you application loads, two things happen:</p><ul><li>It will tell you if it has connected to DB successfully</li><li>It will return all customer’s information registered in DB</li></ul><p>First, you should create a Customer class that holds the customer’s details.</p><pre><em>import </em>lombok.<em>AllArgsConstructor</em>;<br><em>import </em>lombok.<em>Data</em>;<br><em>import </em>lombok.<em>NoArgsConstructor</em>;<br><em>import </em>lombok.<em>ToString</em>;</pre><pre><em>@Entity<br>@Table</em>(name = &quot;CUSTOME&quot;)<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@ToString<br><em>public class </em>Customer {<br>    @Id <br>    @GeneratedValue(strategy = GenerationType.IDENTITY) <br>    @Column(name = &quot;ID&quot;)<br>    <em>private </em>Long id;</pre><pre>    @Column(name = &quot;NAME&quot;, length = 25)<br>    <em>private </em>String name;</pre><pre>    @Column(name = &quot;BIRTH&quot;)<br>    @Temporal(TemporalType.DATE)<br>    <em>private </em>Date birthDate;</pre><pre>    @Column(name = &quot;SALARY&quot;)<br>    <em>private int </em>salary;<br>}</pre><ul><li>@Data is a notation which will add the getter(), setter(), hashCode(), and also equals() automatically.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*peQ72VdpNbqAQllk0CZjeg.png" /></figure><ul><li>@NoArgsConstructor will insert a default constructor without any arguments.</li></ul><pre>public Customer(){}</pre><ul><li>Conversely, @AllArgsConstructor will add a default constructor with all arguments from class.</li></ul><pre>public Customer(Long id, String name, Date birthDay, int salary){</pre><pre>this.id = id;<br>  this.name = name;<br>  this.birthDay = birthDay;<br>  this.salary = salary;</pre><pre>}</pre><ul><li>@id defines that this filed will be chosen as the primary key.</li><li>@Column(name = “ID”) defines the name of column which will register this field’s data.</li></ul><p>Beside our Customer class, we also need to generate an <strong>Repository</strong> interface in order to store the Customer data.</p><pre><em>public interface </em>CustomerRepository <em>extends </em>JpaRepository&lt;Customer, Long&gt; {}</pre><p>Please pay attention to how the Customer are persisted in the database:</p><ul><li>The type of the Customer is Customer</li><li>The id of the Customer is of type Long</li></ul><p>You should notice the two types in the interface signature</p><pre>JpaRepository&lt;Customer, Long&gt;</pre><p>Spring Boot can help us to access the repository by auto-wiring it using @Autowired. Which means it will generate its class that implements the interface and then return an instance.</p><p>Next, you should create a new class with the @Controller annotation to select the RESTful method(GET, POST, PUT, DELETE) in your application to deal with different URL demands.</p><pre><em>@RestController<br>public class </em>CustomerController {</pre><pre>    <em>@Autowired<br>    private </em>CustomerRepository customerRepository;</pre><pre>    <em>@GetMapping</em>(&quot;/customers&quot;)<br>    <em>public </em>List&lt;Customer&gt; customers(){<br>        <em>return </em>customerRepository.findAll();<br>    }</pre><pre>    <em>@PostMapping</em>(&quot;/&quot;)<br>    <em>public </em>Customer saveCustomer(<em>final @RequestBody </em>Customer customer){<br>        <em>return </em>customerRepository.save(customer);<br>    }</pre><pre>    <em>@DeleteMapping</em>(&quot;/customers&quot;)<br>    <em>public void </em>deleteCustomer(<em>@PathVariable </em>Long id){<br>        customerRepository.deleteById(id);<br>    }</pre><pre>}</pre><p>When a user access the /customers route, they should see all customers.</p><p>Your application is functional now although not yet complete. And we can already run this application at this stage. But to do so, we still need to run a MySQL as well.</p><p>In order to test your application and to see how it works properly. I suggest you can directly use a temporary in-memory SQL database no more than one line of claim in application.propertities.</p><pre><em>spring.datasource.url=jdbc:h2:mem:DB_CUSTOMER</em></pre><p>Where <em>DB_CUSTOMER </em>is your SQL Table name. And after running your application you can directly access its UI by visiting URL <a href="http://localhost/h2-console">http://localhost/h2-console</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*rjbWPympMDjwNR9BcVBy6Q.png" /><figcaption>H2 Consol UI</figcaption></figure><p>Don’t forget to modify JDBC URL with your own Table name. By default User Name is ‘sa’ and Password is blank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*_9ucQo92G-dEsvsgPCnAOQ.png" /></figure><p>You can get Customer DB Table above if you login in with correct authentication.</p><p>But it’s necessary to connect to the real MySQL server. We have two solutions in order to authenticate.</p><ul><li>Declare all arguments in the file application.properties</li></ul><pre><em>spring.datasource.url=jdbc:mysql://localhost:3702/DB_CUSTOMER<br>spring.datasource.username=root<br>spring.datasource.password=password</em></pre><ul><li>Add env variables manually or declare env into yaml files. Where Spring Boot will detect automatically those env variables and consider as one part of <strong>application.propertites</strong>.</li></ul><pre><em>Use &quot;</em><strong><em>SPRING_DATASOURCE_URL</em></strong><em>&quot;<br>equals to &quot;spring.datasource.url&quot;</em></pre><pre><em>-------------------------------------------------------------------<br>Use &quot;</em><strong><em>SPRING_DATASOURCE_USERNAME</em></strong><em>&quot; <br>equals to &quot;spring.datasource.username&quot;</em></pre><pre><em>-------------------------------------------------------------------<br>Use &quot;</em><strong><em>SPRING_DATASOURCE_PASSWORD&quot; <br></em></strong><em>equals to &quot;spring.datasource.password&quot;</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lnb2S9SBB8lftLafCVSDfw.png" /><figcaption>StackOverFlow solution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*8Ax7l9ZPOn4CWf3I56iNdg.png" /><figcaption>springboot.yaml</figcaption></figure><p>Now you’re now ready to build Docker image.</p><ul><li>Docker image can be built from Dockerfile</li></ul><pre>FROM openjdk:11<br>WORKDIR /opt<br>ENV PORT 8082<br>EXPOSE 8082<br>COPY target/*.jar /opt/app.jar<br>ENTRYPOINT exec java $JAVA_OPTS -jar app.jar</pre><ul><li>Docker image can also be built from a Maven plug-in <strong>Fabric8</strong>. And add it into pom.xml.</li></ul><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;io.fabric8&lt;/groupId&gt;<br>    &lt;artifactId&gt;docker-maven-plugin&lt;/artifactId&gt;<br>    &lt;extensions&gt;true&lt;/extensions&gt;<br>    &lt;configuration&gt;<br>        &lt;images&gt;<br>            &lt;image&gt;<br>                &lt;name&gt;jpa_project&lt;/name&gt;<br>            &lt;/image&gt;<br>        &lt;/images&gt;<br>    &lt;/configuration&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;<br>                    build<br>                &lt;/goal&gt;<br>            &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>Use <strong>./mvnw clean install</strong> to generate your docker image from your local environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3zu6zWVk0JZeNYTrZHoZg.png" /></figure><p>You can run the container with 8080 port exposed where you’are allowed to access <a href="http://localhost:8080/">http://localhost:8080</a> in your navigator.</p><pre>docker run -p 8080:8080 jpa_project</pre><h4>Upload the container image to a container registry</h4><p>Maybe you’re familiar with how docker pull images from internet. You can also create your own DockerHub with your own images and push them to internet.</p><p>To used Docker Hub, you first have to create a Docker ID.</p><p>A Docker ID is your Docker Hub username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*mQu8LfElQ0AXJv-B3_9Q2Q.png" /></figure><p>Before uploading your image, please take the notes that there is one last thing to do. Images uploaded to Docker Hub must have a name of form username/image:tag :</p><ul><li>username is your Docker ID</li><li>image is the name of the image (Where you can find out from your local machine using Commend Line: <strong>docker image ls</strong>)</li><li>tag is an <strong>optional </strong>additional attribute which is used to indicate the version of current image (<strong>image_name:1.0.0</strong> where 1.0.0 is the tag or version of image).</li></ul><p>Let’s upload our image:</p><ul><li>To rename your image according to this format.</li></ul><pre>docker tag &lt;image_name&gt; &lt;username&gt;/&lt;image_name&gt;:&lt;version&gt;</pre><ul><li>To upload your image to Docker Hub:</li></ul><pre>docker push &lt;username&gt;/&lt;image_name&gt;:&lt;version&gt;</pre><p>Your image is now publicly available &lt;username&gt;/&lt;image_name&gt;:&lt;version&gt; on your Docker Hub and everybody can download and run it if you make it as “<strong>public image</strong>” instead of “<strong>private image</strong>”.</p><p>Because MySQL docker image has already been uploaded and presented on Docker Hub as an official version. So we don’t need to upload any MySQL image on our own Docker Hub.</p><h4>To deploy your application from Kubernetes</h4><p>Container orchestrators are designed to run complex applications with large numbers of scalable components.</p><p>They work by inspecting the underlying infrastructure and determining the best server to run each containers.</p><p>They can scale to thousands of computers and tens of thousands of containers and still word efficiently and reliably.</p><p>As a micro-service, it is possible for your servers to encounter a sudden enormous requests from Internet. That’s why the load balancer is becoming more and more indispensable.</p><p>So in this chapter, I will teach you how to create a replicated pods for your Spring Boot Service, bound with a external load balancer and connect to MySQL pod as well.</p><p>You will use minikube to deploy the cluster of your application from your local machine.</p><blockquote>Minikube creates a single-node Kubernetes cluster running in a virtual machine. And it is only intended for testing purposes, not for production.</blockquote><p>Before you install minikube, you have to install kubectl.</p><blockquote>kubectl is the primary Kubernetes CLI — you use it for all interactions with a Kubernetes cluster, no matter how the cluster was created.</blockquote><h4>Defining a Deployment</h4><p>First of all, create a folder named k8s in your application directory:</p><pre>mkdir k8s</pre><p>The purpose of this folder is to hold all the Kubernetes YAML files that you will create.</p><p>A Deployment creates and runs containers and keeps them alive.</p><p>Here is the definition of Deployment for your Spring Boot Application.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: springboot<br>  namespace: springboot-project<br>  labels:<br>    app: springboot<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: springboot<br>  template:<br>    metadata:<br>      labels:<br>        app: springboot<br>    spec:<br>      containers:<br>        - name: springboot<br>          image: byckles/jpa_project:2.0.0<br>          imagePullPolicy: IfNotPresent<br>          ports:<br>            - containerPort: 8082<br>          env:<br>            - name: SPRING_DATASOURCE_URL<br>              valueFrom:<br>                configMapKeyRef:<br>                  name: mysql-configmap<br>                  key: database_url<br>            - name: SPRING_DATASOURCE_USERNAME<br>              valueFrom:<br>                secretKeyRef:<br>                  key: mysql-user-username<br>                  name: mysql-secret<br>            - name: SPRING_DATASOURCE_PASSWORD<br>              valueFrom:<br>                secretKeyRef:<br>                  key: mysql-user-password<br>                  name: mysql-secret</pre><p>That looks complicated, but we will break it down and explain it in detail.</p><ul><li><strong>apiVersion </strong>: The version of this resource type.</li><li><strong>Kind</strong>:The type of resource.</li><li><strong>metadata.name</strong>: The name of this specific resource.</li><li><strong>spec.replicas</strong> : The number of replicas (copies) of your container.</li><li><strong>template.metadata.labels</strong> : The label for the pods that wrap your Spring Boot container.</li><li><strong>selector.matchLabels : </strong>To select those pods with a specific label to belong to this Deployment resource.</li></ul><h4>Defining a Service</h4><p>A Service resource makes Pods accessible to other Pods or users outside the cluster.</p><p>Without a Service, a Pod cannot be accessed at all.</p><p>A service forwards requests to a set of Pods.</p><p>In this regard, a Service works similarly as a load balancer we talk from outside frequently.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FWRRjPprxfXM6TmIPXb%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FWRRjPprxfXM6TmIPXb%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FWRRjPprxfXM6TmIPXb%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb62590b93e2cf41708f64bc1ab7e7a/href">https://medium.com/media/5eb62590b93e2cf41708f64bc1ab7e7a/href</a></iframe><p>Here is the definition of a Service that makes your application Pod accessible from outside the cluster.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: springboot-service<br>  namespace: springboot-project<br>spec:<br>  selector:<br>    app: springboot<br>  type: LoadBalancer<br>  ports:<br>    - protocol: TCP<br>      port: 8082<br>      targetPort: 8082<br>      nodePort: 30001</pre><p>Service will look for all nodes with same value declared in spec.selector. In our case, it tries to match all Pods have a label of <strong>app: springboot </strong>and establish a bridge between them and outside the cluster.</p><p>The next important part is the port. In this case, the Service listens for requests on port 8082 and forwards them to port 8082 of the target Pods. And port 30001 is exposed to outside the cluster where we can directly access to it using this port number.</p><h4>Defining the database</h4><p>In principle, a MySQL Pod can be deployed similarly as your app — that is, by defining a Deployment ands Service resource.</p><p>However, deploying MySQL need some additional configuration if you want to persist your data.</p><p><strong>MySQL needs a persistent storage.</strong></p><p>This storage myst not be affected by whatever happens to the MySQL Pod. Which means if the MySQL Pod is deleted accidentally, the storage should still persist and if the MySQL Pod is moved to another node, the storage must persist.</p><p>Consequently, the description of your database components should consist of four resource definitions:</p><ul><li>Deployment</li><li>Service</li><li>PersistentVolumeClaim</li><li>PersistentVolume</li></ul><p>Here is the definition of Deployment and Service of MySQL.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: mysql-service<br>  namespace: springboot-project<br>spec:<br>  ports:<br>    - port: 3306<br>  selector:<br>    app: mysql<br>  clusterIP: None<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: mysql<br>  namespace: springboot-project<br>spec:<br>  selector:<br>    matchLabels:<br>      app: mysql<br>  strategy:<br>    type: Recreate<br>  template:<br>    metadata:<br>      labels:<br>        app: mysql<br>    spec:<br>      containers:<br>        - image: mysql:5.6<br>          name: mysql<br>          env:<br>            - name: MYSQL_DATABASE<br>              value: db_customers<br>            - name: MYSQL_USER<br>              valueFrom:<br>                secretKeyRef:<br>                  key: mysql-user-username<br>                  name: mysql-secret<br>            - name: MYSQL_PASSWORD<br>              valueFrom:<br>                secretKeyRef:<br>                  key: mysql-user-password<br>                  name: mysql-secret<br>            - name: MYSQL_ROOT_PASSWORD<br>              valueFrom:<br>                secretKeyRef:<br>                  key: mysql-user-password<br>                  name: mysql-secret<br>          ports:<br>            - containerPort: 3306<br>              name: mysql<br>          volumeMounts:<br>            - name: mysql-persistent-storage<br>              mountPath: /var/lib/mysql<br>      volumes:<br>        - name: mysql-persistent-storage<br>          persistentVolumeClaim:<br>            claimName: mysql-pv-claim</pre><p>Volume field defines a storage volume, which references the <strong>PersistentVolumeClaim</strong>.</p><p>The VolumeMount field mounts the referenced volume at the specified path in the container, which in this case is /var/lib/mysql. And data will be stored in /var/lib/mysql which is referenced by /mnt/data which comes from node’s filesystem.</p><p>The definition of PersistentVolume and PersistentVolumeClaim of MySQL.</p><pre>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: mysql-pv-volume<br>  namespace: springboot-project<br>  labels:<br>    type: local<br>spec:<br>  storageClassName: manual<br>  capacity:<br>    storage: 20Gi<br>  accessModes:<br>    - ReadWriteOnce<br>  hostPath:<br>    path: &quot;/mnt/data&quot;<br>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: mysql-pv-claim<br>  namespace: springboot-project<br>spec:<br>  storageClassName: manual<br>  accessModes:<br>    - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: 20Gi</pre><p><strong>PersistentVolumeClaim </strong>:<strong> </strong>It requests a persistent storage of 20GB (You can modify to different size according to your needs).</p><p><strong>Service </strong>: The Service is similar to the Service that we defined for the application component. By default, its <strong>type</strong> is ClusterIP and can be accessed inside of the cluster which can avoid data being modified by outside the cluster without passing by our application/</p><p><strong>There’s one more important thing to node</strong></p><p>You need to declare all necessary env variables inside of your Pods. Otherwise, Spring Boot cannot connect to MySQL and itself cannot either run properly. So declare them in your YAML file.</p><ul><li><strong>MYSQL_DATABASE</strong>: It will specify the name of a database to be created on image startup.</li><li><strong>MYSQL_USER</strong>: User name of custom account which has already be granted superuser permissions.</li><li><strong>MYSQL_PASSWORD</strong>: User password of custom account which has already be granted superuser permissions.</li><li><strong>MYSQL_ROOT_PASSWORD</strong>: The default password of Root account.</li></ul><pre>env:<br>  - name: MYSQL_DATABASE<br>    value: xxx<br>  - name: MYSQL_USER<br>    value: xxx<br>  - name: MYSQL_PASSWORD<br>    value: xxx<br>  - name: MYSQL_ROOT_PASSWORD<br>    value: xxx</pre><h3>Deploying the application</h3><p>So far, you created all YAML files with resources definitions.</p><p>Let’s submit your resource definitions to Kubernetes.</p><p>First of all, make sure that you keep all YAML files from your local machine. Also, make sure that minikube cluster is running.</p><pre>minikube run</pre><p>Then submit your resource definitions to Kubernetes with the following command.</p><pre>kubectl apply -f any_file.yaml</pre><p>As soon as Kubernetes receives your resources, it creates the Pods.</p><pre>kubectl get pods --watch</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTCztkZDKkULKSj2SI36Rg.png" /></figure><p>When you try to find the external IP address, but our application Service is still pending without any results after few minutes.</p><pre>kubectl get services</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHLWcQp-NieR-JoF2DNARg.png" /></figure><p>Because minikube doesn’t support LoadBalancer services, so the service will never get an external IP. But you can access the service anyway with its external port. You can get the IP and Port by running.</p><pre>minikube service &lt;service_name&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r03OpXEUrjDUtNnqxCnWBw.png" /></figure><p>So now, we are allowed to everything we can. For example, we can add new data, get all data and remove data from DB, etc.</p><p>Here I use Postman to connect to service’s URL.</p><ul><li>Add our first customer into our MySQL</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cD5gKTc2N2EQ_6xHk8P9KQ.png" /></figure><ul><li>Get all customers from our MySQL</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Id5jAbG-ecdHwgcg_LOPmg.png" /></figure><p>As MySQL has been attached with a <strong>PersistentVolume</strong>, so we can assume that data will persist even MySQL Pods are removed anyway. Let’s check it out.</p><p>First of all, I remove our MySQL Pods from my local machine. And another MySQL Pod is created automatically but with different ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXO-WVBPRoglAEyuraRR7Q.png" /></figure><p>When I try to GET our data one more time just after removing the previous MySQL Pod where another Pod is generated and replace it. Our data is still persist and returned correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9CUGurg2O1_A84LSxUF5Q.png" /></figure><p>So far, you’ve learnt how to:</p><ul><li>Develop a Customer taking application that stores in MySQL</li><li>Packaged it as a Docker container</li><li>Deployed it in a local Kubernetes cluster</li></ul><p>All files have already pushed to my Github. 😜</p><p><a href="https://github.com/linzhou-zhong/springboot_jpa">https://github.com/linzhou-zhong/springboot_jpa</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c1d298c1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Classes in Python ]]></title>
            <link>https://justgiveacar.medium.com/data-classes-in-python-991a3f68ddf9?source=rss-bd4ace02d0ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/991a3f68ddf9</guid>
            <category><![CDATA[data-class]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Justgiveacar]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 15:29:25 GMT</pubDate>
            <atom:updated>2021-07-16T15:29:25.108Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Classes in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyxfatC2xvd73XwGybFpbg.jpeg" /></figure><p>Data classes in python allow you to write shorter code and initialize print compare and audio data much more easily. Let’s take a look !</p><p>First of all, classes are a combination of two things: Behaviour in the form of methods and data in the form of class attributes. Their blueprint for objects, they form the basis of object-oriented programming and developers use them in a million different ways. Some classes are mostly containers of behaviours, for example a class that allows you to draw all kinds of shapes on the screen or a class that provides password hashing functionality. Other classes act more as containers of data. Think of class for representing a vehicle in a vehicle registration system. A class that behaves more like a data container is often used differently, you may need to create many instances and you want to order them, compare them easily inspect the data that’s in them.</p><p>Since version 3.7 python has provided a data classes module. ow are data classes are different from regular classes ?</p><ul><li>First, data class have a built-in initialise to help you quickly fill an object with data.</li><li>Second, there’re the easiest ways to print, compare and order data and you can also create data that’s read-only.</li></ul><p>Let’s dive deeper with me 🤿</p><h4><strong>Regular Classes</strong></h4><p>Starting with this very simple class Dog that has a name, a breed and an age.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e0676002fc848cf55efe92ab07a5460/href">https://medium.com/media/3e0676002fc848cf55efe92ab07a5460/href</a></iframe><p>Dog has nothing more at the moment than an initialiser that allows us to create a Dog with those three values. Here I’m creating two Dogs: <strong>Rudy </strong>is an Australian Terrier dog<strong> </strong>and <strong>Teddy</strong> is a Bichon Frise dog.</p><pre>print(poppy_one == poppy_two)<br># False</pre><p>If you try to compare these two objects, the result is absolutely False because they are different objects. That’s when you’re dealing with regular classes, when you’re dealing with data, you prefer we could have different behaviour in order to achieve a deeper comparisons like detecting the difference between their attributes instead of their references.</p><p>So let’s turn Dog into a Data Classe and see what happends.</p><h4><strong>Data Classes</strong></h4><p>I’m going to import the data class decorator and add it to our Dog class. So far our Dog class is already a data class so we no long need the initialisation method where the Data Class does this job for us. But it is important that you need provide the type-ins of each attributes so Data Class knows what type of data it’s dealing with.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23bfbed37600b8ec6e0b6925ff856015/href">https://medium.com/media/23bfbed37600b8ec6e0b6925ff856015/href</a></iframe><p>I’ve added our third poppy 🐶 with exactly the same attributes value of poppy_two. If I try to compare once again between poppy_two and poppy_three and what will happen ?</p><pre>print(poppy_two == poppy_three)<br># True</pre><p>The answer is T<strong>rue </strong>instead of <strong>False, </strong>because they contain the same data they’ll no long compare the references with.</p><p>Another thing we often want to do with data is comparing data.</p><pre>print(poppy_two &gt; poppy_three)<br># Error</pre><p>Unfortunately, at the moment we cannot compare these objects with because we didn’t define what that means. Here some steps to make our Data Classes can be compared with other objects.</p><ul><li>To set the order flag to True in Data Classes</li><li>To add a sort_index attribute</li><li>To initialise sort_index attribute using __post_init__</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78cc553a1c7cbd47388c164105d6388e/href">https://medium.com/media/78cc553a1c7cbd47388c164105d6388e/href</a></iframe><pre>print(poppy_one &gt; poppy_two)<br># True</pre><p>Now poppy Rudy is larger than poppy Teddy according to their ages.</p><h4><strong>Read-only</strong></h4><p>Alright, let’s jump to another nice thing that you can also do with data classes is that you can freeze them which means creating objects that are read-only.</p><p>Only one thing we need to do is to add frozen and set it to be True.</p><pre>@dataclass(order=True, <strong>frozen</strong>=<strong>True</strong>)<br>class Dog:<br>   XXX</pre><p>Here we have one potential problem is that as Data Class is already frozen, we’re not allowed to assigned the filed <strong>sort_index</strong> again. There’s a trick that instead of assigning this directly, we’re calling the set attribute method.</p><pre>def __post_init__(self):<br>    object.__setattr__(self, &#39;sort_index&#39;, self.age)</pre><p>And now our comparison can work eventualy.</p><p>Data has become the core of every software application and the amount of data we’re consuming is mind-blowing.</p><p>Be ready for our new generation !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=991a3f68ddf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use equals() and hashCode() in Java]]></title>
            <link>https://justgiveacar.medium.com/how-to-use-equals-and-hashcode-in-java-e10b8fd1aba5?source=rss-bd4ace02d0ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/e10b8fd1aba5</guid>
            <category><![CDATA[equals]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hashcode]]></category>
            <dc:creator><![CDATA[Justgiveacar]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 21:52:26 GMT</pubDate>
            <atom:updated>2021-07-06T21:52:26.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*owEhezwMa2sEbjHD" /></figure><p>Hi there !</p><p>Today I’m going to talk about one of questions that are important but easily ignore by us : equals() and hashCode() methods in Java.</p><p>I found both these methods extremely important in the development process, so if the person knows nothing about them, it can cause a lot of the issues in the application like missing data inside the hashed data structures, wrong equality process results, etc.</p><p>So, come with me and let’s move on to discover these 2 methods.</p><p>As you might know, there is a class Object, that is a parent of each other class in Java, which means that if we create a new class Humanity in such a way :</p><pre>public class Humain { </pre><pre>// TODO</pre><pre>}</pre><p>It will implicitly extend the Object class. That&#39;s why, even if it seems that our Humanity class is empty, it has several methods available inherited from the Object class:</p><ul><li>equals()</li><li>hashCode()</li><li>toString()</li><li>getClass()</li><li>notify()</li><li>notifyAll()</li><li>wait()</li></ul><p>As rest of the methods are out of the scope of the current article 😅, let’s focus on equals() and hashCode() ones.</p><h3>equals()</h3><p>So equals(Object o) method is used to indicate whether some other Object o is equal to the current object (on which the method has been invoked).</p><p>The explanation looks very clear, but one question could appear: “Wait, why do we need this method, we have == operation will be enough right ?&quot;</p><p>Well, thanks for this common question, but I have to say == operator works perfectly for the primitive data types like int, long, boolean, etc. But for the non-primitive (or reference) data type (like Humanity, Animal, or even Alien) == operator shows not the equality of the objects, but whether they refer to the same object in memory. It works in such a way due to Java Memory Model (JMM) : primitives and reference objects are kept in different memory parts.</p><p>Let me demonstrate this in code.</p><pre>public class Humanity {<br>    private String name;</pre><pre>    public Humanity(String name){<br>        this.name = name;<br>    }<br>}</pre><pre>class Main {<br>    public static void main(String[] args) {<br>        Humanity h1 = new Humanity(&quot;Linzhou&quot;);<br>        Humanity h2 = new Humanity(&quot;Simpson&quot;);</pre><pre>        System.out.println(h1 == h2);<br>    }<br>}</pre><p>We’ll have the following output:</p><pre>false</pre><p>But what would it be, if use equals() method to compare these 2 Humanity instances instead of == operator ?</p><pre>class Main {<br>    public static void main (String[] args) {<br>        Humanity h1 = new Humanity(&quot;Linzhou&quot;);<br>        Humanity h2 = new Humanity(&quot;Simpson&quot;);</pre><pre>        System.out.println(h1.equals(h2));<br>    }<br>}</pre><p>Would it return true? Nope, the output is false again. How come ? The answer is simple: right now we are using the Object class implementation of equals() method,so let&#39;s take a look how it looks like:</p><pre>public boolean equals(Object o) {<br>    return (this == o);<br>}</pre><p>As we see, it calls the == operator under the hood, so the false output looks more clear more.</p><p>Of course, this implementation doesn’t satisfy our needs, so we can override it.</p><p>But first let’s postpone the overriding process a little bit to learn several equals() method rules, that are going to help us in our implementation:</p><ol><li>Reflexive: a.equals(a) must always return true (of course, if a != null, otherwise NullPointerException will be thrown);</li><li>Symmetric: if a.equals(b) return true, then b.equals(a) must always return true as well.</li><li>Transitive: if a.equals(b) returns true and a.equals(c) returns true, it means, that b.equals(c) must be true as well.</li><li>Consistent: if a.equals(b) return true (or false) and neither a nor b has been changed, a.equals(b) should always return the same result.</li></ol><p>The rules are simple and intuitive, but anyway it is extremely important to follow them to omit the possbile issues in the apllication.</p><p>Let’s get back to our Humanity comparison problem:<br>I propose not to hurry up, but take a look at the method signature to think, how to override it correctly. As you might have noticed, equals() method accepts Object o as a parameter, so it will be impossible to write something like this:</p><pre>@Override<br>public boolean equals(Object o){<br>    return this.name.equals(o.name);<br>}</pre><p>as Object class knows notoriously nothing about name property - compiler error. Also, this code could throw NullPointerException if name == null or o == null. And, yes, we could write something like this:</p><pre>public boolean equals(Humanity h){<br>    return name.equals(h.name);<br>}</pre><p>But it will not the overriding, but the overloading.<br>There are a lot of libraries and APIs, that use equals() method under the hood, so as you might have understood, they know nothing about our overloading version of the equals() method, but will call that one from the Object class and our comparison issue will appear again. It means that the overloading is not an appropriate solution for our case.</p><p>As we have seen before, the Object class equals() implementation uses == operator to compare the objects. If two objects point to the same object in memory, they are definitely equal. It&#39;s a good point to start our overriding.</p><ol><li>Compare objects using == operator.</li></ol><pre>@Override<br>public boolean equals(Object o){<br>    return this == o;<br>}</pre><p>We have mentioned above, that we could face the NullPointerException if Object o is equal to null. Alse, we do know, that our current object (Humanity instance, on which we are going to call equals() method) is not null for sure, as otherwise the NullPointerException will be thrown on method call on null Humanity instance, but it is not our business right now. It goes with another step:</p><ol><li>Check, whether the Object o parameter is not null. If yes, return false.</li></ol><pre>@Override<br>public boolean equals(Object o){<br>    if (this == o)<br>        return true;<br>    if (o == null)<br>        return false;<br>    return true;<br>}</pre><p>Looks better, but not enough. As we have mentioned before, there is one more difficulty left: o is Object type, so it&#39;s impossible to reach Humanity data from it. Of course, we could cast it to Humanity and it seems that we are good to go. But, unfortunately, it is not safe. Just take a look at the code:</p><pre>@Override<br>public boolean equals(Object o){<br>    if (this == o)<br>        return true;<br>    if (o == null)<br>        return false;<br>   Humanity h = (Humanity) o;<br>    return this.name.equals(h.name);<br>}</pre><p>Let me introduce the new class Dog:</p><pre>public class Dog{<br>    private String name;</pre><pre>    public Dog(String name)<br>        this.name = name;<br>}</pre><p>Take a look how to break our equals() implementation:</p><pre>class Main{<br>    public static void main (String[] args){<br>        Humanity h = new Humanity(&quot;Linzhou&quot;);<br>        Dog dog = new Dog(&quot;poppy&quot;);</pre><pre>        System.out.println(h.equals(dog));<br>    }<br>}</pre><p>Unfortunately there is no compile error, as even dog is Dog type, but it is an Object type as well(Object is a parent of each class), so it is allowed to pass the dog inside our method. But if we run this code, we&#39;ll have an exception:</p><p>Exception in thread &quot;main&quot; java.lang.ClassCastException: Dog cannot be cast to Humanity</p><p>How can we cast a dog to a humanity, which makes no sense right ?</p><ol><li>Check, whether the Object o parameter has the same type, as our instance. If no, return false.</li></ol><pre>@Override<br>public boolean equals(Object o){<br>    if (this == o)<br>        return true;<br>    if (o == null)<br>        return false;<br>    if (this.getClass() != o.getClass())<br>        return false;</pre><pre>    return true;<br>}</pre><p>Here we have used getClass() method, that comes from the Object class. This method just returns the Class of the object, that calls it. So for dog.getClass(); it returns Dog, for h.getClass() which returns Humanity and so on.</p><ol><li>Cast the Object to the current class</li><li>Compare the chosen fields values.</li></ol><pre>@Override<br>public boolean equals(Object o){<br>    if (this == o)<br>        return true;<br>    if (o == null)<br>        return false;<br>    if (this.getClass() != o.getClass())<br>        return false;<br>    Humanity h = (Humanity) o;<br>    return Objects.equals(this.name, h.name);<br>}</pre><p>We have used Objects.equals() method here to simplify the logic and omit this.name null checking, as it has been already implemented inside the used method of Objects class:</p><pre>public static boolean equals(Object a, object b){<br>    return (a == b) || (a != null &amp;&amp; a.equals(b));<br>}</pre><p>Let’s try to check, whether it works correctly:</p><pre>class Main {<br>    public static void main(String[] args){<br>        Humanity h1 = new Humanity(&quot;Linzhou&quot;);<br>        Humanity h2 = new Humanity(&quot;Linzhou&quot;);<br>        Dog dog = new Dog(&quot;poppy&quot;);</pre><pre>        System.out.println(h1.equals(h2));<br>        System.out.println(h1.equals(dog));<br>    }<br>}</pre><p>The output is finally predictable:<br>true and false.</p><p>For now, that’s for the equals() method, but we&#39;ll return to it a little bit later. Let&#39;s move on to hashCode().</p><h3>hashCode()</h3><p>hashCode() method returns a hash code value of the object. Hash code, for now, is some int value. And that&#39;s it.</p><p>Let’s try to see how it works to make it more clear. I propose to use our well-known Humanity class for this:</p><pre>class Main {<br>    public static void main(String[] args){<br>        Humanity h = new Humanity(&quot;Linzhou&quot;);<br>        int hashCode = h.hashCode();<br>        System.out.println(hashCode);<br>    }<br>}</pre><p>The output will be different from several computers. But how could is it possibile ?<br>To answer this question, we need to remember that we have not override the hashCode() method yet, so we are using the Object implementation now. If we go to the Object class, we&#39;ll see the following:</p><pre>public native int hashCode();</pre><p>First, native in Java is used with methods to indicate, that the method is implemented in other languages (for example, C or C ++). It is possible to call such methods using JNI. Such methods are used for the performance reasons or to access system or hardware resources, that is not possible to proceed using Java.</p><p>Bref, let’s make this method behave predictably by overriding it:</p><pre>@Override<br>public int hashCode() {<br>    return 50;<br>}<br>Class Main {<br>    public static void main(String[] args){<br>        Humanity h = new Humanity(&quot;Linzhou&quot;);<br>        int hashCode = h.hashCode();<br>        System.out.println(hashCode);<br>    }<br>}</pre><p>As we might expect, the output is 50.</p><p>Let me present several hashCode() method rules and I hope we can understand why we need equals() combined with hashCode().</p><ol><li>Each invocation of hashCode() method on the same object that hasn&#39;t been changed must produce the same result each time.</li><li>If two objects are equal through the equals() method, then invoking the hashCode() method on each of these two objects must produce the same result:</li></ol><pre>// if : <br>a.equals(b) is true<br>//then :<br>a.hashCode() == b.hashCode()</pre><ol><li>but if invoking the hashCode() method on two objects produces the same result, it doesn&#39;t mean that both of them are equal (through equals() method). Because, the int type has a limited scope of the values from -2147483648 to 2147483647, which means if we have a number of objects over than its limited scope and it will create a pair of hashCode with same values of two objects even if both of them are completely not the same type.</li></ol><p>So as we have noticed, the 2nd and 3rd rules show that equals() and hashCode() are connected.</p><p>Let’s go deeper, hashed collections can provide fast access to elements (Time complexity O(1)). The most popular Java Hashed collections is HashMap. It is used to keep &#39;key - value&#39; pairs.</p><pre>Map&lt;Integer, String&gt; map = new HashMap&lt;&gt;();<br>map.put(1, &quot;Hello&quot;);<br>map.put(2, &quot;Bonjour&quot;);<br>map.put(3, &quot;Hola&quot;);</pre><p>If we need to get the third pair:</p><pre>String str = map.get(3);<br>System.out.println(str);</pre><p>The output is Hola.</p><p>When put(Key k, Value v) method is called, the following steps are performed under the hood:</p><ol><li>If key is null, the key-value pair (Entry) is put into the first bucket.</li><li>If not null, the hashCode() method is called on the key.</li><li>HashMap takes the key hash value, processes it through the internal computations to get the number of the bucket to be used.</li><li>If the chosen bucket is empty, the Entry is out there.</li><li>If the bucket is not empty, it iterates through all the existing entries inside the bucket and pares their keys with key from the put() method using equals().</li><li>if equals() returns false for each iteration, the Entry will be stored in the current bucket.</li><li>if equals() returns true for some case, so the Entry has the same key as from the put() method, this Entry value will be replaced by the new value.</li></ol><p>When get(Key k) method is called:</p><ol><li>If key is null, we go to the first bucket and look for the Entry with the key == null, if exists, its value is returned.</li><li>If key is not null, the hashCode() method is called on the key.</li><li>hashMap takes the key hash value, processes it through the internal computations get get the number of the bucket to be used.</li><li>If the bucket is empty, return null.</li><li>if Bucket contains several elements, we iterate through each of them and compare equals() the key of each Entry with our key. If true return matching Entry value, else return null.</li></ol><p>So, we have just seen that the equals() and hashCode() methods work together inside the HashMap to get and put the data: hashCode() is used to compute the bucket number and equals() is used to find the Entry with the same key.</p><p>Now we know more than enough to implement the hashCode() and equals() methods.</p><pre>@Override<br>public int hashCode(){<br>    return Objects.hash(idNumber);<br>}</pre><p>And the final version :</p><pre>public class Humanity {<br>    private long idNumber;<br>    private String name;</pre><pre>    public Humanity(long idNumber, String name){<br>        this.idNumber = idNmber;<br>        this.name = name;<br>    }</pre><pre>    @Override<br>    public boolean equals(Object o){<br>        if (this == o)<br>            return true;<br>        if (o == null)<br>            return false;<br>        if (this.getClass() != o.getClass())<br>            return false;<br>        Humanity h = (Humanity) o;<br>        return this.idNumber == h.idNumber;<br>    }</pre><pre>    @Override<br>    public int hashCode() {<br>        return Objects.hash(idNumber);<br>    }<br>}</pre><p>Thanks for reading my article. If you like it, please give me a small 👏. Appreciate ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e10b8fd1aba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Checked and Unchecked Exceptions in Java]]></title>
            <link>https://justgiveacar.medium.com/checked-and-unchecked-exceptions-in-java-b7bfe55473af?source=rss-bd4ace02d0ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7bfe55473af</guid>
            <category><![CDATA[oca]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Justgiveacar]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 21:42:58 GMT</pubDate>
            <atom:updated>2021-07-06T21:42:58.451Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there !</p><p>I’m recently reading some books and preparing for the OCA certification assessment and I want to share some interesting parts that are always omitted by us.</p><p>In Java, there are two types of exceptions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*HDwcxC-uYHqlPsj6_oidmA.png" /></figure><h3>Checked Exception</h3><p>They are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.</p><p>Invalid external conditions that cannot be directly controlled by the program.</p><ul><li><strong>FileNotFoundException: </strong>Thrown programmatically when code tries to reference a file that does not exist.</li><li><strong>IOException: </strong>Thrown programmatically when there’s problem reading or writing a file.</li></ul><h3>Unchecked Exception</h3><p>They are the exceptions that are not checked at compile time. It is up to the programmers to be civilized, and specify or catch the exceptions.</p><p>Defects or logical errors of the program, and cannot be recovered at Runtime.</p><ul><li><strong>ArithmeticException: </strong>Trying to divide an int by zero gives an undefined result. When this occurs, the JVM will throw an ArithmeticException.</li><li><strong>ArrayIndexOutOfBoundsException: </strong>You know that array indexes start with 0 and go up to 1 less than the length of the array. If you try to get an element by an illegal index (-1 for example), an exception will be thrown.</li><li><strong>ClassCastException: </strong>hrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. Java tries to protect you from impossible casts.</li><li><strong>IllegalArgumentException: </strong>Thrown to indicate that a method has been passed an illegal or inappropriate argument. IllegalArgumentException is a way for your program to protect itself.</li><li><strong>NullPointerException: </strong>Instance variables and methods must be called on a non-null reference. If the reference is null, the JVM will throw a NullPointerException.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7bfe55473af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithm — Bubble Sort]]></title>
            <link>https://justgiveacar.medium.com/sorting-algorithm-bubble-sort-b3cab76cbc4f?source=rss-bd4ace02d0ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3cab76cbc4f</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sort]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[bubble-sort]]></category>
            <dc:creator><![CDATA[Justgiveacar]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 21:34:28 GMT</pubDate>
            <atom:updated>2021-02-15T21:34:28.492Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sorting Algorithm — Bubble Sort</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*BQEX-SSnvTBumsfTZ_ZMMg.png" /></figure><p>Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort.</p><p>Bubble sort has a worst-case and average complexity of O(n²), where n is the number pf items being sorted.</p><h3>How Bubble Sort Works ?</h3><ol><li>Starting from the first index, compare the first and the second elements. If the first element is greater than the second, they are swapped. And we keep comparing the second and the third elements, swap them if they are not in order.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*pqQ4y82G65ysL8dI6vSniw.png" /></figure><p>2. The same process goes on for the remaining iterations except for the last number which is the largest number right now by previous sorting process. After each iteration, the largest element among the unsorted elements is placed at the end. In each iteration, the comparison takes place up to the last unsorted element. The array is sorted when all the unsorted elements are placed at their correct positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*ewSM2E_u5ynxh4z2M6C-TQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*-L4eNglsydiCsIMxXfkBjQ.png" /></figure><p>Let’s take a look at the Java Code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08f9667d355f4a459d4816da7fe3f04e/href">https://medium.com/media/08f9667d355f4a459d4816da7fe3f04e/href</a></iframe><p>Actually, in the above code, all possible comparisons are made even if the array is already sorted. It increases the execution time. We can add an extra variable <strong>swapped</strong>. After each iteration, if there is no swapping taking place then, there is no need for performing further loops.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/024b60bad80f4f3a6975026390bf2f24/href">https://medium.com/media/024b60bad80f4f3a6975026390bf2f24/href</a></iframe><p>Alright, that’s pretty much it.</p><p>Thanks for reading my article. If you like it, please give me a small 👏. Appreciate ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3cab76cbc4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Java Operators]]></title>
            <link>https://justgiveacar.medium.com/understanding-java-operators-140e38266888?source=rss-bd4ace02d0ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/140e38266888</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[operators]]></category>
            <dc:creator><![CDATA[Justgiveacar]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 22:35:20 GMT</pubDate>
            <atom:updated>2021-02-15T21:59:06.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*f-iE5aBGs7ANKP-cu_crNw.jpeg" /></figure><p>A <em>Java operator </em>is a symbol that can be applied to a set of variables, values, or literals — referred to as operands — and that returns a result. Three types of operators are available in Java: unary, binary, and ternary. These types of operators can be applied to one, two or three operands, respectively. You’ll need to know a specific subset of Java operators, how to apply them, and the order in which they should be applied.</p><p>Java operators are not necessarily evaluated from left-to-right order. For example, the following java expression is actually evaluated from right-to-left given the specific operators involved:</p><pre>int x = 4;</pre><pre>double y = 3 + 2 * --x;</pre><p>In this example, you would first decrement <em>x</em> from 4 to 3, and then multiply the resulting value by 2, and finally add 3. The value would then be automatically upcast from <strong>9</strong><em> (Integer) </em>to<strong> 9.0</strong> <em>(Double)</em> and assigned to <em>y</em>. The final value of <em>x</em> and <em>y</em> would be 3 and 9.0 respectively.</p><p>Unless overridden with parentheses, Java operators follow <em>order of operation</em>, listed in Table below, by decreasing order of <em>operator precedence</em>. If two operators have the same level of precedence, then Java guarantees left-to-right evaluation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ca16657064e2704860e1a1a801f1132/href">https://medium.com/media/6ca16657064e2704860e1a1a801f1132/href</a></iframe><p>Thanks for reading my article. If you like it, please give me a small 👏. Appreciate ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=140e38266888" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A real perspective of an Array]]></title>
            <link>https://justgiveacar.medium.com/a-real-perspective-of-an-array-44198d12e091?source=rss-bd4ace02d0ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/44198d12e091</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Justgiveacar]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 17:42:33 GMT</pubDate>
            <atom:updated>2021-02-02T17:49:01.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*MLHDLn7AILHgqWDO8sT7_Q.jpeg" /></figure><h3>What are Arrays in Java ?</h3><p>“An <em>array</em> is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.”</p><p>The above paragraph is from Oracle Java Official Document, we can know that an array has features such as:</p><ul><li>Multiple spaces</li><li>Unchangeable length</li><li>Arbitrary type</li></ul><p>That is, generally, an array can help us to store several elements with same type (like a bank but only provide service to one specific currency), however, we are not allowed to add one more element to the array if length has already reached its maximum capacity.</p><p>That’s pretty much it, let’s take a look at an array in practice.</p><pre>dataType[] nameOfArray; // preferred way<br>dataType nameOfArray[]; // works but not preferred way</pre><p>To declare an array, define the variable type with square brackets:</p><pre>String[] elements;</pre><p>We have now declared a variavle that holds an array of strings. To insert value to it, we can use an array literal, place the values in a comma-separated list, inside curly braces:</p><pre>String[] elements = {&#39;a&#39;, &#39;b&#39;, &#39;c&#39;};</pre><p>To create an array of integers, you could write:</p><pre>int[] arr = new int[5];</pre><pre>arr[0] = 0;<br>arr[1] = 0;<br>...</pre><p>We can directly create an array with some elements only on one line.</p><pre>int[] arr = {1, 2, 3};</pre><p>In order to change an array element:</p><pre>// elements[index] = new_value;</pre><pre>elements[0] = &#39;new_a&#39;;</pre><p>Multidimensional arrays is an also a type of array which is an array containing one or more arrays. To create a two-dimensional array, add each array within its own set of curly braces:</p><pre>int[][] multiNums = { {1, 2, 3}, {4, 5, 6} };</pre><p>If you are interested, I want to talk about the underlying knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*y7_kpiw-JXaLjI1zj3grFg.png" /><figcaption>Figure 1 : How arrays are created in memory</figcaption></figure><p>Neither the Java Language Specification nor the Java Virtual Specification makes any guarantees about how arrays are implemented internally. All it requires is that array elements are accessed by an int index number having a value from 0 to length-1.</p><p>A perfectly conformant JVM could use a HashMap to implement arrays. In that case, the elements would be non-consecutive, scattered around memory, and it would need to record the indexes of elements, to know that they are.</p><p>Furthermore, the JVM will allocate the storage for array elements as a flat, contiguous chunk of memory. Locating a particular element is trivial: multiply the fixed memory size of each element by the index of the wanted element and add that to the memory address of the start of the array where index * elementSize + startOfArray. This means that the array storage consists of nothing but raw element values, consecutively, ordered by index. There is no purpose to also storing the index value with each element, because the element’s address in memory implies its index, and vice-versa. The complexity of accessing an element is O(1) since it only needs to calculate the address offset by formula given above.</p><p>Thanks for reading my article. If you like it, please give me a small 👏. Appreciate ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44198d12e091" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>