<?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 rahul reddy on Medium]]></title>
        <description><![CDATA[Stories by rahul reddy on Medium]]></description>
        <link>https://medium.com/@rahulreddyr3?source=rss-18acaa2d57ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_DJMF6zAYRGS8H6D</url>
            <title>Stories by rahul reddy on Medium</title>
            <link>https://medium.com/@rahulreddyr3?source=rss-18acaa2d57ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:41:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulreddyr3/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[The Case(s) Of Postgres Not Using Index]]></title>
            <link>https://medium.com/gojekengineering/if-postgres-is-not-using-index-here-could-be-why-d7bb0131f2cc?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7bb0131f2cc</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[index]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 19:52:52 GMT</pubDate>
            <atom:updated>2021-03-16T05:18:10.719Z</atom:updated>
            <content:encoded><![CDATA[<h4>Our learnings when we ventured into finding out multiple cases where Postgres was not using index.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uL6XX_LP31SibxK0EOJvCQ.png" /></figure><p>Each time we face a production issue, or design something which leads to lowering our BCR (booking conversion rate), or do just about anything which doesn’t have a positive impact on our ecosystem, we do two things for sure:</p><p>One 👉 We leave no stone unturned to fix the issue<br>Two 👉 We write about it so no one else does the same mistakes as us</p><p>Recently, we faced one such blog-triggering issue. The use case was simple:</p><p>Upon receiving a request, schedule/re-schedule a task in the scheduler and execute the task at the scheduled time. To achieve this, we were using <a href="https://github.com/quartz-scheduler/quartz">Quartz</a>, an open source library. It was running well until one dreadful night. 😣</p><p>We saw response times for the service going up. Initially, we thought the database box was the bottleneck, so we upgraded it. Nothing changed. 🙄After digging more, we finally found the issue — a particular query used by the Quartz library was taking about 1 second to execute.</p><p>You thought it was all sunshine and rainbows? ☀️🌈</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FoJuQOH0sxewWMMjJnQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FoJuQOH0sxewWMMjJnQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FoJuQOH0sxewWMMjJnQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdc80fb59280352e3e3256996d1b9e1a/href">https://medium.com/media/cdc80fb59280352e3e3256996d1b9e1a/href</a></iframe><p>The problem here was that the indices were already present for that query. To add to that, when we tried to reproduce the issue by running the query from Postgres CLI, it was using the index and we were back to square one. But this post is not about how we debugged the <a href="https://github.com/quartz-scheduler/quartz/issues/612">issue</a>.</p><blockquote>Our concern was the fact that Postgres was not using index, which led us to deep dive into cases where this could be happening.</blockquote><p>Unsettlingly, we found quite a few cases. 😑</p><p>To give a bird’s-eye view: Postgres will not use Index whenever the query planner thinks (Hope it is not actually “thinking”… Remember Skynet? 🤖). The query complexity of using Index scan is more than that of doing a simple sequential scan. Sometimes, it’s actually beneficial to do a sequence scan over Index scan, but this issue arrises when Postgres decides to do a sequential scan at the wrong times.</p><p>So without further ado, let’s get to the cases.</p><h4>Case 1: Table is very small</h4><p>When the table size is small, Postgres generally goes with the sequential scan as it will be much more economical than an index scan. To understand this, you need to understand <a href="https://medium.com/@rahulreddyr3/indexing-in-postgresql-b-tree-4377bd72d7e5">how indices work</a>. The basic reasoning is, if we use indexing, we need to first access the blocks corresponding to the index and then the actual blocks of the table. But, with sequence scan, we just need to access the blocks of the table.</p><blockquote>Postgres is right to not use index in this case, since index scan takes more time. So, this should not cause any issues in production.</blockquote><p>But knowing about this would prevent wasting time, debugging why index is not being used in dev/staging environment. (Still remember doing this on my first day 😭)</p><h4>Case 2: Query is on one of the fields in multi index</h4><p>Though a multicolumn B-tree index can be used with query conditions that involve any subset of the index’s columns, the index is most efficient when there are constraints on the leading (leftmost) columns.</p><p>For example: If there’s an index created on (a.b.c) and have query a=5 and b=6 will use the index, but the query on b=6 and c=7 will not use the index. Think of the index as a sorted list of lists. In our example the entire table is sorted on a first and all the rows with same values for a are sorted on b, and similarly then on c. So we just make a query on bor c, then the entire index has to be accessed. This is more inefficient than doing a direct sequential scan on the table.</p><h4>Case 3: Query is returning almost all of the table</h4><p>This is an interesting case. If the query is such that the result would include most rows from the table, then Postgres would prefer a sequence scan to index scan. This is the result of reducing the number of block accesses same as above.</p><blockquote>How would Postgres know the number of rows a query can return without actually running the query?</blockquote><p>Postgres achieves this by continuously analysing and storing the statistics about the rows of the table in pg_statistic table.</p><p>Note: This is not an actual measure, rather a close guess.</p><p>An example of this would be when you’re selecting for the only value of the column. That is, if a column, say a, has only one value of true and your query is for select * where a=true This would mean that all the rows of the table are to be returned, hence using a sequential scan on table is beneficial in this case.</p><h4>Case 4: When column data type and query data type don’t match</h4><p>This happens when the application is setting wrong datatype for one of the columns in the query. Not that by default Postgres can do some datatype conversions as referenced by <a href="https://www.postgresql.org/docs/11/catalog-pg-cast.html">pg_cast</a> table. So even if the datatype doesn’t match, the query goes through without any errors in these case.</p><p>With pg_cast there are two cases. One, where the data in query can be converted to match the datatype of the table (say, we give bigint in query and the column is of numeric type). In this case every thing works as expected, Postgres will do the type casting and use the index.</p><p>The problem arrises with the other case, where the values from the table are to be converted to match the datatype of the query (i.e., we give numeric in query and the column is of bigint type). As Postgres can only cast a bigint to numeric, the only option it has is to convert every row in the table to numeric and then compare. Thus in this case, the index won’t be used.</p><p>If you’re wondering, this is exactly what happened in our case. To add to it, this is quite difficult to debug. If we do an explain analyse on the query in db directly, Postgres will use the index, and in normal queries we don’t specify the datatypes of the columns.</p><h4>Case 5: When the query contains LIMIT</h4><p>This is a tricky one. Sometimes, a query like select * from abc where col_1 = 5 limit 1; doesn’t use the index while select * from abc where col_1 = 5; does. This is happens when the pg_stats on that table suggests that the col_1 table has enough random values in the table such that, the total cost of fetching required number if sequential blocks from db, would be less than that of fetching the index blocks first and then the corresponding data blocks.</p><blockquote><strong>Note</strong>: With the default settings, the planner considers the cost of a random page read (required in an index scan) four times the cost of a sequential page read (required in sequentially scanning the table from beginning).</blockquote><p>The worse case for this is when the sequential scan has to be done on the entire table as the query results in 0 rows.</p><h4>Case 6: Index is not present</h4><p>This might look straightforward, but does happen in practice. 🤷‍♂️</p><p>Know of any more cases I might’ve have missed? Leave a comment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPWwoozDxeKoXMtXEyrtLw.png" /></figure><p>Click <a href="https://blog.gojekengineering.com/">here</a> to read more stories on how we build our #SuperApp. 💚</p><p>Click below to build it with us.</p><figure><a href="https://bit.ly/gojekjobsblogs2021"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*c2_eIvR2WDUWnP6YmzcGpQ.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7bb0131f2cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/if-postgres-is-not-using-index-here-could-be-why-d7bb0131f2cc">The Case(s) Of Postgres Not Using Index</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Indexing in PostgreSQL (B-Tree)]]></title>
            <link>https://rahulreddyr3.medium.com/indexing-in-postgresql-b-tree-4377bd72d7e5?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/4377bd72d7e5</guid>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[b-tree]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Mon, 12 Aug 2019 15:38:53 GMT</pubDate>
            <atom:updated>2019-08-14T14:51:15.766Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Indexing in data bases:</strong></p><p>Indexing is common strategy used by databases to reduce the query times. PostgreSQL supports multiple types of indexing like B-Tree, Generalized Inverted Index (GIN), Generalized Inverted Search Tree (GiST), Hash to name few. The basic idea in all of them is that query performance can be improved by minimizing the number of disk accesses required to execute the query. <strong>In this blog we will be focusing on B-Tree index type.</strong></p><p>Before going further, let look at some definitions:</p><p><strong>Index:</strong> An index is a specific structure that organizes a reference to your data that makes it easier to look up. In PostgreSQL it is a copy of the item you wish to index combined with a reference to the actual data location.</p><p><strong>Page: </strong>A page, memory page, or virtual page is a fixed-length contiguous block of virtual memory, described by a single entry in the page table. It is the smallest unit of data for memory management.</p><p><strong>Block: </strong>A block is the smallest unit of data that an operating system can either write to a file or read from a storage devices. Typically it is equal to page size.</p><p><strong>B-Tree: </strong>B-Tree is a self-balancing search tree. Unlike most other self-balancing search trees (like <a href="https://www.geeksforgeeks.org/avl-tree-set-1-insertion/">AVL</a> and Red-Black Trees), the main use case for B-Tree’s is when the data is too much to keep all of it in memory and is read from disk in the form of blocks. This reading from disk is very expensive.</p><p><strong>Important things about B-Tree:</strong></p><ul><li>B-Tree is a balanced tree hence operations like search, insert, delete are O(h) complex where h is the height of the tree.</li><li>In the case of B-Tree the complexity is measured in terms of disk accesses.</li><li>In general B-Tree’s have huge number of branching factor to keep their height as small as possible. ( As b^h= N)</li><li>The height of B-Trees is kept low by putting maximum possible keys in a B-Tree node. Generally, a B-Tree node size is kept equal to the disk block size.</li><li>Since h is low for B-Tree, total disk accesses for most of the operations are reduced significantly compared to balanced Binary Search Trees like AVL Tree, Red-Black Tree etc.</li></ul><p><strong>Query:</strong> The look-up in a B-Tree are straight forward. We start at the root node and the follow the pointer till we reach a leaf node. Within each node we can use binary search to determine which pointer to take next. In leaf node a binary search will result in the required element if present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2z3Iq-wH5xg56Lu7OKuuXQ.png" /><figcaption>Sample B-Tree</figcaption></figure><p><strong>Insertion:</strong> Insertion in a B-Tree is also fairly simple. Similar to search we will find the root node where the data should be inserted and:</p><ol><li>If the node has space in the node and redistribute the node.</li></ol><p>2. If the node is full then break the node into two other nodes with median as parent and push the new node to the previous parent node and repeat step 1 in parent.</p><p>This ensures that the entire tree is balanced.</p><p><strong>B-Tree Indexing in PostgreSQL:</strong></p><p>Now that the definitions are clear lets understand B-Tree Indexing in PostgreSQL. As the name suggests the primary data structure used in B-Tree index is a B-Tree. <strong>In PostgreSQL the node size of the B-Tree is kept same as the page/block size which is default size 8KB.</strong> PostgreSQL uses <a href="https://www.csd.uoc.gr/~hy460/pdf/p650-lehman.pdf">Efficient Locking for Concurrent Operations on B-Trees</a> version of B-Tree’s.</p><p><strong>B-Tree Index Implementation in PostgreSQL:</strong></p><ul><li>The order of all the nodes in index tree need not be same unlike the convention as each node is limited by total size of the node rather than total number of key in it. Meaning if you have variable-size data, each node in your index tree can have different number of children.</li><li>All the non-leaf nodes are only useful for traversal. No information regarding the actual data is stored in them.</li><li>Each key in leaf node stores the information of pointer to block in which actual record is stored.</li></ul><blockquote>The O(h) insert and search capability provided by the B-Tree is the reason behind the magical promise of indexes to tremendously decrease of query time while only marginally affecting the insert time.</blockquote><p><strong>Some interesting facts about Indexes in PostgreSQL:</strong></p><ul><li>Even when there is an index present PostgreSQL will sometimes not use it if the query results in large percentage of data from the table. This is because it is easier to scan the entire table only once than using the index getting the block addresses for almost all of the table, and then actually accessing the data from table.</li><li>When all the required information for the query is in index PostgreSQL (&gt;9.2) will not access the table at all.</li><li>Having index on columns which has smaller individual data entries can increase performance very slightly compared to having index on column with larger data as more number of index entries can be fit in a single disk page, which reduces the number of disk accesses required for getting index.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4377bd72d7e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How SSL handshake works?]]></title>
            <link>https://rahulreddyr3.medium.com/how-ssl-handshake-works-686b60c02a4e?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/686b60c02a4e</guid>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[encription]]></category>
            <category><![CDATA[network-security]]></category>
            <category><![CDATA[computer-networking]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 03:17:08 GMT</pubDate>
            <atom:updated>2019-03-27T03:21:56.948Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s start with what is SSL. <strong>SSL stands for “Secure Sockets Layer”</strong>. It is a protocol that operates directly on top of Transmission Control Protocol(although there are also implementations for datagram based protocols such as UDP) and ensures that the information exchange between two parties is done with authenticity, integrity and confidentiality.</p><p>SSL protocol requires <strong>SSL certificates</strong> to be present on the server side so that any client connecting to the server can verify the SSL certificate from the server to verify it authenticity. There are <strong>certification authorities or certificate authorities (CA)</strong> which can provide such certificates for servers and help clients verify the certificates. These certificates not only help with encryption but also authenticate the identity of the owner of a website, adding another layer of security. The SSL certificate is then used as proof of the company’s identity. These certificates can be divided into three authentication groups, based on the level of authentication, which are:</p><ol><li>DOMAIN VALIDATION CERTIFICATES: Can just verify if the control over domain name.</li><li>ORGANISATION VALIDATION CERTIFICATES: Can verify both domain name and the authenticity of the company as a legal entity.</li><li>EXTENDED VALIDATION CERTIFICATES: Has both the above and various other verifications proving that the SSL certificate belongs to a registered company</li></ol><p>Now that we know what SSL certificates are lets go to the <strong>SSL handshake</strong>. As mentioned earlier SSL protocol works on top of TCP, hence the SSL handshake begins after TCP connection is established between two parties (say client and server). The SSL handshake enables the client and server to establish the secret keys with which they communicate for the rest of the message. On a high level the following are done during this handshake:</p><ol><li>Agree on the version of the protocol to use.</li><li>Select cryptographic algorithms.</li><li>Authenticate each other by exchanging and validating SSL certificates. Although client validation is generally optional.</li><li>Use asymmetric encryption techniques to generate a shared secret key, which avoids the key distribution problem. SSL or TLS then uses the shared key for the symmetric encryption of messages, which is faster than asymmetric encryption.</li></ol><p>The basic principle is that using SSL certificates and asymmetric encryption, a secret key can be established which is only known to the server or client even when all the messages sent/received during this handshake can be seen by anyone in the channnel. Once the secret key is established this can be used to communicate securely.</p><p>As SSL operates directly on top of the TCP, it allows higher protocol layers to remain unchanged while still providing a secure connection. So underneath the SSL layer, the other protocol layers are able to function as normal.</p><p>If an SSL certificate is being used correctly, all an attacker will be able to see is which IP and port is connected and roughly how much data is being sent. They may be able to terminate the connection but both the server and user will be able to tell this has been done by a third party. However, they will not be able to intercept any information, which makes it essentially an ineffective step.</p><p>In typical use, the attacker will also be able to figure out which hostname you’re connecting to (but not the rest of the URL) as although HTTPS itself does not expose the hostname, your browser will usually need to make a DNS request first to find out what IP address to send the request to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=686b60c02a4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FOMO]]></title>
            <link>https://rahulreddyr3.medium.com/fomo-6c314275a4aa?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c314275a4aa</guid>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[fear]]></category>
            <category><![CDATA[fomo]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Tue, 16 Oct 2018 04:23:33 GMT</pubDate>
            <atom:updated>2018-10-16T04:23:33.061Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>FOMO</strong>, or <strong>Fear of missing out </strong>is “a pervasive apprehension that others might be having rewarding experiences from which one is absent”. This social anxiety is characterised by “a desire to stay continually connected with what others are doing”. FOMO is also defined as a <strong>fear of regret</strong>, which may lead to a compulsive concern that one might miss an opportunity for social interaction, a novel experience, a profitable investment, or other satisfying events.</p><blockquote>In other words, FOMO perpetuates the fear of having made the wrong decision on how to spend time since “you can imagine how things could be different”.</blockquote><p>This definition of FOMO is particularly interesting because in modern world managing time is considered to be ‘the’ most important thing. Hence its not surprising that most people fear doing it wrong.</p><p>From an evolutionary perspective fear exists a life saving emotion in rare situation. Fear helps us out run a lion when we come face to face, but being in fear continuously is not a good thing. As time management is a regular task being stressed about may have health consequences.</p><p>So what to do, you just need to ask. One can do the following to keep their FOMO in check.</p><ol><li><strong>Slow down.</strong></li><li><strong>Practice discernment</strong> in regard to distinguishing what is truly important and necessary from what is merely desirable.</li><li><strong>Be willing to not have it all</strong>. Needs are limited. Desires are endless. Accept the essential futility of trying to fulfill every desire.</li><li><strong>One thing at a time.</strong></li><li><strong>Practice Mindfulness.</strong> Rather than chasing after what may be just an illusion of happiness, we can gently strive for the deep satisfaction that comes with the cultivation of mindfulness — the practice of being present in our lives and giving non-judgmental awareness to our moment-to-moment experience.</li><li><strong>Savour the moment.</strong> Take time to linger over pleasurable experiences rather than rushing through them in quest of the next thrill.</li><li><strong>Cultivate an attitude of gratitude</strong>. Instead of chasing fantasies we believe will fulfill us, we can cultivate gratitude.</li></ol><blockquote>But be careful that using these above prescribed level can also be harmfull. The goal should not be to make ourself free from FOMO, it is to controll FOMO and use the fear to our advantage. The aim is one must be able to chose what is Fears Missing Out and thus try hard for that cause, by not getting distracted by every desire that one experiences.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c314275a4aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Linear Regression using Gradient Descent]]></title>
            <link>https://rahulreddyr3.medium.com/implementing-linear-regression-using-gradient-descent-81f370fb9964?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/81f370fb9964</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[gojek-bootcamp]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Sun, 07 Oct 2018 21:07:39 GMT</pubDate>
            <atom:updated>2018-10-07T21:07:39.849Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog I write about my experiences of implementing Linear regression using “Gradient Descent”.</p><p>In linear regression we try to model the relation between the features and the predictions as a linear relation. i,e <strong><em>Y = a + bX </em></strong>where a and b are called the coefficients and constant respectively. The problem of linear regression is to come up with values for these coefficients and the constant(parameters) such that the net error in predictions is least. The error is measured as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*Utp8sgyLk7H39qOQY9pf1A.png" /></figure><p>The parameters of linear regression can be found out using the below code directly:</p><pre>def get_linear_regression_parameters(X, y):<br>    X_with_constant = np.c_[np.ones((len(X),1)), X]<br>    a = np.matmul(X_with_constant.T, X_with_constant)<br>    b = np.matmul(X_with_constant.T, y)<br>    params = np.matmul(np.linalg.inv(a), b)<br>    return params</pre><p>This implements the below expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*xVx1uB1OpU2_Y9wFv12IUw.png" /><figcaption>(for proof refer to <a href="https://ayearofai.com/rohan-3-deriving-the-normal-equation-using-matrix-calculus-1a1b16f65dda">this</a>)</figcaption></figure><p>We can also find the parameters using gradient descent to minimise the cost function. In python this can be done as shown below:</p><pre>def gradient_descent(matrix_x, y, theta, learning_rate=0.01):<br>    length_of_y = len(y)<br>    theta_new = theta + 1<br>    while True:<br>        prediction = np.dot(matrix_x, theta)<br>        theta_new = theta - ((1/length_of_y) * learning_rate * (matrix_x.T.dot(prediction - y)))<br>        if np.linalg.norm(theta_new - theta) &lt; 0.00001:<br>            return theta<br>        theta = theta_new</pre><pre>def linear_regression(data, target, learning_rate=0.01):<br>    theta = np.random.randn(14, 1)<br>    target = np.array(target,ndmin=2).T<br>    data_with_constant = np.c_[np.ones((len(data),1)), data]<br>    return gradient_descent(data_with_constant, target, theta)</pre><p>The above code implements the logic as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*lIthvknHt9Tok5aIj4e__g.png" /></figure><p>Implementing linear regression with gradient descent will allow us to verify the results from gradient descent using the direct implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81f370fb9964" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing in android — Part 2]]></title>
            <link>https://rahulreddyr3.medium.com/unit-testing-in-android-part-2-2e4d07d9a966?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e4d07d9a966</guid>
            <category><![CDATA[gojek-bootcamp]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mocking]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Sun, 07 Oct 2018 19:32:13 GMT</pubDate>
            <atom:updated>2018-10-07T19:32:13.090Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit Testing in android — Part 2</h3><p>This blog is the part 2 of the this <a href="https://medium.com/@rahulreddyr3/unit-testing-in-android-part-1-679dc328508e">blog</a>. Previous blog was about unit testing in java. This blog will be about doing the same in Kotlin. Consider the below presenter, view and activity:</p><p>SplashScreenPresenter.kt:</p><pre><strong>package </strong>com.example.rahulreddy.kotlinexample.splash<br><br><strong>class </strong>SplashScreenPresenter(<strong>private val splashView</strong>: SplashScreenView) {<br><br>    <strong>fun </strong>navigateToNextScreen(userName: String?) {<br>        <strong>if </strong>(userName != <strong>&quot;&quot;</strong>) {<br>            <strong>splashView</strong>.goToHomeScreen(userName)<br>        } <strong>else </strong>{<br>            <strong>splashView</strong>.goToLoginScreen()<br>        }<br>    }<br>}</pre><p>SplashScreenActivity.kt:</p><pre><strong>package </strong>com.example.rahulreddy.kotlinexample.splash<br><br><strong>import </strong>android.content.Context<br><strong>import </strong>android.content.Intent<br><strong>import </strong>android.os.Bundle<br><strong>import </strong>android.support.v7.app.AppCompatActivity<br><strong>import </strong>com.example.rahulreddy.kotlinexample.R<br><strong>import </strong>com.example.rahulreddy.kotlinexample.login.LoginScreenActivity<br><strong>import </strong>com.example.rahulreddy.kotlinexample.home.HomeScreenActivity<br><br><br>@Suppress(<strong>&quot;NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS&quot;</strong>)<br><strong>class </strong>SplashScreenActivity : AppCompatActivity(), SplashScreenView {<br><br>    <strong>override fun </strong>goToLoginScreen() {<br>        <strong>val </strong>intent = Intent(<strong>this</strong>, LoginScreenActivity::<strong>class</strong>.<em>java</em>)<br>        startActivity(intent)<br>        finish()<br>    }<br><br>    <strong>override fun </strong>goToHomeScreen(userName: String?) {<br>        <strong>val </strong>intent = Intent(<strong>this</strong>, HomeScreenActivity::<strong>class</strong>.<em>java</em>)<br>        intent.putExtra(<strong>&quot;name&quot;</strong>, userName)<br>        startActivity(intent)<br>        finish()<br>    }<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_splash_screen)<br>        <strong>val </strong>preference = getSharedPreferences(<strong>&quot;session&quot;</strong>, Context.<em>MODE_PRIVATE</em>)<br>        <strong>val </strong>name = preference.getString(<strong>&quot;name&quot;</strong>, <strong>&quot;&quot;</strong>)<br>        SplashScreenPresenter(<strong>this</strong>).navigateToNextScreen(name)<br>    }<br>}</pre><p>SplashScreenView.kt:</p><pre><strong>package </strong>com.example.rahulreddy.kotlinexample.splash<br><br><strong>interface </strong>SplashScreenView {<br>    <strong>fun </strong>goToLoginScreen()<br>    <strong>fun </strong>goToHomeScreen(userName: String?)<br>}</pre><p>To write the unit tests for this presenter we need to mock the view. For this we can use mockito. To add mockito to your project add the below line to your build.gradle</p><pre>testImplementation <strong>&quot;org.mockito:mockito-core:1.10.19&quot;</strong></pre><p>also make sure that the below line is present in the build.gradle</p><pre>testImplementation <strong>&#39;junit:junit:4.12&#39;</strong></pre><p>Now go to your presenter and do a ‘cmd + shift + T’ or the equivalent in your key map and let android studio to automatically create a test for you and create tests in this file.</p><p>The most general type of testing in presenter is to verify if the correct function in the view is called from the presenter. For this we can use the ‘Mockito.verify’. It will verify if the corresponding function of the mocked object is called. For the above example this looks like below:</p><pre><strong>package </strong>com.example.rahulreddy.kotlinexample.splash<br><br><strong>import </strong>org.junit.Test<br><strong>import </strong>org.mockito.Mockito<br><br><strong>class </strong>SplashScreenPresenterTest {<br><br>    @Test<br>    <strong>fun </strong>testNavigateToNextScreenBasedOnUserNameWhenUserNameIsNotEmpty() {<br>        <strong>val </strong>mockedSplashScreenViewObject = Mockito.mock(SplashScreenView::<strong>class</strong>.<em>java</em>)<br>        <strong>val </strong>splashScreenPresenter = SplashScreenPresenter(mockedSplashScreenViewObject)<br>        <strong>val </strong>userName = <strong>&quot;rahul&quot;<br>        </strong>splashScreenPresenter.navigateToNextScreen(userName)<br>        Mockito.verify(mockedSplashScreenViewObject).goToHomeScreen(userName)<br>    }<br>}</pre><p>If you notice the Junit doesn’t allow you name the test freely. You need to follow the name conventions of function in Kotlin/Java. But in Kotlin we can name a function whatever we want by using <strong>inverted commas</strong>. This will be most helpful in case of tests as now we can name a test to completely describe what it does. In code this looks like below.</p><pre><strong>package </strong>com.example.rahulreddy.kotlinexample.splash<br><br><strong>import </strong>org.junit.Test<br><strong>import </strong>org.mockito.Mockito<br><br><strong>class </strong>SplashScreenPresenterTest {<br><br>    @Test<br>    <strong>fun </strong>testNavigateToNextScreenBasedOnUserNameWhenUserNameIsNotEmpty() {<br>        <strong>val </strong>mockedSplashScreenViewObject = Mockito.mock(SplashScreenView::<strong>class</strong>.<em>java</em>)<br>        <strong>val </strong>splashScreenPresenter = SplashScreenPresenter(mockedSplashScreenViewObject)<br>        <strong>val </strong>userName = <strong>&quot;rahul&quot;<br>        </strong>splashScreenPresenter.navigateToNextScreen(userName)<br>        Mockito.verify(mockedSplashScreenViewObject).goToHomeScreen(userName)<br>    }<br><br>    @Test<br>    <strong>fun </strong>`when user name is empty in splash screen navigate to login screen`() {<br>        <strong>val </strong>mockedSplashScreenViewObject = Mockito.mock(SplashScreenView::<strong>class</strong>.<em>java</em>)<br>        <strong>val </strong>splashScreenPresenter = SplashScreenPresenter(mockedSplashScreenViewObject)<br>        splashScreenPresenter.navigateToNextScreen(<strong>&quot;&quot;</strong>)<br>        Mockito.verify(mockedSplashScreenViewObject).goToLoginScreen()<br>    }<br>}</pre><p>As we can see that the unit tests can only cover non android logic. So in order to fully test the app one should also have integration tests in place. Only having unit test will not help much in finding the exact location bug in code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e4d07d9a966" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing in android - Part 1]]></title>
            <link>https://rahulreddyr3.medium.com/unit-testing-in-android-part-1-679dc328508e?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/679dc328508e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mvp]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Wed, 03 Oct 2018 03:08:31 GMT</pubDate>
            <atom:updated>2018-10-03T04:42:32.295Z</atom:updated>
            <content:encoded><![CDATA[<p>Writing unit test is an important part of coding. Developers will be more confident in refactoring a code with good number of unit tests that one with out unit tests. Also it will be easy to find bugs in a code with unit tests because we can know exactly which part of the code is breaking. So how to write unit tests for android easily?</p><p>In android main problem in writing unit tests is all the android components that are to be mocked. So in order to make writing unit tests simple we generally follow one of the following design patterns:</p><ol><li>MVP (Model View Presenter)</li><li>MVVP (Model View ViewModel)</li></ol><p>In this I will cover MVP model. In MVP:</p><ol><li><strong>Model </strong>is typically POJO’s that are used by Presenter and View to convey information or to act upon.</li><li><strong>View </strong>is passive interface that displays data.This is place where we set data &amp; make UI related changes like hiding , moving view.</li><li><strong>Presenter </strong>decides presentation logic , our business logic resides here. It talks to repository gets data, format it to display in view. It decides what should be displayed on View.</li></ol><p>The trick of making writing unit tests easy lies in designing the code such that the basic business logic is separated from the android related components. For this we wrap all the android related components using custom interfaces so that we need to mock only our objects, not the android objects. MVP design pattern helps with this. In MVP we try to isolate business logic as much as possible into presenter. Android related objects are hidden under the interface provided by the view.</p><p>This allows us to write normal unit tests for the presenter and <a href="https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests">Instrumental tests</a> for the android components. In this post I will discuss the unit testing using JUNIT and Java. In the next post I will explain unit testing using kotlin.</p><p>Consider presenters like bellow:</p><pre><strong>public class </strong>MyPresenter {</pre><pre>    private MyView myView;</pre><pre><strong>    public </strong>MyPresenter(MyView myView) {<br>        <strong>this</strong>.myView = myView;<br>    }</pre><pre>    <strong>public </strong>void doSomeThing(int decisionValue) {<br>        <strong>if</strong>(decisionValue == 1) {<br>            myView.goToFirstScreen();<br>        }<br>        <strong>else </strong>{<br>            myView.goToDefaultScreen();<br>        }<br>    }<br>}</pre><p>for this type of presenters we need to mock the view. In this I will use Mockito.</p><p>To mock a function call we use verify. See the below example.</p><pre>@Test<br><strong>public void </strong>doSomeThingGoToFirstScreenTest()<br>{<br>    MyView loginView= mock(MyView.<strong>class</strong>);<br>    MyPresenter loginPresenter = <strong>new </strong>MyPresenter(loginView);<br>    myPresenter.doSomeThing(1);<br>    verify(myView).goToFirstScreen();<br>}<br><br>@Test<br><strong>public void </strong>doSomeThingGoToDefaultScreenTest()<br>{<br>    MyView loginView= mock(MyView.<strong>class</strong>);<br>    MyPresenter loginPresenter = <strong>new </strong>MyPresenter(loginView);<br>    myPresenter.doSomeThing(0);<br>    verify(myView).goToDefaultScreen();<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=679dc328508e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID one by one — L]]></title>
            <link>https://rahulreddyr3.medium.com/solid-one-by-one-l-1a8053b21ad9?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a8053b21ad9</guid>
            <category><![CDATA[lsp]]></category>
            <category><![CDATA[liskov-substitution]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[oo-design]]></category>
            <category><![CDATA[gojek-bootcamp]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Mon, 17 Sep 2018 02:59:09 GMT</pubDate>
            <atom:updated>2018-09-17T02:59:09.666Z</atom:updated>
            <content:encoded><![CDATA[<h4>Date — 16/Sep/2018</h4><p>This is the fourth post in the series of posts on Solid. In this I will explain the third principle in SOLID, L. It stands for Liskov Substitution Principle. The most popular definition of Liskov Substitution Principle is as below:</p><blockquote>Liskov Substitution Principle states that in a computer program, if S is a subtype of T, then objects of type T may be <em>replaced</em> with objects of type S (i.e. an object of type T may be <em>substituted</em> with any object of a subtype S) without altering any of the desirable properties of the program (correctness, task performed, etc.).</blockquote><p>The exact definition given by Liskov is as bellow:</p><blockquote><em>Let Φ(x) be a property provable about objects x of type T. Then Φ(y)should be true for objects y of type S where S is a subtype of T.</em></blockquote><p>Liskov Substitution Principle requires a semantic Is-A relation to be maintained between the super class and sub class. In simple terms this proposes that objects of a superclass can be replaceable with objects of its subclasses without breaking the application. One can achieve this by following a few rules, which are pretty similar to the design by contract concept defined by Bertrand Meyer.</p><p>An overridden method of a subclass needs to accept the same input parameter values as the method of the superclass. That means we can implement less restrictive validation rules, but we should not enforce stricter ones in our subclass. Otherwise, any code that calls this method on an object of the superclass might cause an exception, if it gets called with an object of the subclass.</p><p>Similar rules apply to the return value of the method. The return value of a method of the subclass needs to comply with the same rules as the return value of the method of the superclass.</p><p>To make sure that Liskov Substitution Principle is followed we should implement our own checks. This can be done by using tests. We can add extra tests to existing one to make sure that, that part of code works with objects of subclasses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a8053b21ad9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID one by one — O]]></title>
            <link>https://rahulreddyr3.medium.com/solid-one-by-one-o-2a00bffedee2?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a00bffedee2</guid>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[gojek-bootcamp]]></category>
            <category><![CDATA[branch-on-type]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Mon, 17 Sep 2018 02:36:15 GMT</pubDate>
            <atom:updated>2018-09-17T02:36:15.450Z</atom:updated>
            <content:encoded><![CDATA[<h4>Date — 14/Sep/2018</h4><p>This is the third post in the series of posts on Solid. In this I will explain the second principle in SOLID, O. It stands for Open Closed principle. The most popular definition of Open Closed principle is as below:</p><blockquote>The <strong>open/closed principle</strong> states “<em>software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification</em>”</blockquote><p>The general idea of this principle is to write code so that you will be able to add new functionality to it without changing the existing code. Robert C. Martin considered this principle as the “the most important principle of object-oriented design”. Bertrand Meyer was the one who proposed this idea. Meyer’s proposed method for maintaining open closed principle relied on the inheritance. The explanation was as bellow:</p><blockquote>A class is closed, since it may be compiled, stored in a library, baselined, and used by client classes. But it is also open, since any new class may use it as parent, adding new features. When a descendant class is defined, there is no need to change the original or to disturb its clients.</blockquote><p>But later on other authors like, Robert C. Martin in his articles about the SOLID principles or Joshua Bloch in his book Effective Java,taught inheritance introduces tight coupling if the subclasses depend on implementation details of their parent class.</p><p>To avoid this they proposed the use of polymorphism and interfaces instead. Using <em>interfaces</em> instead of superclasses to allow different implementations in different sub classes, thus reducing the coupling and providing an extra level of abstraction at the same time. This follows the open closed principle because interfaces are closed for modifications, while one can extend them to provide new implementations thus making them open for modifications.</p><p><strong>An example of open closed principle violation can be branch on types. In case of branch on types a software entity cannot be open for extension without being modified.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a00bffedee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID one by one — S]]></title>
            <link>https://rahulreddyr3.medium.com/solid-one-by-one-s-362b5ea6eec2?source=rss-18acaa2d57ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/362b5ea6eec2</guid>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[rp]]></category>
            <category><![CDATA[god-class]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[rahul reddy]]></dc:creator>
            <pubDate>Thu, 13 Sep 2018 02:32:13 GMT</pubDate>
            <atom:updated>2018-09-13T02:32:26.798Z</atom:updated>
            <content:encoded><![CDATA[<h4>Date — 12/Sep/2018</h4><p>This is the second post in the series of posts on Solid. In this I will explain the first principle in SOLID, S. It stands for Single responsibility principle. The most popular definition of SRP is as below:</p><blockquote>The <strong>single responsibility principle</strong> is a computer programming principle that states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.</blockquote><blockquote>Robert C. Martin who introduced this principle defined it as, “A class should have only one reason to change.” The key word being “change”. According to this definition state of a class changes only for a single reason.</blockquote><p>What it means is that any class in an object oriented code base should have only one responsibility and the state of a class should change only in one way. This is very difficult to implements in practice espically the second part of it. So generally people try to have different classes for each method of a class even when it doesn&#39;t make any sense. So another way to understand SRP and avoid falling in this trap can be</p><blockquote>“a class should do everything it can do and only things it can do. Nothing less nothing more.”</blockquote><p>The ideal design will follow the above rule while maintaining change only for one reason rule. One should be extremely careful while using the above rule because if misused it will create GOD classes every thing SRP stands aganist. To illustrate this point consider a common class like Application class. Now if you say this class should do everything an application should do then we should write entire code in this class making it a GOD class. Insted what we can do is make sub classes to do smaller works and use them in the application class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=362b5ea6eec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>