<?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 Skrew Everything on Medium]]></title>
        <description><![CDATA[Stories by Skrew Everything on Medium]]></description>
        <link>https://medium.com/@skreweverything?source=rss-877f86012ce8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*wDyX5kSQBxiRfTS7.</url>
            <title>Stories by Skrew Everything on Medium</title>
            <link>https://medium.com/@skreweverything?source=rss-877f86012ce8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 06:29:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skreweverything/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[Are Math and CS knowledge really necessary for developers, engineers, and programmers?]]></title>
            <link>https://medium.com/from-the-scratch/are-math-and-cs-knowledge-really-necessary-for-developers-engineers-and-programmers-427ad0ec3822?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/427ad0ec3822</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 15:44:03 GMT</pubDate>
            <atom:updated>2021-03-09T15:44:03.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLC2K6LeJWjBeNCBqp2e0Q.jpeg" /></figure><p>The infamous question among beginners and programming enthusiasts who are just getting started is-</p><blockquote>“Should I know the topics of computer science and mathematics to become a good software developer or engineer or programmer?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*XYhThxYWSP9eW0LRrL7xvw.jpeg" /></figure><p><strong><em>If God can make a random person billionaire every time this question was asked, then the price of a single bread slice would be 1 Billion 💸💸💸</em></strong></p><p>If you are just starting out and search in Google whether math is really necessary then there is a 99 in 100 chance that you come across these type of answers</p><h3>JavaScript is not available.</h3><p>Once headmaster (HM) of my school asked me: who do you want to become?Me: a programmer.HM: are you good at math?Me: no.HM: oh, you&#39;ll need that in order to become a programmer.Me: ...Now, 8 years later, I am a Web developer, working from home.I&#39;m still not good at math.</p><blockquote><strong>Once headmaster (HM) of my school asked me</strong>: who do you want to become?</blockquote><blockquote><strong>Me</strong>: a programmer.</blockquote><blockquote><strong>HM</strong>: are you good at math?</blockquote><blockquote><strong>Me</strong>: no.</blockquote><blockquote><strong>HM</strong>: oh, you’ll need that in order to become a programmer.</blockquote><blockquote><strong>Me</strong>: …</blockquote><blockquote>Now, 8 years later, I am a Web developer, working from home.</blockquote><blockquote>I’m still not good at math.</blockquote><p>The problem with these types of answers is, although they are not wrong but often taken out of context and quite misleading for beginners who fail to distinguish between developers and engineers.</p><p>So, let’s answer some basic questions before we go for a debate over the importance of Math.</p><p>In the software industry, the terms <strong>developer</strong>, <strong>engineer</strong> and <strong>programmer</strong> are used interchangeably.</p><h3>Who is a Software Developer?</h3><p>A Software Developer is a person who develops applications or software using libraries, APIs, and frameworks.</p><p>The libraries, APIs, and frameworks do all the heavy-lifting and the job of the developer is to piece everything together to meet the requirements.</p><p>The developer needs to have good logical thinking to reason the components and working of the software. Developers are not expected to solve problems. The job of a software developer is to convert requirements into working code.</p><p><strong>When a person is being interviewed for a developer position, the organization expects the person to be fluent in the programming languages, libraries, and frameworks that are being used by them in the production.</strong></p><p>For example, if you need to develop a website with animations, you just use the framework. Usually, animation requires the knowledge of mathematics but the framework does all the heavy and exposes an API.</p><p>Another example, every database is built on top of complex algorithms, data structures, and memory management techniques, etc., which are used by software developers.</p><h3>Who is a Software Engineer?</h3><p>A software engineer is a person who develops software, frameworks, and also systems that will be used by other developers.</p><p>These people are the ones who do all the heavy work that’s going into libraries and frameworks etc.</p><p>Like any other engineer, Software Engineer should have strong problem-solving, and math skills. Additionally, knowledge of algorithms, data structures is a must no matter what you hear on public forums.</p><p>Apart from having those skills, they are also expected to have minimum knowledge about Operating Systems, Databases, Networks, Distributed Computing, Architectures, and Design Patterns, etc.</p><p><strong>When a person is being interviewed for an engineer position, the organization expects the person to be fluent in the algorithms, data structures, and minimum knowledge in Operating Systems, Databases, Networks, Distributed Computing, Architectures, and Design Patterns, etc.</strong></p><p>This is the reason why many companies during the whiteboard interviews, don’t insist on a particular language. Even in the job postings, they just mention “<em>experience with at least one OOP-based programming language</em>”. The main thing the companies are looking for in an interview is for a person who can solve problems and the ability to build systems that are highly scalable, performant, and maintainable.</p><p>For example, if a website needs an auto-suggestion system for its search bar, then the Software Engineer writes a code that takes text as input and produces an array of suggestions, <strong>efficiently</strong>. Then the software developer uses the API to send the text and display the suggestions to the user.</p><p><strong>So, for building an auto-suggestion API that can handle high Queries per second(QPS), the use of data structures, algorithms, and a plethora of other concepts like Memory Management taught in Operating System class, distributed computing, databases, etc., are a must.</strong></p><h3>Who is a Programmer or Coder?</h3><p>A programmer is a person who can write code in general. It doesn’t matter whether you can build Tesla’s autonomous driving system, create websites, or participate in hackathons.</p><blockquote>If you can write a code, then congratulations!🥳🎉 You are a Programmer now.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8r46JeiBCug2icHnE1gSkw.gif" /><figcaption>Avengers Infinity War</figcaption></figure><blockquote><strong><em>Disclaimer</em></strong><em>: Sorry to break your heart 💔 but HTML and CSS doesn’t count 😑.</em></blockquote><h3>Conclusion</h3><p><strong>Software Developer</strong>: Math and Computer Science topics are not needed but can help in the long run.</p><p><strong>Software Engineer</strong>: Math and Computer Science topics are must. No excuses! No shortcuts! Although there are multiple frameworks for every small thing these days, still you are expected to learn the internals or at least have a high-level understanding just in case to tear it and modify it to suit your needs.</p><p><strong>Programmer</strong>: A Superset of Software Developer and Engineer. Nothing more than that. And please don’t call yourself a “<strong>Programmer</strong>” or “<strong>Coder</strong>”. It is really cringy to hear. Especially, experienced developers and engineers hate it and look like you are an amateur. So, never use this word in the software industry!</p><h4><strong><em>For reference, the below articles are examples of what Software Developers are expected to have knowledge about:</em></strong></h4><ul><li><a href="https://medium.com/from-the-scratch/cookies-visualized-everything-you-ever-need-to-know-about-web-cookies-c5f3b403dc65">Cookies Visualized: Everything you ever need to know about Web Cookies</a></li><li><a href="https://medium.com/from-the-scratch/react-custom-hooks-a-simple-intuition-if-you-still-cant-hit-it-off-8d27fa4ba10">React Custom Hooks: A simple intuition if you still can’t hit it off</a></li><li><a href="https://medium.com/from-the-scratch/javascript-writing-your-own-non-blocking-asynchronous-functions-60091ceacc79">JavaScript: Writing your own non-blocking asynchronous functions</a></li><li><a href="https://medium.com/from-the-scratch/wtf-is-synchronous-and-asynchronous-1a75afd039df">WTF is Synchronous and Asynchronous!</a></li><li><a href="https://medium.com/from-the-scratch/reactjs-introduction-with-and-without-jsx-and-babel-for-beginners-57a5b6a4eb08">ReactJS Intro: With and without JSX and Babel for beginners</a></li><li><a href="https://medium.com/from-the-scratch/reactjs-intro-using-babel-on-the-fly-during-production-vs-compiling-during-development-3faa8a62b44b">ReactJS Intro: Using Babel on the fly during production vs compiling during development</a></li><li><a href="https://medium.com/from-the-scratch/sql-vs-nosql-a-senior-software-engineers-perspective-72a778df3098">SQL vs NoSQL: A Senior Software Engineer’s perspective</a></li><li><a href="https://medium.com/from-the-scratch/git-commands-you-need-to-know-when-you-are-messed-up-e880fbf03819">Git: Commands you need to know when you are messed up😨!</a></li></ul><p>If you look at the titles of articles above, you realize that those are language and platform-specific, just like how I told you in the beginning.</p><h4><strong><em>For reference, the below articles are examples of what Software Engineers are expected to have knowledge about:</em></strong></h4><ul><li><a href="https://medium.com/from-the-scratch/http-server-what-do-you-need-to-know-to-build-a-simple-http-server-from-scratch-d1ef8945e4fa">HTTP Server: Everything you need to know to Build a simple HTTP server from scratch</a></li><li><a href="https://medium.com/from-the-scratch/software-engineering-101-time-zones-and-working-with-dates-a138364ac769">Software Engineering 101: Time zones and Working with Dates</a></li><li><a href="https://medium.com/from-the-scratch/software-engineering-101-stuffing-multiple-values-into-a-single-64bit-value-50aebe396559">Software Engineering 101: Stuffing multiple values into a single 64bit value</a></li><li><a href="https://medium.com/from-the-scratch/sql-vs-nosql-a-senior-software-engineers-perspective-72a778df3098">SQL vs NoSQL: A Senior Software Engineer’s perspective</a></li><li><a href="https://medium.com/from-the-scratch/deep-learning-deep-guide-for-all-your-matrix-dimensions-and-calculations-415012de1568">Deep Learning: Deep guide for all your matrix dimensions and calculations!</a></li><li><a href="https://medium.com/from-the-scratch/dont-be-confused-between-concurrency-and-parallelism-eac8e703943a">Don’t be confused between Concurrency and Parallelism</a></li><li><a href="https://medium.com/from-the-scratch/oop-everything-you-need-to-know-about-object-oriented-programming-aee3c18e281b">OOP: Everything you need to know about Object Oriented Programming</a></li><li><a href="https://medium.com/from-the-scratch/wtf-is-synchronous-and-asynchronous-1a75afd039df">WTF is Synchronous and Asynchronous!</a></li><li><a href="https://medium.com/from-the-scratch/stop-it-there-are-no-compiled-and-interpreted-languages-512f84756664">STOP IT! There are no Compiled and Interpreted Languages!</a></li><li><a href="https://medium.com/from-the-scratch/git-commands-you-need-to-know-when-you-are-messed-up-e880fbf03819">Git: Commands you need to know when you are messed up😨!</a></li></ul><p>So, first, decide what you want to become and then try to concentrate on things which are necessary. If are interested in UI/UX and your ultimate goal is to be a front-end developer then wasting your time learning algorithms and data structures is impractical. And the same goes for the back-end developers. If your work is to query the database, use third-party APIs and scheduling tasks, etc., then learning about memory management, distributed computing is futile.</p><blockquote>But learning a new thing is never a waste of time. It will always come in handy when needed</blockquote><p>So, go ahead and bookmark it, and don’t be selfish! Share it with fellow developers to help them out</p><p>Want to have a talk with me? <a href="http://twitter.com/@SkrewEverything">Twitter.com/@SkrewEverything</a>.</p><p>Liked it? 👏👏👏 it and Share it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=427ad0ec3822" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/are-math-and-cs-knowledge-really-necessary-for-developers-engineers-and-programmers-427ad0ec3822">Are Math and CS knowledge really necessary for developers, engineers, and programmers?</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookies Visualized: Everything you ever need to know about Web Cookies]]></title>
            <link>https://medium.com/from-the-scratch/cookies-visualized-everything-you-ever-need-to-know-about-web-cookies-c5f3b403dc65?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f3b403dc65</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Tue, 01 Dec 2020 22:06:42 GMT</pubDate>
            <atom:updated>2020-12-01T22:23:14.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4xFsG1LX9aw9lfdt" /><figcaption>Photo by <a href="https://unsplash.com/@starvingartistfoodphotography?utm_source=medium&amp;utm_medium=referral">Christina Branco</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Web Cookies are more or less like a child 👶. Most of the time, they both are harmless.</p><p>But once you don’t give enough attention and leave cookies alone, they can bring down even the most secure websites. By the time you realize, your website is compromised and burned to the ground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*ESeqkI2KZd_e3vPLndq_zA.jpeg" /><figcaption><a href="https://funnyfoto.org/20-funny-kid-pictures/10/">Never leave a child alone</a></figcaption></figure><blockquote>Never think web cookies (or kids) are harmless. Give maximum attention for your better future!</blockquote><h3>The most confusing things about the cookies are—</h3><ol><li>When they are sent</li><li>When they are not sent</li><li>To which domains they are sent</li><li>How cookies work for cross-domain requests</li></ol><h3>Let me put an end to all these by visualizing how cookies work in the wild!</h3><h3>The basics of a cookie —</h3><p>When you first visit a website that you have never visited, the browser doesn’t have any cookies associated with that website.</p><ol><li>So, <strong>the initial request doesn’t have any cookies</strong>.</li><li><strong>Then in the response from the server, a cookie is sent to the browser. </strong>The browser saves this received cookie for future requests.</li><li>From now onwards, whenever the client makes a request, <strong>the browser attaches the saved cookies and sends it to the server</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMPJ7kGH9-oSDCB9oauPNQ.gif" /></figure><p>This is how the basic concept of cookies work.</p><h4>There are many important things that most of you don’t realize —</h4><blockquote>FYI, Cookies are a feature of the browser. For server, it is just a normal header.</blockquote><p>The browser takes care of storing and attaching cookies based on the domain(we will come to this) and the expiration time.</p><p>If you are familiar with <strong>cURL</strong>, you might remember that handling of cookies(storing from the response and attaching to the request) must be done by the user by using -c flag.</p><p><strong>From cURL man pages:</strong></p><blockquote>-c, — cookie-jar &lt;filename&gt;<br> (HTTP) Specify to which file you want curl to write all cookies after a completed operation. Curl writes all cookies from its in-memory cookie stor-<br> age to the given file at the end of operations. If no cookies are known, no data will be written. The file will be written using the Netscape cookie<br> file format. If you set the file name to a single dash, “-”, the cookies will be written to stdout.</blockquote><blockquote>This command line option will activate the cookie engine that makes curl record and use cookies. Another way to activate it is to use the -b,<br> — cookie option.</blockquote><blockquote>If the cookie jar can’t be created or written to, the whole curl operation won’t fail or even report an error clearly. Using -v, — verbose will get<br> a warning displayed, but that is the only visible feedback you get about this possibly lethal situation.</blockquote><blockquote>If this option is used several times, the last specified file name will be used.</blockquote><p>Also, if you observe the request and response headers for a cookie, <strong>you will see that not all the information is sent to the server. Only the name and value of the cookies are sent.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxbHX1VVMhbf0a23L4COAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4YHIr4ICnZ71PNhoeqfLA.png" /><figcaption>In request headers, only the cookie’s name and value are sent</figcaption></figure><p>This is because, the browser is responsible for managing cookies, and the cookie’s attributes like <strong><em>domain</em></strong>, <strong><em>path</em></strong>, <strong><em>secure</em></strong>, <strong><em>httponly</em></strong>, and <strong><em>expiration</em></strong> <strong><em>time</em></strong> help the browser manage its store of cookies. Therefore, although you can read the name and value of a cookie, you cannot read the cookie’s other attributes(through javascript on the client-side). And also when the browser sends the cookie information to the server, the browser only includes the name and value.</p><h3>Cookies are always sent to the domain(or sub-domains) that it was created by!</h3><p>This is the most important rule the cookies follow —</p><blockquote>No matter what, the cookies are only sent to the domain it was set by, even during cross-origin requests, PERIOD.</blockquote><p>If your browser is making two requests for two different domains, then —</p><p>Cookies are sent to their respective domains only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7W0HlvycoEzmh8Y4THm7Q.gif" /></figure><p>The below scenario is not possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_dwsTNHs7r3c4UDyRgbOg.gif" /></figure><p>Again, to be clear, cookies set by A-DOMAIN.COM will never be sent to B-DOMAIN.COM</p><p>This is a major security feature that prevents cookies to be read by other domains. This is necessary because cookies are used for <strong>Sessions</strong>(to store the sessionID of the user). If this is allowed then it leads to <strong>Session Hijacking</strong>.</p><p>For those of you who don’t know what a <strong>Session Hijacking</strong> means, the <strong>attacker steals the session cookie to pose as the victim without needing to authenticate(without entering/knowing the victim’s password)</strong>.</p><p>Session Hijacking is just one possible threat. Not the only one though.</p><h3>The server can only set cookies for its own domain —</h3><p>The thing with the cookies is, the <strong>browser only accepts the cookies with the domain name attribute with the same value as the domain name it was sent from</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uzgz3uwyDkT1IomNNLpNww.gif" /></figure><p>That means <strong>facebook.com</strong> can only set cookies for <strong>facebook.com</strong>.</p><p>If <strong>google.com</strong> tries to set cookies for <strong>facebook.com</strong> by providing <strong>Domain=facebook.com</strong> in the <strong>Set-Cookie</strong> header, then the cookie is rejected by the browser —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XS1aUtPIhXHT2tzUDJPpfA.gif" /></figure><p>Till here, I hope the concepts are clear. If not, make sure you understand them clearly because the whole thing gets complicated as soon as sub-domains are introduced.</p><h3>Domain Matching</h3><p>The most confusing thing about cookies is how to share and not to share cookies between your sub-domains</p><p>Before getting down the rabbit hole, memorize the below anatomy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBHLHYQRQc0698WSk5WXZA.gif" /></figure><h3>We also need to know how domain matching works in the browsers.</h3><p>Domain matching is used to decide whether the browser should accept or reject a cookie with a particular domain attribute in response and which cookies need to be sent while performing a request.</p><blockquote>The domain matching test always tries to match the suffix of the host name with the domain attribute. If the domain attribute is present in the host name as the suffix, then the domain matching test is passed and cookies are sent(in request) and cookies are accepted(in response).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVYbMZM_ZyjNyZoGVzNmxA.gif" /></figure><p>Another important detail about cookies that most people don’t know is —</p><blockquote>Cookies are not affected by Port numbers.</blockquote><blockquote>Cookies can work even for IP Addresses as host name.</blockquote><p>Below example table shows which domains are accepted and rejected for domain attribute for example.com host in a browser response —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e7dcaf6077e2eafb14e9b77628b2c82/href">https://medium.com/media/8e7dcaf6077e2eafb14e9b77628b2c82/href</a></iframe><p>Below example table shows to which hostnames which cookies are sent with a particular domain attribute for a request —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48a668deb81ab490ef5bc86ca5b49e7e/href">https://medium.com/media/48a668deb81ab490ef5bc86ca5b49e7e/href</a></iframe><h3>First, let&#39;s see how to share cookies —</h3><p>To share cookies between sub-domains and second-level domains, domain attribute must be set.</p><h3>Parent domain can set cookies which can be used by sub-domains</h3><p>If the parent domain sets cookies using a domain attribute then the cookies can be accessed by all of its sub-domains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qeHRC37s5VtAzNCNHF0_ww.gif" /></figure><h3>Sub-domains can set cookies not to share it with the parent domains but can be shared with its relative subdomains</h3><p>If a sub-domain(x.example.com) sets a cookie using the domainattribute with the sub-domains hostname(x.example.com), then the parent domain(example.com) cannot access it. But, the sub-domains(y.x.example.com) of it can access it as it becomes parent(x.example.com) to other relative subdomains(like y.x.example.com, z.y.x.example.com, zy.x.example.com etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SlvlTvGcKFmUTaeeQEIB_A.gif" /></figure><h3>Now, How not to share cookies using HostOnly Cookies</h3><p>Sharing cookies is not always desired. Sometimes, a particular cookie must be made available exclusively to the host to which it set the cookie.</p><p>This can be achieved by not mention anything in the domain attribute in the Set-Cookie header. This makes the cookie hostOnly , which means the cookie is only available to the host it created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgZ-pGcgBx3gbclVXFymeA.gif" /></figure><h3>How Secure Flag works in Cookies</h3><p>Secure flag in Cookies can be used to only transfer the cookies if and only if the connection is Secure ie., over <strong>HTTPS</strong>. If the connection is not secure, then no cookies are transferred between the client(browser) and the server.</p><p>This can help to prevent <strong>Man In Middle Attacks</strong> in which, a person reads/modifies the unsecured content while transferring between two people without their knowledge.</p><p>From <a href="https://en.wikipedia.org/wiki/HTTP_cookie#Secure_cookie">Wikipedia</a>:</p><blockquote>Secure cookie</blockquote><blockquote>A <em>secure cookie</em> can only be transmitted over an encrypted connection (i.e. <a href="https://en.wikipedia.org/wiki/HTTP_Secure">HTTPS</a>). They cannot be transmitted over unencrypted connections (i.e. <a href="https://en.wikipedia.org/wiki/HTTP">HTTP</a>). This makes the cookie less likely to be exposed to cookie theft via eavesdropping. A cookie is made secure by adding the Secure flag to the cookie.</blockquote><p>If the connection is not Secure i.e., over <strong>HTTP</strong>, then the cookie is not accepted(or not sent to the server.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNxY4FPCz-21VXjZdPtTRA.gif" /></figure><p>If the connection is Secure i.e., over <strong>HTTPS</strong>, then the cookie is accepted(or sent to the server.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoJXdxHULWaOYxAB3UYqSg.gif" /></figure><h3>How HTTPOnly Flag works in Cookies</h3><p>If the httpOnly flag is enabled on a cookie, then it is not accessible to client Javascript.</p><p>This is useful when you don’t want anyone to read/modify the cookie on the client-side. For example, a user session cookie doesn’t need to be available for reading and modifying on the client-side.</p><p>From <a href="https://en.wikipedia.org/wiki/HTTP_cookie#Http-only_cookie">Wikipedia</a>:</p><blockquote>Http-only cookie</blockquote><blockquote>An <em>http-only cookie</em> cannot be accessed by client-side APIs, such as <a href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a>. This restriction eliminates the threat of cookie theft via <a href="https://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting</a> (XSS). However, the cookie remains vulnerable to <a href="https://en.wikipedia.org/wiki/Cross-site_tracing">cross-site tracing</a> (XST) and <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">cross-site request forgery</a> (CSRF) attacks. A cookie is given this characteristic by adding the HttpOnly flag to the cookie.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_nRhlkW7j5FTASKmZh-sA.gif" /></figure><h3>How Session Cookies work</h3><p>Every cookie can be provided with an expiration DateTime either using maxAge or expires attribute. After the expiration DateTime, the cookie gets invalidated/removed from the browser.</p><p>But if no value is provided for maxAge or expires attribute, then the cookie is said to be a session cookie.</p><p>From <a href="https://en.wikipedia.org/wiki/HTTP_cookie#Session_cookie">Wikipedia</a>:</p><blockquote>Session cookie</blockquote><blockquote>A <em>session cookie</em>, also known as an <em>in-memory cookie</em>, <em>transient cookie</em> or <em>non-persistent cookie</em>, exists only in temporary memory while the user navigates the website. Web browsers normally delete session cookies when the user closes the browser. Unlike other cookies, session cookies do not have an expiration date assigned to them, which is how the browser knows to treat them as session cookies.</blockquote><blockquote>As there is no expiration datetime is mentioned for a session cookie while creating it, the browser deletes this cookie when the browser window(not a tab) is closed/quit.</blockquote><h3>Cookie behavior in Ajax Requests</h3><p>While making ajax requests, we can choose whether to send cookies are not using credentials property.</p><p>credentials has 3 values:</p><ol><li>omit</li><li>include</li><li>same-origin</li></ol><p>You can send requests to either to the same origin or cross-origin using ajax.</p><h3>Same-origin requests</h3><p>Same-origin requests are when you make an ajax request to the same hostname displayed in the address bar of a browser.</p><h4>credentials: &#39;omit&#39;</h4><p>While making the request, the browser doesn’t send any cookies to the server.</p><p>This option means “<strong><em>don’t send any cookies in the request</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_U5K-bEJDR5KQt2_TASVw.gif" /></figure><h4>credentials: &#39;same-origin&#39;</h4><p>While making the request, the browser sends available cookies to the server.</p><p>This option means that “<strong><em>send the cookies if and only if the request is to the same origin</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACQIdGd9vTFw-dcS1F0yyA.gif" /></figure><h4>credentials: &#39;include&#39;</h4><p>While making the request, the browser sends available cookies to the server.</p><p>This option means “<strong><em>send the cookies with the request</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27JaC_RFDyrFRHqTdfcuDQ.gif" /></figure><h3>Cross-origin requests</h3><p>Cross-origin requests are when you make an ajax request to a server that has a different hostname from what is displayed in the address bar of a browser.</p><blockquote>I have seen many people thinking that in cross-origin requests, cookies from different origins are also sent, which is completely wrong!</blockquote><p>The above rules still hold, even for cross-origin requests! Again, this is never possible —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_dwsTNHs7r3c4UDyRgbOg.gif" /></figure><p>All the rules about domain matching still hold in cross-origin requests.</p><h4>credentials: &#39;omit&#39;</h4><p>While making the request, the browser doesn’t send any cookies to the server.</p><p>This option means “<strong><em>don’t send any cookies in the request</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m22AD6jMSH0KbObhwzbWcw.gif" /></figure><h4>credentials: &#39;same-origin&#39;</h4><p>While making the request, the browser doesn’t send any cookies to the server.</p><p>This option means that “<strong><em>send the cookies if and only if the request is to the same origin</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUeedO3Hz_tJly4FvdzK2g.gif" /></figure><h4>credentials: &#39;include&#39;</h4><p>While making the request, the browser sends available cookies to the server.</p><p>This option means “<strong><em>send the cookies with the request</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PI_snwDLmVwtBvIbkBTZig.gif" /></figure><p><strong>To make the above thing easy, remember this matrix:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d6092c393a5472017bd8fcf8057e22f/href">https://medium.com/media/0d6092c393a5472017bd8fcf8057e22f/href</a></iframe><p>So, go ahead and bookmark it, and don’t be selfish! Share it with fellow developers to help them out</p><p>Want to contact me? <a href="http://twitter.com/@SkrewEverything">Twitter.com/@SkrewEverything</a>.</p><p>Found any mistakes or got anything to say? Comment down below.</p><p>Liked it? 👏👏👏 it and Share it.</p><h3>References</h3><ul><li><a href="https://stackoverflow.com/q/2959010/4859791">How to get the domain value for a cookie in Javascript?</a></li><li><a href="https://stackoverflow.com/q/32579803/4859791">How to get cookie&#39;s path using javascript</a></li><li><a href="https://stackoverflow.com/q/47574555/4859791">Can I see cookie domain specificity in JS?</a></li><li><a href="https://stackoverflow.com/q/1062963/4859791">How do browser cookie domains work?</a></li><li><a href="https://docs.microsoft.com/en-us/previous-versions/aspnet/ms178194(v=vs.100)">ASP.NET Cookies Overview</a></li><li><a href="https://stackoverflow.com/q/3089199/4859791">Can subdomain.example.com set a cookie that can be read by example.com?</a></li><li><a href="https://hover.blog/whats-a-domain-name-subdomain-top-level-domain/">What&#39;s in a Domain Name: Sub, Second-Level, Top-Level, &amp; Country Code Domains What&#39;s in a Domain Name? All about TLDs!</a></li><li><a href="https://tools.ietf.org/html/rfc6265">RFC 6265 - HTTP State Management Mechanism</a></li><li><a href="https://tools.ietf.org/id/draft-abarth-cookie-00.html">HTTP State Management Mechanism</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f3b403dc65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/cookies-visualized-everything-you-ever-need-to-know-about-web-cookies-c5f3b403dc65">Cookies Visualized: Everything you ever need to know about Web Cookies</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[GCP] Everything you need to know to setup Firebase and GCP emulators — Part 2]]></title>
            <link>https://medium.com/from-the-scratch/gcp-everything-you-need-to-know-to-setup-firebase-and-gcp-emulators-part-2-1c2e07da76d9?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c2e07da76d9</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 22:27:48 GMT</pubDate>
            <atom:updated>2020-10-11T22:28:23.231Z</atom:updated>
            <content:encoded><![CDATA[<h3>[GCP] Everything you need to know to setup Firebase and GCP emulators — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KR5tXiUK65q1JG3ZP_ifg.jpeg" /></figure><p>Generally speaking, cloud helps us to optimize computing costs based on our demands and takes away unnecessary overhead of purchasing, maintaining and forecasting hardware needs. But cloud makes it difficult for us to test our apps locally. Good thing is, Google provides a bunch of emulators to help us test our apps locally without incurring cloud costs.</p><blockquote>But if you are pulling an all-nighter and not careful, your GCP bill will be on 🔥🔥🔥</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ikp7pY6TulQAZV4IMIIKfw.gif" /></figure><p>So, to avoid a heart attack at the end of the month, you need to devote your maximum attention while setting up the emulators. BTW, setting up the emulators is not hard but doing it right is crucial.</p><p>Emulators provided by the Google Cloud Platform are —</p><ol><li>Firebase Functions</li><li>Firebase Hosting</li><li>Firebase Firestore</li><li>Firebase Realtime Database</li><li>Google Cloud Spanner</li><li>Google Cloud BigTable</li><li>Google Cloud PubSub</li><li>Google Cloud DataStore</li></ol><p>Setting up the above emulators require zero to minimum code change depending on from where(client or server) your code is using GCP.</p><p>In this part, we look at setting up Google Cloud Platform Emulators. For Firebase Emulators, check out this part —</p><p><a href="https://medium.com/from-the-scratch/firebase-everything-you-need-to-know-to-setup-firebase-and-gcp-emulators-part-1-9be3c9f10929">[Firebase] Everything you need to know to setup Firebase and GCP emulators — Part 1</a></p><h3>Google Cloud Platform</h3><p>To see the list of emulators and other components provided by GCP, use this command —</p><pre>gcloud components list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-3hKgRdHql26Lmm7okEzA.png" /></figure><p><strong>Note: Firebase and GCP offers same emulators for pubsub and firestore. You can install it using either one of them.</strong></p><p><strong>Note</strong>: Even though GCP provides an emulator for Spanner but it is a docker image. Spanner emulator native binary is only available for Linux. The above image is from macOS. That is the reason there is no Spanner emulator in the list. When you start the Spanner emulator, gcloud automatically downloads docker image if there is none present.</p><p>From <a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/spanner/start">Google Spanner emulator documentation</a>:</p><blockquote>Use the cloud spanner emulator docker image even if the platform has a native binary available in the sdk. Currently we only provide a native binary for Linux. For other systems, you must install docker for your platform before starting the emulator.</blockquote><h4>To install all the emulators —</h4><pre>gcloud components install pubsub-emulator cloud-datastore-emulator cloud-firestore-emulator bigtable</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVtUB4eo7mUhR7DCbZ7Y4Q.png" /></figure><p><a href="https://cloud.google.com/sdk/docs/components">Managing SDK Components | Cloud SDK Documentation | Google Cloud</a></p><h4>To start the GCP emulators —</h4><pre>gcloud beta emulators [emulator_name] start [flags]</pre><p>Unlike Firebase, GCP doesn’t provide a nice json file to configure ports. To give your desired port, you need to pass it as command line argument while starting the emulator. If you are feeling lazy, gcloud gives default port values to each emulator.</p><h4>Pubsub:</h4><p><strong>Note</strong>: If you have started pubsub using firebase tools, then no need to do it using gcloud</p><pre>gcloud beta emulators pubsub start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6K6Gmh6ULJl-SWDL2ZneCg.png" /></figure><ul><li><a href="https://cloud.google.com/pubsub/docs/emulator">Testing apps locally with the emulator | Pub/Sub | Google Cloud</a></li><li><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/pubsub/start">gcloud beta emulators pubsub start | Cloud SDK Documentation</a></li></ul><h4>Firestore:</h4><p><strong>Note</strong>: If you have started firestore using firebase tools, then no need to do it using gcloud</p><pre>gcloud beta emulators firestore start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXemvWL7xT2VJq-EJMbNRQ.png" /></figure><p><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/firestore/start">gcloud beta emulators firestore start | Cloud SDK Documentation</a></p><h4>Bigtable:</h4><pre>gcloud beta emulators bigtable start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nviDY-SquLVDf2qrFdKCDQ.png" /></figure><ul><li><a href="https://cloud.google.com/bigtable/docs/emulator">Using the Cloud Bigtable Emulator | Cloud Bigtable Documentation</a></li><li><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/bigtable/start">gcloud beta emulators bigtable start | Cloud SDK Documentation</a></li></ul><h4>Spanner:</h4><pre>gcloud beta emulators spanner start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZiFPiy9NUNXwmhrqmnu2A.png" /><figcaption>Need Docker to run Spanner emulator</figcaption></figure><p>If you are using other than Linux, then you have to install and start Docker before starting the Spanner Emulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zC-3jCocz8o5HCD2scoviA.png" /></figure><p>If you don’t have Spanner Docker image, then a new one is downloaded and started.</p><p>If you already have it, then you will see something like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yo-FoX5oAeFEaR5evrYO4w.png" /></figure><ul><li><a href="https://cloud.google.com/spanner/docs/emulator">Emulate Spanner locally | Google Cloud</a></li><li><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/spanner/start">gcloud beta emulators spanner start | Cloud SDK Documentation</a></li></ul><h4>DataStore:</h4><pre>gcloud beta emulators datastore start</pre><p>Sometimes you might encounter this error —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPKMkG5AAExCCGYPifAkew.png" /></figure><p>Don’t worry though. It requires a Project to run the datastore. You have 2 options here.</p><ol><li>Export a random string to export CLOUDSDK_CORE_PROJECT=&#39;my-project-id&#39; . This is not advisable because as this may make datastore not work with other emulators without additional setup.</li><li>You need to login and choose your project. Don’t worry, this will not make your code to hit production servers. You can do it with confidence.</li></ol><p>After doing one of the above —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6i0QOoaY5Jm7gay7x9ceg.png" /></figure><ul><li><a href="https://cloud.google.com/datastore/docs/tools/datastore-emulator">Running the Datastore Emulator | Cloud Datastore Documentation</a></li><li><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/datastore/start">gcloud beta emulators datastore start | Cloud SDK Documentation</a></li></ul><p>Now that we have installed all the required emulators in our working machine and everything is running, next we see how to use those emulators instead of our production GCP servers.</p><h3>Using Emulators</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cefssyz0gsbR5FoaArZLMw.gif" /></figure><h4>The above visualisation should be self explanatory on how the emulator works.</h4><h3>GCP</h3><p>Pubsub, Spanner, Datastore and Bigtable can only be accessed from your GCP or other servers but not from client side.</p><p>Unlike Firebase, you don’t have a json file pointing to the local emulators. Just like how we gave the port number through command line while starting the emulators, we need to export that same port numbers to point our services to our emulators.</p><h4>Pubsub:</h4><p>Executing this command shows the environment variables you have to export in order to point your services to local emulators.</p><pre>gcloud beta emulators pubsub env-init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*N_9z_48MOicLCxdLzFhYAg.png" /></figure><p>Execute the command returned by the command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-XPS9p6VDm6Bji_na-zwQ.png" /></figure><p>From Google <a href="https://cloud.google.com/pubsub/docs/emulator#manually_setting_the_variables">documentation</a>:</p><blockquote>On the machine that runs your application, set the PUBSUB_EMULATOR_HOST environment variable and value as directed by the output of the env-init command. You can optionally set the PUBSUB_PROJECT_ID environment variable for the project you want to use for the emulator, but you only need to set PUBSUB_EMULATOR_HOST for your application to connect to the emulator.</blockquote><p><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/pubsub/env-init">gcloud beta emulators pubsub env-init | Cloud SDK Documentation</a></p><h4>Bigtable:</h4><pre>gcloud beta emulators bigtable env-init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9gGuBhKgbIjZ0mA1F-CgQ.png" /></figure><p><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/bigtable/env-init">gcloud beta emulators bigtable env-init | Cloud SDK Documentation</a></p><h4>Datastore:</h4><pre>gcloud beta emulators datastore env-init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-OB0fIQCdEczZ9b7bKwGQ.png" /></figure><ul><li><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/datastore/env-init">gcloud beta emulators datastore env-init | Cloud SDK Documentation</a></li><li><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/datastore/env-unset">gcloud beta emulators datastore env-unset | Cloud SDK Documentation</a></li></ul><h4>Spanner:</h4><pre>gcloud beta emulators spanner env-init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*0alsVEmkf0RUoBnTjBrKbg.png" /></figure><p><a href="https://cloud.google.com/sdk/gcloud/reference/beta/emulators/spanner/env-init">gcloud beta emulators spanner env-init | Cloud SDK Documentation</a></p><h4>Firestore:</h4><pre>export FIRESTORE_EMULATOR_HOST=localhost:$PORT</pre><h3>That’s it</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fb5Cj0cAsg3buE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fb5Cj0cAsg3buE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fb5Cj0cAsg3buE%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="434" frameborder="0" scrolling="no"><a href="https://medium.com/media/099de03ebf0fda891e36325058f4f578/href">https://medium.com/media/099de03ebf0fda891e36325058f4f578/href</a></iframe><p>You must be feeling tired going through all those commands, codes and links.</p><p>So, go ahead and bookmark it and don’t be selfish! Share it with fellow developers to help them out</p><p>Want to contact me? <a href="http://twitter.com/@SkrewEverything">Twitter.com/@SkrewEverything</a>.</p><p>Found any mistakes or got anything to say? Comment down below.</p><p>Liked it? 👏👏👏 it ( come on! If I can spend this much time to write then you can spend few seconds to clap it 50 times 🤷) and Share it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2e07da76d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/gcp-everything-you-need-to-know-to-setup-firebase-and-gcp-emulators-part-2-1c2e07da76d9">[GCP] Everything you need to know to setup Firebase and GCP emulators — Part 2</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Firebase] Everything you need to know to setup Firebase and GCP emulators — Part 1]]></title>
            <link>https://medium.com/from-the-scratch/firebase-everything-you-need-to-know-to-setup-firebase-and-gcp-emulators-part-1-9be3c9f10929?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9be3c9f10929</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 22:26:40 GMT</pubDate>
            <atom:updated>2020-10-11T22:29:06.436Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Firebase] Everything you need to know to setup Firebase and GCP emulators — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KR5tXiUK65q1JG3ZP_ifg.jpeg" /></figure><p>Generally speaking, cloud helps us to optimize computing costs based on our demands and takes away unnecessary overhead of purchasing, maintaining and forecasting hardware needs. But cloud makes it difficult for us to test our apps locally. Good thing is, Google provides a bunch of emulators to help us test our apps locally without incurring cloud costs.</p><blockquote>But if you are pulling an all-nighter and not careful, your GCP bill will be on 🔥🔥🔥</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ikp7pY6TulQAZV4IMIIKfw.gif" /></figure><p>So, to avoid a heart attack at the end of the month, you need to devote your maximum attention while setting up the emulators. BTW, setting up the emulators is not hard but doing it right is crucial.</p><p>Emulators provided by the Google Cloud Platform are —</p><ol><li>Firebase Functions</li><li>Firebase Hosting</li><li>Firebase Firestore</li><li>Firebase Realtime Database</li><li>Google Cloud Spanner</li><li>Google Cloud BigTable</li><li>Google Cloud PubSub</li><li>Google Cloud DataStore</li></ol><p>Setting up the above emulators require zero to minimum code change depending on from where(client or server) your code is using GCP.</p><p>In this part, we look at setting up Firebase Emulators. For Google Cloud Platform emulators, check out this part —</p><p><a href="https://medium.com/from-the-scratch/gcp-everything-you-need-to-know-to-setup-firebase-and-gcp-emulators-part-2-1c2e07da76d9">[GCP] Everything you need to know to setup Firebase and GCP emulators — Part 2</a></p><h3>Installing Emulators —</h3><h4>Firebase</h4><p>If you haven’t setup your firebase project already in your working directory, go ahead and do it with the command —</p><pre>firebase init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZSqewFEQ_OSHB33UHjJRQ.png" /></figure><p>You can install the emulators while initialising your firebase project or later with the command —</p><pre>firebase init emulators</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8rT2_DaTOc0oF_kh-QxKw.png" /></figure><p>Firebase CLI provides 5 emulators to install. You can install whatever emulators you like from the list. After installing the emulators, in your firebase project directory, you can see <strong>firebase.json</strong> file. That contains all the info about your emulators. You can change the port numbers and path to your rules json files.</p><h4>Note: Firebase and GCP offers same emulators for pubsub and firestore. You can install it using either one of them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvOQILT84LW3eWhqpJh0Lw.png" /><figcaption>firebase.json</figcaption></figure><p><strong>Note</strong>: I have intentionally skipped installing <strong>Hosting</strong> emulator. You’ll know why in a moment.</p><p>To run the firebase emulators —</p><pre># To start all emulators<br>firebase emulators:start</pre><pre># To start only selected emulators<br>firebase emulators:start --only functions firestore [other emulators]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHtqFvQJOb_bo3VOtKqymQ.png" /></figure><p>Let’s go through each one of them —</p><ol><li>It shows the list of emulators started</li><li>Do you still remember that I didn’t setup a Hosting emulator? This is what I want to show you. Firebase CLI is kind enough to warn that “Hey! for whatever reason, you are not running [this] emulator. So, be careful as your test runs will hit your production servers”</li><li>Those are the logging files for each emulator</li><li>These URLs are the cloud functions URLs for your local emulator. These can be used to call your cloud functions from client side code.</li><li>This one uses “triggers”. I have setup a function trigger to be run after every upload to Cloud Storage. The thing is, firebase doesn’t provide a Cloud Storage emulator, so the cloud function is being ignored. If you have a Cloud Firestore triggers, it will be executed only if you enable the Cloud Firestore emulator.</li><li>You can visit the mentioned URL to visit the UI of Firebase Emulators.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dv7fXzt_07g5cm2TJzvdqg.png" /><figcaption>Firebase Emulator Suite UI</figcaption></figure><p>If you look at the image carefully, you can see <strong>Firestore</strong> and <strong>Realtime Database</strong> tabs. You can use those tabs to insert or view your data just like you do it in the <strong>Firebase Console</strong>.</p><p>But there is a bug in Firestore UI where the data is being written from the Firebase SDKs but you can’t see the data visually. I have commented a workaround on this bug. Check out if you experience the same bug —</p><p><a href="https://github.com/firebase/firebase-tools/issues/2322#issuecomment-643653196">Firebase real time database at local emulator is not showing updated data · Issue #2322 · firebase/firebase-tools</a></p><p>For example if you have created a document at the path in your code —</p><pre>list/users/1003/details</pre><p>Then create a dummy document in the same path through Emulator UI —</p><pre>list/users/dummy</pre><p>Now you can see your original data.</p><p><a href="https://firebase.google.com/docs/emulator-suite/install_and_configure">Install, configure and integrate Local Emulator Suite | Firebase Local Emulator Suite</a></p><p>Now we are done with Installing all Firebase specific emulators. Let’s move on to using the emulators.</p><h3>Using Emulators</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cefssyz0gsbR5FoaArZLMw.gif" /></figure><h4>The above visualisation should be self explanatory on how the emulator works.</h4><h3>Firebase</h3><p>There are 2 cases you have to consider while using firebase emulators in your code —</p><ol><li>Client-side code accessing Firebase products</li><li>Server-side code accessing Firebase products</li></ol><h4>Firebase Client-side code —</h4><p>If you are using Firebase products, you can access the backend directly from the client code using Firebase Client SDKs.</p><p>There is one important step to follow to make sure the Firebase Client SDKs are hitting emulators — <strong>Point the Firebase Client SDK to your localhost:port</strong>.</p><h4>Firebase Functions:</h4><p>In Firebase Functions, there are 3 types to invoke a function:</p><ol><li>Callable Functions</li><li>HTTPS Functions</li><li>Trigger Functions</li></ol><h4>Callable Functions:</h4><p>While initialising the functions, pass the localhost:port</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%28160%252C160%252C235%252C0%29%26t%3Dmaterial%26wt%3Dnone%26l%3Djavascript%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2520Code%26fs%3D14px%26lh%3D152%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252F%25252F%252520Firebase%252520App%252520%28the%252520core%252520Firebase%252520SDK%29%252520is%252520always%252520required%252520and%25250A%25252F%25252F%252520must%252520be%252520listed%252520before%252520other%252520Firebase%252520SDKs%25250Avar%252520firebase%252520%25253D%252520require%28%252522firebase%25252Fapp%252522%29%25253B%25250A%25250A%25252F%25252F%252520Add%252520the%252520Firebase%252520products%252520that%252520you%252520want%252520to%252520use%25250Arequire%28%252522firebase%25252Ffunctions%252522%29%25253B%25250A%25250Afirebase.initializeApp%28%25257B%25250A%252520%252520apiKey%25253A%252520%2527%252523%252523%252523%252520FIREBASE%252520API%252520KEY%252520%252523%252523%252523%2527%25252C%25250A%252520%252520authDomain%25253A%252520%2527%252523%252523%252523%252520FIREBASE%252520AUTH%252520DOMAIN%252520%252523%252523%252523%2527%25252C%25250A%252520%252520projectId%25253A%252520%2527%252523%252523%252523%252520CLOUD%252520FUNCTIONS%252520PROJECT%252520ID%252520%252523%252523%252523%2527%25250A%252520%252520databaseURL%25253A%252520%2527https%25253A%25252F%25252F%252523%252523%252523%252520YOUR%252520DATABASE%252520NAME%252520%252523%252523%252523.firebaseio.com%2527%25252C%25250A%25257D%29%25253B%25250A%25250A%25252F%25252F%252520Initialize%252520Cloud%252520Functions%252520through%252520Firebase%25250Aconst%252520functions%252520%25253D%252520firebase.functions%28%29%25253B%25250Aif%28location.hostname%252520%25253D%25253D%25253D%252520%2527localhost%2527%29%25250A%252520%252520functions.useFunctionsEmulator%28%252522http%25253A%25252F%25252Flocalhost%25253A5001%252522%29%25250A%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%28160%25252C160%25252C235%25252C0%29%26t%3Dmaterial%26wt%3Dnone%26l%3Djavascript%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%252520Code%26fs%3D14px%26lh%3D152%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525252F%2525252F%25252520Firebase%25252520App%25252520%28the%25252520core%25252520Firebase%25252520SDK%29%25252520is%25252520always%25252520required%25252520and%2525250A%2525252F%2525252F%25252520must%25252520be%25252520listed%25252520before%25252520other%25252520Firebase%25252520SDKs%2525250Avar%25252520firebase%25252520%2525253D%25252520require%28%25252522firebase%2525252Fapp%25252522%29%2525253B%2525250A%2525250A%2525252F%2525252F%25252520Add%25252520the%25252520Firebase%25252520products%25252520that%25252520you%25252520want%25252520to%25252520use%2525250Arequire%28%25252522firebase%2525252Ffunctions%25252522%29%2525253B%2525250A%2525250Afirebase.initializeApp%28%2525257B%2525250A%25252520%25252520apiKey%2525253A%25252520%252527%25252523%25252523%25252523%25252520FIREBASE%25252520API%25252520KEY%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520authDomain%2525253A%25252520%252527%25252523%25252523%25252523%25252520FIREBASE%25252520AUTH%25252520DOMAIN%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520projectId%2525253A%25252520%252527%25252523%25252523%25252523%25252520CLOUD%25252520FUNCTIONS%25252520PROJECT%25252520ID%25252520%25252523%25252523%25252523%252527%2525250A%25252520%25252520databaseURL%2525253A%25252520%252527https%2525253A%2525252F%2525252F%25252523%25252523%25252523%25252520YOUR%25252520DATABASE%25252520NAME%25252520%25252523%25252523%25252523.firebaseio.com%252527%2525252C%2525250A%2525257D%29%2525253B%2525250A%2525250A%2525252F%2525252F%25252520Initialize%25252520Cloud%25252520Functions%25252520through%25252520Firebase%2525250Aconst%25252520functions%25252520%2525253D%25252520firebase.functions%28%29%2525253B%2525250Aif%28location.hostname%25252520%2525253D%2525253D%2525253D%25252520%252527localhost%252527%29%2525250A%25252520%25252520functions.useFunctionsEmulator%28%25252522http%2525253A%2525252F%2525252Flocalhost%2525253A5001%25252522%29%2525250A%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdbed54799a2d47a77df1e4a0fee1869/href">https://medium.com/media/fdbed54799a2d47a77df1e4a0fee1869/href</a></iframe><p><strong>Link</strong>:</p><ul><li><a href="https://firebase.google.com/docs/functions/callable#initialize_the_client_sdk">Call functions from your app | Firebase</a></li><li><a href="https://firebase.google.com/docs/emulator-suite/connect_functions#callable_functions">Connect your app to the Cloud Functions Emulator | Firebase</a></li></ul><h4>HTTPS Functions:</h4><p>If you are using axios, fetch etc type of libraries to run the functions, use the URL returned by the Firebase CLI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oELFXqIlGeY3a3tIFXikcQ.png" /></figure><p>Use the URL returned by Firebase CLI tool like mentioned in 4.</p><h4>Trigger Functions:</h4><p>There is no setup required for using trigger functions.</p><h4>Firebase Firestore:</h4><p>While initialising the Firestore, pass an object to point it to the localhost —</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%28160%252C160%252C235%252C0%29%26t%3Dmaterial%26wt%3Dnone%26l%3Djavascript%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2520Code%26fs%3D14px%26lh%3D152%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252F%25252F%252520Firebase%252520App%252520%28the%252520core%252520Firebase%252520SDK%29%252520is%252520always%252520required%252520and%25250A%25252F%25252F%252520must%252520be%252520listed%252520before%252520other%252520Firebase%252520SDKs%25250Avar%252520firebase%252520%25253D%252520require%28%252522firebase%25252Fapp%252522%29%25253B%25250A%25250A%25252F%25252F%252520Add%252520the%252520Firebase%252520products%252520that%252520you%252520want%252520to%252520use%25250Arequire%28%252522firebase%25252Ffirestore%252522%29%25253B%25250A%25250Afirebase.initializeApp%28%25257B%25250A%252520%252520apiKey%25253A%252520%2527%252523%252523%252523%252520FIREBASE%252520API%252520KEY%252520%252523%252523%252523%2527%25252C%25250A%252520%252520authDomain%25253A%252520%2527%252523%252523%252523%252520FIREBASE%252520AUTH%252520DOMAIN%252520%252523%252523%252523%2527%25252C%25250A%252520%252520projectId%25253A%252520%2527%252523%252523%252523%252520CLOUD%252520FUNCTIONS%252520PROJECT%252520ID%252520%252523%252523%252523%2527%25252C%25250A%252520%252520databaseURL%25253A%252520%2527https%25253A%25252F%25252F%252523%252523%252523%252520YOUR%252520DATABASE%252520NAME%252520%252523%252523%252523.firebaseio.com%2527%25252C%25250A%25257D%29%25253B%25250A%25250A%25252F%25252F%252520Initialize%252520Cloud%252520Firestore%252520through%252520Firebase%25250Alet%252520db%252520%25253D%252520firebase.firestore%28%29%25253B%25250Aif%28location.hostname%252520%25253D%25253D%25253D%252520%2527localhost%2527%29%252520%25257B%25250A%252509db.settings%28%25257B%25250A%252520%252520%252520%252520host%25253A%252520%252522localhost%25253A8080%252522%25252C%25250A%252520%252520%252520%252520ssl%25253A%252520false%25250A%252520%252520%25257D%29%25253B%25250A%25257D%25250Aelse%252520%25257B%25250A%252509db%252520%25253D%252520firebase.firestore%28%29%25253B%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%28160%25252C160%25252C235%25252C0%29%26t%3Dmaterial%26wt%3Dnone%26l%3Djavascript%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%252520Code%26fs%3D14px%26lh%3D152%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525252F%2525252F%25252520Firebase%25252520App%25252520%28the%25252520core%25252520Firebase%25252520SDK%29%25252520is%25252520always%25252520required%25252520and%2525250A%2525252F%2525252F%25252520must%25252520be%25252520listed%25252520before%25252520other%25252520Firebase%25252520SDKs%2525250Avar%25252520firebase%25252520%2525253D%25252520require%28%25252522firebase%2525252Fapp%25252522%29%2525253B%2525250A%2525250A%2525252F%2525252F%25252520Add%25252520the%25252520Firebase%25252520products%25252520that%25252520you%25252520want%25252520to%25252520use%2525250Arequire%28%25252522firebase%2525252Ffirestore%25252522%29%2525253B%2525250A%2525250Afirebase.initializeApp%28%2525257B%2525250A%25252520%25252520apiKey%2525253A%25252520%252527%25252523%25252523%25252523%25252520FIREBASE%25252520API%25252520KEY%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520authDomain%2525253A%25252520%252527%25252523%25252523%25252523%25252520FIREBASE%25252520AUTH%25252520DOMAIN%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520projectId%2525253A%25252520%252527%25252523%25252523%25252523%25252520CLOUD%25252520FUNCTIONS%25252520PROJECT%25252520ID%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520databaseURL%2525253A%25252520%252527https%2525253A%2525252F%2525252F%25252523%25252523%25252523%25252520YOUR%25252520DATABASE%25252520NAME%25252520%25252523%25252523%25252523.firebaseio.com%252527%2525252C%2525250A%2525257D%29%2525253B%2525250A%2525250A%2525252F%2525252F%25252520Initialize%25252520Cloud%25252520Firestore%25252520through%25252520Firebase%2525250Alet%25252520db%25252520%2525253D%25252520firebase.firestore%28%29%2525253B%2525250Aif%28location.hostname%25252520%2525253D%2525253D%2525253D%25252520%252527localhost%252527%29%25252520%2525257B%2525250A%25252509db.settings%28%2525257B%2525250A%25252520%25252520%25252520%25252520host%2525253A%25252520%25252522localhost%2525253A8080%25252522%2525252C%2525250A%25252520%25252520%25252520%25252520ssl%2525253A%25252520false%2525250A%25252520%25252520%2525257D%29%2525253B%2525250A%2525257D%2525250Aelse%25252520%2525257B%2525250A%25252509db%25252520%2525253D%25252520firebase.firestore%28%29%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/14d831b9d77fbcd42428f30ee51d1e03/href">https://medium.com/media/14d831b9d77fbcd42428f30ee51d1e03/href</a></iframe><p><strong>Link</strong>:</p><p><a href="https://firebase.google.com/docs/emulator-suite/connect_firestore">Connect your app to the Cloud Firestore Emulator | Firebase</a></p><h4>Firebase Realtime Database:</h4><p>While initialising the Firebase object, pass an object to point it to the localhost —</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%28160%252C160%252C235%252C0%29%26t%3Dmaterial%26wt%3Dnone%26l%3Djavascript%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2520Code%26fs%3D14px%26lh%3D152%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252F%25252F%252520Firebase%252520App%252520%28the%252520core%252520Firebase%252520SDK%29%252520is%252520always%252520required%252520and%25250A%25252F%25252F%252520must%252520be%252520listed%252520before%252520other%252520Firebase%252520SDKs%25250Avar%252520firebase%252520%25253D%252520require%28%252522firebase%25252Fapp%252522%29%25253B%25250A%25250A%25252F%25252F%252520Add%252520the%252520Firebase%252520products%252520that%252520you%252520want%252520to%252520use%25250Arequire%28%252522firebase%25252Fdatabase%252522%29%25253B%25250A%25250Avar%252520firebaseConfig%252520%25253D%252520null%25253B%25250A%25252F%25252F%252520Initialize%252520Realtime%252520Database%252520through%252520Firebase%25250Aif%252520%28location.hostname%252520%25253D%25253D%25253D%252520%252522localhost%252522%29%252520%25257B%25250A%25250A%252520%252520firebaseConfig%252520%25253D%252520%25257B%25250A%252520%252520%252520%252520apiKey%25253A%252520%2527%252523%252523%252523%252520FIREBASE%252520API%252520KEY%252520%252523%252523%252523%2527%25252C%25250A%252520%252520%252509authDomain%25253A%252520%2527%252523%252523%252523%252520FIREBASE%252520AUTH%252520DOMAIN%252520%252523%252523%252523%2527%25252C%25250A%252520%252520%252509projectId%25253A%252520%2527%252523%252523%252523%252520CLOUD%252520FUNCTIONS%252520PROJECT%252520ID%252520%252523%252523%252523%2527%25252C%25250A%252520%252520%252520%252520%25252F%25252F%252520Point%252520to%252520the%252520RTDB%252520emulator%252520running%252520on%252520localhost.%25250A%252520%252520%252520%252520%25252F%25252F%252520In%252520almost%252520all%252520cases%252520the%252520ns%252520%28namespace%29%252520is%252520your%252520project%252520ID.%25250A%252520%252520%252520%252520databaseURL%25253A%252520%252522http%25253A%25252F%25252Flocalhost%25253A9000%25253Fns%25253DYOUR_DATABASE_NAMESPACE%252522%25250A%252520%252520%25257D%25250A%25257D%252520%25250Aelse%252520%25257B%25250A%252520%252520firebaseConfig%252520%25253D%252520%25257B%25250A%252520%252520%252520%252520apiKey%25253A%252520%2527%252523%252523%252523%252520FIREBASE%252520API%252520KEY%252520%252523%252523%252523%2527%25252C%25250A%252520%252520%252509authDomain%25253A%252520%2527%252523%252523%252523%252520FIREBASE%252520AUTH%252520DOMAIN%252520%252523%252523%252523%2527%25252C%25250A%252520%252520%252509projectId%25253A%252520%2527%252523%252523%252523%252520CLOUD%252520FUNCTIONS%252520PROJECT%252520ID%252520%252523%252523%252523%2527%25252C%25250A%252520%252520%252509databaseURL%25253A%252520%2527https%25253A%25252F%25252F%252523%252523%252523%252520YOUR%252520DATABASE%252520NAME%252520%252523%252523%252523.firebaseio.com%2527%25252C%25250A%252520%252520%25257D%25250A%25257D%25250A%25250Avar%252520myApp%252520%25253D%252520firebase.initializeApp%28firebaseConfig%29%25253B%25250Avar%252520db%252520%25253D%252520myApp.database%28%29%25253B%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%28160%25252C160%25252C235%25252C0%29%26t%3Dmaterial%26wt%3Dnone%26l%3Djavascript%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%252520Code%26fs%3D14px%26lh%3D152%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525252F%2525252F%25252520Firebase%25252520App%25252520%28the%25252520core%25252520Firebase%25252520SDK%29%25252520is%25252520always%25252520required%25252520and%2525250A%2525252F%2525252F%25252520must%25252520be%25252520listed%25252520before%25252520other%25252520Firebase%25252520SDKs%2525250Avar%25252520firebase%25252520%2525253D%25252520require%28%25252522firebase%2525252Fapp%25252522%29%2525253B%2525250A%2525250A%2525252F%2525252F%25252520Add%25252520the%25252520Firebase%25252520products%25252520that%25252520you%25252520want%25252520to%25252520use%2525250Arequire%28%25252522firebase%2525252Fdatabase%25252522%29%2525253B%2525250A%2525250Avar%25252520firebaseConfig%25252520%2525253D%25252520null%2525253B%2525250A%2525252F%2525252F%25252520Initialize%25252520Realtime%25252520Database%25252520through%25252520Firebase%2525250Aif%25252520%28location.hostname%25252520%2525253D%2525253D%2525253D%25252520%25252522localhost%25252522%29%25252520%2525257B%2525250A%2525250A%25252520%25252520firebaseConfig%25252520%2525253D%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520apiKey%2525253A%25252520%252527%25252523%25252523%25252523%25252520FIREBASE%25252520API%25252520KEY%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520%25252509authDomain%2525253A%25252520%252527%25252523%25252523%25252523%25252520FIREBASE%25252520AUTH%25252520DOMAIN%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520%25252509projectId%2525253A%25252520%252527%25252523%25252523%25252523%25252520CLOUD%25252520FUNCTIONS%25252520PROJECT%25252520ID%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520%25252520%25252520%2525252F%2525252F%25252520Point%25252520to%25252520the%25252520RTDB%25252520emulator%25252520running%25252520on%25252520localhost.%2525250A%25252520%25252520%25252520%25252520%2525252F%2525252F%25252520In%25252520almost%25252520all%25252520cases%25252520the%25252520ns%25252520%28namespace%29%25252520is%25252520your%25252520project%25252520ID.%2525250A%25252520%25252520%25252520%25252520databaseURL%2525253A%25252520%25252522http%2525253A%2525252F%2525252Flocalhost%2525253A9000%2525253Fns%2525253DYOUR_DATABASE_NAMESPACE%25252522%2525250A%25252520%25252520%2525257D%2525250A%2525257D%25252520%2525250Aelse%25252520%2525257B%2525250A%25252520%25252520firebaseConfig%25252520%2525253D%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520apiKey%2525253A%25252520%252527%25252523%25252523%25252523%25252520FIREBASE%25252520API%25252520KEY%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520%25252509authDomain%2525253A%25252520%252527%25252523%25252523%25252523%25252520FIREBASE%25252520AUTH%25252520DOMAIN%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520%25252509projectId%2525253A%25252520%252527%25252523%25252523%25252523%25252520CLOUD%25252520FUNCTIONS%25252520PROJECT%25252520ID%25252520%25252523%25252523%25252523%252527%2525252C%2525250A%25252520%25252520%25252509databaseURL%2525253A%25252520%252527https%2525253A%2525252F%2525252F%25252523%25252523%25252523%25252520YOUR%25252520DATABASE%25252520NAME%25252520%25252523%25252523%25252523.firebaseio.com%252527%2525252C%2525250A%25252520%25252520%2525257D%2525250A%2525257D%2525250A%2525250Avar%25252520myApp%25252520%2525253D%25252520firebase.initializeApp%28firebaseConfig%29%2525253B%2525250Avar%25252520db%25252520%2525253D%25252520myApp.database%28%29%2525253B%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/232b2a4ae0e6a113fb6145c82b3aa94e/href">https://medium.com/media/232b2a4ae0e6a113fb6145c82b3aa94e/href</a></iframe><p><strong>Link</strong>:</p><p><a href="https://firebase.google.com/docs/emulator-suite/connect_rtdb">Connect your app to the Realtime Database Emulator | Firebase</a></p><h4>Firebase Server-side code —</h4><p>If you are using Firebase admin SDK to interact with the firebase products then the good news is, you don’t have to do any additional work to make it work with the Firebase Emulators.</p><p>Remember the firebase.json? It is used by the Firebase admin SDK to find out in which port our emulators are running. If any emulator is not running, then Firebase admin SDK hits your production server (remember the warning about Hosting emulator not running while starting the emulator?). If the emulator is running, then the SDK hits your emulator. How convenient ❤️</p><h3>That’s it</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fb5Cj0cAsg3buE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fb5Cj0cAsg3buE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fb5Cj0cAsg3buE%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="434" frameborder="0" scrolling="no"><a href="https://medium.com/media/099de03ebf0fda891e36325058f4f578/href">https://medium.com/media/099de03ebf0fda891e36325058f4f578/href</a></iframe><p>You must be feeling tired going through all those commands, codes and links.</p><p>So, go ahead and bookmark it and don’t be selfish! Share it with fellow developers to help them out</p><p>Want to contact me? <a href="http://twitter.com/@SkrewEverything">Twitter.com/@SkrewEverything</a>.</p><p>Found any mistakes or got anything to say? Comment down below.</p><p>Liked it? 👏👏👏 it ( come on! If I can spend this much time to write then you can spend few seconds to clap it 50 times 🤷) and Share it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9be3c9f10929" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/firebase-everything-you-need-to-know-to-setup-firebase-and-gcp-emulators-part-1-9be3c9f10929">[Firebase] Everything you need to know to setup Firebase and GCP emulators — Part 1</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Engineering 101: Time zones and Working with Dates]]></title>
            <link>https://medium.com/from-the-scratch/software-engineering-101-time-zones-and-working-with-dates-a138364ac769?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a138364ac769</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 14:54:09 GMT</pubDate>
            <atom:updated>2020-08-15T14:54:09.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KN10q70LLfQW3GRevWm6MQ.png" /><figcaption>GMT +00:00</figcaption></figure><p>There are some things which every software engineer should know but unfortunately it is not taught in the schools. <strong>One of them is: Time Zones and Working with Dates.</strong></p><h3>Software Engineering 101 Series —</h3><ol><li><a href="https://medium.com/from-the-scratch/software-engineering-101-stuffing-multiple-values-into-a-single-64bit-value-50aebe396559">Stuffing multiple values into a single 64bit value</a></li><li>Time Zones and Working with Dates(<em>you are here</em>)</li></ol><p>The most important thing in any app with a database is about getting the dates and timestamps right. You might not experience any problems when your app only caters single timezone, but if your app is used by people all around the world, you need to be very careful about getting the dates and timestamps right for your users who are in different time zones around the world.</p><p>There are 2 different types to mark an instant of time —</p><ol><li>Timestamp</li><li>Datetime</li></ol><h3>Timestamp —</h3><p><strong>Epoch</strong>, also known as <strong>Unix timestamps</strong>, is the number of <strong>seconds</strong> (not milliseconds!) that have elapsed since <strong>January 1, 1970 at 00:00:00 GMT</strong> (1970–01–01 00:00:00 GMT).</p><p>You might be thinking why <strong>January 1, 1970 at 00:00:00 GMT</strong> is the starting point in computer systems. Well, I could explain why but it completely deviates from the context of our article. So, below links have all the details about “why”.</p><ul><li><a href="https://stackoverflow.com/q/2533563/4859791">Why are dates calculated from January 1st, 1970?</a></li><li><a href="https://stackoverflow.com/q/1090869/4859791">Why is 1/1/1970 the &quot;epoch time&quot;?</a></li></ul><p>Another important thing is — <strong>Unix Epoch Common, But Not Dominant</strong>. There are many epochs which are used by various fields. If you are interested to know about them, follow the below link —</p><p><a href="https://stackoverflow.com/a/26391999/4859791">Why are dates calculated from January 1st, 1970?</a></p><p>But the most crucial thing to remember is, it is gonna work only till <strong>January 09, 2038 03:14:07 GMT </strong>(2038–01–09 03:14:07 GMT). Why? Because in most of the systems Unix timestamps use signed 32-bit wide integer to represent the seconds. This is known as <a href="https://en.wikipedia.org/wiki/Year_2038_problem"><strong>Year 2038 problem</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*k2-G9NVw7p1HhIfSdruZtg.gif" /><figcaption>Year 2038 problem visualization from <a href="https://en.wikipedia.org/wiki/Year_2038_problem">Wikipedia</a></figcaption></figure><p>Although default unix timestamps are signed 32-bit integers, programming languages like Java can return a timestamp with a 64-bit integers. But most of the softwares like MySQL still uses the signed 32-bit integers to represent timestamps and it will return 0 after 03:14:07 UTC on 19 January 2038.</p><p>More about this MySQL behaviour below —</p><p><a href="https://bugs.mysql.com/bug.php?id=12654">MySQL Bugs: #12654: 64-bit unix timestamp is not supported in MySQL functions</a></p><p>But it won’t be a problem if you are using a 64-bit systems, because by the time 2038 year arrives, it will be shifted to signed 64-bit integer by major software providers. The problem will be with the embedded systems which use 32-bit systems like military, aviation etc. More about that below —</p><p><a href="https://en.wikipedia.org/wiki/Year_2038_problem#Vulnerable_systems">Year 2038 problem</a></p><blockquote>The problem you should be anticipating as a Software Engineer is when you want to work with or store a time after January 09, 2038 or before January 01, 1970.</blockquote><p>This problem has been <a href="https://en.wikipedia.org/wiki/Year_2038_problem#Early_problems">experienced by AOLServer in 2006</a>:</p><blockquote>In May 2006, reports surfaced of an early manifestation of the Y2038 problem in the <a href="https://en.wikipedia.org/wiki/AOLserver">AOLserver</a> software. The software was designed with a <a href="https://en.wikipedia.org/wiki/Kludge">kludge</a> to handle a database request that should “never” time out. Rather than specifically handling this special case, the initial design simply specified an arbitrary time-out date in the future. The default configuration for the server specified that the request should time out after one billion seconds. One billion seconds (approximately 32 years) after 01:27:28 UTC on 13 May 2006 is beyond the 2038 cutoff date. Thus, after this time, the time-out calculation overflowed and returned a date that was actually in the past, causing the software to crash. When the problem was discovered, AOLServer operators had to edit the configuration file and set the time-out to a lower value.</blockquote><blockquote>Players of games or apps which are programmed to impose waiting periods are running into this problem when they attempt to work around the waiting period on devices which harbor the coding, by manually setting their devices to a date past 19 January 2038, but are unable to do so, since a 32-bit Unix time format is being used.</blockquote><blockquote>Remember: Only use the timestamps if and only if you want to store the current date and time. Don’t use it to work on or to store future or past explicitly</blockquote><h3>DateTime —</h3><p>Datetime is used to store the exact date and/or time, like a string. Unlike timestamp, which always stores in UTC, datetime has its own time zone. So, you need to be careful while storing a datetime.</p><p>Datetime can be in the form “<strong>YYYY-MM-DD</strong>” or “<strong>YYYY-MM-DD HH:MM:SS</strong>”. Though the name suggests it stores date and time together, you can store only the date also by making “<strong>HH:MM:SS</strong>” all zeros like — “<strong>YYYY-MM-DD 00:00:00</strong>”</p><p>As I already told you, datetime values are stored just like a string literals without any information about the time zone it belongs. For example, if you store the datetime in New York and then access it from Tokyo, then the datetime will represent the New York’s time zone, without any explicit info that it is a New York’s time zone. So, unless the person who is storing the datetime provides the time zone info, nobody can know about the time zone used to store it for sure.</p><blockquote>Remember: Always store datetime in UTC! Never store it in your local or any other time zone</blockquote><p>Always storing the datetime in UTC makes it very easy to reason and when you want to display it to your users, just convert from UTC to local time zone.</p><blockquote>One more advantage of saving in UTC is — there is no confusion about Daylight Savings.</blockquote><h3>UTC/GMT/Zulu —</h3><p>If you are not familiar with dealing time zones, you might be wondering what is UTC/GMT.</p><p><strong>UTC stands for Universal Time Coordinated, and it’s the primary time standard by which the world regulates clocks and time.</strong> UTC use to be called Greenwich Mean Time (GMT), but still is in English speaking countries, or Zulu Time (Z), which is used in plane and ship navigation. <strong>UTC is the time at the Prime Meridian (0° Longitude) given in hours and minutes on a 24 hour clock.</strong></p><p>To obtain your local time you need to subtract or add a certain number of hours from UTC depending on how many time zones you are away from Greenwich. The map below shows the standard difference from UTC time to local time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KlqfwBBF91h-0R1Y.png" /><figcaption><a href="https://community.windy.com/topic/7872/difference-between-utc-gmt-zulu-time-and-z">windy.com</a></figcaption></figure><p>To know more about the differences between UTC and GMT —</p><p><a href="https://www.thoughtco.com/zulu-time-and-coordinated-universal-time-3444435">Can You Tell Zulu Time Like A Meteorologist?</a></p><blockquote>The main difference you should be knowing as a software engineer between GMT and UTC is that UTC does not observe Daylight Saving Time</blockquote><h3>Zulu Time —</h3><p>You might have seen a datetime like <strong>2020–12–31T20:17:46.384Z</strong>.</p><h4>ISO 8601</h4><p>This format is defined by the sensible practical standard, <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.</p><p>The T separates the date portion from the time-of-day portion. The Z on the end means <a href="https://en.m.wikipedia.org/wiki/Coordinated_Universal_Time">UTC</a> (that is, an offset-from-UTC of zero hours-minutes-seconds). The Z is <a href="https://en.wikipedia.org/wiki/Coordinated_Universal_Time#Time_zones">pronounced “Zulu”</a>.</p><p><a href="https://stackoverflow.com/q/8405087/4859791">What is this date format? 2011-08-12T20:17:46.384Z</a></p><p>Zulu time zone is used by military services which usually means UTC. You can find other list of time zones used by military services around the world below, if you are curious but we only deal with “Zulu”.</p><p><a href="https://en.wikipedia.org/wiki/List_of_military_time_zones">List of military time zones</a></p><h3>Choosing a Time zone for your servers —</h3><p>This is a very important topic but most beginners don’t have enough knowledge.</p><blockquote>Always! Always keep your server’s time in UTC</blockquote><p>No matter in which time zone your server is in, always configure it to UTC. Because every software, program, programming language, logging systems etc like MySQL, MongoDB, Java, node(JavaScript) will return your server’s time when you ask for datetime or timestamp.</p><p>If you are having all your servers in a single time zone, then it doesn’t matter because you can infer about the default time zone based on your server’s region. But distributed servers across different regions will produce a lot of problems like <strong>out of order logs and data due to timestamps from different time zones and daylight savings</strong>.</p><h3>Summary—</h3><p>There is a famous rule while developing any program/software —</p><blockquote>Never trust any data coming from the user! Not even from your grandma… Always sanitize user inputs!</blockquote><p>Remember this even while storing info about date like when was the data created, posted or edited.</p><ol><li>Set all your servers’ time zone to UTC.</li><li>Always use the Server’s time to fill up metadata like created, edited, posted etc.</li><li>Always store the datetime in UTC time zone.</li><li>While displaying the datetime to the user, convert it to their local time zone at the application layer.</li><li>Never use timestamps to store past or future.</li><li>Try to use datetime format instead of timestamps as it makes visual debugging easy. With timestamp, you have to convert from seconds to date but datetime is like a string. So, if you find yourself accessing the raw values for debugging, then try to use datetime.</li></ol><p>Want to contact me? <a href="http://twitter.com/@SkrewEverything">Twitter.com/@SkrewEverything</a>.</p><p>Found any mistakes or got anything to say? Comment down below.</p><p>Liked it? 👏👏👏 it 50 times and Share it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a138364ac769" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/software-engineering-101-time-zones-and-working-with-dates-a138364ac769">Software Engineering 101: Time zones and Working with Dates</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Engineering 101: Stuffing multiple values into a single 64bit value]]></title>
            <link>https://medium.com/from-the-scratch/software-engineering-101-stuffing-multiple-values-into-a-single-64bit-value-50aebe396559?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/50aebe396559</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Tue, 11 Aug 2020 08:15:14 GMT</pubDate>
            <atom:updated>2020-08-15T16:34:55.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQjONNdWCkhlcwLg-AGApw.png" /></figure><p>There are some things which every software engineer should know but unfortunately it is not taught in the schools. <strong>One of them is: How to stuff multiple values into a single value.</strong></p><h3>Software Engineering 101 Series —</h3><ol><li>Stuffing multiple values into a single 64bit value (<em>you are here</em>)</li><li><a href="https://medium.com/from-the-scratch/software-engineering-101-time-zones-and-working-with-dates-a138364ac769">Time Zones and Working with Dates</a></li></ol><p>If you don’t know about this, you may be wondering</p><ol><li>How does that help?</li><li>Why can’t I use different variables for each value?</li><li>Why to complicate things unnecessarily? I have 8GiB of RAM, why should I care about saving 8 bytes?</li></ol><p>The main aim of stuffing multiple values into a single large value is not to save memory or decrease the number of variables in the program.</p><blockquote>The main aim is to encode multiple useful values into a single value to identify it uniquely, most of the time</blockquote><p>Instead of going into “<strong>how to do it</strong>” first, let’s take an unconventional route and first go into a use case to understand why it is needed and where you can use it. This can make you understand the “<strong>how to do it</strong>” intuitively.</p><h3>Use Case</h3><p>Let’s consider a scenario where this technique is used extensively, database sharding at application level.</p><p>Database sharding at an application level means the application itself knows where the data is residing among your swarm of database instances. Instead of having some kind of routing mechanism or hash tables to locate the data on the server, the application knows which database has the data it needs. This type of sharding doesn’t depend on the database you are using and doesn’t matter if the database doesn’t provide any sharding features like MySQL.</p><p>For example, you are just starting your website and designing a database for it. Normally, if you don’t have any natural key, you would use the auto-increment value as the primary key. And also you use that auto-incremented ID as a part of the url to map to the data(like how Stackoverflow does).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*meVfPlVPhUmDzIhFL2RhqA.png" /><figcaption>15505515 is the postID</figcaption></figure><p>After 1 year, your database server is struggling to catch up with the traffic requirements. To solve that, you have 2 options.</p><ol><li>Vertical Scaling</li><li>Horizontal Scaling</li></ol><p>Vertical Scaling is costly and finite. So, you want to opt for horizontal scaling but MySQL doesn’t provide horizontal scaling feature. So, you add a new MySQL instance to shard the data. Now, you need to find a new mapping to find the sharded data directly instead of searching all the instances.</p><p>This is where we can use the “<strong>stuffing multiple values into the single 64bit value</strong>” technique.</p><p>Before doing that, we need to do some things:</p><ol><li>Give every database shard a unique ID and call it as <strong>dbID</strong></li><li>Now, you already have auto-incremented <strong>postID</strong> for every row in a database.</li><li>Decide how many bits you want to allocate for each ID above. For example, you allocated 10 bits for <strong>dbID</strong> and 42 bits for <strong>postID</strong>.</li></ol><p>10 bits can store 2¹⁰ = 1024 values, 42 bits can store 2⁴² = 43,98,04,65,11,104</p><p>It means you can create 1024 shards and each shard can have 43,98,04,65,11,104 rows.</p><p>So, instead of identifying the post using the <strong>postID</strong>, you also need to identify shard i.e., <strong>dbID</strong>.</p><p>So, instead of encoding your url like “<strong>your_domain.com/posts/postID</strong>”, we encode it like “<strong>your_domain.com/posts/newID</strong>”. Now, the <strong>newID</strong> contains the info about <strong>postID</strong> and <strong>dbID</strong> so that your app knows which shard to ask for the data directly without any middleware.</p><p>Now, we are going to encode <strong>postID</strong> and <strong>dbID</strong> into the <strong>newID</strong> like:</p><p><em>(I’m using Java, so Java’s Long is 63 bytes. Why is this important? We’ll see about it below in “</em><strong><em>how to do it</em></strong><em>”.)</em></p><p><strong><em>Disclaimer</em></strong><em>: Don’t be intimidated if you don’t know what it is. We will talk about how to do it after this.</em></p><pre>long dbID = 997;<br><em>long </em>postID = 8_04_65_11_104L;<br><em>long </em>newID = (dbID &lt;&lt; 53) | (postID &lt;&lt; 11);</pre><pre>System.out.println(&quot;newID: &quot; + newID);<br>System.out.println(&quot;dbID: &quot; + ((newID &gt;&gt; 53) &amp; 0x3FF))<br>System.out.println(&quot;postID: &quot; + ((newID &gt;&gt; 11) &amp; 0x3FFFFFFFFFFL));</pre><p>The output will be:</p><pre>newID: 8980194136231510016<br>dbID: 997 <br>postID: 8046511104</pre><p>So, now your new url can be “<strong>your_domain.com/posts/8980194136231510016</strong>” instead of “<strong>your_domain.com/posts/8046511104</strong>”</p><p>This “<strong>8980194136231510016</strong>” has the information about the <strong>shard ID</strong> and <strong>post ID</strong>.</p><p>This is called application level sharding because your application knows that postID: <strong>8046511104</strong> lives in database id: <strong>997</strong>. There is no need for middleware which needs to check in which database the postID: <strong>8046511104</strong> is.</p><p>I’m pretty sure that now you know why it is useful with a real-world use-case. Now, let’s see how it is done</p><h3>How to do it</h3><p>First and foremost thing you need to be careful about the size of Integer in your preferred language.</p><p>For example,</p><p>Javascript has only one type both for floating and integers i.e., Number. Javascript only uses 53 bits to store the integers but not 64 bits. In that 53 bits, 1 bit is used for sign. So, you can only use 52 bits to encode.</p><p>Java has “Long” type which can store 64 bit integers. But unlike C and C++, Java doesn’t have “unsigned”. So, you can only use 63 bits because 1 bit is used for sign.</p><p>So assume “<strong>B</strong>” is your number of bits you can use. In the example above, we have used Java, so <strong>B = 63</strong>.</p><p><strong>NOTE</strong>: Whatever you wanna encode, your sum of individual values in bits cannot exceed “<strong>B</strong>” and also only positive numbers are allowed</p><p>Let’s assume we want to store the following values in a single value:</p><ol><li>A with 15 bits — range can be from 0 to 32, 767 (2¹⁵-1)</li><li>B with 35 bits — range can be from 0 to 34,35,97,38,367 (2³⁵-1)</li><li>C with 10 bits — range can be from 0 to 1,023 (2¹⁰-1)</li><li>D with 3 bits — range can be from 0 to 7 (2³-1)</li><li>E with 1 bit — range can be from 0 and 1 (2¹-1)</li></ol><p>The sum of individual values in bits is 15 + 35 + 10 + 3 + 1 = 64 bits.</p><p>But our “<strong>B</strong>” is only 63. So, you have to let go any one of them to bring it below 64. We will let go “<strong>E</strong>” , which is 1 bit. Now, our sum of bits will be 63 bits, which is equal to “<strong>B</strong>”.</p><p>This is how we want to arrange all our values at the end</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_DOASKve_7TOhN0cEnglg.png" /><figcaption>visual representation of our 63 bits with various values</figcaption></figure><p>There are 2 parts for this.</p><ol><li>Encoding</li><li>Decoding</li></ol><h3>Encoding —</h3><h4>This is how “A” with 15 bits looks in a 63 bit data type:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofveMQe0lZsPAJFgkeAezg.png" /><figcaption>Visual representation of 15 bits in a 63 bits</figcaption></figure><p>We need to move all the 15 A ’s to the leftmost empty bit. We need to left shift by 63–15(<strong>A</strong>) = 48 bits</p><pre>A &lt;&lt; 48</pre><p>After the left shift, this is how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nM6nj_478P6WftxSVU36OQ.png" /><figcaption>Visual representation of 15 bits in a 63 bits after left shift by 48 bits</figcaption></figure><h4>This is how “B” with 35 bits looks in a 63 bit data type:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vng9Z5fe3kQDDx-HLMuiyw.png" /><figcaption>Visual representation of 35 bits in a 63 bits</figcaption></figure><p>If you look at the previous image, “<strong>A</strong>” has already occupied 15 bits from the left side. So, we need to shift all the 35 B’s where 15 A’s end.</p><p>We need to left shift by 63-15(<strong>A</strong>)-35 (<strong>B</strong>)= 13 bits</p><pre>B &lt;&lt; 13</pre><p>After the left shift, this is how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcwwVDMpKRmVoH23762zWw.png" /><figcaption>Visual representation of 35 bits in a 63 bits after left shift by 13 bits</figcaption></figure><h4>This is how “C” with 10 bits looks in a 63 bit data type:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iP4p-rpEOfalx-ipdTRaag.png" /><figcaption>Visual representation of 10 bits in a 63 bits</figcaption></figure><p>If you look at the previous image, “<strong>A</strong>” has already occupied 15 bits and “<strong>B</strong>” has already occupied 35 bits from the left side. So, we need to shift all the 10 C’s where 35 B’s end</p><p>We need to left shift by 63–15(<strong>A</strong>)–35(<strong>B</strong>)-10(<strong>C</strong>) = 3 bits</p><pre>C &lt;&lt; 3</pre><p>After the left shift, this is how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmf-0eTQit6D_QyzsGEnUg.png" /><figcaption>Visual representation of 10 bits in a 63 bits after left shift by 3 bits</figcaption></figure><h4>This is how “D” with 3 bits looks in a 63 bit data type:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqmmSDS_jN9-BiFUAB3aZA.png" /><figcaption>Visual representation of 3 bits in a 63 bits</figcaption></figure><p>If you look at the previous image, “<strong>A</strong>” has already occupied 15 bits, “<strong>B</strong>” has already occupied 35 bits and “<strong>C</strong>” has already occupied 10 bits from the left side. So, we need to shift all the 3 D’s where 10 C’s end</p><p>We need to left shift by 63–15(<strong>A</strong>)–35(<strong>B</strong>)-10(<strong>C</strong>)-3(<strong>D</strong>) = 0 bits</p><pre>D &lt;&lt; 0</pre><p>After the left shift, this is how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xz2mYUrIRwsI9Ycv3uvp9w.png" /><figcaption>Visual representation of 3 bits in a 63 bits after left shift by 0 bits</figcaption></figure><p>Now, we have all the “<strong>A</strong>”, “<strong>B</strong>”, “<strong>C</strong>”, “<strong>D</strong>” bits at their respective positions like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nM6nj_478P6WftxSVU36OQ.png" /><figcaption>(A &lt;&lt; 48)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcwwVDMpKRmVoH23762zWw.png" /><figcaption>(B &lt;&lt; 13)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmf-0eTQit6D_QyzsGEnUg.png" /><figcaption>(C &lt;&lt; 3)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xz2mYUrIRwsI9Ycv3uvp9w.png" /><figcaption>(D &lt;&lt; 0)</figcaption></figure><p>Now we want to combine these into one variable. The | operator works by looking at each bit, and returning 1 if the bit is 1 in either of the inputs. So:</p><pre>0011 | 0101 = 0111</pre><p>If a bit is 0 in one input, then you get the bit from the other input. Looking at (A &lt;&lt; 48), (B &lt;&lt; 13), (C &lt;&lt; 3)and (D &lt;&lt; 0) you&#39;ll see that, if a bit is 1 for one of these, it&#39;s 0 for the others. So:</p><pre>encodedValue = (A &lt;&lt; 48) | (B &lt;&lt; 13) | (C &lt;&lt; 3) | (D &lt;&lt; 0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_DOASKve_7TOhN0cEnglg.png" /><figcaption>encodedValue = (A &lt;&lt; 48) | (B &lt;&lt; 13) | (C &lt;&lt; 3) | (D &lt;&lt; 0)</figcaption></figure><p>Now that we have completed with the Encoding part, let’s get into Decoding part.</p><h3>Decoding —</h3><p>In encoding, we have used left shift( &lt;&lt; ) and OR( | ) but we use the opposite in decoding. We use right shift ( &gt;&gt; ) and AND ( &amp; ).</p><p>Now we want to unpack the bits. Let’s start with the D. We want to get the last 3 bits, and ignore the first 60 bits.</p><p>To do this, we use the &amp; operator, which returns 1 only if both of the input bits are 1. So:</p><pre>0011 &amp; 0101 = 0001</pre><blockquote>So, if you want to unpack only “n” bits from right side, you need to perform AND with “n” bits in which all the “n” bits should be 1.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldQNwytIUTqQLqJB1-PgLQ.png" /><figcaption>We got “D”</figcaption></figure><p>To get “<strong>C</strong>”, we need to right shift till it reaches the rightmost bit. Right shift “<strong>C</strong>” with the same number you have used to left shift during encoding and perform <strong>AND</strong> operation with 10 bits(because “<strong>C</strong>” is 10 bits) set to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPKSeHJSozsySbGfqz0oZw.png" /><figcaption>We got “C”</figcaption></figure><p>Keep performing the same thing for the rest of “<strong>B</strong>” and “<strong>A</strong>”.</p><p>Right shift “<strong>B</strong>” by 13 and perform <strong>AND</strong> operation with 35 bits(because “<strong>B</strong>” is 35 bits) set to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64PuoNk2mWcrwLsRPgW60g.png" /><figcaption>We got “B”</figcaption></figure><p>Right shift “<strong>A</strong>” by 48 bits and perform <strong>AND</strong> operation with 15 bits(because “<strong>A</strong>” is 15 bits) set to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DPETJbnt4Di5Cu694GE4w.png" /><figcaption>We got “A”</figcaption></figure><p>Now, we have decoded the single encoded value into their own individual values</p><pre>decodedD = (encodedValue &gt;&gt; 0)  &amp; 0x7<br>decodedC = (encodedValue &gt;&gt; 3)  &amp; 0x3FF<br>decodedB = (encodedValue &gt;&gt; 13) &amp; 0x7FFFFFFFF<br>decodedA = (encodedValue &gt;&gt; 48) &amp; 0x7FFF</pre><h3>The magic numbers —</h3><p>There is a very high probability that you must be wondering what is that Hex value and how to arrive at that particular value.</p><p>In many programming languages, you can use different radixs like 2(binary), 6(hexa), 8(octal) and 10(decimal) to represent numbers.</p><p>Here, we are using Hex to represent the numbers. Why? Because it is easy to represent multiple 1 in Hex than in any other radix systems.</p><p>For example, if you want a number which has 4 bits set to 1, then in binary it will be represented as 0b1111 and in hex it is represented as 0xF. If you don’t know Hexadecimal, then binary might be easy for you to write but you can’t write 48 1s in binary. But in Hex you can write it like 0xFFFFFFFFFFFF. Instead of writing 48 1s in binary system, we write 12 Fs in hexadecimal system.</p><p>So, if you don’t know how hexadecimal system works, you need to learn about that. It’s an interesting topic of its own.</p><p>Want to contact me? Contact me on <a href="http://twitter.com/@SkrewEverything">Twitter.com/@SkrewEverything</a>.</p><p>Found any mistakes? Comment down below.</p><p>Liked it? 👏👏👏 it and Share it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50aebe396559" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/software-engineering-101-stuffing-multiple-values-into-a-single-64bit-value-50aebe396559">Software Engineering 101: Stuffing multiple values into a single 64bit value</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My experience of breaking the claim of most secure OS, Apple macOS]]></title>
            <link>https://medium.com/from-the-scratch/my-experience-of-breaking-the-claim-of-most-secure-os-apple-macos-c3e7550164a4?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3e7550164a4</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 23:00:25 GMT</pubDate>
            <atom:updated>2020-07-07T13:13:40.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-6TT-rXY5198JFTBxqx5A.png" /><figcaption><a href="https://clipartart.com/">https://clipartart.com/</a></figcaption></figure><p>Apple constantly claims “<strong>macOS is the most secure operating system</strong>” and if you are an average user(just like my past self), then chances are you are in delusion just like younger me(well, I’m older and wiser now🧑‍🎓).</p><p>Apple repeats that phrase way too often that subconsciously we believe that macOS is indeed most secure operating system in the world. <strong>But the truth is:</strong> <strong>it is not so secure after all</strong>. macOS is just difficult to break for an average programmer but not impossible for any programmer who has enough time and intuition of where to look and what to do.</p><p>First, let me clear something. The reason why people think that windows is not secure is because it makes into the news most of the time whenever there was a virus attack around the world. But have you once stopped and considered why?</p><ol><li>Because many people use cracked versions of Microsoft Windows</li><li>Because many people install cracked versions of software</li><li>Because there are no restrictions/warnings when untrusted software is being installed</li></ol><p>So, how is Apple doing it differently?</p><ol><li>To begin with, macOS is free for macs. The major thing is, updates are also free since long time.</li><li>Using cracked version of macOS on non-macs(Hackintosh) is very tricky and buggy. So, most of them avoid it.</li><li>Unless you are an average user, you can’t even install softwares from unidentified sites and developers. Apple straight out blocks installation.</li></ol><p>So, now you can see why Windows is more susceptible to virus attacks.</p><h3>Another new feature coming in iOS 14 is, Apple notifies users what the app is doing behind the scenes</h3><h3></h3><p></p><p>I wonder how many developers in the world actually use a specific library intended to use the clipboard and a specific function to copy the contents **<strong>accidentally</strong>**🤔.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQxk593RbYQ6MCbWtTV%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQxk593RbYQ6MCbWtTV%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FQxk593RbYQ6MCbWtTV%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/95deb39e366047afcb7a518f1f0790be/href">https://medium.com/media/95deb39e366047afcb7a518f1f0790be/href</a></iframe><h4>And as usually, the Linkedin’s response was “It’s a bug”</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FcNNvWGiYWr31DsIhdx%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FcNNvWGiYWr31DsIhdx%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FcNNvWGiYWr31DsIhdx%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/7be9a07f030fce80419635529c65e757/href">https://medium.com/media/7be9a07f030fce80419635529c65e757/href</a></iframe><p>So, now you know how Apple is trying to secure its operating system. It is not secure by default. It just lets users decide and take control instead of letting users use it blindly. If you don’t know, in macOS, whenever an app tries to read a file from a directory, it asks for the user permission to allow it or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*efSOi3WA9kxT9hWO" /></figure><p>If android and windows used the same *features*, then both can also become a secure one.</p><h3>So, what exactly breaking a system mean?</h3><p>Well, to keep it simple, bypassing the system also comes under Breaking the system.</p><p>I wrote a Keylogger for macOS, which bypasses notifying users that it is being used in the settings and actually no password is required to run the keylogger.</p><p>For some of you who don’t know, macOS doesn’t prevent anyone from creating a keylogger. But to log the key strokes, the new APIs provided by the Apple comes under Accessibility functionality, which requires user password to run and the name of the app we are running in the Settings -&gt; Security &amp; Privacy section.</p><p>The below link takes you to some of known open source keyloggers for macOS on GitHub and you can try that and see. Everything requires the user password to actually run the app and it will be shown in the settings app.</p><p><a href="https://github.com/search?q=mac+keylogger">Build software better, together</a></p><p>Well, that’s a pretty good security from Apple.</p><h3>So, how did I break it?</h3><blockquote>The trick is simple to break/hack anything. Look at the past versions of the system and try to modify it to break the new updated system</blockquote><p>If the engineers are really good and actually had time, they would completely remove it from the systems. But most of the engineers don’t have enough time to remove it. So, as they are good, they just fix it on the surface level and forget about it later or if the functionality is tightly coupled with the systems then they remove every known documentation about it to restrict its further usage. And that’s what apple did. That API is one of the essential APIs and Apple cannot remove it completely. Instead they removed most of the documentation and archived it.</p><p>Usually, the API docs for old versions are not properly available on the internet. Most of the companies remove it. But once I coincidentally came across a website which conveniently archives every apple developer docs released, which is maintained by Apple itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l0Jvom0LT0FC00B-" /></figure><p>It has a total of <strong>5219</strong> documents, with the oldest one dated <strong>1985–03–01</strong> (That is some serious dedication of Apple towards its developers).</p><p>And going through one by one is not gonna happen. So, as a wannabe coder, I did what every wannabe coder does. Yes, I wrote a script to parse the contents of every document and flagged some documents with particular keywords which would likely appear in the developer docs which might help me to write a keylogger. Now, I reduced the number of documents from around <strong>5,000</strong> to about <strong>500</strong>. I can reduce further(by removing documents with low frequency of occurrences), but I don’t wanna take any chances. So, instead of reducing the number, I sorted the documents with the frequency of keywords and started going through one by one.</p><p>It probably took over a month to shortlist some documents which can help me to write a keylogger. It might sound stupid but once again I went through the new set of shortlisted documents to further shortlist.</p><p>Finally, after 3 months of going through those, I was left with 1 document. Uff… that was a hell of a journey to reach 1 document from 5,000 documents.</p><p>The document is: <a href="https://developer.apple.com/library/archive/technotes/tn2187/_index.html">Technical Note TN2187</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sl89kDBtVFQ2nDsc" /></figure><p>It was published on <strong>2007–12–18</strong> for developers to develop apps for Mac OS X 10.5 (Leopard)</p><p>The keywords that picked up this document is “<strong>USB</strong>” and “<strong>KEYBOARD</strong>”. Surprisingly, their occurrences in the document is:</p><ul><li>USB: <strong>6 times</strong></li><li>KEYBOARD: <strong>8 times</strong></li></ul><h4>If I had further reduced the number of documents by removing low frequency occurrences then I wouldn’t have came across this document for sure. I guess it’s time for another tip:</h4><blockquote>If you want to break a system, there are no shortcuts. You have to go through every single thing you got. You never know what you missed. Or the best thing to remember while coding anything is: <a href="https://en.wikipedia.org/wiki/Murphy%27s_law">Murphy’s Law</a></blockquote><p>Now, back to why you are here. That document is so old that, most of the links mentioned in that no longer exists. Everything is 404.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*Z4P8ZvNrbakTAJ_N" /></figure><p>Those links are very important because it clearly states that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFOsHFxF4xWlUKvTEt7PsQ.png" /></figure><p>So, now I don’t have any references to actually have the basic understanding about how to use this doc. To further complicate things, the docs are in Objective — C, which I have never touched.</p><blockquote>But the odds are on my side. I got plenty of time to waste and if you ask any programmer/engineer, they will say that anything could be built, given enough time.</blockquote><p>Without a further a due, I started coding it in Swift and logging every line of code to understand what’s it doing exactly. It took well over 2 weeks to decode everything and map every key code generated by that interface to the actual keyboard values.</p><blockquote>Finally, after 4 months of persistent work, I completed writing the code for my keylogger. It just took 420 lines of unoptimised code(I swear I did not plan to reach that exact number) to break the most secure OS, the macOS.</blockquote><h3>Link to the keylogger</h3><p>I open-sourced the keylogger on <strong>2017–02–01</strong> on GitHub. It became so popular that it was on the trending page of GitHub for multiple days world freaking wide.</p><p><a href="https://github.com/SkrewEverything/Swift-Keylogger">SkrewEverything/Swift-Keylogger</a></p><p>And don’t think it won’t steal passwords by seeing the below disclaimer in the Readme in my github link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynZ_CMda3OUVoGgE7z75rQ.png" /><figcaption><a href="https://github.com/SkrewEverything/Swift-Keylogger#disclaimer">https://github.com/SkrewEverything/Swift-Keylogger#disclaimer</a></figcaption></figure><p>It can also be bypassed very easily and putting it on the internet won’t be “<strong>for educational purpose</strong>” anymore, even if I state it explicitly in the documentation. So, I excluded it from the open-source.</p><h3>What is the current status of the project?</h3><p>Unfortunately, it doesn’t work anymore as initially intended on <strong>macOS Catalina (10.15 ),</strong> which was released on <strong>2019–10–07</strong></p><p>From <strong>10.15</strong> onwards, it asks for the user’s permission to run and it shows up in the <strong>Settings -&gt; Security &amp; Privacy -&gt; Privacy -&gt; Input Monitoring</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9MoFGREmO2_XXJqGPCDTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aluEAmABO99Xi8U2eyANYA.png" /><figcaption>New behaviour on macOS Catalina</figcaption></figure><p>But it still works perfectly fine till <strong>macOS Catalina</strong>, without requiring any permissions to run and also without showing up in the Settings app.</p><h3>But, am I sad that Apple fixed it?</h3><p>No, in fact I’m happy. It’s probably a good thing that Apple fixed this. It prevents so many clueless people from being spied on or protecting them from losing important stuff from their personal computers by sniffing.</p><p>For example, it stops <strong>Linkedin</strong> like corporations from spying on people and stealing data without their consent and when caught, they say “<strong><em>it’s a bug</em></strong>”</p><p>Hate Apple how much you want to hate for their expensive products or imposing “<strong>Apple Tax</strong>” on it’s customers but, when it comes to security and privacy, particularly in this age, it’s still worth to pay that “<strong>Apple Tax</strong>” to own Apple products, at least for important stuff.</p><p><em>**</em><strong><em>Inner me</em></strong><em>: I really hope Apple comes across this page and sponsors me for this post for talking good and promoting it🤞**</em></p><h3>Summary</h3><p>If you reached till here, you might be thinking is it really breaking the macOS?</p><p>To recap what I said in the beginning —</p><blockquote>Well, to keep it simple, bypassing the system also comes under Breaking the system.</blockquote><blockquote>I wrote a Keylogger for macOS, which bypasses notifying users that it is being used in the settings and actually no password is required to run the keylogger.</blockquote><blockquote>For some of you who don’t know, macOS doesn’t prevent anyone from creating a keylogger. But to log the key strokes, the new APIs provided by the Apple comes under Accessibility functionality, which requires user password to run and the name of the app we are running in the Settings -&gt; Security &amp; Privacy section.</blockquote><blockquote>So, yeah… I broke it 🤷</blockquote><p>Whether it’s <strong>Linux</strong>, <strong>Windows</strong>, <strong>macOS</strong> or any other Operating system, it doesn’t matter. Every OS has their fair share of never ending bugs. That’s why companies constantly release <strong>Security Updates</strong>.</p><p>The only thing <strong>Apple</strong> is doing differently is that they are providing maximum details about what the apps are doing to its customers. So, even if the OS fails to protect, users can at least see what’s happening and mitigate the damage ASAP. For example, people wouldn’t know how some companies are stealing data from the clipboard of the users if its not for <strong>iOS 14</strong>. Or my <strong>keylogger</strong> stealing from your mac.</p><blockquote><em>Liked it? Then 👏🏻👏🏻👏🏻 it and share it!</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*WCCZwN8IVU5sP2HO.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3e7550164a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/my-experience-of-breaking-the-claim-of-most-secure-os-apple-macos-c3e7550164a4">My experience of breaking the claim of most secure OS, Apple macOS</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hooks: A simple intuition if you still can’t hit it off]]></title>
            <link>https://medium.com/from-the-scratch/react-custom-hooks-a-simple-intuition-if-you-still-cant-hit-it-off-8d27fa4ba10?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d27fa4ba10</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 12:32:12 GMT</pubDate>
            <atom:updated>2020-04-18T12:32:12.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQ8ImOHesf_OetU9uLpOmQ.jpeg" /><figcaption><a href="https://www.wallpaperup.com/415502/baby_child_children_kids_glasses.html">Now I get it!</a></figcaption></figure><blockquote>Let’s be honest, React Hooks are awesome 😍 but confusing as hell 😵</blockquote><p>Previously, I’ve strictly used <strong>Class Components</strong> instead of <strong>Functional Components</strong> even if I didn’t need the <strong>lifecycles</strong> and <strong>state</strong> functionality as I’m lazy to refactor my code from <strong>functional component</strong> to <strong>class component</strong> if by any chance I ever wanted to introduce <strong>lifecycles</strong> or/and <strong>state</strong> functionalities in a component.</p><p>When <strong>React</strong> introduced <strong>Hooks</strong>, I was reluctant to use them as they were confusing, at least when I read the docs initially.</p><blockquote>But hey! Time makes everything better and Hooks are no exception</blockquote><p>What changed my mind? Well, boredom of this lockdown🥱. I was so bored that I gave another chance to <strong>Hooks</strong> and after creating a simple app while learning it, it kind off hit me in the head and now I can see everything around me in <strong>Hooks</strong>🧑🏻‍🎓.</p><blockquote>Ok, I was exaggerating for the effect.</blockquote><p>So, let’s look at some points, tips, explanations to understand Hooks as simple as possible.</p><h3>What are React Hooks anyway?</h3><p>It’s a new feature(well, not so new. It was released in 2018) to use lifecycles and states in <strong>Functional components</strong>.</p><p>Before the introduction of the Hooks, the only way to use lifecycles and states is through Class component.</p><h3>Why is everyone losing their minds over Hooks anyway?</h3><p>If you haven’t, then you have to look at these tweets from <strong>2018</strong> first.</p><h3>Sunil Pai on Twitter</h3><p>ok so - I took dan&#39;s classes/hooks code from react conf, blacked out the &#39;unnecessary&#39; bits, then colour coded bits by &#39;concern&#39;. so much nicer. the effect is amplified in more complex components, where concerns are split and mixed across lifecycle methods.</p><h3></h3><p></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*pTulpC_wXNl6LI2UXuM74Q.gif" /></figure><p>Got it why everyone is losing their minds over Hooks?</p><p>If you didn’t then let me tell you what’s going on in the above GIF.</p><p>The first part of the GIF uses Class Component and second part uses Functional Component with Hooks. And color codes are used to group lines based on their logic required to do THEIR THING.</p><p>If you observe, when using Class Component, the logic of the code is spread all over the component. But, when using Functional Component with Hooks, the logic of the code is confined to their own places.</p><p>This greatly increases developer productivity while reading through the code or debugging it. With Hooks, you don’t have to scroll your IDE to relevant sections of the code responsible for its job. If you want to know how a feature works, you just have to look at one place to make sense.</p><p>Also, the amount of code to write a component decreases significantly with Hooks as you don’t have to deal with “<strong>bind</strong>”ings, “<strong>constructors</strong>”, repeating code in different methods etc.</p><blockquote>The best thing about Hooks is: You can create and re-use your custom Hooks in other components, which reduces code duplication substantially.</blockquote><p>And also, one more trivial advantage is: you don’t have to shuffle between Class and Functional Components based on your needs. You can just learn Functional Components with Hooks and you can forget about Class Components all together. Unless, you have to maintain your old React code which was written in Classes. But, if you are starting a new project, then you can just write all your components using Functional Components and later if you need lifecycles and state, then use Hooks to introduce them into your already written Functional Component instead of refactoring it into Class Component.</p><blockquote>NOTE: If you are a beginner or starting to learn React, then start with the Class Components. Class Components are more detailed and explicit, which helps you to understand the concepts and how things work more concretely. After you grasp how React works, then you can shift to the Hooks.</blockquote><p>Before getting into the explanations and intuitions, I hope you know the basic syntax of the useState and useEffect .</p><p>If you don’t, then come back after learning the basic syntax. I can explain it though, but there are already numerous wonderful tutorials and articles on the basics of Hooks. Writing them provides no value and diverts the aim of this article, which is to get the intuition but not an another tutorial on Hooks.</p><p>The Facebook’s documentation is pretty good actually with some use-cases.</p><p><a href="https://reactjs.org/docs/hooks-intro.html">Introducing Hooks - React</a></p><p>Just don’t go deep. Get the basics on how-to use them. Once you get the intuition here, you will get when-to and then you can learn the more advanced concepts like useReduce .</p><p><em>Let me know in the comments if you would like a tutorial on Hooks too.</em></p><h3>Getting the intuition</h3><p><strong>Let’s look at some code first:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6efc63a4112c245821ea259bb06a78f/href">https://medium.com/media/e6efc63a4112c245821ea259bb06a78f/href</a></iframe><p>If you are familiar with the Class Components, this is how you must be doing your input handling in your components.</p><h4>So, what’s wrong in that?</h4><p>First of all, nothing is wrong with that. If it is wrong, then Facebook wouldn’t have introduced it in the first place.</p><p>But when you look at the above code after the introduction of the Hooks, you can realise how the logic is spread across the whole component and there’s a lot of code duplication(we will get to this below) in multiple Class Components.</p><p><strong>This is how it looks in Hooks</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/854e59a8930f9e58916e76a4f9269efd/href">https://medium.com/media/854e59a8930f9e58916e76a4f9269efd/href</a></iframe><h4>If you notice, the Hooks gist looks more elegant, concise and cleaner than the Class Component gist.</h4><p>Whatever I mentioned above is aesthetics. Now, let’s get to the most interesting topic: <strong>Reducing code duplication through custom Hooks.</strong></p><blockquote>Building your own Hooks lets you extract component logic into reusable functions.</blockquote><p><strong>Consider a scenario:</strong> You have multiple components in your UI, which takes inputs from the users. Before Hooks, you can only use Class Component to handle input data. So, you have to write the samehandleInputs(event) method logic in every component that takes input from the User. If you have 10 different components in your app, then you have to write the same handleInputs(event) method logic 10 times in those 10 components.</p><p>But with custom Hooks, you can write it only 1 time and use it in “N” number of components. This reduces code duplication substantially as mentioned before.</p><p>I’ve changed the above Hooks code a little to make it a custom Hook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96c44aabc4f97850df56c064e7e74726/href">https://medium.com/media/96c44aabc4f97850df56c064e7e74726/href</a></iframe><p>Can you comprehend what I did there?</p><p>I just removed the logic from the component to its own function so that it can be re-used in our other functional components.</p><p>Now, you can move the function useHandleInputs() {...} into another file, and can be import ed into your other components.</p><p>And now, we have successfully written our first custom Hook.</p><h3>How can a normal JavaScript function can maintain state of its own?</h3><p>If you know React, then this will be your first question after seeing the code above.</p><h4>Just remember one thing about React Hooks,</h4><blockquote>React Hooks are plain JavaScript functions, which can maintain their own state and lifecycles, isolated from components.</blockquote><h4>That’s it! That’s what you need to know to get the intuition on how-to, when-to and what-to use custom Hooks for.</h4><p>Those custom Hooks works exactly like when a Class Components update it’s state.</p><p>The main thing you have to do is, return the state s from your custom Hook to the functional component you want to use it and that’s it.</p><p>Whenever the state inside your custom Hooks is changed, your component is re-rendered to reflect the new changes.</p><p>If you still haven’t got it, then try to reason this simple code that we always do and also a common practice in React.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfcdc9a90df5ce23051a4441a59fee7a/href">https://medium.com/media/cfcdc9a90df5ce23051a4441a59fee7a/href</a></iframe><p>We send the states and callbacks from the Class Component to Functional Component as props and whenever a change happens in the Class Component states, the new states are passed to Functional Component as props to re-render to reflect the new state.</p><p>If we want to compare our custom Hooks with the above code, then assume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Uv66F4aMbnNuaF1PNq9yQ.png" /><figcaption>Class component vs. Functional component with a Custom Hook</figcaption></figure><p>The code sections are color coded to group how similar they are in functionality.</p><p><strong>Yellow</strong>: Maintains the state and passes it to Purple components</p><p><strong>Purple</strong>: Purple doesn’t have it’s own state but depends on the Yellow’s state to render</p><blockquote>In Class Component, the state and lifecycles are tied to its component. So, it can be re-used as a component but can’t be re-used as a logic.</blockquote><blockquote>In Custom Hooks, the state and lifecycles are not tied to any component. Custom Hooks can exist individually — logically as a function. So, it can be re-used as a logic in other components.</blockquote><h3>A tip for writing your own Hooks easily</h3><p>I know custom Hooks are cool and awesome but don’t always try to write a custom Hook.</p><p>First, use the Hooks provided by the React in a Functional Component. Then if you find that it can be re-used in another component, then try to extract it outside of that Functional Component like we did in the above:</p><ol><li>We wrote a Functional Component App using useState Hook.</li><li>We found out that we can use the handleInputs() function in other Functional Components also.</li><li>Extracted that function from our App Functional Component to its own function useHandleInputs() , which is our custom Hook.</li><li>Import our custom Hook useHandleInputs() into App Functional Component or any other Functional Components.</li></ol><p>Also, you might find in most of the articles/tutorials that custom Hooks are written using useState()and useEffect() in combination always. Writing custom Hooks doesn’t require you to use both useEffect() and useState() Hooks compulsorily. You can use any combination of Hooks. You can either use useEffect() or useState() . You can use both of them. You can even use your own custom Hook to write another custom Hook.</p><h3>More Resources</h3><p>React docs has explained custom Hooks with state and lifecycle with a use-case, which is pretty simple and useful. Check it out 👇🏻👇🏻👇🏻</p><p><a href="https://reactjs.org/docs/hooks-custom.html">Building Your Own Hooks - React</a></p><p>And don’t forget to checkout the 2 rules you have to follow while using Hooks. React docs has pretty good explanation for this also 👇🏻👇🏻👇🏻</p><p><a href="https://reactjs.org/docs/hooks-rules.html">Rules of Hooks - React</a></p><p>I hope this helped you to get the intuition on <strong>“How to write your own Hooks”</strong></p><p>If you still got any doubts, then comment down🙂</p><blockquote>Liked it? Then comment down, 👏🏻👏🏻👏🏻 it and share it!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*MjD6Iol54j9pGurMQAMHqg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d27fa4ba10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/react-custom-hooks-a-simple-intuition-if-you-still-cant-hit-it-off-8d27fa4ba10">React Custom Hooks: A simple intuition if you still can’t hit it off</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL vs NoSQL: A Senior Software Engineer’s perspective]]></title>
            <link>https://medium.com/from-the-scratch/sql-vs-nosql-a-senior-software-engineers-perspective-72a778df3098?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/72a778df3098</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 18:16:49 GMT</pubDate>
            <atom:updated>2020-07-07T00:35:31.209Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL vs NoSQL: An experienced Software Engineer’s perspective</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1Yz7p0m3chn3SwA8KUlOQ.jpeg" /><figcaption>Ok, I’m not that old 😅</figcaption></figure><p>There are 1000s of articles on “<strong>The difference between SQL vs NoSQL</strong>” and we don’t need more of those articles but still many people keep writing the same points in every articles. As a result, many beginners can recite the pros and cons like a parrot but tend to struggle while deciding when to use and which one to use.</p><blockquote>The problem is not with the beginners but with those redundant articles which contribute no value.</blockquote><p>The struggle to decide is inevitable even if you read 100s of articles more because everything is just a copy and paste of previous articles.</p><p>I’m not gonna repeat all those redundant points here. Instead, let’s look at the “SQL vs NoSQL” in a different perspective — A Senior Software Engineer’s perspective.</p><p>In this article, I’m gonna talk specifically about MySQL vs. MongoDB as they are the most popular ones.</p><h3>So, When you should use MySQL?</h3><p>MySQL is not just a database but a relational database. If you want to enforce some relations between the data, then you need a relational database i.e., MySQL.</p><p>Seems little vague right? Lets see what you can actually achieve from this relational databases that everyone keeps talking.</p><p><strong>Consider a scenario</strong> where you have built a webapp where a User can comment on Posts.</p><p>This is the minimum schema for that table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/140d2ceb99d92efe730506284de973da/href">https://medium.com/media/140d2ceb99d92efe730506284de973da/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82Dchs-oJFs7xhYIpH8kwA.png" /><figcaption>Visual Representation of the schema</figcaption></figure><p>So, what type of constraints we can think of?🤔</p><ol><li>userName should be unique for every user.</li><li>Only users present in the Users Table can write a post</li><li>Only users present in the Users Table can comment under the posts present in the Posts Table.</li></ol><p>Can you guess a general flow for every table for inserting new rows?</p><h4>For Users Table:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*p_B86ztq0hCQvdFDPNe96Q.png" /></figure><h4>For Posts Table:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*VStDIZdPNc7Vq2Y-hhOjIQ.jpeg" /></figure><h4>For Comments Table:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*0mv6nkyKOz14WdGOm2bfrg.png" /></figure><p>So, this is how the naïve approach is when there are no relationships in the MySQL.</p><p>We need to check all the constraints in our application server. And this is what you need to do in MongoDB and in MySQL(if you don’t create any constraints or relationships).</p><p>This is too much code to write, makes too many requests to database and the transfer of data between database server and application server. Also, there is a possibility of introducing bugs in the code and becomes hard to maintain the code if the complexity of the constraints and relationship increases.</p><p>Let’s see how to simplify this process and delegate this whole checking to the database server.</p><p>Just introduce some relationships into the schema and you are good to go</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHAO2EUHFPRFSISr9ctqjQ.png" /></figure><p><strong>The above relationships states that:</strong></p><ol><li>userName is unique(defined in the schema but you can’t see here visually)</li><li>A user in the Users Table can post any number of Posts</li><li>A user in the Users Table can Comment any number of times on any number of posts present in the Posts Table.</li></ol><p>So, if a user is not present in the Users Table tries to post a Post, then MySQL automatically throws an Error and no insertion takes place and same thing happens with the Comments Table if either user or post is not found in their respective tables.</p><p>Now, instead of checking for whether an insertion can be done explicitly in the application server by you, MySQL takes care of that for you. So, you can just execute only one INSERT command instead of executing 2–3 commands for insertion operation.</p><p>Here is the schema used to define tables and relationships and constraints:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/711ce7054a2df31ed90e4b2439044289/href">https://medium.com/media/711ce7054a2df31ed90e4b2439044289/href</a></iframe><p><strong>Consider another scenario</strong> where if the user deletes their account, we have to delete all their posts and comments from all the tables.</p><p>In MongoDB, you have to write a command to delete all the posts and comments with the userID, who deleted their account. If you make a mistake, there is a probability to delete the posts and comments with userID as <strong>NOT</strong> it’s owner. You might think “<em>this is a simple operation and how can I screw up?</em>”. This is just a simple example. In large production systems, you have 1000s of tables and you have to explicitly mention every one of them to delete it correctly. If you miss a single table/collection, then you start to have orphan records, which leads to data integrity problems.</p><p>In MySQL, while creating foreign keys, you can provide extra information on what to do if the parent record is edited/deleted. It is called “<strong>CASCADING</strong>”</p><p>You can read more about here👇🏻👇🏻👇🏻</p><p><a href="https://dba.stackexchange.com/q/74627">Difference between On Delete Cascade &amp; On Update Cascade in mysql</a></p><p>Now, you can delegate this responsibility to the server, like what to do when you update and what to do when you delete the parent record. This helps to reduce the bugs or more accurately prevents us from introducing unnecessary bugs. This will in turn helps us to maintain data integrity.</p><h4><strong>A new thing to remember for you,</strong></h4><blockquote>MySQL Database actually holds business logic in them</blockquote><p>If anyone says “Databases are not supposed to have business logic”, they are wrong or they don’t understand the concept of relational databases. So, next time, hit them with this explanation.</p><h3>So, When you should use MongoDB?</h3><p>There are use cases for MongoDB where it excels and where we don’t need the overhead(we will talk about this below) of a SQL.</p><p>MongoDB can be used for storing Sessions data/notification systems etc…</p><blockquote>In MongoDB, there are no relationships, no normalization, no schema.</blockquote><p>So, to store the data of a Session, which doesn’t require any relationships, doesn’t require normalization and schema can change based on what type of data you want to store and there is no need to parse the retrieved data(in JavaScript) as the data returned from the MongoDB is JSON. The same concept applies for creating a notification system where a document is a userID and fields are numbered sequentially for each notification or can be saved in an array. You can just query the MongoDB for new notifications using userID and display them directly, without any processing.</p><p><strong>Consider a scenario</strong> where you are storing the Session data in the database and like every other session, you need to delete those records after some time for the expiration of the Session.</p><p>Can you guess a general flow for deleting the existing expired records?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*xnlH0U9A5SDXW1E05bl2GQ.png" /></figure><p>You need to write a background program or write a function which needs to run for every “n” seconds.</p><p>But in MongoDB, you can delegate this to the Database Server. The only work you have to do is to specify the expiry date and MongoDB takes care of it automatically.</p><p>You can read more about this functionality here 👇🏻👇🏻👇🏻</p><p><a href="https://docs.mongodb.com/manual/tutorial/expire-data/">Expire Data from Collections by Setting TTL - MongoDB Manual</a></p><p><strong>Consider another scenario</strong> where you have to store logs for the last 7 days and keep deleting the old data and if the logs exceed storage limits, the logs need to overwrite the old data to store new data.</p><p>Can you guess a general flow for this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*AFShcbfANNfvqUCiQrZhUw.png" /></figure><p>This is how you need to do if you are using MySQL. But if you are using MongoDB, you can use the combination of “<strong>Capped Collections</strong>” and “<strong>TTL</strong>” to do all this for you without writing a single line of code.</p><h4>Capped Collections:</h4><blockquote><a href="https://docs.mongodb.com/manual/reference/glossary/#term-capped-collection">Capped collections</a> are fixed-size collections that support high-throughput operations that insert and retrieve documents based on insertion order. Capped collections work in a way similar to circular buffers: once a collection fills its allocated space, it makes room for new documents by overwriting the oldest documents in the collection.</blockquote><blockquote><strong>Insertion Order:</strong></blockquote><blockquote>Capped collections guarantee preservation of the insertion order. As a result, queries do not need an index to return documents in insertion order. Without this indexing overhead, capped collections can support higher insertion throughput.</blockquote><blockquote><strong>Automatic Removal of Oldest Documents:</strong></blockquote><blockquote>To make room for new documents, capped collections automatically remove the oldest documents in the collection without requiring scripts or explicit remove operations.</blockquote><blockquote><strong>Consider the following potential use cases for capped collections:</strong></blockquote><blockquote>Store log information generated by high-volume systems. Inserting documents in a capped collection without an index is close to the speed of writing log information directly to a file system. Furthermore, the built-in <em>first-in-first-out</em> property maintains the order of events, while managing storage use.</blockquote><blockquote>Cache small amounts of data in a capped collections. Since caches are read rather than write heavy, you would either need to ensure that this collection <em>always</em> remains in the working set (i.e. in RAM) <em>or</em> accept some write penalty for the required index or indexes.</blockquote><ul><li><a href="https://docs.mongodb.com/manual/core/capped-collections/">Capped Collections</a></li><li><a href="https://docs.mongodb.com/manual/tutorial/expire-data/">Expire Data from Collections by Setting TTL - MongoDB Manual</a></li></ul><h3>Let’s talk about the overheads that everyone keeps mentioning without any explanation</h3><p>MySQL has more overhead than MongoDB. If you still haven’t figured that for yourself by now, read the article again.</p><p>Most of the Software Engineers whom I interviewed always say one thing about why MongoDB is faster than MySQL</p><p>If you are a developer, then most probably you know that the most of the CPU time is wasted on waiting for I/O. So, most of them I interviewed gave me the same answer: “<strong><em>MongoDB performs faster I/O and that’s why it is faster than MySQL</em></strong>”</p><p>The thing most of them don’t realise is, both of them are open-source projects (<strong>GPL</strong>) and if MongoDB is implementing a new faster strategy for I/O, then nothing is stopping MySQL team from pulling that code and pasting it in MySQL.</p><h3>So, why insertions are slower in MySQL than in MongoDB?</h3><p>Why MySQL is slower than MongoDB is because: MySQL has to check for a lot of rules before inserting, deleting and updating the data. This slows down the MySQL a lot for insertions. Look at the above flowcharts for yourself. For MongoDB, we are doing all the checks explicitly and then inserting into the database. Most of the benchmarks present on the internet doesn’t log the time during the checks we were performing. They only log the time needed for insertions.</p><p>But in MySQL, the database server performs all the checks implicitly based on our constraints and foreign keys before inserting into the database. And if you haven’t guessed it, benchmarks measure all these timings.</p><blockquote>In MongoDB, an insertion command → Inserts the data</blockquote><blockquote>In MySQL, an insertion command → Check all the rules and insert only if it satisfies all those rules.</blockquote><p>This is why MySQL has more overhead than MongoDB and effects the insertion throughput.</p><p>If you actually log only the time taken to insert into the databases with more complex relations like in real world instead of dumping data, you see that both are not so apart in benchmarks.</p><h3>So, why retrieving data is slower in MySQL than in MongoDB?</h3><p>In MongoDB, all the data of an entity is stored in a single document. So, if you want a particular data about a certain entity, then MongoDB uses Indexes to find the location of the document in the filesystem and retrieves that data. The document is stored in one location, so it is easy to retrieve that in one go.</p><p>In MySQL, all the data of an entity is stored in different tables. So, if you want a particular data about a certain entity, then MySQL uses many Indexes to find the location of the record in the filesystem and retrieves that data which is scattered around the filesystem and requires to visit different parts of the filesystem.</p><p>This slows down the MySQL greatly when compared to MongoDB.</p><p><a href="https://stackoverflow.com/a/9703513/4859791">MySQL vs MongoDB 1000 reads</a></p><h3>So, what’s the summary?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*wM_IbFGipSq-pL16RnhQ9g.jpeg" /></figure><p>MySQL is not slower than MongoDB without any advantages and MongoDB is not the database to choose for every project just because you see a bunch of articles claiming MongoDB is faster than MySQL. You also need to look at why MySQL is slower than MongoDB at what costs.</p><h3><strong>Let me summarise for you for the last time:</strong></h3><p>MySQL is slower because of the normalization, foreign keys, constraints, associations(relationships between tables) etc but reduces programmer bugs to maintain data integrity perfectly and MySQL does all the heavy lifting behind the scenes. But MySQL requires heavy optimisation from your side to perform fast and efficiently.</p><p>MongoDB is faster because there is no normalization(everything is stored in one place), foreign keys, associations etc but the programmer has to take care to maintain the data integrity. And to make sure performance doesn’t degrade with large data, you have to denormalize the data and store the same data in multiple collections or documents and if you want to change the data in one location, you have to programatically update all the locations(if you miss any location by chance, then your data will be inconsistent and data integrity is 💨💨) and let’s not forget about the increase in storage size.</p><h3>A suggestion in choosing your next database for your personal project</h3><p>Honestly, it doesn’t matter. The traffic you are expecting is too small to notice any difference between MySQL or MongoDB.</p><p>Remember, Twitter and Facebook still uses MySQL for their parts of databases. If they can use it, then you can use it without worrying about the performance in the initial stages of your projects.</p><p>So, don’t stress on which one to use. The more important thing is your IDEA. Focus more on that than on choosing types of servers, frontend, backend and database.</p><p>Just use whatever you know in your project. If you need an improvement to meet new traffic, then you will be obviously in a position to hire someone to do it from the revenue you get from the traffic.</p><blockquote>So, don’t stress. Use whatever you know and improve it with time when the need comes.</blockquote><blockquote>Liked it? Then 👏🏻👏🏻👏🏻 it and share it!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a778df3098" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/sql-vs-nosql-a-senior-software-engineers-perspective-72a778df3098">SQL vs NoSQL: A Senior Software Engineer’s perspective</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git: Commands you need to know when you are messed up!]]></title>
            <link>https://medium.com/from-the-scratch/git-commands-you-need-to-know-when-you-are-messed-up-e880fbf03819?source=rss-877f86012ce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e880fbf03819</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Skrew Everything]]></dc:creator>
            <pubDate>Sun, 01 Mar 2020 15:03:07 GMT</pubDate>
            <atom:updated>2020-03-09T08:34:47.010Z</atom:updated>
            <content:encoded><![CDATA[<h3>Git: Commands you need to know when you are messed up😨! [Part-1]</h3><p>First things first, this is not an another “KNOW THESE GIT COMMANDS TO BE MORE PRODUCTIVE!” or “GIT COMMANDS LIST THAT EVERY DEVELOPER MUST KNOW!”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Z1TIcJ-kHSXdmqPXhmah8Q.gif" /><figcaption>Readers on Medium</figcaption></figure><p>We got enough of those in the internet. What we don’t have is: “COMMANDS YOU NEED TO KNOW WHEN YOU ARE MESSED UP!”😇</p><blockquote>If anyone say they never messed up in Git, Don’t trust them! Unless it’s Linus Torvalds or Jeff Dean.</blockquote><p>Git is every junior developer’s nightmare when they are working in a group. Especially with the people who are experienced and know their shit. Because,</p><ol><li>If you make some mistake, you can’t just delete .git from the root folder and pretend everything is ok. (Ohhhhh… I’m guilty of doing this🤫. I hope my boss doesn’t read this article😰)</li><li>When they see your mess, they might not think you are dumb or inept of doing work but your conscious will think about it constantly. For people like me, the brain suddenly remembers all the embarrassing things even done during the childhood at 2 A.M.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*jLxdvvECXe135hkJDCNUYA.gif" /><figcaption>Yeah, that’s me most of the time</figcaption></figure><p>The above two points makes everyone nervous before making every commit and pushing to the remote.</p><p>But sometimes, that extra care we take won’t even save us and sooner or later we do something stupid, which we want to hide desperately from our peers and manager. So, obviously we turn to Google, frantically searching for some commands for hours to bury the body and pretend everything is normal.</p><p>Ok. Ok. Fine😑. I’m gonna stop blabbering and get to the stuff you are here for before you feel sleepy🥱 and leave 🏃🏻‍♀️💨.(Sometimes, I get distracted 😅. I’m known to talk about ………….. See, I’m again getting distracted 🤦🏻🤷🏼)</p><p>Actually, it’s a two part series. I don’t want to fry your brains with too much information in one day(Yes, I do care for you🥺). So, this part mainly concentrates on commands which has effects on your local working directory. The next part will be on remote repo like on reverting, deleting, editing commits etc. which requires more of your attention while learning.</p><h3>What’s in this?</h3><ol><li><strong>Accidentally staged files for commit?</strong></li><li><strong>Accidentally tracking files or don’t want to track a file anymore?</strong></li><li><strong>Want to delete untracked and ignored files?</strong></li><li><strong>Want to revert un-committed changes?</strong></li></ol><p>So, let’s see some of the things we can mess up and how to clean it without jeopardizing our whole work.</p><h3>Accidentally staged files for commit?</h3><p>Have you ever executed the below command and wanted to undo?</p><pre>git add .</pre><pre>git add *</pre><pre>git add -A</pre><pre>git add -u</pre><p>(Yes, there are 4 variations! Checkout this SO post to know everything about them)</p><p><a href="https://stackoverflow.com/q/26042390/4859791">git add * (asterisk) vs git add . (period)</a></p><p>Now, you got multiple commands to do that</p><ol><li>git reset &lt;filename&gt; or git reset HEAD &lt;filename&gt;</li><li>git rm --cached &lt;filename&gt;</li><li>git restore --staged &lt;filename&gt; — Added in Git v2.23 (August 2019)</li></ol><p>Actually, these three commands will be recommended to you by the Git itself when you add the files to index or to staging area. If you are using Git v2.23+ then you will be suggested git restore --staged &lt;filename&gt; instead of git reset HEAD &lt;filename&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*nVr79yrGAGsl2hnVplwmRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*0J06HYGaNGZSa-vSUuSdmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*QNbKBPp4dRKuCgtGcWKuvg.png" /><figcaption>There is never really only one way to do anything in git. That is the beauty of it :)</figcaption></figure><p>I guess the new command git restore --staged &lt;filename&gt; is self explanatory. Let me explain the other two commands.</p><p>git reset HEAD &lt;filename&gt; : reset command resets the INDEX or STAGING AREA to previous commit i.e., the position of the HEAD in the Git.</p><p>git rm --cached &lt;filename&gt; : removes the files from the INDEX or STAGING AREA completely. If you deleted a file which is already in the repo and run this command, the file will be removed from the INDEX or STAGING AREA and also from the repo in the next commit. That said, if you used git rm --cached on a new file that is staged, it would basically look like you had just un-staged it since it had never been committed before.</p><h4>Now, why does Git suggest two different commands?</h4><p>For git reset HEAD &lt;filename&gt; or git restore --staged &lt;filename&gt; to work, there should be at least 1 commit in the repo. Because git reset HEAD command is saying to reset the files to the HEAD but HEAD is not created until the first commit is made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weY9iKYKszfKGohnCL5HLg.png" /><figcaption>Because HEAD is created only when first commit is made</figcaption></figure><p>But you can still run it by excluding Head option and it works perfectly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8aE6b-9xV0A4C8f8pJwS9g.png" /><figcaption>Now you don’t have any error</figcaption></figure><blockquote>WHY🤔?</blockquote><blockquote>In old versions of Git, the above commands are equivalent to git reset HEAD &lt;file&gt; and git reset HEAD respectively, and will fail if HEAD is undefined (because you haven&#39;t yet made any commits in your repository) or ambiguous (because you created a branch called HEAD, which is a stupid thing that you shouldn&#39;t do). This <a href="https://git.kernel.org/cgit/git/git.git/tree/Documentation/RelNotes/1.8.2.txt#n179">was changed in Git 1.8.2</a>, though, so in modern versions of Git you can use the commands above even prior to making your first commit:</blockquote><blockquote><em>“git reset” (without options or parameters) used to error out when you do not have any commits in your history, but it now gives you an empty index (to match non-existent commit you are not even on).</em></blockquote><p><strong>Note:</strong> I will use git revert instead of git revert Head in the following article.</p><p>You can read more about git revert vs git revert HEAD in the below SO posts</p><ul><li><a href="https://stackoverflow.com/a/348234/4859791">How do I undo &#39;git add&#39; before commit?</a></li><li><a href="https://stackoverflow.com/q/33849704/4859791">git reset vs git reset HEAD</a></li></ul><p>So, if you observe next time, Git suggests git rm --cached &lt;filename&gt; when you don’t have initial commit and when you have at least one commit, Git suggests git reset HEAD or git restore --staged</p><p>Now, you might be scratching your head thinking: <em>“I understand everything but still I don’t understand anything and how to use it”</em>. Don’t worry, been there, done that. So, how about we look at those commands from a different perspective with a mess up to understand it actually.</p><h3>git reset</h3><p>git reset HEAD &lt;filename&gt; : You are lazy and you commit only at the end of the day by staging files and committing multiple times to organise the work.(Yeah… Sometimes I do this too😑)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkwoZvFNyc3hvt9m7Xt-8w.png" /></figure><p>Entire day you have added/edited many different files like above. Now you want to group server config files in one commit and database config files in one commit. But accidentally you have executed git add .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-zAsXyEqv2FouoSkKnDVA.png" /></figure><p>Now, you see that and want to remove the db config files and any other files to commit only server config files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XaW165-RkYI3GacU6OsI9A.png" /></figure><p>Now, you can commit server config files and then commit db config files in separate commits.</p><blockquote>Doing this doesn’t delete anything from your local working directory.</blockquote><h3>git rm — cached</h3><p>git rm --cached : Now you see why Git suggests this only when there are no commits. Tip: Don’t use this to unstage files without knowing completely about this!</p><p>I repeat! The behaviour of git rm --cached and git reset is same when there are no commits!</p><p>First, let’s see what is the output when we run git rm --cached with at least one commit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAWZu-pQc42buqLtt-WEcg.png" /></figure><p>Can you comprehend what happened by just looking at the above image? If not, don’t worry. That’s why everyone is here. Nobody is gonna judge you.</p><p>git rm --cached deletes the file from the INDEX or STAGING AREA but you still have the file in your filesystem with all it’s content and also Git removes it from it’s tracking.</p><p>In simple terms, git rm --cached makes it look like you copied a new file into your folder.</p><p>Another effect is, this command removes the file from the repo. If anyone pulls the code after you have run git rm --cached &lt;file&gt; &amp;&amp; git push , then that &lt;file&gt; will also be deleted from their local filesystem. Because it only exists in your local filesystem as an untracked file.</p><p>I’m gonna give you an embarrassing mess once I made so that you can get an intuition when to use this.</p><p><strong>Story Time</strong>: Once, I initialised my node project and forgot to add .gitignore and ran my alias to add everything and push it to the remote server.(Yeah I know how dumb it is and my brain is known to glitch out sometimes) Doing that pushed my entire node_modules to the remote server. So, what can I do?</p><ol><li>Add .gitignore, run rm -r node_modules &amp;&amp; git add . &amp;&amp; git commit &amp;&amp; git push &amp;&amp; npm install OR</li><li>Add .gitignore, run git rm --cached -r node_modules &amp;&amp; git commit &amp;&amp; git push</li></ol><p>The second option is more nice and short. When you run git rm --cached -r ( -r stands for recursive)it removes the node_modules from the INDEX or STAGING AREA and also removes it from it’s tracking files but it is not removed from your local file system. So, you don’t have to install it again like in first option. Now, whenever you run git add . , it checks .gitignore and you won’t see node_modules in your git status as untracked files.</p><blockquote>Doing this doesn’t delete anything from your local working directory.</blockquote><h3>Summary:</h3><p>Always use git reset &lt;filename&gt; to unstage some files or git reset . to unstage all files. This works even if there was no prior commit in the repo.</p><p>Use git rm --cached only when you want to remove the file from the repo but keep a local copy in your local file system. Don’t use it interchangeably with git reset !</p><p>If you want to know from more why there are two ways, checkout this SO post:</p><p><a href="https://stackoverflow.com/q/6919121/4859791">Why are there two ways to unstage a file in Git?</a></p><h3>Accidentally tracking files or don’t want to track a file anymore?</h3><p>This is where git rm --cached is useful actually.</p><p>Like I said before, (read the Story Time above if you skipped it to understand)</p><p>Ok Fine. I’m gonna say it again in a summary what it does for some lazy people.</p><p>git rm --cached command actually removes it from the INDEX or STAGING AREA and also deletes it from the repo. So, git push actually removes the file from the repo and any subsequent git pull by others will also delete that file from their local file systems(not yours. You actually have your copy).</p><p>To remove/untrack everything: git rm --cached .</p><p>To remove/untrack one file: git rm --cached &lt;filename&gt;</p><p>To remove/untrack a directory: git rm --cached -r &lt;directoryname&gt;</p><blockquote>Doing this doesn’t delete anything from your local working directory.</blockquote><p><strong>Note</strong>: git rm is not same as git rm --cached . git rm actually deletes the file from your local file system, repo, and others file system. So, be careful not to forget — -cachedoption!</p><p><a href="https://stackoverflow.com/questions/1274057/how-to-make-git-forget-about-a-file-that-was-tracked-but-is-now-in-gitignore">How to make Git &quot;forget&quot; about a file that was tracked but is now in .gitignore?</a></p><h3>Want to delete untracked and ignored files?</h3><p>Suppose you added some new files to the working folder and later decided to remove those. There are too many files to run rm file1 file2 file3 .... .</p><p>Another scenario is, you want to delete the temporary files which are mentioned in .gitignore</p><blockquote>Doing this deletes from your local working directory.</blockquote><blockquote>Be careful!</blockquote><p>You can run git clean</p><p><strong>From man pages:</strong></p><blockquote>Cleans the working tree by recursively removing files that are not under version control, starting from the current directory.</blockquote><blockquote>Normally, only files unknown to Git are removed, but if the -x option is specified, ignored files are also removed. This can, for example, be useful to<br> remove all build products.</blockquote><p>As said, it removes recursively from current directory(where you run that command). So, to remove all untracked and/or ignored files/directories, run it from the root of the project directory.</p><p>To remove untracked files: git clean -f</p><p>To remove untracked and ignored files: git clean -xf</p><p>To remove untracked directories and files: git clean -fd</p><p>To remove untracked and ignored directories and files: git clean -xfd</p><p>Why -f, --force?</p><blockquote>If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to delete files or directories unless given -f, -n or<br> -i. Git will refuse to delete directories with .git sub directory or file unless a second -f is given.</blockquote><p>This command actually deletes files and directories physically. So, you might be intimidated by running this command and hope you are not doing wrong by deleting “not-to-delete” files/directories.</p><p>If you are scared(like me), you can use this command in “Interactive Mode” by running git clean -fi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPufe4faCuyYFQw3wCzLeg.png" /></figure><p>You can select option 4 and Git asks whether to remove it or not for every file.</p><p><strong>From man pages:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quTopIxu7wyMK_0FBKIojg.png" /><figcaption>git clean — help</figcaption></figure><h3><strong>Want to revert un-committed changes?</strong></h3><p>You have run git commit and later edited some files in the project. After hours of work, you want to delete the changes or un-edit those files to previous staging version.</p><p>You can use: git checkout</p><p>Yeah. You heard that right. The innocent git checkout which we often use to change branches can actually cause some destruction if used improperly.</p><blockquote>Doing this deletes the work from your local working directory up until previous commit.</blockquote><blockquote>Be careful!</blockquote><p><strong>From man pages:</strong></p><blockquote>git-checkout — Switch branches or restore working tree files</blockquote><blockquote>Updates files in the working tree to match the version in the index or the specified tree. If no paths are given, git checkout will also update HEAD to set<br> the specified branch as the current branch.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lR7UvfH7C-bTtByBbzF6yg.png" /></figure><p><strong>Just a side note</strong>: You might have seen git restore &lt;filename&gt; as a suggestion by Git in the above image(that might be because I’m using latest version v2.25.0). Don’t use that because it is experimental as it is mentioned in the man pages</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qyn4QknE4oe1RFPc6u7cvA.png" /><figcaption>git restore — help</figcaption></figure><p>Moving on ….</p><p>git checkout . can only revert any modified file to previous staging version but not to previous commit!</p><p>In the above image, the previous staging version of somedbconfigfile1 is empty. So doing git checkout . reverted the contents First message to commit to empty.</p><blockquote>But you might think “In the above image, git checkout .reverted to previous commit right?”</blockquote><p>Now, let’s see another example to really understand what reverting to previous staging version means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHPRIkD00jVqHuBw5pSrfg.png" /></figure><p>Git doesn’t keep history of INDEX or STAGING AREA. It only has two states.</p><ol><li>What’s there in INDEX</li><li>What’s not there in INDEX</li></ol><p>If you run git add , Git replaces/adds it’s “What’s there in INDEX” with new “What’s not there in INDEX” data. So, you cannot iterate over your INDEX history like with your COMMIT history and restore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSWrynGWFNYjp-vWNl09hQ.jpeg" /></figure><p>So, as there are no INDEX versions left, Git gets the copy from previous commit which is somedbconfigfile1 is empty.</p><p>git checkout &lt;filename&gt; command can only be run on un-staged files. That’s the reason I have used git reset . to unstage the file in the above image.</p><p>I know that’s a lot of things to absorb about the innocent git checkout .</p><p>I think it’s enough for today. Don’t forget to comeback to check the part 2! If your memory is as bad as mine, Hit that FOLLOW 😉</p><h3>Other useful articles</h3><p>If you still got some energy to burn, then read this one about git reset. It is a must! Complete guide for git reset : <a href="https://git-scm.com/book/en/v2/Git-Tools-Reset-Demystified">https://git-scm.com/book/en/v2/Git-Tools-Reset-Demystified</a></p><p>If anyone finds another way to do the same things with different commands, Congratulations! Do share and enlighten our fellow developers! If you don’t know then yes, we can do same thing using different commands in Git. Don’t trust me? Look 👇🏻👇🏻👇🏻</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sYotl1hHwEwRu3wwassrg.png" /><figcaption><a href="https://stackoverflow.com/a/6919749/4859791">https://stackoverflow.com/a/6919749/4859791</a></figcaption></figure><p><strong><em>Disclaimer</em></strong><em>: Before anyone calls me out for not giving credits for memes, I have a dope stash of them saved on my phone from all over the internet since the “dot com bubble”. So, if you need some, mail me🙂</em></p><blockquote><em>Liked it? Then 👏🏻👏🏻👏🏻 it and share it!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e880fbf03819" width="1" height="1" alt=""><hr><p><a href="https://medium.com/from-the-scratch/git-commands-you-need-to-know-when-you-are-messed-up-e880fbf03819">Git: Commands you need to know when you are messed up😨!</a> was originally published in <a href="https://medium.com/from-the-scratch">From The Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>