<?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 Richard Rosier on Medium]]></title>
        <description><![CDATA[Stories by Richard Rosier on Medium]]></description>
        <link>https://medium.com/@jimmyroro58?source=rss-72d1cb2506e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PDADj3TvZl8iBRLo.jpg</url>
            <title>Stories by Richard Rosier on Medium</title>
            <link>https://medium.com/@jimmyroro58?source=rss-72d1cb2506e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:31:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jimmyroro58/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[Accessible Rich Internet Applications - ARIA]]></title>
            <link>https://medium.com/@jimmyroro58/accessible-rich-internet-applications-aria-3137e1e9f001?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3137e1e9f001</guid>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 01:38:05 GMT</pubDate>
            <atom:updated>2020-07-27T01:38:05.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was creating a website using React.js, and found myself wanting to make an image clickable. So I wrote the following code:</p><pre>&lt;img<br>     onClick={setChangeName(true)}<br>     alt=&quot;edit&quot;<br>     src=&quot;images/w3c-logo.png&quot;<br>/&gt;</pre><p>My linter rewarded me with an error I had never seen before: “Non-interactive elements should not be assigned mouse or keyboard event listeners.” Naturally, I Googled what exactly the problem was and how I could resolve it. This led me to discover the technical specification of ARIA: Accessible Rich Internet Applications. ARIA aims to increase accessibility of web pages, particularly those with dynamic content. So what exactly did my &lt;img&gt; element have to do with ARIA? Well, you’ve got to think about what each HTML element is actually doing behind the scenes, and how they behave when the user is using a screen reader or other assistive technology. I’ll show you some examples.</p><p>Consider the following elements:</p><p>&lt;div&gt;Hello World!&lt;/div&gt;</p><p>&lt;h5&gt;Hello World&lt;/h5&gt;</p><p>&lt;p&gt;Hello World&lt;/p&gt;</p><p>If you rendered them to a website, they would all look the same. But they are most certainly not interchangeable, because each element carries meaning and function that extends beyond just appearance. &lt;div&gt; tags denote divisions between elements and act as containers — they should not have text in them; &lt;h?&gt; tags are for headers of various sizes; &lt;p&gt; tags are paragraphs. Although they render the same, each one explicitly sections off a website, so screen readers can more accurately convey information.</p><p>While messing up some &lt;p&gt; or &lt;div&gt; elements could cause confusion, the clickable &lt;img&gt; I created in my initial example would not be visible to screen readers at all, making my website very inaccessible. The easiest solution was to wrap the image in a button like so:</p><pre>&lt;button type=&quot;button&quot; onClick={() =&gt; { setChangeName(true); }}&gt;   <br>  &lt;img<br>     onClick={setChangeName(true)}<br>     alt=&quot;edit&quot;<br>     src=&quot;images/w3c-logo.png&quot;<br>  /&gt;<br>&lt;/button&gt;</pre><p>This utilizes the innate power of native HTML elements: the &lt;button&gt; element will let any screen reader know that its contents are clickable, with no effort on my part. It sounds obvious, but <strong>simply using native elements appropriately will keep your website accessible. </strong>Take a moment to really read about what that &lt;span&gt; tag really means, or when it’s appropriate to use a &lt;nav&gt; tag. Then, if you really need to, you can use ARIA roles, states, or properties to make an element’s purpose obvious. Let’s take a look at another way to make that clickable image happen using a role attribute.</p><h4>“A Role is a Promise”</h4><p>Take a look at this way of making an image clickable, and I will walk you through what is happening:</p><pre>&lt;div tabIndex=&quot;0&quot;<br> onKeyUp={setChangeName(true)}<br> role=&quot;button&quot;<br> onClick={setChangeName(true)}<br> &gt;<br>   &lt;img <br>    src=&quot;images/w3c-logo.png&quot;<br>    alt=&quot;edit&quot;<br>    /&gt;<br>&lt;/div&gt;</pre><p>First of all, we are wrapping the image inside of a div, then making that div do the things that a button element normally would.</p><p>The div has a ‘tabIndex’, which includes the element in the tab sequence. You might not know, but you can cycle through interactive elements on a page by pressing the tab key. Now users can highlight this element without the use of a mouse.</p><p>Next is ‘onKeyDown’, which will run a function when a key is pressed. In this case we aren’t checking which key is pressed, because the function is just going to show some extra information. We could certainly listen for which key is pressed with onKeyUp={(e) =&gt; {console.log(e.keyCode)}} .</p><p>Lastly, ‘role’ attribute identifies the div element as a button element instead. Note that it doesn’t actually give the div all the functionality of a button — we are doing that ourselves. We are making a promise that this div is going to have the functionality of a button. <strong>It’s important to mention that using ‘role’ overwrites the inherit functionality of the div, so it doesn’t interfere with the functionality we are giving it</strong>. So if we assigned it a role of button but didn’t add any button functionality, the element would essentially have no functionality at all. This is why it’s preferable to not use a role attribute if you don’t have to, because there might be unintended consequences of overwriting an element.</p><p>If you take anything away from this, it’s that you should keep all users in mind and strive to make your code accessible. Use native HTML elements appropriately, and if you make any drastic changes, ensure that they are done properly. ARIA’s own website has this warning:</p><blockquote>“No ARIA is better than Bad ARIA. Incorrect ARIA misrepresents visual experiences, with potentially devastating effects on their corresponding non-visual experiences.”</blockquote><p>It’s important to to keep ARIA in mind, for cases when you can’t do exactly what you want with regular HTML. But with great power comes great responsibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3137e1e9f001" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging in with Google, using React hooks, Part 2]]></title>
            <link>https://medium.com/@jimmyroro58/logging-in-with-google-using-react-hooks-part-2-466d87793f03?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/466d87793f03</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[google-auth]]></category>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Mon, 20 Jul 2020 13:49:26 GMT</pubDate>
            <atom:updated>2020-07-20T13:49:26.510Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://medium.com/@jimmyroro58/logging-in-with-google-using-react-hooks-19c8300e8950">last blog</a>, I showed you how to use create-react-app and react-google-login to authenticate users. Login sessions were being persisted between page refreshes, but the website had no way to retrieve that information. Now I will show you how to check if a user has already logged in to your website when it loads.</p><p>The top of your App.js should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*74cS8SxXk3_kgvhO61Rtdw.png" /></figure><h4>Import useEffect:</h4><p>We will use useEffect to invoke a function when our component renders. Import it at the top of the page as usual:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*rcmBh-qNO2u9y0GE8ySzrA.png" /></figure><p>And call it like so (notice we aren’t assigning it to a variable):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*JMp1jvdcH-vo9hN3XtI3_A.png" /></figure><p>If you aren’t familiar with React hooks, useEffect is like componentDidMount and componentDidUpdate combined into one function. By default, it will run every time the component renders. The second parameter tells it to run only when that parameter changes (it should be a state that your component is holding). By passing an empty array, we are calling this useEffect only once, on initial render. Read more about this powerful tool <a href="https://reactjs.org/docs/hooks-effect.html">here</a>.</p><h4>Load the auth2 library</h4><p>Remember that script we used in our index.html file? It creates a global gapi object that will allow us to use Google’s Sign-In API. The first thing we’ll need to do is load the auth2 library using that object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*748RD93emY7ZIRKijOZ-Gw.png" /></figure><p>Inside of the function, we will next initialize the GoogleAuth object. We configure it with our client ID, and use its methods to interact with user information. This must happen after the function that loads the auth2 library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Kb71_d-9fPicMR8XHSbuyw.png" /></figure><p>There are several other optional parameters we could pass here, including scope and cookie-policy, but their defaults serve our purpose right now.</p><h4>Using the GoogleAuth object</h4><p>After initialization using your client id, we can save the GoogleAuth object. This object will have methods on it that we use to access a user’s data. You can look over them all <a href="https://developers.google.com/identity/sign-in/web/reference#authentication">here</a>. We use a .then to ensure that gapi.auth2.init has resolved, then call getAuthInstance() , saving our return as our authObj .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*t6DSJ6KoMHksJ1G2UCrbSQ.png" /></figure><p>Now, we can simply call the appropriate methods on our authObj:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*iuJ8P0fnEX8LcVY2W_g2iQ.png" /></figure><p>We’ll use isSignedIn.get() to check if there is currently a user signed in with Google. It will resolve to a boolean. If there is a user, we’ll use currentUser.get() to retrieve that object of the user and then call setUser(user) to have our state hold that data. If isSignedIn.get() is false, we do nothing.</p><h4>Next steps</h4><p>At this point, the website is allowing users to login and logout with a button, as well as checking to see if a user is already logged in when the website loads. You may be tempted to simply be done here, but Google actually has a warning about using this information as is, so we want to do one final step to actually verify our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qyVj3wn8is61bXtfaIOdUw.png" /></figure><p>You don’t want someone sending you arbitrary user IDs, so verify an ID is real by using ID tokens. Google’s <a href="https://developers.google.com/identity/sign-in/web/backend-auth">tutorial </a>on this is solid, with a couple ways to do it. I would recommend using a Google API Client Library.</p><p>Run npm i google-auth-libraryand import the following at the top of App.js: const {OAuth2Client} = require(&#39;google-auth-library&#39;) . The following code is taken directly from the above tutorial. It seems daunting, but really you only need to be concerned with changing lines 32, 35, 36, and 42.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*Jp0tYb6EKuPDPsF8daAIJg.png" /></figure><p>After calling verify() , you will know that the user object you are using is legitimate, and can continue saving it to your server or whatever you want to do with it.</p><p>This wraps up my tutorial on logging users in with Google. Hopefully you see now that authentication doesn’t have to be hard, and there are very powerful tools available to help you out. For you copy-pasters out there, here is the code</p><pre>import React, {useState, useEffect} from &#39;react&#39;;</pre><pre>import logo from &#39;./logo.svg&#39;;</pre><pre>import &#39;./App.css&#39;;</pre><pre>import { GoogleLogout, GoogleLogin } from &#39;react-google-login&#39;;</pre><pre>const {OAuth2Client} = require(&#39;google-auth-library&#39;);</pre><pre>function App() {</pre><pre>const [user, setUser] = useState();</pre><pre>const responseGoogle = (response) =&gt; {</pre><pre>console.log(response);</pre><pre>setUser(response.Qt)</pre><pre>};</pre><pre>const logout = () =&gt; {</pre><pre>console.log(&#39;logged out&#39;)</pre><pre>setUser();</pre><pre>}</pre><pre>useEffect(() =&gt; {</pre><pre>let authObj;</pre><pre>window.gapi.load(&#39;auth2&#39;, () =&gt; {</pre><pre>window.gapi.auth2.init({</pre><pre>client_id:</pre><pre>&#39;YOUR_CLIENT_ID_HERE.apps.googleusercontent.com&#39;,</pre><pre>})</pre><pre>.then(() =&gt; {</pre><pre>authObj = window.gapi.auth2.getAuthInstance();</pre><pre>if (authObj.isSignedIn.get()) {</pre><pre>const userObj = authObj.currentUser.get();</pre><pre>const client = new OAuth2Client(&#39;YOUR_CLIENT_ID_HERE.apps.googleusercontent.com&#39;);</pre><pre>async function verify() {</pre><pre>const ticket = await client.verifyIdToken({</pre><pre>idToken: userObj.wc.id_token,</pre><pre>audience: &#39;YOUR_CLIENT_ID_HERE.apps.googleusercontent.com&#39;,</pre><pre>});</pre><pre>const payload = ticket.getPayload();</pre><pre>const userid = payload[&#39;sub&#39;];</pre><pre>}</pre><pre>verify()</pre><pre>.then(() =&gt; setUser(userObj.Qt))</pre><pre>.catch(console.error);</pre><pre>}</pre><pre>})</pre><pre>.catch((err) =&gt; {</pre><pre>console.error(err);</pre><pre>});</pre><pre>});</pre><pre>}, []);</pre><pre>return (</pre><pre>&lt;div className=&quot;App&quot;&gt;</pre><pre>&lt;header className=&quot;App-header&quot;&gt;</pre><pre>&lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;</pre><pre>{user &amp;&amp; (</pre><pre>&lt;h1&gt;Welcome, {user.Bd}&lt;/h1&gt;</pre><pre>)}</pre><pre>&lt;GoogleLogin</pre><pre>clientId=&quot;YOUR_CLIENT_ID_HERE.apps.googleusercontent.com&quot;</pre><pre>buttonText=&quot;Login&quot;</pre><pre>onSuccess={responseGoogle}</pre><pre>onFailure={responseGoogle}</pre><pre>/&gt;</pre><pre>&lt;GoogleLogout</pre><pre>clientId=&quot;YOUR_CLIENT_ID_HERE.apps.googleusercontent.com&quot;</pre><pre>buttonText=&quot;Logout&quot;</pre><pre>onLogoutSuccess={logout}</pre><pre>/&gt;</pre><pre>&lt;a</pre><pre>className=&quot;App-link&quot;</pre><pre>href=&quot;https://reactjs.org&quot;</pre><pre>target=&quot;_blank&quot;</pre><pre>rel=&quot;noopener noreferrer&quot;</pre><pre>&gt;</pre><pre>Learn React</pre><pre>&lt;/a&gt;</pre><pre>&lt;/header&gt;</pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><pre>export default App;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=466d87793f03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging in with Google, using React hooks]]></title>
            <link>https://medium.com/@jimmyroro58/logging-in-with-google-using-react-hooks-19c8300e8950?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/19c8300e8950</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[google-sign-in]]></category>
            <category><![CDATA[login]]></category>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 13:41:23 GMT</pubDate>
            <atom:updated>2020-07-20T11:14:00.616Z</atom:updated>
            <content:encoded><![CDATA[<h3>Logging in with Google, using React hooks, Part 1</h3><p>If you are making a website or an app, it is very likely that you’ll need to authenticate users somehow. Authenticating and remembering users has become the standard, so it’s good to know how to do it in several different ways. I’ll show you an easy way to log your users in with Google in a React.js app with hooks.</p><h4>Create the website</h4><p>The first thing we will do is to create a website that we can visit. We can run create-react-app test to make a new react project in a new folder called ‘test’. If you want a back-end server as well, check out <a href="https://medium.com/@jimmyroro58/create-a-react-app-with-an-express-backend-24740b0a6f5e">my other article</a> for creating both front-end and back-end. After creation, you can run npm start to visit the website on localhost:3000.</p><h4>Obtain Google credentials</h4><p>We need to register our website and get credentials for it. Go to the <a href="https://console.developers.google.com/apis/credentials">credentials</a> page of Google Api (you’ll need to create an account if you don’t have one already). On the left navigation bar, click <strong>Credentials</strong>, then click <strong>Create Credentials</strong>, choosing <strong>Oauth client ID</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxlKThY87cKs4wmyoZzFWA.png" /></figure><p>Choose <strong>Web Application</strong>, and while we are here, we need to add our domain name to the list of authorized domains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZeww9MJMTIyiiN8PW_Ahw.png" /></figure><p>Notice that we are using <a href="https://localhost:3000.">http<strong>s</strong>://localhost:3000.</a> Google will not allow you to use their APIs without https, so we’ll need to use it on our server. Click create, and you should be able to see the name of the website you just created and its client id. Keep that id handy.</p><p>To make our server run using https, we can give ourselves a self-signed certificate. In the package.json file, change the start script to be the following: &quot;start&quot;:”HTTPS=true react-scripts-start . A self-signed certificate is not a good idea in production, but in development it’s okay. Be aware that you will get a security notification the first time you visit the website.</p><p>Back in in the head of our public/index.html file, we’ll import a script to give us access to Google Sign in: &lt;script src=&quot;https://apis.google.com/js/platform.js&quot; async defer&gt;&lt;/script&gt; .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Lgc1B8hNOBDM8G0Pw3MWw.png" /></figure><h4>Get login and logout buttons</h4><p>Although you can do this <a href="https://developers.google.com/identity/sign-in/web/reference#googleauthsignin">manually</a>, there is an npm package we can import to make it much easier: <a href="https://www.npmjs.com/package/react-google-login">react-google-login</a>. Install it by running npm i react-google-login . Then import it in the top of App.js like so: import { GoogleLogout, GoogleLogin } from ‘react-google-login</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*OUcoQdFY95dWUGWNraRa4A.png" /></figure><p>Let’s add these buttons right in the middle of our page:</p><pre>&lt;GoogleLogin</pre><pre>clientId=&quot;YOUR ID HERE.apps.googleusercontent.com&quot;</pre><pre>buttonText=&quot;Login&quot;</pre><pre>onSuccess={responseGoogle}</pre><pre>onFailure={responseGoogle}</pre><pre>/&gt;</pre><pre>&lt;GoogleLogout</pre><pre>clientId=&quot;YOUR ID HERE.apps.googleusercontent.com&quot;</pre><pre>buttonText=&quot;Logout&quot;</pre><pre>onLogoutSuccess={logout}</pre><pre>/&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*nN1slUShnyH4P9G6WZ-seQ.png" /></figure><p>Notice the Login button has an onSuccess and onFailure; these run a function depending on if the login was successful or not. They don’t have to both be the same. The Logout button has a similar feature, running a function only if the logout is successful.</p><p>Let’s make it so that the user is saved in App.js’s state when they log in. Import useState from react: import React, { useState } from &#39;react&#39; . Then change the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*rve_Q29pdz3lCqe7LwfeGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*_9tCrHVS3T2_CxViW8k8Hg.png" /></figure><p>And right above the Login button add this.</p><p>Let me break this down. React hooks hold their data in state, so we need to import useState from react. We tell the component to have a state called ‘user’, and we make a function that matches it, ‘setUser’, which we will use to modify the ‘user’ state. useState() means the state starts off empty, but we could pass it anything to be the default state. And now responseGoogle will set the user to be the user object that Google sends back.</p><p>In the bottom picture, {user &amp;&amp; (...is like an if statement. If user evaluates to true, render that &lt;h1&gt; element. User starts off undefined, so this element will not render until we click login, setting the user state, and making user truthy.</p><p>Let’s go ahead and add this to our logout function: setUser(); . Now when we click logout our user becomes undefined again, and that &lt;h1&gt; tag no longer renders.</p><p>We have successfully allowed users to log into and out of our website! And you might have noticed that this login already is persisting. You can test it yourself: the logout function does not run unless a logout was successful. Clicking logout when you aren’t logged in will not log anything. So login, close the browser, and reopen it. Immediately click logout, and you can see the log of ‘logged out’, meaning you were still logged in from the last time. So the next step is to check to see if a user is already logged in when the page loads. I’ll likely write my next blog about that, but here’s a hint: it involves useEffect() and the GoogleAuth object found <a href="https://developers.google.com/identity/sign-in/web/reference#googleauthsignin">here</a>.</p><p>Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19c8300e8950" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a React Website with an Express backend]]></title>
            <link>https://levelup.gitconnected.com/create-a-react-app-with-an-express-backend-24740b0a6f5e?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/24740b0a6f5e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 12:49:24 GMT</pubDate>
            <atom:updated>2020-07-15T21:37:29.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*600bP6rXZkuc_Sna" /><figcaption>Photo by <a href="https://unsplash.com/@joannakosinska?utm_source=medium&amp;utm_medium=referral">Joanna Kosinska</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Starting a new project can be difficult, with many tiny but crucial steps. I hope to help you make some very basic scaffolding that will get you started on your website as quickly as possible. We’ll take advantage of create-react-app, tweaking it slightly to give us a backend server we can use.</p><h4>Create directory</h4><p>First, create a new directory and enter it by running the following commands.</p><pre>mkdir example<br>cd example</pre><p>Then, run this command to initialize your directory with some basic information (leaving off the -y will allow you to manually enter that information):</p><pre>npm init -y</pre><h4>Create backend</h4><p>Next, create a folder called server and a file inside of it called index.js. You can do all this by clicking file, add new folder, etc.., but here are some quick commands to do so instead:</p><pre>mkdir server<br>cd server<br>touch index.js<br>cd ..</pre><p>Now that we have an index.js, let’s install Express:</p><pre>npm install express</pre><p>And inside the index.js, fill it like so:</p><pre>const express = require(&#39;express&#39;);</pre><pre>const path = require(&#39;path&#39;);</pre><pre>const app = express();<br>// a test route to make sure we can reach the backend<br>//this would normally go in a routes file</pre><pre>app.get(&#39;/test&#39;, (req, res) =&gt; {</pre><pre>res.send(&#39;Welcome to the backend!&#39;)</pre><pre>})</pre><pre>//Set the port that you want the server to run on</pre><pre>const port = process.env.PORT || 8080;</pre><pre>app.listen(port);</pre><pre>console.log(&#39;App is listening on port &#39; + port);</pre><p>We want to be able to run our server with a simple command, so go into the package.json scripts and add this start script:</p><pre>&quot;scripts&quot;: {<br>    &quot;server&quot;: &quot;node server/index.js&quot;<br>  },</pre><p>At this point you should be able to run the server by typing npm server and it should say that the server is listening on the specified port. Go to localhost:8080/test to see our “Welcome to the backend” message. Now let’s make our frontend.</p><h4>Create React frontend</h4><p>The docs for using create-react-app are very <a href="https://create-react-app.dev/docs/getting-started/">straightforward</a>. One line of code will give us everything we need to get started:</p><pre>npx create-react-app client</pre><p>client is the name of where we want the react app to be created. Because we want our backend and frontend separated, we used create-react-app inside a separate folder (client) within our website’s directory (example).</p><p>Note that there are <a href="https://www.npmjs.com/search?q=cra-template-*">templates</a> available for create-react-app, and you can use them by simply runningnpx create-react-app &lt;folder-name&gt; &lt;template-name&gt;</p><p>At this point your file tree should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*6JCB6m6JoNWZcUGOQekBPg.png" /></figure><h4>Connect the two</h4><p>The last thing we need to do is make sure our frontend and backend can communicate. The development server is running on localhost:3000 (by default) and our backend server is running on localhost:8080. Because they are different servers, sending a request like axios.get(&#39;/test&#39;) would send the request to localhost:3000/test, rather than localhost:8080/test. So go into the <strong>client/package.json</strong> and add a proxy:</p><pre>&quot;proxy&quot;: &quot;http://localhost:8080&quot;,</pre><p>This proxy will tell React that any unknown requests to localhost:3000 should be sent to localhost:8080. Now we can make requests to our server easily from the frontend.</p><p>To test this, we can add a button with a custom function in App.js:</p><pre>&lt;button onClick={hitBackend}&gt;Send request&lt;/button&gt;</pre><p>And here is the function:</p><pre>const hitBackend = () =&gt; {</pre><pre>axios.get(&#39;/test&#39;)</pre><pre>.then((response) =&gt; {</pre><pre>console.log(response.data)</pre><pre>})</pre><pre>}</pre><p>Now clicking that button will display a console log of “Welcome to the backend”, so we know that we are hitting our server.</p><h4>Quality of life additions</h4><p>You’ll notice that there are two package.json files in this setup. This can get tedious and confusing, as you have to switch directories to do each npm install . So I recommend creating a couple scripts in the <strong>root package.json</strong> so you can do everything from there without having to change directories.</p><pre>&quot;scripts&quot;: {<br>&quot;server&quot;: &quot;node server/index.ts&quot;,<br>&quot;client&quot;: &quot;cd client &amp;&amp; npm run start&quot;,<br>&quot;build:client&quot;: &quot;cd client &amp;&amp; npm run build&quot;,<br>&quot;iall&quot;: &quot;npm i &amp;&amp; cd client &amp;&amp; npm i&quot;,<br>&quot;startboth&quot;: &quot;npm run server &amp; npm run client&quot;</pre><pre>},</pre><p>Now you can start and build the client without changing directories, and running iall will install everywhere so you don’t forget to do it in both. The startboth script will start the server and run it in the background (because of the &amp;), then start the client.</p><p>You probably also want to install a linter such as eslint. You’ll need to do these steps both in the <strong>root directory and in the client</strong>:</p><pre>npm install -D  eslint</pre><p>The -D installs the package as a developer dependency, meaning it will be purged when you build it, saving space. Next, run</p><pre>eslint --init</pre><p>This will ask questions to setup the eslint configuration files. The questions are pretty simple, here are my preferences for this project:</p><ul><li><strong>How would you like to use ESLint? </strong>To check syntax, find problems, and enforce style</li><li><strong>What type of modules does your project use? </strong>Javascript module (import/export)</li><li><strong>Which framework does your project use? </strong>React</li><li><strong>Where does your code run? </strong>both</li><li><strong>How would you like to define a style for your project? </strong>Airbnb</li><li><strong>What format do you want your config file to be in? </strong>JSON</li></ul><p>After running that you should see two .eslintrc.json files, and if you make mistakes in your files they will be underlined in red.</p><p>At this point we’ve gotten everything set up, so we can actually start coding. After removing some of the files that came with create-react-app, I would save this example as a template, so that you can quickly clone it when you need to spin up another react app. That way you are not constantly spending time creating a new app each time. I hope you found this guide helpful and that it saved you some time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24740b0a6f5e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/create-a-react-app-with-an-express-backend-24740b0a6f5e">Create a React Website with an Express backend</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL in a nutshell]]></title>
            <link>https://medium.com/@jimmyroro58/ssl-in-a-nutshell-fbde788e1047?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbde788e1047</guid>
            <category><![CDATA[tsl]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[ssl]]></category>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 12:09:18 GMT</pubDate>
            <atom:updated>2020-06-29T12:09:18.950Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was making an app using Google’s API, and I received an error message telling me I couldn’t use the API without upgrading to HTTPS. I thought ‘Easy enough, it’s just one letter different from the HTTP I’m using’. I obviously had no idea what I was talking about. Several hours and lots of frustration later, I had used certbot to obtain a certificate and successfully upgrade my site to HTTPS. Let me share what I’ve learned.</p><h4>SSL and TLS</h4><p>Secure Sockets Layer. Transport Layer Security. What is are these things? They are both <a href="https://www.globalsign.com/en/blog/ssl-vs-tls-difference">cryptographic tools for authentication and data encryption</a> between machines over a network. The two have a common, long history together, creating confusion between them. But in fact, TSL is just a shiny, newer SSL.</p><p>SSL was launched in 1995 by Netscape, where it went through several versions over the years. It was given to the IETF (Internet Engineering Task Force) in 1999. That same year, IEFT changed the name from SSL to TLS and released TLS version 1.0 (i.e. SSL version 3.1). TLS was much more robust than SSL and grew in popularity, with new versions coming out in 2006 and 2008. However, websites still used (and are still using!) SSL 3.0, hence the confusion and interchangeability between the two. SSL was officially deprecated in 2015, and TSL 1.3 was approved in 2018. As time passes, references to SSL will become less common, though it is <a href="https://www.watchguard.com/wgrd-resource-center/security-report-q3-2018">certainly still active today</a>.</p><h4>HTTP vs HTTPS</h4><p>Now, how is SSL/TSL used? You probably know that HyperText Transfer Protocol (HTTP) is the protocol that browsers and webservers use to communicate. But you might not know about how this connection is established. Whenever you go to a website, the browser (the user accessing the page) and server (the computer serving the website) engage in a ‘handshake’ before any data is transferred. During this process, they agree on how they will communicate, which is a four step process:</p><ul><li>Client hello: the browser sends a list of all SSL/TLS algorithms it can use</li><li>Server hello: the server chooses the best SSL/TLS configuration, based on its setup, and replies with its SSL/TSL certificate</li><li>Client key exchange: the browser checks the certificate. It then generates a ‘pre-master key’, encrypts it using the server’s public key from the certificate, and sends it back</li><li>Change Cipher: the server uses its private key to decrypt the pre-master key. Now both server and browser generate a master ‘shared secret’ that they use to encrypt and decrypt communication.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xlV6caCfQjEMvU2O.png" /></figure><p>At this point, all data between the two are securely encrypted; you are now using HTTPS! You can check to see if you are using HTTPS by looking in the URL bar: a lock will denote a secure connection, while red will show an insecure connection.</p><p>The differences arise from the server’s certificate. Browsers check the certificates they receive for verification. It’s possible for a server to sign its own certificate, which really provides no verification at all that the server is legitimate. It’s like me handing a police officer a driver’s license I drew myself. This certificate would generate scary warnings when you visit the site.</p><p>Ideally, a website is verified by a third-party, kind of like a background check. The more intensely scrutinized, the more secure (and expensive) the certificate will be. I was able to use <a href="https://certbot.eff.org/">certbot </a>to create a free certificate, and all I needed was an email. My site gave some yellow warnings about security, because my certificate was not well verified. It’s closer to a real driver’s license, but not quite there. Well known sites like Google or Amazon have extended validation, and their certificates would be like full-blown passports.</p><p>The gist of it all is that SSL and TSL are arguably the same thing, but just different versions. Your website needs a certificate to prove that it is legitimate, and that certificate should probably be in TSL because SSL is deprecated. The strength of your certificate depends on who verifies it, and it needs to be renewed periodically. If you are still aren’t sure about everything, check out this <a href="https://howhttps.works/">amazing cartoon</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbde788e1047" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment, starring Microsoft Azure]]></title>
            <link>https://medium.com/@jimmyroro58/deployment-starring-microsoft-azure-4b4153083e22?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b4153083e22</guid>
            <category><![CDATA[microsoft-azure]]></category>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Sun, 31 May 2020 23:28:16 GMT</pubDate>
            <atom:updated>2020-05-31T23:28:16.700Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MYhZ_eoTNWC14qT8.png" /></figure><p>The time has come. You’ve spent hours perfecting your website. You have routes, endpoints, a server, beautiful HTML, everything is perfect and working on your local machine. So now you just have to make your website available to other people. It is very often the case that you’ll want to host your server/database on another computer that is dedicated to running it. Using a cloud service has many benefits, particularly in security and scalability. This process is called deployment, and it can be very tricky.</p><p>Before deployment, you need to make sure that your code will still work when moved to a different computer. You have to ensure that the computer has the correct node version, dependencies, file paths, API keys and more, which are all things you take for granted when working on a local computer. You can use <a href="https://coderwall.com/p/8nhqeg/relative-paths-from-the-root-in-javascript">root-relative URLs</a> instead of absolute ones so that you don’t get messed up by differing file trees. I would also highly recommend reading this article on <a href="https://medium.com/chingu/an-introduction-to-environment-variables-and-how-to-use-them-f602f66d15fa">environment variables</a>.</p><p>Getting back to deployment, it’s time we actually got to using Azure. First you should create an account at <a href="http://azure.portal.com/">azure.portal.com</a>. When you sign up, you get a $200 credit to let you experiment with their services, and you won’t be automatically enrolled for billing, so you don’t have to remember to unsubscribe if you don’t like the service. Azure has tons of options to choose from, so picking the right one for the job is half the battle. In this example, we will create a virtual machine.</p><p>After logging into Azure Portal, type into the searchbar ‘virtual machine’ and click on it from the results. You probably don’t have a virtual machine set up, so click create virtual machine at the bottom. Your page should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyZRyYSLBFonMODPPUPmLQ.png" /></figure><p>You’ll select the subscription that you want to use and create a new resource group. A resource group is a way to organize your apps, databases, and storage into one logical place. We don’t have anything else yet, so this isn’t important now, but if we wanted to add another virtual machine later we might put them both in the same resource group if they were related.</p><p>Next, choose our Instance details. Name the machine whatever you want, and select the region. It’s recommended that you choose a region closest to where you anticipate most traffic to come from to reduce latency. The farther a request has to travel, the longer it will take for your website to respond, so choose a close region unless you have reason to do otherwise.</p><p>If you’d like, you can choose an availability set or zone to provide you with redundancy. You don’t have to worry about this right now, but redundancy makes your resources more resilient against disruptions. For example, if you have multiple resources from Azure you might consider housing them in different zones or sets. That way, if something happens and there is an outage in one zone, all of your resources won’t be affected, only those in that zone.</p><p>Image and size are probably the most important choice you have to make here. The image refers to what OS you want to run, and Azure has many options to choose from. We’ll choose Ubunto 18.04 LTS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*e0_Kd1nJdH65GUbw7qJ-tg.png" /></figure><p>Size refers to the power of the machine, including memory, storage, and speed. The size also largely determines how much it will cost each month to run your machine. We have that $200 credit, so feel free to go crazy if you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*8L83UTt3E6Ozb588M_Dn-w.png" /></figure><p>Next is the option to use an SSH key or a password to secure your machine. An SSH key consists of a public and private cryptographic string. You store the private one on your computer and will give the virtual machine your public one. The virtual machine will allow access to anyone with authorized SSH keys. Consider reading <a href="https://www.ssh.com/ssh/public-key-authentication">this</a> article on what exactly an SSH is. And creating your own is pretty simple, just run this in your local terminal:</p><pre>ssh-keygen -b 4096</pre><p>It will ask you for a password (if you don’t want a password, just hit enter) and then save your new keys in the root directory here: /home/&lt;your_home&gt;/.ssh/id_rsa Go to that directory and open up <strong>id_ras.pub. Do not use the private one! </strong>Copy the contents of that file (which should begin with ssh-rsa) into the SSH public key field on Azure’s site:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*F2UVh4JM7V1biduvxHZqnQ.png" /><figcaption>user and machine name should be the name of your local machine</figcaption></figure><p>Lastly, we’ll want to choose HTTP 80 and SSH 22 so that all IPs can access our the website (or whatever) our machine will be serving. If we select none, then only other virtual machines that are within the same network can access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*aEAgT5azOBTeDsKjlnFmJQ.png" /></figure><p>You can certainly customize it more, but for now we can go ahead and create the machine!</p><p>After it’s created, we can access it through the same terminal that we used to create our SSH keys. Just run the following(remember you don’t need the &lt;&gt;)</p><pre>ssh &lt;the username you created&gt;@&lt;public ip address&gt;</pre><p>You can find both of those values on the overview tab when viewing the virtual machine on Azure Portal. It will say that its authenticity can’t be established; that’s normal because it’s the first time we’ve used this virtual machine. Type yes, enter the SSH password if you made one, and voila! We are now using our virtual machine from our bash terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*E6MTjSYCdfm-nrwKjGufHQ.png" /><figcaption>Run this command for accessing our virtual machine.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*QDLgSuDvmCvRjOLUbgG7yw.png" /><figcaption>We know we are using the virtual machine because our user@machine in the terminal changed</figcaption></figure><p>If you want to exit your session on this virtual machine press ctrl d or type logout .</p><p>Creating the machine is just the tip of the iceberg. You can spend many days viewing the customization options and learning about the nuances of cloud hosting, but hopefully this tutorial was enough the get you going. Remember that your virtual machine is a brand new environment, so you’ll need to reinstall dependencies and packages and all the other fun stuff your code needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b4153083e22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DOMS, Shadow and virtual]]></title>
            <link>https://medium.com/@jimmyroro58/doms-shadow-and-virtual-38b6cff0f7f3?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/38b6cff0f7f3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Mon, 25 May 2020 13:53:26 GMT</pubDate>
            <atom:updated>2020-05-25T19:15:45.943Z</atom:updated>
            <content:encoded><![CDATA[<p>When you visit a URL, the page is created using HTML. But this HTML has to get on the page somehow, right? So your browser uses the DOM. The DOM (Document Object model) is a representation of the structure of a document on the internet. When a webpage is loaded, the browser parses the static HTML into an in-memory representation of this text, which has a tree-like structure. This tree creates a standard programming interface, allowing any scripting language to be used to manipulate it — all my examples use JavaScript, but they could just as easily be in Python, for example. Here is how a single list element would look when written as HTML:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*sCB2nTTL6m6Q2NgUAOuXkg.png" /><figcaption>An html document written in JavaScript</figcaption></figure><p>And here is the DOM of that same HTML:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*xXnLiJUb9RGZD8xPUM3qBA.png" /><figcaption>A DOM tree that represents that html document</figcaption></figure><p>If you wanted to add a second item to your list, you would do so by using the DOM’s APIs to create that element (line 5), find where you want to add it (line 4), and add it (line 8). Adding this one element to our list will cause the DOM to re-render, and our second list will appear on the page! But there is a problem: even though we only added one thing, the entire DOM is re-rendered. Imagine if we had thousands of things on our list: each time we added something, we’d have to re-load all of them! So we need a way to only render what has been modified and not the entire DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*qPpsjEgFuTvZqUQW5ftvag.png" /></figure><p>Virtual DOM — Representing a Representation</p><p>You can overcome this problem by using something called the <a href="https://bitsofco.de/understanding-the-virtual-dom/">virtual DOM</a>. The DOM is an object representation of our page’s HTML, and the virtual DOM is a plain JavaScript object that represents that representation (crazy!). Our list from above would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*lXR0ySvUaoZHEBN9UlI2JQ.png" /></figure><p>React and Vue use the virtual DOM as this sort of ‘testing ground.’ Any change you would make to the DOM is instead made to the virtual DOM. Then, the virtual DOM is compared to the actual DOM in a process called ‘diffing’. During diffing, all the differences between the virtual DOM and the actual DOM are aggregated. Lastly, the DOM is re-rendered, but <strong>only the changed elements are re-rendered. </strong>It might sound like there are many extra steps and they’d take up more time, but the performance gains from using a virtual DOM are significant, especially with larger webpages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*egvB2QsGt9oprP-Wda0yAw.png" /><figcaption>The DOM is only updated at the end, and only elements that need to be updated</figcaption></figure><p>Tangentially, the <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM">Shadow DOM</a></p><p>While we’re talking about the two DOMs, I figured I would introduce you to a third: the Shadow DOM. It sounds pretty spooky, but the Shadow DOM is a handy tool specifically designed for <a href="https://www.freecodecamp.org/news/here-are-some-practical-javascript-objects-that-have-encapsulation-fc4c1a79c655/">encapsulation</a>. Encapsulation means hiding information and complexity, and keeping a minimal interface. You attach Shadow DOMs to particular elements within the DOM, and from there the Shadow DOM begins to function as its own separate, hidden DOM. These hidden DOMS create their own scope, where none of the code inside can escape and affect anything outside them. You can then specify whether you want code from outside the Shadow DOM to be able to get in and affect the inner code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*hvVOiSxFfmWR7z0k.png" /><figcaption>The shadow tree is rendered similarly to other elements, except it has its own code within it</figcaption></figure><p>The node you attach a Shadow DOM to is called the shadow host. Within the Shadow DOM you have a shadow tree and a shadow root, all <strong>encapsulated </strong>within the shadow boundary. Shadow DOMS can come in really handy if you have many different elements on a webpage that need their own css, as each Shadow DOM can have its own stylesheet and set of unique IDs. Shadow DOMs can improve performance somewhat, as each can be rendered independently of the DOM, but they are largely used to create elements that follow their own rules.</p><p>To recap:</p><p><strong>The DOM</strong> is a representation of the structure of a document on the internet. It is a tree-like object that allows scripting languages to modify webpages.</p><p>The <strong>virtual DOM</strong> is a Javascript object representation of the DOM, which we can modify as frequently as we need to. Changes made to this object are collected, and modifications to the actual DOM are targeted and made less often.</p><p>Each <strong>Shadow DOM</strong> is like its own sub-DOM. They encapsulate elements and allow them to run code that is bound to the limits of the Shadow DOM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38b6cff0f7f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript or Java?]]></title>
            <link>https://medium.com/@jimmyroro58/javascript-or-java-16123fca011a?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/16123fca011a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Mon, 18 May 2020 13:17:44 GMT</pubDate>
            <atom:updated>2020-05-18T13:19:45.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java or Javascript: What’s the Difference?</h3><p>Something that can be really confusing is the similarity in names of two languages, Java and Javascript. Although you can find both languages in use today and there is overlap between them, they occupy different niches and operate in fundamentally different ways. <strong><em>Java was designed to build standalone applications, while Javascript specifically interacts with web HTML</em></strong><em>.</em> I’ll walk you through the similarities and differences between them, and when you should consider using one over the other.</p><h3><strong>Similarities</strong></h3><ul><li><a href="https://en.wikipedia.org/wiki/Object-oriented_programming"><strong>Object-oriented programming (OOP)</strong></a><strong>: </strong>both languages use objects and the objects’ relationships to each other to create computer programs. By being object based, techniques like <a href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)">inheritance</a>, <a href="https://stackify.com/oop-concept-for-beginners-what-is-encapsulation/">encapsulation</a>, and <a href="https://stackify.com/oop-concept-polymorphism/">polymorphism </a>can be used.</li><li><strong>Front-end use</strong>: The way they do it is different, but both Java and Javascript can run in a browser to make websites more interactive; Java uses applets and Javascript is directly embedded in HTML. However, Java applets have been declining in use in websites over the years due to compatibility and security reasons.</li><li><strong>Back-end: </strong>The two can also be used server-side. Java outshines Javascript here, with long-time services Apache, JBoss, and WebSphere. The release of Node.js has allowed Javascript to gain popularity in the back-end area.</li></ul><h3><strong>Differences</strong></h3><p>The chart below offers a side by side comparison of the differences between the two languages. They stem from four larger, fundamental differences in how the languages operate: compiling, type-checking, concurrency, and inheritance patterns. These differences allow each to have its own specialization and not be directly competing with the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*VbqIFA-zOH_eq0iM" /></figure><p><strong>Compiled vs Interpreted</strong></p><ul><li>Java is <a href="https://en.wikipedia.org/wiki/Compiler"><em>compiled</em></a>, meaning that after the source code is written, it’s first translated into unreadable machine code, and then implemented using a java virtual machine (JVM) or browser. The advantage of compiling first is that it tends to be faster than translating at run time. One disadvantage is that code becomes set once compiled — if you change the source code, you’ll need to recompile. Another is that compiled files cannot be read by people.</li><li>Javascript is <em>interpreted directly by the browser</em>, without being translated or changed. This allows human readability and is simpler to implement, but is generally not as fast as compiling beforehand.</li></ul><p><strong>Static vs Dynamic Type Checking</strong></p><ul><li>Java is strongly typed, meaning that it has stricter syntax and rules on its usage. For example, you must specify the type of data when declaring a variable (integer, string, etc). The code is checked at compile-time to see what data types are used and if there are errors. The compiler will then know exactly what data type is being used at run-time, and so it will likely execute faster or use less memory.</li><li>Javascript is not as strongly typed, and you don’t need to specify the data type when making a variable. This allows programmers more freedom, as you can assign types as needed, but does slow down execution because the types of data must be checked at run-time.</li></ul><p><strong>Concurrency</strong></p><ul><li>Perhaps the greatest strength of Java compared to Javascript, concurrency is the ability to process multiple tasks at once. Java can work on many threads in parallel and share memory between threads, resulting in faster execution of code.</li><li>Javascript has one main thread, a queue system called the event loop, and a forking system called Node Clustering. It uses asynchronous calls, callbacks, promises, and event loops to simulate multi-threadedness. This whole process is a topic unto itself, but suffice it to say that it is a good system, but not as good as actually being multi-threaded.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*BCbOpISxyyZ3tCpE.png" /><figcaption>A very simplified diagram of how multiple thread processing looks</figcaption></figure><p><strong>Class vs Prototype inheritance</strong></p><ul><li>Inheritance is very important in making DRY (Don’t Repeat Yourself) code. In Java, <strong>all </strong>objects are classed based: you can’t make a program without making a class. It’s a top down, hierarchical relationship that creates parent/child taxonomies. These relationships can sometimes get tangled up — be careful not to overuse a base class, lest you create the<a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-s-the-difference-between-class-prototypal-inheritance-e4cd0a7562e9"> <em>fragile class problem</em></a><em>. </em>Additionally, classes are immutable: they can’t be modified at runtime</li><li>Javascript uses a prototype inheritance pattern: all objects are able to inherit from any other object. So, you can have an object inheriting methods from many unrelated objects, without them being parent/children. You are creating the relationships as you go, and so it is easier give an object <strong>only</strong> what it needs. Javascript can also modify methods at runtime if desired.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*7zXum3BMQL-YRQSE.png" /><figcaption>v1 and v2 are vehicle objects. In Java, they are <strong><em>created</em></strong> using the Vehicle class. In Javascript, they are <strong><em>linked</em></strong> to the Vehicle Prototype. Notice that the arrows are reversed between Class and Prototypal.<em> Information flows downward from a class in Classical, but Prototypal looks up and backward for information.</em></figcaption></figure><h3><strong>Which Should You Use?</strong></h3><p>Now that you know more about how Java and Javascript differ from each other, you may be wondering when you should use which. Both have their strengths, and it really depends on what your goal is.</p><p>As I mentioned earlier, Javascript has been designed to be used in a web browser, so consider using it if you are <strong>creating single page applications</strong> or using <strong>front-end technologies like jQuery, ReactJS, AngularJS, or Backbone. </strong>You don’t need a compiler to run Javascript, and it is a more forgiving, human-friendly language.</p><p>Java, on the other hand, is a more general purpose language. You might consider using Java to <strong>create Android apps, analyze big data, or to program hardware. </strong>Java typically runs faster, but is heavier, harder to alter, and a stricter language than Javascript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16123fca011a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[But I Have Promises to Keep]]></title>
            <link>https://medium.com/swlh/but-i-have-promises-to-keep-dad0bf5a3f7e?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dad0bf5a3f7e</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Mon, 11 May 2020 05:07:27 GMT</pubDate>
            <atom:updated>2020-05-12T16:55:08.421Z</atom:updated>
            <content:encoded><![CDATA[<h4>and script to write before I sleep</h4><p>You may not know, but you likely just made a promise right now viewing this web page. Promises are powerful tools that arrived with the release of the ECMAScript 6 update (aka ES6), and they can save a lot of headache when dealing with asynchronous requests. I will give you a brief overview on the problem and how promises solves it.</p><h3>The Problem</h3><p>Javascript is a <strong>single threaded language</strong>, meaning that it processes tasks in order, one at a time. Code bits cannot run simultaneously. Say you had a web page with two buttons. One initiates a giant, tedious, recursive call that renders images on the screen and takes seconds to complete. The other logs ‘hello world’ to the console. If you click the first button and then click the second, the console log will not appear until the first button completes its actions.</p><p>You might use some asynchronous code to help circumvent this. When loading a web page, for example, you can use AJAX requests to render some elements onto the page before others, so that the user can use the website while other parts load. If you’re not comfortable with asynchronicity ,you can read more about it <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests">here</a>.</p><p>But what if one of your functions depended on something retrieved asynchronously? You don’t know exactly how long the request might take.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*t8bHKSryHRkvbFH2jFSECw.png" /></figure><p>Imagine Function A is loading an image asynchronously and Function B attempts to reference Function A; a reference error would be thrown because Function A hasn’t returned anything yet. You’d need a way to ensure that B doesn’t execute until A had.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*6pP6bmLPn60tgHlx-KCnrQ.png" /></figure><p>Things might get even more complicated if Function D relied on the output of A, B, and another asynchronous Function C. And then something else relied on D. And so on, forever.</p><p>You can handle this by passing in functions as callbacks, with one to execute on success and one for failure.</p><pre>doSomething(parameter, successCallback, failureCallback)</pre><p>But what if you had many asynchronous calls? You might end up with some nasty code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*YHFyCtjlIZvufDIdA9AbCQ.png" /><figcaption>“The Pyramid of Doom.” Each function takes a callback that will be executed on success and a callback to be executed on failure. This ensure that no errors are thrown, because something will always be returned. But at what cost?</figcaption></figure><h3>Enter the promise!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*H965e4ThhdTX7y8E.jpg" /></figure><p>ES6’s promise object allows us to chain functions together in an elegant way while ensuring that the timing of those functions is appropriate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*I5iM6BKh0Nur2h5DVqyApQ.png" /><figcaption>Very similar to the above, but notice .then()</figcaption></figure><p>When using a promise, doSomething won’t be called until the Javascript event loop completes its current run; when the interpreter gets to the promise, the asynchronous method returns a <em>promise</em> to supply the value at some point in the future and the interpreter continues on.</p><p>Below, once doSomething completes, doSomethingElse will be invoked if it was successful and failureCallback will be invoked otherwise. Then, if doSomethingElse was successful, doThirdThing will execute. In this way, you can think of promises as if….then chains but for asynchronous requests. The benefit of promises is that they are <strong>chainable </strong>and <strong>easy to use. </strong>Here, all the failures would run the same function, failureCallback, but you could certainly have each function have its own unique function to run if failure is encountered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*DnwswpEMV2YM11gtDQCtig.png" /></figure><p>You can even do things after a failure is encountered by chaining .then() after your .catch().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*hnIMw-hDUdpI3rMysv4ILA.png" /><figcaption>This will log ‘Initial’, then an error will be thrown and so the reader would move down to the catch statement and log ‘Do that’, and then it would log “Do this, no matter what happened before’</figcaption></figure><p>An important thing to note during chaining is that each function in the chain does require the previous function to return something in order to be triggered.</p><p>I hope you can see how powerful promises are now! They allow us to deal with issues that arise from asynchronous functions in a more intuitive way. Check out MDN’s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">webpage </a>to see other things you can do with promises, like overriding Javascript’s default behavior when an error is encountered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dad0bf5a3f7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/but-i-have-promises-to-keep-dad0bf5a3f7e">But I Have Promises to Keep</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[So you want to implement a hash table?]]></title>
            <link>https://medium.com/swlh/so-you-want-to-implement-a-hash-table-8a8053c9db51?source=rss-72d1cb2506e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a8053c9db51</guid>
            <category><![CDATA[hash-table]]></category>
            <dc:creator><![CDATA[Richard Rosier]]></dc:creator>
            <pubDate>Mon, 04 May 2020 05:02:59 GMT</pubDate>
            <atom:updated>2020-05-05T12:26:21.951Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve found this page, you’re likely a beginner coder who is starting to learn the ropes of data structures. I’m going to try to keep things brief while still explaining key concepts, and I’ll be focusing on Javascript implementations and explanations. If you know what a hash table is already and are just looking for code, just skip to the bottom :)</p><h4><strong>What is a hash table?</strong></h4><p>Programming languages use hash tables to store <a href="https://en.wikipedia.org/wiki/Unique_key">keys</a> and <a href="https://en.wikipedia.org/wiki/Value_(computer_science)">values</a>. If you’re a Javascript user, you know a hash table already: objects {}. Other programming languages refer to them as maps or dictionaries. Hash tables use arrays, or lists, internally to organize data, and offer advantages over arrays in certain areas, like data retrieval and insertion.</p><p>Hash tables work by storing keys and values as an array inside buckets, which are arrays of arrays. Confused yet? Check this out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*9HBve1zUFfw0sWdrTIFYdg.png" /><figcaption>We have three key value pairs in this table. Two of them are stored in bucket 1, one is stored in bucket 2, and bucket 3 is empty.</figcaption></figure><p>In code, this would look like this, but without the extra whitespace:</p><pre>[ [ [key,value], [key,value] ], [ [key,value] ], [ ] ]</pre><p>By separating the key/values into buckets, we can cut down on our retrieval time, which I will get into later. Right now, I want to explain about why they are called hash tables.</p><p>Consider how you access data from an array vs. from an object. Arrays use an index, objects use a key. But if objects are hash tables and hash tables are arrays, how can you access the information without an index? Enter the <strong>hash function</strong>! Hash functions have a wide range of complexities but the gist is that they take an input and convert that input to a number, and that input will always produce the same number, called a <strong>hash</strong>.<strong> </strong>So every time we input the string of ‘cat’ it will always return 12, for example. <a href="https://privacycanada.net/hash-functions/what-are-hash-functions/">Here </a>is a little bit more info on them. For hash tables, the hash function will typically take an input of the array’s length and perform a modulo (%) operation to prevent a hash that is longer than the array’s length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*QCDoJtiQHpeAcoJcH-SveQ.jpeg" /></figure><p>Our given key is passed in through a hasher function, which will generate a number, or hash. That number is then used as the index for placing the key and value into a bucket. Depending on how advanced your hashing function is, you will likely encounter two keys that generate the same hash.</p><p>When you put a key/value into a bucket that already has something in it, it’s called a <strong>collision</strong>. Collisions can be avoided by using a better hashing function and increasing the number of buckets (the size of your hash table array). Well implemented hash tables will resize themselves to maintain an optimal amount of buckets. Too many buckets are a waste of space, while too few buckets create more collisions. Divide the number of keys by the number of buckets; hash tables work best when that number is between .25 to .75.</p><h4><strong>Why do we need hash tables?</strong></h4><p>The reason we have both hash tables and arrays is that by storing data in different ways, they perform operations at differing speeds. Consider the time it takes to add, delete, or find something in a hash table vs. an array.<br>(If you are unfamiliar with <a href="https://www.bigocheatsheet.com/">Big-O time complexity</a>, O(<em>1</em>) is constant speed, O(<em>n</em>) is linear and grows as the size of the inputs, n, grows.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0x4UbvK3AiQbmm_cZchWQ.png" /><figcaption>By grouping key/values into buckets, we can search, add, and delete things from the object much faster than if we had put those values into an array.</figcaption></figure><p><strong>Key takeaways of the differences between hash tables and arrays:</strong></p><ul><li>Search on an array is <em>O(n)</em> while on a hash table is <em>O(1).</em></li><li>Arrays’ keys (index) are always a number 0 or greater. They can have any type of value, and values can be duplicated.</li><li>Hash table’s keys can be anything, as long as your hasher can handle them and each key is unique. Values can be any type and can have duplicates.</li></ul><h4>A hash table implementation</h4><p>Here is a basic, mostly working has table. I say mostly working because it doesn’t automatically resize itself or overwrite keys. Can you figure out how to make it do that? If you can’t, I recommend you go visit <a href="https://adrianmejia.com/data-structures-time-complexity-for-beginners-arrays-hashmaps-linked-lists-stacks-queues-tutorial/#HashMaps">Adrian Mejia</a>’s guide on data structures. It’s very in depth, and you can see an optimized hash table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*wNXztULZnDDVU_nUFnirdQ.png" /></figure><p>Ultimately, hash tables are another tool that allows us to handle data in different ways. Using them solves some problems and creates others, and knowing when to use a hash table vs an array is part of the knowledge gained when learning to code. If you’re like me, you’ve used objects in javascript without even thinking about what’s going on under the hood, and I hope this has allowed you to understand how they work a little better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a8053c9db51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/so-you-want-to-implement-a-hash-table-8a8053c9db51">So you want to implement a hash table?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>