<?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 Santiago on Medium]]></title>
        <description><![CDATA[Stories by Santiago on Medium]]></description>
        <link>https://medium.com/@santiagobedoa?source=rss-30d1fd7806fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ANV9zN3-7TZl1mDex5eb5g.jpeg</url>
            <title>Stories by Santiago on Medium</title>
            <link>https://medium.com/@santiagobedoa?source=rss-30d1fd7806fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:41:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@santiagobedoa/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[Building a Full-Stack Blog Application: A Step-by-Step Tutorial]]></title>
            <link>https://medium.com/@santiagobedoa/building-a-full-stack-blog-application-a-step-by-step-tutorial-ad9067a8ec90?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad9067a8ec90</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 00:10:19 GMT</pubDate>
            <atom:updated>2023-09-19T18:53:09.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPpP8am56WNp6HfGs-Z8Lg.png" /></figure><p>Blogging has become an essential tool for individuals and organizations alike to share their thoughts, opinions, and knowledge with the world. With the advancement of technology, creating and managing a blog has become easier than ever. In this post, we will discuss how to build a blog post app using React, Node.js and MySQL. React is a popular front-end JavaScript library for building user interfaces, while Node.js is a powerful back-end JavaScript runtime environment that can be used with MySQL, a popular open-source relational database management system to create scalable, robust and efficient web applications.</p><p>By combining these technologies, we can create a powerful and dynamic blog post app that will allow users to create, view, and interact with blog posts. We’ll be creating a database to store posts and user information using MySQL, we’ll use Node.js and Express to create a server that interacts with the database. Next, we’ll build a front-end user interface using React, allowing users to create and edit blog posts. By the end of this tutorial, you will have gained a solid understanding of how to integrate these technologies to create a fully functional web application. So let’s get started and learn how to build a blog post app with React, Node.js, and MySQL.</p><h4>How will the application be?</h4><p>On the Home page of our blog post application, we will employ a query to retrieve all posts stored in the MySQL database. Upon clicking a specific post, the application will execute a query to retrieve the details of the post, including the user who wrote it. This functionality will require a demonstration of how to join different tables within the MySQL database.</p><p>User registration and login features will be implemented and only authorized users, who are the creators of posts, will be granted editing and deleting permissions. Additionally, the application will offer to the users the ability to write posts using a rich text editor, allowing the application to manipulate text style, and upload images to use as post covers.</p><p>The application will also provide a sidebar displaying only similar posts to the one being viewed. This project will help developers in understanding the basic concepts of React and MySQL, database relationships, user authentication, JSON, web tokens for security, cookies manipulation, and other essential functionalities.</p><h4>Quick overview of React and Node.js</h4><p>React is a popular open-source JavaScript library used for building user interfaces. It was developed by Facebook and released in 2013. React uses a virtual DOM (Document Object Model) which is a lightweight copy of the actual DOM that allows React to efficiently update only the parts of the UI that need to be changed. This approach provides better performance compared to traditional approaches where the entire DOM is updated.</p><p>React’s component-based architecture is another key feature. Components are reusable pieces of code that define the structure and behavior of a part of the user interface. Components can be nested within each other, allowing developers to create complex UIs by combining smaller and simpler components. This approach promotes code reusability, maintainability, and testability.</p><p>Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows developers to write server-side JavaScript code. This enables the use of a single language (JavaScript) for both client-side and server-side development. Node.js provides non-blocking I/O operations, which means that I/O operations do not block the event loop and can be executed asynchronously. This makes Node.js a great choice for building scalable, high-performance web applications.</p><p>Node.js also has a large and active community with a wide range of modules and packages available through the npm registry. These modules and packages provide functionality that can be easily integrated into Node.js applications, which speeds up development and improves the overall quality of the code.</p><p>Overall, React and Node.js are powerful tools that can be used to build modern web applications. Their popularity is driven by their ease of use, performance, and active communities.</p><h3>let’s get started</h3><p>We will initiate our project by creating a root directory and subsequently adding two subdirectories named ‘client’ (where React app will be located) and ‘api’ (will be the back-end of our app) within it.</p><p>To avoid creating unnecessary files when setting up a React application and to save time on cleaning up the project, please refer to the react-mini branch in my <a href="https://github.com/santiagobedoa/tutorial-blog_post_app">GitHub repository</a>, where you can find a basic project structure to use as a starting point.</p><p>With that said, go to the ‘client’ folder and run the following command:</p><p>git clone --single-branch -b &quot;react-mini&quot; <a href="https://github.com/santiagobedoa/tutorail-blog_post_app.git">https://github.com/santiagobedoa/tutorial-blog_post_app.git</a> .</p><p>Once cloned, run npm install to install all dependencies.</p><p>Note that the ‘pages’ folder found inside ‘src’ contains some .jsx files that will be the pages that our application will have, but how we’re going to reach all those pages? The answer is react-router-dom, but what is it?</p><h3>react-roueter-dom</h3><p>React Router DOM is a library that provides routing capabilities to a React application. It is built on top of the React Router library and provides a higher-level API for building client-side applications with routing. With React Router DOM, you can easily manage the application state and change the content displayed on the screen based on the URL path. It provides a set of components and methods that allow you to define routes and navigate between them using links or programmatic navigation. It also supports server-side rendering and integration with popular state management libraries such as Redux.</p><h4>Example</h4><p>Here is a simple example of how you can use react-router-dom to create a navigation bar with links to different pages in your React application:</p><pre>import { BrowserRouter as Router, Route, Link } from &quot;react-router-dom&quot;;<br><br>function Home() {<br>  return &lt;h2&gt;Welcome to the Home page&lt;/h2&gt;;<br>}<br><br>function About() {<br>  return &lt;h2&gt;Learn more about us on the About page&lt;/h2&gt;;<br>}<br><br>function Contact() {<br>  return &lt;h2&gt;Contact us through the Contact page&lt;/h2&gt;;<br>}<br><br>function App() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;div&gt;<br>        &lt;nav&gt;<br>          &lt;ul&gt;<br>            &lt;li&gt;<br>              &lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt;<br>            &lt;/li&gt;<br>            &lt;li&gt;<br>              &lt;Link to=&quot;/about&quot;&gt;About&lt;/Link&gt;<br>            &lt;/li&gt;<br>            &lt;li&gt;<br>              &lt;Link to=&quot;/contact&quot;&gt;Contact&lt;/Link&gt;<br>            &lt;/li&gt;<br>          &lt;/ul&gt;<br>        &lt;/nav&gt;<br><br>        &lt;Route exact path=&quot;/&quot; component={Home} /&gt;<br>        &lt;Route path=&quot;/about&quot; component={About} /&gt;<br>        &lt;Route path=&quot;/contact&quot; component={Contact} /&gt;<br>      &lt;/div&gt;<br>    &lt;/Router&gt;<br>  );<br>}<br><br>export default App;</pre><p>In this example, we’re using BrowserRouter as the router and Link to create links to different pages. We&#39;re also defining three different page components (Home, About and Contact) that are rendered when the user navigates to the corresponding URL path.</p><h4><strong>Note</strong></h4><p>The Router component is the root component of the routing system. It is responsible for keeping the current URL in sync with the current set of Route components that are being rendered.</p><p>The Route component is used to declare which components should be rendered for a specific URL path. It can take a path prop to specify the URL path and a component prop to specify the component to render for that path.</p><p>It’s important to have all Route components inside the Router component so that the router can match the current URL with the path props of the Route components and render the corresponding components. If the Route components were not inside the Router component, the router would not be able to match the current URL with the path props of the Route components and no components would be rendered.</p><h3>react-router-dom implementation</h3><p>Now you know the basics of react-router-dom let’s install it by running npm install react-router-dom(remember to be located in ‘client’ folder).</p><p>Before continuing we’re going to create the navbar and the footer that will be common components in our pages excluding the login and register page. Let’s create a folder within ‘src’ named components. Within the folder create two files Footer.jsx and Navbar.jsx. Add the following code to each file:</p><pre>// Footer.jsx<br>import React from &quot;react&quot;;<br><br>const Footer = () =&gt; {<br>  return &lt;div&gt;Footer&lt;/div&gt;;<br>};<br><br>export default Footer;</pre><pre>// Navbar.jsx<br>import React from &quot;react&quot;;<br><br>const Navbar = () =&gt; {<br>  return &lt;div&gt;Navbar&lt;/div&gt;;<br>};<br><br>export default Navbar;</pre><p>Now let’s add the routes to App.js file:</p><pre>// App.js<br>// Import the necessary components from the react-router-dom package and other custom components<br>import { createBrowserRouter, RouterProvider, Outlet } from &quot;react-router-dom&quot;;<br>import Home from &quot;./pages/Home&quot;;<br>import Login from &quot;./pages/Login&quot;;<br>import Register from &quot;./pages/Register&quot;;<br>import Single from &quot;./pages/Single&quot;;<br>import Write from &quot;./pages/Write&quot;;<br>import Navbar from &quot;./components/Navbar&quot;;<br>import Footer from &quot;./components/Footer&quot;;<br><br>// Create a Layout component that defines the structure of the web page<br>const Layout = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;Navbar /&gt;<br>      &lt;Outlet /&gt;<br>      &lt;Footer /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>// Define the application routes and components using the createBrowserRouter function<br>const router = createBrowserRouter([<br>  {<br>    path: &quot;/&quot;,<br>    element: &lt;Layout /&gt;,<br>    // Remember that Home, Single post and Write are the pages that will have a Navbar and a Footer<br>    children: [<br>      {<br>        path: &quot;/&quot;,<br>        element: &lt;Home /&gt;,<br>      },<br>      {<br>        path: &quot;/post/:id&quot;,<br>        element: &lt;Single /&gt;,<br>      },<br>      {<br>        path: &quot;/write&quot;,<br>        element: &lt;Write /&gt;,<br>      },<br>    ],<br>  },<br>  {<br>    path: &quot;/login&quot;,<br>    element: &lt;Login /&gt;,<br>  },<br>  {<br>    path: &quot;/register&quot;,<br>    element: &lt;Register /&gt;,<br>  },<br>]);<br><br>// Define the App function that returns the RouterProvider component that provides the routing context to the entire app<br>function App() {<br>  return (<br>    &lt;div className=&quot;app&quot;&gt;<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;RouterProvider router={router} /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Export the App component as the default export<br>export default App;</pre><p>The code defines a Layout component that provides the basic structure of the web page, with a navigation bar, content, and a footer. It then defines the application routes using the createBrowserRouter function from react-router-dom, which takes an array of objects with path and element properties. The path property specifies the URL path, while the element property specifies the component to be rendered when the path is matched. The Layout component is used as a container for the routes, with the Outlet component used to render the nested routes inside the Layout.</p><p>Finally, the App function provides the routing context to the entire app using the RouterProvider component, which takes the router object as a prop. The router object contains all the defined routes. The App function returns a div containing the RouterProvider component wrapped in a container div with the class container.</p><p>Now, if you run your app using npm start and visit <a href="http://localhost:3000/">http://localhost:3000/</a> you should see something like:</p><pre>Navbar<br>Home<br>Footer</pre><p>Or if you visit <a href="http://localhost:3000/write">http://localhost:3000/write</a> you should see:</p><pre>Navbar<br>Write<br>Footer</pre><p>With this, I hope you have a clear understanding of how routes and the Outlet component work.</p><h3>Basic Front-end</h3><p>As the primary objective of this tutorial is to illustrate the integration of React, Node.js, and MySQL to develop a functional application, I will omit the fundamental front-end creation phase, which is more aligned with HTML and CSS writing practices than React programming. However, a template for the basic front-end will be available in the basic-frontend branch of the <a href="https://github.com/santiagobedoa/tutorial-blog_post_app">project repository</a>, which can be used for further development.</p><h4>Make sure</h4><ul><li>You have modified the following files located in client/src/pages/: Home.jsx, Login.jsx, Register.jsx, Single.jsx, Write.jsx</li><li>You have modified the following files located client/src/components/: Footer.jsx, Menu.jsx,Navbar.jsx</li><li>You have created client/src/style.scss file.</li><li>npm install sass: <strong>will be used to style our front-end</strong>. But, what is sass? short for Syntactically Awesome Stylesheets, is a preprocessor scripting language that is compiled into CSS. It extends the functionality of CSS by providing a variety of features such as variables, nested rules, mixins, functions, and more. Sass allows developers to write more maintainable and scalable stylesheets with less repetition and boilerplate code, and it can be integrated into a wide range of development workflows, including front-end frameworks like React, Vue, and Angular. Sass files can be compiled into regular CSS files that can be used in web applications.</li><li>npm install react-quill: <strong>will be used to write articles</strong>. But, what is react-quill? is a React-based rich text editor component that allows users to format and edit text using a toolbar with a variety of options. It is built on top of the Quill.js library, and provides a flexible and customizable interface for creating rich text editors in React applications. With React Quill, developers can easily add rich text editing capabilities to their applications, and allow users to create and format text content with ease.</li></ul><p>If you start the application ( npm start ) it should look like this:</p><ul><li><a href="http://localhost:3000/login">http://localhost:3000/login</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPMN1h3YjGI0QFl5xGUKcw.png" /><figcaption>basic-frontend Login.jsx</figcaption></figure><ul><li><a href="http://localhost:3000/register">http://localhost:3000/register</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZACF84nZnMV_CqCWH0EVg.png" /><figcaption>basic-frontend Register.jsx</figcaption></figure><ul><li><a href="http://localhost:3000/">http://localhost:3000/</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JX3aq2jJUuwjBwFDdTXYQ.png" /><figcaption>basic-frontend Home.jsx</figcaption></figure><ul><li><a href="http://localhost:3000/post/1">http://localhost:3000/post/1</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwzwuPF2yEMfOpscyrO4dA.png" /><figcaption>basic-frontend Single.jsx</figcaption></figure><ul><li><a href="http://localhost:3000/write">http://localhost:3000/write</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6koYhTE_0R0F0rQ0y2thA.png" /></figure><p>Before you go any further, I recommend that you stop and review each of the components that were created and make sure you understand the code, as we will be working on this code from now on.</p><h3>Back-end</h3><p>We will proceed to navigate to the API folder, and initialize a Node application through the npm init -y command. Prior to continuing, let&#39;s install the necessary libraries that we will be working with. First, we will install express via npm install express which will provide us with the ability to create our server. We will also be utilizing mysql2 by installing it via npm install mysql2, and finally, nodemon through npm install nodemon to enable auto-refresh upon changes.</p><p>We will modify the script “test” to “start” in the package.json file and set it to &quot;nodemon index.js&quot; command in order to refresh the server automatically. Additionally, we will add &quot;types&quot;: &quot;modules&quot; in the same file to allow importing libraries in the ES6 module format. package.json should looks like:</p><pre>{<br>  &quot;name&quot;: &quot;api&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;nodemon index.js&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^4.18.2&quot;,<br>    &quot;mysql2&quot;: &quot;^3.1.2&quot;,<br>    &quot;nodemon&quot;: &quot;^2.0.20&quot;<br>  }<br>}</pre><p>Now let’s create index.js file, where we will create our server:</p><pre>// index.js<br>import express from &quot;express&quot;;<br><br>// Create an instance of the Express application<br>const app = express();<br><br>// Use the built-in JSON middleware to parse incoming requests<br>app.use(express.json());<br><br>// Start the server and listen on port 8800<br>app.listen(8800, () =&gt; {<br>  console.log(&quot;Connected...&quot;);<br>});</pre><p>This code sets up an Express application with a JSON middleware and starts a server on port 8800. The app constant is an instance of the Express application, which is used to define the routes and middleware for the server. The express.json() middleware is used to parse incoming JSON data in request bodies. Finally, the app.listen() method is called to start the server and listen on port 8800.</p><p>After executing the npm start command in your terminal, you should see the message “Connected…” which indicates that the server is listening to incoming requests on the port 8800 and ready to handle them appropriately.</p><h4>MySQL Connection</h4><p>To be able to perform CRUD operations in our Node.js application, we need to establish a connection with the MySQL database. In order to do that, we will use the mysql2 library. We will create a new file called db.js inside the API folder to hold the database connection details.</p><pre>// db.js<br>import mysql from &quot;mysql2&quot;;<br><br>export const db = mysql.createConnection({<br>  host: &quot;localhost&quot;,<br>  user: &quot;root&quot;,<br>  password: null,<br>  database: &quot;blog_app&quot;,<br>});</pre><p>In order to establish the connection to the MySQL server, the mysql2 library is used with a createConnection() method that receives an object with the configuration of the connection. It is important to note that depending on the configuration of your MySQL server, the host, user, and password fields may vary. In this example, for practicality, the root user is being used, which doesn&#39;t have a password. However, it&#39;s recommended to create a new user with a password and store this information in an .env file. This file can be accessed using the dotenv library, which loads the environment variables stored in the .env file into process.env so that they can be accessed throughout the application. This is a common practice in production to avoid exposing sensitive information like database credentials in the source code.</p><p>You are probably wondering why the name of the database is “blog_app” if we have never created it at any time. So let’s create it:</p><pre>-- setup_mysql.sql<br>-- create database<br>CREATE DATABASE IF NOT EXISTS blog_app;<br>-- create table users<br>CREATE TABLE IF NOT EXISTS `blog_app`.`users` (<br>  `id` INT NOT NULL AUTO_INCREMENT,<br>  `username` VARCHAR(255) NOT NULL,<br>  `email` VARCHAR(255) NOT NULL,<br>  `password` VARCHAR(255) NOT NULL,<br>  `img` VARCHAR(255) NULL,<br>  PRIMARY KEY (`id`)<br>);<br>-- create table posts<br>CREATE TABLE IF NOT EXISTS `blog_app`.`posts` (<br>  `id` INT NOT NULL AUTO_INCREMENT,<br>  `title` VARCHAR(255) NOT NULL,<br>  `desc` VARCHAR(1000) NOT NULL,<br>  `img` VARCHAR(255) NOT NULL,<br>  `cat` VARCHAR(255) NOT NULL,<br>  `date` DATETIME NOT NULL,<br>  `uid` INT NOT NULL,<br>  PRIMARY KEY (`id`),<br>  INDEX `uid_idx` (`uid` ASC) VISIBLE,<br>  CONSTRAINT `uid`<br>  FOREIGN KEY (`uid`)<br>  REFERENCES `blog_app`.`users` (`id`)<br>  ON DELETE CASCADE<br>  ON UPDATE CASCADE<br>);</pre><p>The above code is a set of SQL commands that creates a new database named “blog_app” and two tables: “users” and “posts”.</p><p>The “users” table has columns named “id”, “username”, “email”, “password”, and “img”. The “id” column is set as the primary key for the table.</p><p>The “posts” table has columns named “id”, “title”, “desc”, “img”, “cat”, “date”, and “uid”. The “id” column is set as the primary key and the “uid” column has a foreign key constraint that references the “id” column in the “users” table. The “INDEX” command creates an index on the “uid” column for faster querying. The “ON DELETE CASCADE” and “ON UPDATE CASCADE” commands ensure that any changes to the “users” table are reflected in the “posts” table.</p><p>To create the database and tables, you can execute the setup_mysql.sql file in the MySQL server. If you&#39;re using root user without password, you can run cat setup_mysql.sql | mysql -u root in the terminal. In case you have set a password for the root user, you can add the -p flag at the end of the command, which will prompt you to enter the password.</p><h4>Route Controller Structure</h4><p>To modularize our code and improve maintainability, we’ll move away from placing all routes and functions in index.js. Instead, we’ll create a new directory called “routes” within the API directory. Inside this directory, we’ll have files for each endpoint of our application, including auth.js, posts.js, and users.js. Each of these files will define the routes for the endpoint and the corresponding function to be executed when a request is made to that route. This approach helps us create specific functions that perform well-defined tasks, making our code more modular and easier to manage.</p><p><strong>Example:</strong></p><pre>// api/routes/posts.js<br>import express from &quot;express&quot;;<br><br>// Creating a new router instance<br>const router = express.Router();<br><br>// Defining a new route on this router for the GET HTTP method for the &#39;/test&#39; endpoint<br>// When the &#39;/test&#39; endpoint is reached, the provided callback function will execute<br>router.get(&quot;/test&quot;, (req, res) =&gt; {<br>  res.json(&quot;this is post&quot;);<br>});<br><br>// Exporting this router module so that it can be used elsewhere in the application<br>export default router;</pre><p>Let’s import router to index.js</p><pre>// api/index.js<br>import express from &quot;express&quot;;<br>// Import router as postRoutes<br>import postRoutes from &quot;./routes/posts.js&quot;;<br><br>// Create an instance of the Express application<br>const app = express();<br><br>// Use the built-in JSON middleware to parse incoming requests<br>app.use(express.json());<br><br>// Routes<br>app.use(&quot;/api/posts&quot;, postRoutes);<br><br>// Start the server and listen on port 8800<br>app.listen(8800, () =&gt; {<br>  console.log(&quot;Connected...&quot;);<br>});</pre><p>Now if you run the server ( npm start ) and visit <a href="http://localhost:8800/api/posts/test">http://localhost:8800/api/posts/test</a> you should get “this is post”. But as we said before, is important to modularize our code. So we are going to create another folder inside api named controller that will contain the following files: auth.js, posts.js, and users.js. Within these files we will have all the functions in charge of doing the CRUD operations.</p><p><strong>Example:</strong></p><p>Let’s add the following code to controller/posts.js:</p><pre>// controller/posts.js<br>// Exporting a function called testPost that takes two parameters, req and res, which represent the request and response objects, respectively.<br>export const testPost = (req, res) =&gt; {<br>  // Sending a JSON response with a string message &quot;this is post from controller&quot; when this function is called.<br>  res.json(&quot;this is post from controller&quot;);<br>};</pre><p>Modify routes/posts.js:</p><pre>// routes/posts.js<br>import express from &quot;express&quot;;<br>import { testPost } from &quot;../controller/posts.js&quot;;<br><br>// Creating a new router instance<br>const router = express.Router();<br><br>// Defining a new route on this router for the GET HTTP method for the &#39;/test&#39; endpoint<br>// When the &#39;/test&#39; endpoint is reached, testPost function will execute<br>router.get(&quot;/test&quot;, testPost);<br><br>// Exporting this router module so that it can be used elsewhere in the application<br>export default router;</pre><p>Now if you visit <a href="http://localhost:8800/api/posts/test">http://localhost:8800/api/posts/test</a> you should get “this is post from controller” instead “this is post”.</p><p>Up to this point, the API folder structure should look like this:</p><pre>api<br>├── controller<br>│   ├── auth.js<br>│   ├── posts.js<br>│   └── users.js<br>├── routes<br>│   ├── auth.js<br>│   ├── posts.js<br>│   └── users.js<br>├── db.js<br>├── index.js<br>├── package.json<br>└── setup_mysql.sql</pre><h3>Authentication with JWT and Cookie</h3><p>Now that we have the basic structure of our project. Let’s create our authentication system. For this we will need to install:</p><ul><li><strong>jsonbwebtoken: </strong>in a nutshell, jsonwebtoken is a compact, URL-safe means of representing claims to be transferred between two parties. These claims can be used to authenticate and authorize users in web applications. The library provides methods for generating, signing, and verifying JSON Web Tokens (JWTs) using a secret key or public/private key pair.</li><li><strong>bcryptjs:</strong> is a JavaScript library used for password hashing. It uses the bcrypt algorithm to securely hash passwords and protect them from attacks such as brute-force and rainbow table attacks. Bcryptjs generates a salt for each password and then hashes the salted password multiple times, making it more difficult for an attacker to crack the password even if they have access to the hashed values. It is commonly used in web development to store user passwords in a secure manner.</li></ul><p><strong>Important!</strong> In cryptography, a <strong>salt</strong> is a random value that is used as an additional input to a one-way function, such as a cryptographic hash function. The purpose of the salt is to make it more difficult to perform attacks such as precomputed hash attacks and dictionary attacks, which try to guess the input of the hash function. By adding a salt to the input, the resulting hash will be different, even if the input is the same. This makes it much more difficult for an attacker to crack the hashed password. The salt value is typically stored alongside the hashed password in a database.</p><p>To install this libraries run npm install bcryptjs jsonwebtoken.</p><h4>Register BACK-END</h4><p>The first thing we need to do is create a function that allows us to register new users , let’s add the following function to controller/auth.js file:</p><pre>// controller/auth.js<br>import { db } from &quot;../db.js&quot;;<br>import bcrypt from &quot;bcryptjs&quot;;<br>import jwt from &quot;jsonwebtoken&quot;;<br><br>// This function is responsible for registering a new user in the database<br>export const register = (req, res) =&gt; {<br>  // CHECK EXISTING USER<br>  // SQL query to check if the user already exists in the database<br>  const query = &quot;SELECT * FROM users WHERE email = ? OR username = ?&quot;;<br>  // Execute the query with the user&#39;s email and username as parameters<br>  db.query(query, [req.body.email, req.body.username], (err, data) =&gt; {<br>    // Check for errors<br>    if (err) return res.json(err);<br>    // If the query returns data, it means the user already exists, return a 409 conflict status code<br>    if (data.length) return res.status(409).json(&quot;User already exists!&quot;);<br><br>    // Hash the password and create a user<br>    // Generate a salt value<br>    const salt = bcrypt.genSaltSync(10);<br>    // Generate a hash value using the password and the salt value<br>    const hash = bcrypt.hashSync(req.body.password, salt);<br><br>    // SQL query to insert the new user in the database<br>    const query = &quot;INSERT INTO users(`username`,`email`,`password`) VALUES (?)&quot;;<br>    // Define the values to be inserted in the query, including the hashed password<br>    const values = [req.body.username, req.body.email, hash];<br><br>    // Execute the query with the values as parameters<br>    db.query(query, [values], (err, data) =&gt; {<br>      // Check for errors<br>      if (err) return res.json(err);<br>      // If successful, return a 200 status code with a message<br>      return res.status(200).json(&quot;User has been created.&quot;);<br>    });<br>  });<br>};</pre><p>This code exports a function named “register” that handles a POST request for registering a new user. The function first checks if the user already exists in the database by executing a SELECT query with the user’s email and username. If the query returns any data, it means the user already exists, so the function returns a response with a 409 status code and a message “User already exists!”.</p><p>If the user does not exist, the function hashes the user’s password using bcrypt library and creates a new user by executing an INSERT query with the user’s username, email, and hashed password. If the query is successful, the function returns a response with a 200 status code and a message “User has been created.”</p><p>The function uses the db object to execute the SQL queries, which should be established in a separate file (db.js) to establish a connection with the database.</p><p>Let’s add the required routes to perform the authentication, let’s open routes/auth.js file and add the following code:</p><pre>// routes/auth.js<br>// importing express and the necessary controller functions<br>import express from &quot;express&quot;;<br>import { login, logout, register } from &quot;../controller/auth.js&quot;;<br><br>// creating a new router instance<br>const router = express.Router();<br><br>// defining routes for register, login, and logout<br>router.post(&quot;/register&quot;, register);<br>router.post(&quot;/login&quot;, login);<br>router.post(&quot;/logout&quot;, logout);<br><br>// exporting the router instance<br>export default router;</pre><p>Note that login and logout functions haven’t been implemented yet.</p><p>Finally, let’s implement authentication routes to our application. index.js file should looks like:</p><pre>// index.js<br>// Import the Express library<br>import express from &quot;express&quot;;<br>// Import routes<br>import authRoutes from &quot;./routes/auth.js&quot;;<br>import postRoutes from &quot;./routes/posts.js&quot;;<br><br>// Create an instance of the Express application<br>const app = express();<br><br>// Use the built-in JSON middleware to parse incoming requests<br>app.use(express.json());<br><br>// Routes<br>app.use(&quot;/api/auth&quot;, authRoutes);<br>app.use(&quot;/api/posts&quot;, postRoutes);<br><br>// Start the server and listen on port 8800<br>app.listen(8800, () =&gt; {<br>  console.log(&quot;Connected...&quot;);<br>});</pre><p>The benefits of modularized code become apparent when considering the specific responsibilities of each function. While it’s possible to centralize database connections, application routes, and data manipulation functions in index.js, separating each function improves maintainability by providing clear points of reference in the event of an issue. It&#39;s optimal to create an index.js file to handle the creation of our Express application with all necessary middleware, a db.js file to establish the database connection, a routes/ directory to contain all application routes, and a controller/ directory to house data processing and CRUD operations.</p><h4>Register FRONT-END</h4><p>In order to test the registration of a user, we must make some changes in the front-end. First we need to install axios (npm install axios) to be able to communicate with the back-end.</p><p>Axios is a popular JavaScript library used to make HTTP requests from a web browser or Node.js. It provides a simple and easy-to-use API for making requests to RESTful web services, and supports a wide range of features such as sending form data, setting headers, handling request and response interceptors, and canceling requests. Axios can be used in both client-side and server-side applications, and is widely used in modern web development for communicating with APIs and fetching data from servers.</p><p>Let’s make the changes to registration page (Register.jsx):</p><pre>// Register.jsx<br>import React, { useState } from &quot;react&quot;;<br>import { Link, useNavigate } from &quot;react-router-dom&quot;;<br>import axios from &quot;axios&quot;;<br><br>const Register = () =&gt; {<br>  const [inputs, setInputs] = useState({<br>    // setting initial state for inputs using useState hook<br>    username: &quot;&quot;,<br>    email: &quot;&quot;,<br>    password: &quot;&quot;,<br>  });<br><br>  const [err, setError] = useState(null); // setting initial state for error using useState hook<br><br>  const navigate = useNavigate(); // using useNavigate hook from react-router-dom to navigate<br><br>  const handleChange = (e) =&gt; {<br>    // function to handle input changes<br>    setInputs((prev) =&gt; ({ ...prev, [e.target.name]: e.target.value }));<br>    // using spread operator to spread previous state and update the current input<br>  };<br><br>  const handleSubmit = async (e) =&gt; {<br>    // function to handle form submit<br>    e.preventDefault(); // preventing the default form submission behavior<br>    try {<br>      await axios.post(&quot;/auth/register&quot;, inputs); // making a post request to register the user using axios library<br>      navigate(&quot;/login&quot;); // navigating to login page after successful registration<br>    } catch (err) {<br>      // handling errors if any<br>      setError(err.response.data); // setting error message from response data<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;auth&quot;&gt;<br>      {/* containing the authentication form */}<br>      &lt;h1&gt;Register&lt;/h1&gt;<br>      &lt;form&gt;<br>        &lt;input<br>          required<br>          type=&quot;text&quot;<br>          placeholder=&quot;username&quot;<br>          name=&quot;username&quot;<br>          onChange={handleChange} // triggering handleChange function on input change<br>        /&gt;<br>        &lt;input<br>          required<br>          type=&quot;email&quot;<br>          placeholder=&quot;email&quot;<br>          name=&quot;email&quot;<br>          onChange={handleChange} // triggering handleChange function on input change<br>        /&gt;<br>        &lt;input<br>          required<br>          type=&quot;password&quot;<br>          placeholder=&quot;password&quot;<br>          name=&quot;password&quot;<br>          onChange={handleChange} // triggering handleChange function on input change<br>        /&gt;<br>        &lt;button onClick={handleSubmit}&gt;Register&lt;/button&gt;{&quot; &quot;}<br>        {/* triggering handleSubmit function on form submit */}<br>        {err &amp;&amp; &lt;p&gt;{err}&lt;/p&gt;} {/* displaying error message if there&#39;s any */}<br>        &lt;span&gt;<br>          Do you have an account? &lt;Link to=&quot;/login&quot;&gt;Login&lt;/Link&gt;{&quot; &quot;}<br>          {/* providing link to login page */}<br>        &lt;/span&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Register; // exporting Register component</pre><p>When a user enters data into the input fields, the handleChange function updates the state accordingly.</p><p>When the user clicks the “Register” button, the handleSubmit function is triggered. This function makes an HTTP POST request to the server with the user’s registration information, and if successful, navigates the user to the login page using the useNavigate hook. If there’s an error during registration, the error message is displayed on the page.</p><p>Finally, we need to add &quot;proxy&quot;:http//localhost:8800/api at the end of client/package.json file. Why? It allows the server to proxy requests to the API server during development.</p><p>This is useful when the React project is hosted on a different server than the API server, as it allows the frontend code to make requests to the backend API without worrying about cross-origin resource sharing (CORS) issues.</p><p>By specifying the proxy in package.json, requests made to paths beginning with “/api” will be automatically forwarded to the specified server (in this case, <a href="http://localhost:8800/">http://localhost:8800</a>).</p><p>Now, if you fill the registration form, you must be redirected to the login page and the user must be added to the database (“users” table).</p><h4>Login and Logout</h4><p>let’s apply the same logic for the login and logout functions. Add this two functions to the bottom of the controller/auth.js file:</p><pre>// This function handles user login<br>export const login = (req, res) =&gt; {<br>  // SQL query to check if the user exists in the DB<br>  const query = &quot;SELECT * FROM users WHERE username = ?&quot;;<br><br>  // Execute the query with the provided username<br>  db.query(query, [req.body.username], (err, data) =&gt; {<br>    // Handle DB errors<br>    if (err) return res.json(err);<br><br>    // If no user is found, return an error<br>    if (data.length === 0) return res.status(404).json(&quot;User not found!&quot;);<br><br>    // Check if the password is correct<br>    const isPasswordCorrect = bcrypt.compareSync(<br>      req.body.password,<br>      data[0].password<br>    );<br><br>    // If the password is incorrect, return an error<br>    if (!isPasswordCorrect)<br>      return res.status(400).json(&quot;Wrong username or password!&quot;);<br><br>    // If the login is successful, create a JSON web token<br>    const token = jwt.sign({ id: data[0].id }, &quot;jwtkey&quot;);<br><br>    // Remove the password from the user data<br>    const { password, ...other } = data[0];<br><br>    // Set the token as a http-only cookie and send user data as response<br>    res<br>      .cookie(&quot;access_token&quot;, token, {<br>        httpOnly: true,<br>      })<br>      .status(200)<br>      .json(other);<br>  });<br>};<br><br>// This function handles user logout<br>export const logout = (req, res) =&gt; {<br>  // Clear the access_token cookie and send a success message<br>  res<br>    .clearCookie(&quot;access_token&quot;, {<br>      sameSite: &quot;none&quot;,<br>      secure: true,<br>    })<br>    .status(200)<br>    .json(&quot;User has been logged out.&quot;);<br>};</pre><p><strong>The </strong><strong>login function:</strong></p><p>The first step is to construct a SQL query to retrieve the user data from the database using the provided username, stored in req.body.username. The query variable stores the SQL statement.</p><p>The db.query() method executes the query, with the username as a parameter. The callback function provides two arguments: err and data. If there is an error, the function returns a JSON response with the error details.</p><p>If the query returns no data, which means that there is no user with the provided username, the function returns a 404 status with an error message as a JSON response.</p><p>If the user is found, the function compares the provided password, req.body.password, with the hashed password stored in the database, using the bcrypt.compareSync() method. If the comparison fails, the function returns a 400 status with an error message as a JSON response.</p><p>If the login credentials are correct, the function generates a JSON web token with the user’s id as payload, using the jwt.sign() method.</p><p>Then, the password is removed from the data object using destructuring assignment, and the user data, excluding the password, is stored in the other variable.</p><p>Finally, the generated token is set as an HTTP-only cookie, and the user data is sent as a JSON response with a 200 status code.</p><p><strong>Note:</strong> jwt.sign() is a method provided by the JSON Web Token (JWT) package that is used to create a new JWT. A JWT is a compact and self-contained token that contains information (i.e., the payload) that can be used to verify the identity of the user. The jwt.sign() method takes two parameters: the payload and a secret key. The payload is the data that will be stored in the JWT, and it can be any JavaScript object that can be serialized as JSON. The secret key is a string that is used to sign the token, ensuring that the token has not been tampered with.</p><p>When the jwt.sign() method is called, it creates a new JWT that includes the payload and a signature that is generated using the secret key. This JWT is then returned as a string, which can be sent to the client and stored in a cookie or local storage. When the client sends a request to the server, the server can verify the identity of the user by decoding the JWT and checking the payload. If the signature is valid and the payload is trusted, the server can use the information in the payload to authenticate the user and respond accordingly.</p><p><strong>The </strong><strong>logout function:</strong></p><p>The function first calls the clearCookie() method on the res (response) object, which removes the access_token cookie from the user&#39;s browser. It takes two arguments: the name of the cookie to clear (&quot;access_token&quot;), and an object containing additional options for the cookie. In this case, the options sameSite: &quot;none&quot; and secure: true are set, which ensure that the cookie is only sent over HTTPS and is not limited to same-site requests.</p><h4>cookie-parser</h4><p>As you may have noticed, we are working with cookies. They are important in web development for a number of reasons:</p><ol><li>Session management: Cookies are often used to manage user sessions on websites. When a user logs in, the website sets a cookie containing a unique session ID, which is then sent with each subsequent request from the user. This allows the server to associate subsequent requests with the same session, and to keep track of user-specific data, such as user preferences or shopping cart items.</li><li>Personalization: Cookies can be used to personalize a user’s experience on a website. For example, a website may use cookies to remember a user’s language preference or to show personalized recommendations based on the user’s browsing history.</li><li>Tracking: Cookies can be used to track user behavior on a website, such as which pages they visit or which products they view. This data can be used to improve the website’s user experience, as well as for advertising and marketing purposes.</li></ol><p>Overall, cookies are a powerful tool for web developers to create more personalized and dynamic web experiences for users, while also providing important functionality such as session management. They are not as bad as they are painted. As developers we have to be careful with the third point, because this is when the line of ethics becomes blurred.</p><p>In order to work with cookies in our back-end we need to install cookie-parser (npm install cookie-parser) and specify to the server to use cookie-parser as middleware:</p><pre>//index.js<br>import express from &quot;express&quot;;<br>import authRoutes from &quot;./routes/auth.js&quot;;<br>import postRoutes from &quot;./routes/posts.js&quot;;<br>import cookieParser from &quot;cookie-parser&quot;;<br><br>// Create an instance of the Express application<br>const app = express();<br><br>// Use the built-in JSON middleware to parse incoming requests<br>app.use(express.json());<br>// Use the cookieParser middleware to parse cookies from incoming requests<br>app.use(cookieParser());<br><br>// Routes<br>app.use(&quot;/api/auth&quot;, authRoutes);<br>app.use(&quot;/api/posts&quot;, postRoutes);<br><br>// Start the server and listen on port 8800<br>app.listen(8800, () =&gt; {<br>  console.log(&quot;Connected...&quot;);<br>});</pre><h4>Login FRONT-END</h4><p>Finally, we need to make some changes to the login page:</p><pre>import React, { useState } from &quot;react&quot;;<br>import { Link, useNavigate } from &quot;react-router-dom&quot;;<br>import axios from &quot;axios&quot;;<br><br>// Define a functional component called Login<br>const Login = () =&gt; {<br>  // Use useState hook to create state variables for inputs and errors<br>  const [inputs, setInputs] = useState({<br>    username: &quot;&quot;,<br>    password: &quot;&quot;,<br>  });<br><br>  const [err, setError] = useState(null);<br><br>  // Use useNavigate hook to create a navigate function<br>  const navigate = useNavigate();<br><br>  // Define handleChange function to update the input state variables when the user types into the input fields<br>  const handleChange = (e) =&gt; {<br>    setInputs((prev) =&gt; ({ ...prev, [e.target.name]: e.target.value }));<br>  };<br><br>  // Define handleSubmit function to handle the form submission when the user clicks the submit button<br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    try {<br>      // Post the user input to the &quot;/auth/login&quot; endpoint and navigate to the home page<br>      await axios.post(&quot;/auth/login&quot;, inputs);<br>      navigate(&quot;/&quot;);<br>    } catch (err) {<br>      // If there is an error, set the error state variable to the error message<br>      setError(err.response.data);<br>    }<br>  };<br><br>  // Render the login form with input fields for username and password and a button to submit the form<br>  return (<br>    &lt;div className=&quot;auth&quot;&gt;<br>      &lt;h1&gt;Login&lt;/h1&gt;<br>      &lt;form&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          placeholder=&quot;username&quot;<br>          name=&quot;username&quot;<br>          onChange={handleChange}<br>        /&gt;<br>        &lt;input<br>          type=&quot;password&quot;<br>          placeholder=&quot;password&quot;<br>          name=&quot;password&quot;<br>          onChange={handleChange}<br>        /&gt;<br>        &lt;button onClick={handleSubmit}&gt;Login&lt;/button&gt;<br>        {err &amp;&amp; &lt;p&gt;{err}&lt;/p&gt;}<br>        &lt;span&gt;<br>          Don&#39;t you have an account? &lt;Link to=&quot;/register&quot;&gt;Register&lt;/Link&gt;<br>        &lt;/span&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Login;</pre><p>It is not worth explaining what was done since the exact same logic was applied as in the Register page. Now, if you login with the user previously registered, you must be redirected to the home page.</p><h4>React Context API</h4><p>It is recommended to persist user information in local storage for efficient retrieval across different React components to present data and enable specific actions. As such, user data should be stored in local storage to ensure availability and accessibility across components.</p><p>For this purpose, we’re going to use react-context. React context is a feature of React that allows data to be passed down the component tree without the need to pass props manually at every level. It provides a way to share data between components, even if they are not directly related in the component hierarchy. Context is often used for global state management, such as user authentication and theme settings. It consists of two parts: a Provider component that provides the data to its children, and a Consumer component that consumes the data. The useContext hook can also be used to consume context data in functional components.</p><p>To begin, we will create a directory named ‘context’, within our client source code, where we will store the file ‘authContext.js’. The full path to this file should be client/src/context/authContext.js. This file will serve as the context for our application:</p><pre>// src/context/authContext.js<br>import axios from &quot;axios&quot;;<br>import { createContext, useEffect, useState } from &quot;react&quot;;<br><br>// Create a new context called AuthContext<br>export const AuthContext = createContext();<br><br>// Define a component called AuthContextProvider that takes in children as props<br>export const AuthContextProvider = ({ children }) =&gt; {<br>  // Initialize a state variable called currentUser and set it to either the user object in local storage or null if it does not exist<br>  const [currentUser, setCurrentUser] = useState(<br>    JSON.parse(localStorage.getItem(&quot;user&quot;)) || null<br>  );<br><br>  // Define a function called login that makes a POST request to the /auth/login endpoint with the given inputs and sets the currentUser state variable to the response data<br>  const login = async (inputs) =&gt; {<br>    const res = await axios.post(&quot;/auth/login&quot;, inputs);<br>    setCurrentUser(res.data);<br>  };<br><br>  // Define a function called logout that makes a POST request to the /auth/logout endpoint and sets the currentUser state variable to null<br>  const logout = async (inputs) =&gt; {<br>    await axios.post(&quot;/auth/logout&quot;);<br>    setCurrentUser(null);<br>  };<br><br>  // Store the currentUser state variable in local storage whenever it changes<br>  useEffect(() =&gt; {<br>    localStorage.setItem(&quot;user&quot;, JSON.stringify(currentUser));<br>  }, [currentUser]);<br><br>  // Return the AuthContext.Provider component with the currentUser, login, and logout functions as values and the children as its child components<br>  return (<br>    &lt;AuthContext.Provider value={{ currentUser, login, logout }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};</pre><p>This code defines a context for managing authentication in a React application. It exports an AuthContext object created with the createContext function, which can be used to provide authentication information to child components in the component tree.</p><p>The AuthContextProvider component is also exported, which is a wrapper around the child components that provides the authentication state and methods for logging in and logging out. It uses the useState hook to maintain the current user&#39;s information in the component&#39;s state. The user&#39;s information is initially set by retrieving the stored user object from the browser&#39;s local storage using localStorage.getItem(&quot;user&quot;).</p><p>The login function is defined to perform a login operation by sending a POST request to the /auth/login endpoint with the user&#39;s input data. If the request is successful, the current user&#39;s state is updated with the response data.</p><p>The logout function sends a POST request to the /auth/logout endpoint to log out the user. It then updates the current user&#39;s state to null.</p><p>The useEffect hook is used to store the current user&#39;s information to the browser&#39;s local storage whenever the currentUser state changes.</p><p>Finally, the AuthContext.Provider component is returned, which provides the currentUser, login, and logout values as the context value to its child components. This enables other components in the application to access the authentication state and methods.</p><p>Since we have functions in charge of doing the login and logout in the app using context, we must make some changes in Login.jsx:</p><pre>  //useContext hook to get the login function from the AuthContext.  <br>  const { login } = useContext(AuthContext);  <br><br>  // Define handleSubmit function to handle the form submission when the user clicks the submit button<br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    try {<br>      // Post the user input to the &quot;/auth/login&quot; endpoint and navigate to the home page<br>      await login(inputs); // new login function<br>      navigate(&quot;/&quot;);<br>    } catch (err) {<br>      // If there is an error, set the error state variable to the error message<br>      setError(err.response.data);<br>    }<br>  };</pre><p>Last, we need to ensure that our application is wrapped with the Provider component so that the components can access the state data and actions provided by the context. Specifically, the App component will be the child component of the Provider component.</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import App from &quot;./App&quot;;<br>import { AuthContextProvider } from &quot;./context/authContext&quot;;<br><br>const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));<br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;AuthContextProvider&gt;<br>      &lt;App /&gt;<br>    &lt;/AuthContextProvider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p>Let’s apply the same logic to the Navbar:</p><pre>// Navbar.jsx<br>import React, { useContext } from &quot;react&quot;;<br>import { Link, useNavigate } from &quot;react-router-dom&quot;;<br>import { AuthContext } from &quot;../context/authContext&quot;;<br>import Logo from &quot;../images/logo.png&quot;;<br><br>const Navbar = () =&gt; {<br>  const { currentUser, logout } = useContext(AuthContext);<br>  const navigate = useNavigate();<br><br>  const logoutNavbar = () =&gt; {<br>    logout();<br>    navigate(&quot;/login&quot;);<br>  };<br><br>  return (<br>    &lt;div className=&quot;navbar&quot;&gt;<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;div className=&quot;logo&quot;&gt;<br>          &lt;a href=&quot;/&quot;&gt;<br>            &lt;img src={Logo} alt=&quot;logo&quot; /&gt;<br>          &lt;/a&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;links&quot;&gt;<br>          &lt;Link className=&quot;link&quot; to=&quot;/?cat=art&quot;&gt;<br>            &lt;h6&gt;ART&lt;/h6&gt;<br>          &lt;/Link&gt;<br>          &lt;Link className=&quot;link&quot; to=&quot;/?cat=science&quot;&gt;<br>            &lt;h6&gt;SCIENCE&lt;/h6&gt;<br>          &lt;/Link&gt;<br>          &lt;Link className=&quot;link&quot; to=&quot;/?cat=technology&quot;&gt;<br>            &lt;h6&gt;TECHNOLOGY&lt;/h6&gt;<br>          &lt;/Link&gt;<br>          &lt;Link className=&quot;link&quot; to=&quot;/?cat=cinema&quot;&gt;<br>            &lt;h6&gt;CINEMA&lt;/h6&gt;<br>          &lt;/Link&gt;<br>          &lt;Link className=&quot;link&quot; to=&quot;/?cat=design&quot;&gt;<br>            &lt;h6&gt;DESIGN&lt;/h6&gt;<br>          &lt;/Link&gt;<br>          &lt;Link className=&quot;link&quot; to=&quot;/?cat=food&quot;&gt;<br>            &lt;h6&gt;FOOD&lt;/h6&gt;<br>          &lt;/Link&gt;          <br>          &lt;span&gt;{currentUser?.username}&lt;/span&gt;<br>          {currentUser ? (<br>            &lt;span onClick={logoutNavbar}&gt;Logout&lt;/span&gt;<br>          ) : (<br>            &lt;Link className=&quot;link&quot; to=&quot;/login&quot;&gt;<br>              Login<br>            &lt;/Link&gt;<br>          )}<br>          &lt;span className=&quot;write&quot;&gt;<br>            &lt;Link className=&quot;link&quot; to=&quot;/write&quot;&gt;<br>              Write<br>            &lt;/Link&gt;<br>          &lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Navbar;</pre><p>Now if you login, you should see the username in the navbar, and if you logout you must be redirected to the login page and localstorage should be empty.</p><h3>Fetch MySQL data</h3><p>Now we will retrieve information about the posts. However, before proceeding, I would like to provide you with an SQL script to insert data into the database. I recommend to delete any pre-existing data to avoid conflicts. Note that the password in the script is already encrypted. To login use the password “test” which was used for the two users.</p><pre>-- data_mysql.sql<br>-- add users<br>INSERT INTO `blog_app`.`users` (`id`, `username`, `email`, `password`, `img`) VALUES (&#39;1&#39;, &#39;Santiago&#39;, &#39;santiago@mail.com&#39;, &#39;$2a$10$VqZJYEYnauC8qrVrVpWZX.E0u95i40pBmAEOc.Vs178nUJNyenzaa&#39;, &#39;https://images.unsplash.com/photo-1633332755192-727a05c4013d?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1760&amp;q=80&#39;);<br>INSERT INTO `blog_app`.`users` (`id`, `username`, `email`, `password`, `img`) VALUES (&#39;2&#39;, &#39;Pablo&#39;, &#39;pablo@mail.com&#39;, &#39;$2a$10$VqZJYEYnauC8qrVrVpWZX.E0u95i40pBmAEOc.Vs178nUJNyenzaa&#39;, &#39;https://images.unsplash.com/photo-1570295999919-56ceb5ecca61?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1760&amp;q=80&#39;);<br><br>-- insert posts<br>insert into `blog_app`.`posts` (`id`, `title`, `desc`, `img`, `uid`, `cat`, `date`) VALUES (&#39;1&#39;, &#39;Lorem ipsum dolor sit amet consectetur adipisicing elit&#39;, &#39;Lorem, ipsum dolor sit amet consectetur adipisicing elit. A possimus excepturi aliquid nihil cumque ipsam facere aperiam at! Ea dolorem ratione sit debitis deserunt repellendus numquam ab vel perspiciatis corporis!&#39;, &#39;https://images.unsplash.com/photo-1513364776144-60967b0f800f?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=2671&amp;q=80&#39;, &#39;1&#39;, &#39;art&#39;, &#39;2023-02-08&#39;);<br>insert into `blog_app`.`posts` (`id`, `title`, `desc`, `img`, `uid`, `cat`, `date`) VALUES (&#39;2&#39;, &#39;Lorem ipsum dolor sit amet consectetur adipisicing elit&#39;, &#39;Lorem, ipsum dolor sit amet consectetur adipisicing elit. A possimus excepturi aliquid nihil cumque ipsam facere aperiam at! Ea dolorem ratione sit debitis deserunt repellendus numquam ab vel perspiciatis corporis!&#39;, &#39;https://images.unsplash.com/photo-1536924940846-227afb31e2a5?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1766&amp;q=80&#39;, &#39;2&#39;, &#39;food&#39;, &#39;2023-02-08&#39;);<br>insert into `blog_app`.`posts` (`id`, `title`, `desc`, `img`, `uid`, `cat`, `date`) VALUES (&#39;3&#39;, &#39;Lorem ipsum dolor sit amet consectetur adipisicing elit&#39;, &#39;Lorem, ipsum dolor sit amet consectetur adipisicing elit. A possimus excepturi aliquid nihil cumque ipsam facere aperiam at! Ea dolorem ratione sit debitis deserunt repellendus numquam ab vel perspiciatis corporis!&#39;, &#39;https://images.unsplash.com/photo-1546069901-ba9599a7e63c?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1180&amp;q=80&#39;, &#39;2&#39;, &#39;art&#39;, &#39;2023-02-08&#39;);<br>insert into `blog_app`.`posts` (`id`, `title`, `desc`, `img`, `uid`, `cat`, `date`) VALUES (&#39;4&#39;, &#39;Lorem ipsum dolor sit amet consectetur adipisicing elit&#39;, &#39;Lorem, ipsum dolor sit amet consectetur adipisicing elit. A possimus excepturi aliquid nihil cumque ipsam facere aperiam at! Ea dolorem ratione sit debitis deserunt repellendus numquam ab vel perspiciatis corporis!&#39;, &#39;https://images.unsplash.com/photo-1493770348161-369560ae357d?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1770&amp;q=80&#39;, &#39;1&#39;, &#39;food&#39;, &#39;2023-02-08&#39;);</pre><p>Now we have two users and some posts created in the database we can proceed. First let’s add the routes that we are going to use:</p><pre>// api/routes/posts.js<br>import express from &quot;express&quot;;<br>import {<br>  addPost,<br>  deletePost,<br>  getPost,<br>  getPosts,<br>  updatePost,<br>} from &quot;../controller/posts.js&quot;;<br><br>// Create a new Router object<br>const router = express.Router();<br><br>// Define routes for various HTTP methods and their corresponding functions<br>router.get(&quot;/&quot;, getPosts); // Get all posts<br>router.get(&quot;/:id&quot;, getPost); // Get a specific post by its ID<br>router.post(&quot;/&quot;, addPost); // Add a new post<br>router.delete(&quot;/:id&quot;, deletePost); // Delete a post by its ID<br>router.put(&quot;/:id&quot;, updatePost); // Update a post by its ID<br><br>export default router;</pre><p>Now let’s create the logic in controller/posts.js:</p><pre>import { db } from &quot;../db.js&quot;;<br>import jwt from &quot;jsonwebtoken&quot;;<br><br>// Retrieves posts from a database<br>export const getPosts = (req, res) =&gt; {<br>  // If the query string includes a category parameter,<br>  // select all posts from the given category. Otherwise,<br>  // select all posts.<br>  const q = req.query.cat<br>    ? &quot;SELECT * FROM posts WHERE cat=?&quot;<br>    : &quot;SELECT * FROM posts&quot;;<br><br>  // Use the database object to query the database with the<br>  // appropriate SQL statement and any necessary parameters.<br>  db.query(q, [req.query.cat], (err, data) =&gt; {<br>    // If there&#39;s an error, send a 500 status code and the error message<br>    if (err) return res.status(500).send(err);<br><br>    // Otherwise, send a 200 status code and the data as JSON<br>    return res.status(200).json(data);<br>  });<br>};<br><br>// Retrieves a single post from the database<br>export const getPost = (req, res) =&gt; {<br>  // Select specific fields from both the users and posts table,<br>  // and join them based on the user ID of the post author.<br>  const q =<br>    &quot;SELECT p.id, `username`, `title`, `desc`, p.img, u.img AS userImg, `cat`,`date` FROM users u JOIN posts p ON u.id = p.uid WHERE p.id = ?&quot;;<br><br>  // Use the database object to query the database for the post with<br>  // the given ID, and any necessary parameters.<br>  db.query(q, [req.params.id], (err, data) =&gt; {<br>    // If there&#39;s an error, send a 500 status code and the error message<br>    if (err) return res.status(500).json(err);<br><br>    // Otherwise, send a 200 status code and the first item in the data array as JSON<br>    return res.status(200).json(data[0]);<br>  });<br>};<br><br>// Adds a new post to the database<br>export const addPost = (req, res) =&gt; {<br>  // Check if the user is authenticated by checking for a token in the cookies<br>  const token = req.cookies.access_token;<br>  if (!token) return res.status(401).json(&quot;Not authenticated!&quot;);<br><br>  // Verify the token using the secret key<br>  jwt.verify(token, &quot;jwtkey&quot;, (err, userInfo) =&gt; {<br>    // If there&#39;s an error, the token is not valid<br>    if (err) return res.status(403).json(&quot;Token is not valid!&quot;);<br><br>    // Otherwise, construct the SQL query to insert a new post into the database<br>    const q =<br>      &quot;INSERT INTO posts(`title`, `desc`, `img`, `cat`, `date`,`uid`) VALUES (?)&quot;;<br><br>    // Define an array of values to be inserted into the database, including the<br>    // post data from the request body and the user ID from the decoded token<br>    const values = [<br>      req.body.title,<br>      req.body.desc,<br>      req.body.img,<br>      req.body.cat,<br>      req.body.date,<br>      userInfo.id,<br>    ];<br><br>    // Use the database object to execute the SQL query with the values array<br>    db.query(q, [values], (err, data) =&gt; {<br>      // If there&#39;s an error, return a 500 status code and the error message<br>      if (err) return res.status(500).json(err);<br><br>      // Otherwise, return a 200 status code and a success message<br>      return res.json(&quot;Post has been created.&quot;);<br>    });<br>  });<br>};<br><br>// Deletes a post from the database<br>export const deletePost = (req, res) =&gt; {<br>  // Check if the user is authenticated by checking for a token in the cookies<br>  const token = req.cookies.access_token;<br>  if (!token) return res.status(401).json(&quot;Not authenticated&quot;);<br><br>  // Verify the token using the secret key<br>  jwt.verify(token, &quot;jwtkey&quot;, (err, userInfo) =&gt; {<br>    // If there&#39;s an error, the token is not valid<br>    if (err) return res.status(403).json(&quot;Token is not valid&quot;);<br><br>    // Otherwise, get the ID of the post to be deleted from the request parameters<br>    const postId = req.params.id;<br><br>    // Construct an SQL query to delete the post with the specified ID, but only if<br>    // the user ID associated with the post matches the ID of the authenticated user<br>    const q = &quot;DELETE FROM posts WHERE `id` = ? AND `uid` = ?&quot;;<br><br>    // Execute the SQL query with the postId and userInfo.id as parameters<br>    db.query(q, [postId, userInfo.id], (err, data) =&gt; {<br>      // If there&#39;s an error, return a 403 status code and an error message<br>      if (err) return res.status(403).json(&quot;You can delete only your post&quot;);<br><br>      // Otherwise, return a 200 status code and a success message<br>      return res.json(&quot;Post has been deleted&quot;);<br>    });<br>  });<br>};<br><br>// Update a post<br>export const updatePost = (req, res) =&gt; {<br>  // Get the access token from the request cookies.<br>  const token = req.cookies.access_token;<br><br>  // Check if the token exists, if not, return an error response.<br>  if (!token) return res.status(401).json(&quot;Not authenticated!&quot;);<br><br>  // Verify the token using the &quot;jwtkey&quot; secret key. If the token is not valid, return an error response.<br>  jwt.verify(token, &quot;jwtkey&quot;, (err, userInfo) =&gt; {<br>    if (err) return res.status(403).json(&quot;Token is not valid!&quot;);<br><br>    // Get the post ID from the request parameters.<br>    const postId = req.params.id;<br><br>    // SQL query to update the post with new values.<br>    const q =<br>      &quot;UPDATE posts SET `title`=?,`desc`=?,`img`=?,`cat`=? WHERE `id` = ? AND `uid` = ?&quot;;<br><br>    // An array containing the new values for the post.<br>    const values = [req.body.title, req.body.desc, req.body.img, req.body.cat];<br><br>    // Execute the query using the values and post ID. If there&#39;s an error, return an error response. Otherwise, return a success response.<br>    db.query(q, [...values, postId, userInfo.id], (err, data) =&gt; {<br>      if (err) return res.status(500).json(err);<br>      return res.json(&quot;Post has been updated.&quot;);<br>    });<br>  });<br>};</pre><p>This code defines several functions to interact with a database.</p><p>The getPosts function retrieves all posts from the database, or only those from a specific category if a category parameter is provided in the request.</p><p>The getPost function retrieves a single post from the database based on its ID, along with information about the user who created it.</p><p>The addPost function adds a new post to the database, but only if the user is authenticated with a valid JSON Web Token (JWT).</p><p>The deletePost function deletes a post from the database, but only if the authenticated user is the one who created the post.</p><p>The updatePost function updates an existing post in the database, but only if the authenticated user is the one who created the post. Like addPost and deletePost, this function also requires a valid JWT for authentication.</p><h4>Home page</h4><p>Given that we have established endpoints within our backend to fetch post data, the next step is to incorporate these endpoints into the Home page component in order to retrieve data from the database and display it accordingly.</p><pre>// Home.jsx<br>import axios from &quot;axios&quot;;<br>import React, { useEffect, useState } from &quot;react&quot;;<br>import { Link, useLocation } from &quot;react-router-dom&quot;;<br><br>const Home = () =&gt; {<br>  // Declaring a state variable called posts and initializing it to an empty array<br>  const [posts, setPosts] = useState([]);<br><br>  // Getting the current URL query string (if any) using the useLocation hook from react-router-dom<br>  const cat = useLocation().search;<br><br>  // Defining an effect that runs when the cat variable changes<br>  useEffect(() =&gt; {<br>    // Defining an asynchronous function called fetchData<br>    const fetchData = async () =&gt; {<br>      try {<br>        // Making an HTTP GET request to the server to retrieve posts data based on the cat variable<br>        const res = await axios.get(`/posts${cat}`);<br>        // Updating the posts state variable with the retrieved data<br>        setPosts(res.data);<br>      } catch (err) {<br>        // Logging any errors that occur during the request<br>        console.log(err);<br>      }<br>    };<br>    // Calling the fetchData function<br>    fetchData();<br>  }, [cat]); // Specifying that this effect should only run when the cat variable changes<br><br>  // Defining a helper function called getText that takes an HTML string and returns the text content<br>  const getText = (html) =&gt; {<br>    const doc = new DOMParser().parseFromString(html, &quot;text/html&quot;);<br>    return doc.body.textContent;<br>  };<br><br>  // Rendering the Home component<br>  return (<br>    &lt;div className=&quot;home&quot;&gt;<br>      &lt;div className=&quot;posts&quot;&gt;<br>        {/* Mapping over the posts state variable and rendering a Post component for each post */}<br>        {posts.map((post) =&gt; (<br>          &lt;div className=&quot;post&quot; key={post.id}&gt;<br>            &lt;div className=&quot;post-img&quot;&gt;<br>              {/* Rendering the post image */}<br>              &lt;img src={`${post.img}`} alt=&quot;post cover&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;content&quot;&gt;<br>              {/* Rendering a link to the post page */}<br>              &lt;Link className=&quot;link&quot; to={`/post/${post.id}`}&gt;<br>                &lt;h1&gt;{post.title}&lt;/h1&gt;<br>              &lt;/Link&gt;<br>              {/* Rendering the post description */}<br>              &lt;p&gt;{getText(post.desc)}&lt;/p&gt;<br>              {/* Rendering a button to read more */}<br>              &lt;Link className=&quot;link&quot; to={`/post/${post.id}`}&gt;<br>                &lt;button&gt;Read More&lt;/button&gt;<br>              &lt;/Link&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Home;</pre><p>This is a React component that displays a list of blog posts. The component retrieves data from a server based on the current URL query string and uses state to store and render the retrieved data. It also defines a helper function to extract text content from HTML strings. The component maps over the retrieved data and renders a Post component for each post, which includes the post image, title, description, and a link to read more.</p><p>If you visit the “art” section you should see only the posts that contain the “art” category, the same should happen for the “food” category:</p><p><strong>Art:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCuG1PzFFpstgQHAccAFMw.png" /></figure><p><strong>Food:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPpP8am56WNp6HfGs-Z8Lg.png" /></figure><h4>Single page: Fetch user and single post</h4><pre>// Single.jsx<br>import React, { useContext, useEffect, useState } from &quot;react&quot;;<br>import EditImage from &quot;../images/edit.png&quot;;<br>import DeleteImage from &quot;../images/delete.png&quot;;<br>import { Link, useLocation, useNavigate } from &quot;react-router-dom&quot;;<br>import Menu from &quot;../components/Menu&quot;;<br>import axios from &quot;axios&quot;;<br>import moment from &quot;moment&quot;;<br>import { AuthContext } from &quot;../context/authContext&quot;;<br><br>const Single = () =&gt; {<br>  const [post, setPost] = useState({});<br><br>  // The useLocation hook returns the current location object, which contains information about the current URL.<br>  const location = useLocation();<br>  // The useNavigate hook returns a navigate function that can be used to navigate to a new location.<br>  const navigate = useNavigate();<br><br>  // Extract the post ID from the current URL.<br>  const postId = location.pathname.split(&quot;/&quot;)[2];<br><br>  // Get the current user from the AuthContext.<br>  const { currentUser } = useContext(AuthContext);<br><br>  // Use the useEffect hook to fetch the blog post data from the server when the component mounts.<br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      try {<br>        const res = await axios.get(`/posts/${postId}`);<br>        setPost(res.data);<br>      } catch (err) {<br>        console.log(err);<br>      }<br>    };<br>    fetchData();<br>  }, [postId]);<br><br>  // Handler function for deleting a blog post.<br>  const handleDelete = async () =&gt; {<br>    try {<br>      await axios.delete(`/posts/${postId}`);<br>      // Navigate to the home page after deleting the post.<br>      navigate(&quot;/&quot;);<br>    } catch (err) {<br>      console.log(err);<br>    }<br>  };<br><br>  // Helper function to extract plain text from an HTML string.<br>  const getText = (html) =&gt; {<br>    const doc = new DOMParser().parseFromString(html, &quot;text/html&quot;);<br>    return doc.body.textContent;<br>  };<br><br>  // Render the blog post.<br>  return (<br>    &lt;div className=&quot;single&quot;&gt;<br>      &lt;div className=&quot;content&quot;&gt;<br>        {/* Render the post image. */}<br>        &lt;img src={`${post?.img}`} alt=&quot;post cover&quot; /&gt;<br>        &lt;div className=&quot;user&quot;&gt;<br>          {/* Render the user image if it exists. */}<br>          {post.userImg &amp;&amp; &lt;img src={post.userImg} alt=&quot;user&quot; /&gt;}<br>          &lt;div className=&quot;info&quot;&gt;<br>            {/* Render the post author and date. */}<br>            &lt;span&gt;{post.username}&lt;/span&gt;<br>            &lt;p&gt;Posted {moment(post.date).fromNow()}&lt;/p&gt;<br>          &lt;/div&gt;<br>          {/* Render the edit and delete buttons if the current user is the author of the post. */}<br>          {currentUser.username === post.username &amp;&amp; (<br>            &lt;div className=&quot;edit&quot;&gt;<br>              &lt;Link to={`/write?edit=2`} state={post}&gt;<br>                &lt;img src={EditImage} alt=&quot;edit&quot; /&gt;<br>              &lt;/Link&gt;<br>              &lt;img onClick={handleDelete} src={DeleteImage} alt=&quot;delete&quot; /&gt;<br>            &lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>        {/* Render the post title and description. */}<br>        &lt;h1&gt;{post.title}&lt;/h1&gt;<br>        &lt;i&gt;&quot;{getText(post.desc)}&quot;&lt;/i&gt;<br>        &lt;p&gt;<br>          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do<br>          eiusmod tempor incididunt ut labore et dolore magna aliqua.<br>          Sollicitudin nibh sit amet commodo nulla facilisi nullam vehicula<br>          ipsum. Enim lobortis scelerisque fermentum dui faucibus in ornare<br>          quam. Viverra justo nec ultrices dui sapien. Aliquam nulla facilisi<br>          cras fermentum odio eu feugiat pretium. Suscipit adipiscing bibendum<br>          est ultricies integer quis auctor elit. Eu volutpat odio facilisis<br>          mauris. Consectetur adipiscing elit pellentesque habitant morbi<br>          tristique. Tristique senectus et netus et malesuada fames. Convallis a<br>          cras semper auctor neque. Sed felis eget velit aliquet sagittis id<br>          consectetur purus ut. Eu feugiat pretium nibh ipsum consequat nisl vel<br>          pretium lectus. Ac odio tempor orci dapibus. Velit scelerisque in<br>          dictum non consectetur a. Nibh tellus molestie nunc non blandit massa<br>          enim nec. Rutrum quisque non tellus orci ac auctor augue mauris.<br>        &lt;/p&gt;<br>        &lt;p&gt;<br>          Diam sollicitudin tempor id eu nisl nunc mi ipsum faucibus. Eu<br>          facilisis sed odio morbi quis commodo. Scelerisque mauris pellentesque<br>          pulvinar pellentesque. Tortor aliquam nulla facilisi cras fermentum.<br>          Accumsan lacus vel facilisis volutpat est. Nam libero justo laoreet<br>          sit. Nunc faucibus a pellentesque sit amet porttitor eget dolor. Cum<br>          sociis natoque penatibus et magnis. Nunc scelerisque viverra mauris in<br>          aliquam sem. Id porta nibh venenatis cras sed. Ac tortor vitae purus<br>          faucibus ornare suspendisse. Montes nascetur ridiculus mus mauris<br>          vitae ultricies leo integer malesuada. Turpis tincidunt id aliquet<br>          risus. Sed adipiscing diam donec adipiscing tristique risus nec.<br>          Tempor id eu nisl nunc mi ipsum faucibus. Iaculis urna id volutpat<br>          lacus laoreet non. Neque volutpat ac tincidunt vitae semper quis<br>          lectus. Vitae ultricies leo integer malesuada nunc vel risus commodo.<br>          Cras sed felis eget velit aliquet sagittis id consectetur. Eros donec<br>          ac odio tempor orci dapibus ultrices in iaculis.<br>        &lt;/p&gt;<br>        &lt;p&gt;<br>          Ut eu sem integer vitae. Aliquam vestibulum morbi blandit cursus risus<br>          at. Convallis aenean et tortor at risus viverra adipiscing at. Sit<br>          amet dictum sit amet justo donec enim. Nulla aliquet porttitor lacus<br>          luctus accumsan tortor. Ultrices mi tempus imperdiet nulla malesuada<br>          pellentesque elit eget gravida. Dui sapien eget mi proin sed. Urna<br>          nunc id cursus metus aliquam eleifend mi in. Euismod quis viverra nibh<br>          cras pulvinar mattis. Consequat nisl vel pretium lectus quam id leo in<br>          vitae. Turpis egestas integer eget aliquet nibh praesent tristique<br>          magna. Dui accumsan sit amet nulla facilisi. Risus ultricies tristique<br>          nulla aliquet enim tortor at auctor.<br>        &lt;/p&gt;<br>        &lt;p&gt;<br>          Morbi tincidunt ornare massa eget egestas purus viverra accumsan in.<br>          Eget nunc lobortis mattis aliquam. Quisque non tellus orci ac auctor.<br>          Gravida quis blandit turpis cursus in hac habitasse platea dictumst.<br>          Id neque aliquam vestibulum morbi blandit cursus risus. Orci porta non<br>          pulvinar neque laoreet suspendisse interdum. In nibh mauris cursus<br>          mattis molestie a. Phasellus faucibus scelerisque eleifend donec<br>          pretium vulputate. Dis parturient montes nascetur ridiculus mus mauris<br>          vitae ultricies. Elit scelerisque mauris pellentesque pulvinar. Enim<br>          praesent elementum facilisis leo vel fringilla est ullamcorper eget.<br>        &lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;Menu cat={post.cat} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Single;</pre><p>The useState hook initializes a state variable called post to an empty object and provides a function called setPost to update the state. The useLocation hook returns the current location object, which contains information about the current URL. The useNavigate hook returns a navigate function that can be used to navigate to a new location. The useContext hook is used to get the current user from the AuthContext. The useEffect hook is used to fetch the blog post data from the server when the component mounts. The handleDelete function is used to delete a blog post. The getText function is a helper function to extract plain text from an HTML string. Finally, the component returns a JSX element that renders the blog post content, including the post image, author and date information, edit and delete buttons, and post title and description.</p><p>The moment library (npm install moment) was used to get the current date to insert into the DB. Note: the description found in the database is in quotation marks and italics. The paragraphs with Lorem Ipsum were left to fill out the information page (aesthetic purposes only).</p><h4>Recommended posts</h4><p>Let’s modify Menu.jsx:</p><pre>// Menu.jsx<br>import axios from &quot;axios&quot;;<br>import React, { useEffect, useState } from &quot;react&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br><br>// Defining a functional component named Menu which takes a single prop named cat<br>const Menu = ({ cat }) =&gt; {<br>  // Initializing posts state with an empty array using useState hook<br>  const [posts, setPosts] = useState([]);<br><br>  // useEffect hook is used to fetch posts related to the category<br>  useEffect(() =&gt; {<br>    // Defining an async function fetchData to fetch posts related to the category using axios<br>    const fetchData = async () =&gt; {<br>      try {<br>        const res = await axios.get(`/posts/?cat=${cat}`);<br>        setPosts(res.data);<br>      } catch (err) {<br>        console.log(err);<br>      }<br>    };<br>    // Calling fetchData function to fetch data when component is mounted or when category is changed<br>    fetchData();<br>  }, [cat]);<br><br>  return (<br>    &lt;div className=&quot;menu&quot;&gt;<br>      &lt;h1&gt;Other posts you may like&lt;/h1&gt;<br>      {posts.map((post) =&gt; (<br>        &lt;div className=&quot;post&quot; key={post.id}&gt;<br>          &lt;img src={`${post.img}`} alt=&quot;post cover&quot; /&gt;<br>          &lt;h2&gt;{post.title}&lt;/h2&gt;<br>          {/* Using Link component to navigate to the post */}<br>          &lt;Link className=&quot;link&quot; to={`/post/${post.id}`}&gt;<br>            &lt;button&gt;Read More&lt;/button&gt;<br>          &lt;/Link&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Menu;</pre><p>As you can see, the logic applied to this component is quite similar to the one we have used for the others. We utilize the useEffect hook to invoke axios for data fetching and employ the useState hook (posts, setPosts) to retain the response. Subsequently, we execute the rendering of posts, pertaining to a specific category, from the “posts” variable.”</p><h3>Write post</h3><p>Before we dive into implementing the article writing feature, let’s first decide how we want to save the images that users attach to their posts. There are several options we could use, like cloud storage services, but for this tutorial, we’re going to keep it simple and show you how to upload your images directly to your server.</p><p>Let’s install multer (npm install multer) which is a popular middleware for handling file uploads in Node.js. Multer is used in conjunction with Express.js and allows us to easily handle multipart/form-data, which is typically used when uploading files through HTML forms. With Multer, we can easily specify where to save uploaded files, limit the size of files that can be uploaded, and perform various validations on the files being uploaded.</p><p>Let’s add multer to index.js in the api server:</p><pre>// api/index.js<br><br>// Use the multer middleware to storage images<br>// Configuration object for setting destination and filename for the uploaded file<br>const storage = multer.diskStorage({<br>  destination: function (req, file, cb) {<br>    // Set the destination folder where the uploaded file should be stored<br>    cb(null, &quot;../client/public/upload&quot;);<br>  },<br>  filename: function (req, file, cb) {<br>    // Set the filename of the uploaded file<br>    cb(null, Date.now() + file.originalname);<br>  },<br>});<br><br>// Set up multer middleware with the defined storage configuration<br>const upload = multer({ storage });<br><br>// Set up a POST endpoint for handling file uploads<br>app.post(&quot;/api/upload&quot;, upload.single(&quot;file&quot;), function (req, res) {<br>  // Get the uploaded file<br>  const file = req.file;<br>  // Send a response with the filename of the uploaded file<br>  res.status(200).json(file.filename);<br>});</pre><p>Don’t forget to import multer!</p><p>Now that we have where to store the image, let’s fetch them. Add the following code to the Write component:</p><pre>// Write.jsx<br>import React, { useState } from &quot;react&quot;;<br>import ReactQuill from &quot;react-quill&quot;;<br>import &quot;react-quill/dist/quill.snow.css&quot;;<br>import axios from &quot;axios&quot;;<br>import { useLocation, useNavigate } from &quot;react-router-dom&quot;;<br>import moment from &quot;moment&quot;;<br><br>const Write = () =&gt; {<br>  // Get the location state using the `useLocation` hook<br>  // will be used to check if we are in writing o edit mode<br>  const state = useLocation().state;<br><br>  // Define the state variables<br>  const [value, setValue] = useState(state?.title || &quot;&quot;);<br>  const [title, setTitle] = useState(state?.desc || &quot;&quot;);<br>  const [file, setFile] = useState(null);<br>  const [cat, setCat] = useState(state?.cat || &quot;&quot;);<br><br>  // Define the navigate function<br>  const navigate = useNavigate();<br><br>  // Define the upload function<br>  const upload = async () =&gt; {<br>    try {<br>      // Create a new FormData object and append the file to it<br>      const formData = new FormData();<br>      formData.append(&quot;file&quot;, file);<br><br>      // Send a POST request to upload the file<br>      const res = await axios.post(&quot;/upload&quot;, formData);<br><br>      // Return the filename of the uploaded file<br>      return res.data;<br>    } catch (err) {<br>      console.log(err);<br>    }<br>  };<br><br>  // Define the handleClick function to handle the form submission<br>  const handleClick = async (e) =&gt; {<br>    e.preventDefault();<br><br>    // Upload the image and get the filename<br>    const imgUrl = await upload();<br><br>    try {<br>      // Send a PUT request to update a post if the location state is defined (writing),<br>      // otherwise send a POST request to create a new post<br>      state<br>        ? await axios.put(`/posts/${state.id}`, {<br>            title,<br>            desc: value,<br>            cat,<br>            img: file ? imgUrl : &quot;&quot;,<br>          })<br>        : await axios.post(`/posts/`, {<br>            title,<br>            desc: value,<br>            cat,<br>            img: file ? imgUrl : &quot;&quot;,<br>            date: moment(Date.now()).format(&quot;YYYY-MM-DD HH:mm:ss&quot;),<br>          });<br><br>      // Navigate to the homepage after the post is saved or updated<br>      navigate(&quot;/&quot;);<br>    } catch (err) {<br>      console.log(err);<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;add&quot;&gt;<br>      &lt;div className=&quot;content&quot;&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          placeholder=&quot;Title&quot;<br>          onChange={(e) =&gt; setTitle(e.target.value)}<br>        /&gt;<br>        &lt;div className=&quot;editor-container&quot;&gt;<br>          &lt;ReactQuill<br>            className=&quot;editor&quot;<br>            theme=&quot;snow&quot;<br>            value={value}<br>            onChange={setValue}<br>          /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;menu&quot;&gt;<br>        &lt;div className=&quot;item&quot;&gt;<br>          &lt;h1&gt;Publish&lt;/h1&gt;<br>          &lt;span&gt;<br>            &lt;b&gt;Status: &lt;/b&gt; Draft<br>          &lt;/span&gt;<br>          &lt;span&gt;<br>            &lt;b&gt;Visibility: &lt;/b&gt; Public<br>          &lt;/span&gt;<br>          &lt;input<br>            style={{ display: &quot;none&quot; }}<br>            type=&quot;file&quot;<br>            id=&quot;file&quot;<br>            name=&quot;&quot;<br>            onChange={(e) =&gt; setFile(e.target.files[0])}<br>          /&gt;<br>          &lt;label className=&quot;file&quot; htmlFor=&quot;file&quot;&gt;<br>            Upload Image<br>          &lt;/label&gt;<br>          &lt;div className=&quot;buttons&quot;&gt;<br>            &lt;button&gt;Save as a draft&lt;/button&gt;<br>            &lt;button onClick={handleClick}&gt;Publish&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;item&quot;&gt;<br>          &lt;h1&gt;Category&lt;/h1&gt;<br>          &lt;div className=&quot;cat&quot;&gt;<br>            &lt;input<br>              type=&quot;radio&quot;<br>              checked={cat === &quot;art&quot;}<br>              name=&quot;cat&quot;<br>              value=&quot;art&quot;<br>              id=&quot;art&quot;<br>              onChange={(e) =&gt; setCat(e.target.value)}<br>            /&gt;<br>            &lt;label htmlFor=&quot;art&quot;&gt;Art&lt;/label&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;cat&quot;&gt;<br>            &lt;input<br>              type=&quot;radio&quot;<br>              checked={cat === &quot;science&quot;}<br>              name=&quot;cat&quot;<br>              value=&quot;science&quot;<br>              id=&quot;science&quot;<br>              onChange={(e) =&gt; setCat(e.target.value)}<br>            /&gt;<br>            &lt;label htmlFor=&quot;science&quot;&gt;Science&lt;/label&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;cat&quot;&gt;<br>            &lt;input<br>              type=&quot;radio&quot;<br>              checked={cat === &quot;technology&quot;}<br>              name=&quot;cat&quot;<br>              value=&quot;technology&quot;<br>              id=&quot;technology&quot;<br>              onChange={(e) =&gt; setCat(e.target.value)}<br>            /&gt;<br>            &lt;label htmlFor=&quot;technology&quot;&gt;Technology&lt;/label&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;cat&quot;&gt;<br>            &lt;input<br>              type=&quot;radio&quot;<br>              checked={cat === &quot;cinema&quot;}<br>              name=&quot;cat&quot;<br>              value=&quot;cinema&quot;<br>              id=&quot;cinema&quot;<br>              onChange={(e) =&gt; setCat(e.target.value)}<br>            /&gt;<br>            &lt;label htmlFor=&quot;cinema&quot;&gt;Cinema&lt;/label&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;cat&quot;&gt;<br>            &lt;input<br>              type=&quot;radio&quot;<br>              checked={cat === &quot;design&quot;}<br>              name=&quot;cat&quot;<br>              value=&quot;design&quot;<br>              id=&quot;design&quot;<br>              onChange={(e) =&gt; setCat(e.target.value)}<br>            /&gt;<br>            &lt;label htmlFor=&quot;design&quot;&gt;Design&lt;/label&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;cat&quot;&gt;<br>            &lt;input<br>              type=&quot;radio&quot;<br>              checked={cat === &quot;food&quot;}<br>              name=&quot;cat&quot;<br>              value=&quot;food&quot;<br>              id=&quot;food&quot;<br>              onChange={(e) =&gt; setCat(e.target.value)}<br>            /&gt;<br>            &lt;label htmlFor=&quot;food&quot;&gt;Food&lt;/label&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Write;</pre><p>It is crucial to utilize the useLocation hook in order to determine the current state of the application. This is especially important when editing an existing post, as the useLoction().state will provide us with the post ID as well as other pertinent information such as the post’s title and description. By utilizing this information, we can distinguish whether we are creating a new post or modifying an existing one.</p><p>Finally, we should change ${post.img} to ../upload/${post.img} in your Home, Single and Menu components to properly render the images that because we are using multer.</p><h3>What’s next?</h3><p>This tutorial provides a comprehensive guide on integrating React, Node.js, and MySQL to develop a full-stack application. It covers the deployment of a server with crucial middleware, routes, and controllers using the Express framework. You have learned how to establish a connection from the server to the database and perform CRUD (Create, Read, Update, Delete) operations from the client to the server.</p><p>Great job on completing the tutorial! Now, if you want to take your app to the next level, here’s a fun challenge for you: add a feature that allows users to upload a profile image when they register. You could also create a user panel where users can edit their profile information such as their name, email, password, and profile picture. Don’t worry if you’re not sure where to start, the route and user controller are ready for you to get creative with! Have fun!</p><h3>Important</h3><p>This project was created by “Lama Dev,” a passionate developer who shares valuable insights and tutorials on their YouTube channel. You can watch the full tutorial series that inspired this blog post <a href="https://www.youtube.com/watch?v=0aPLk2e2Z3g">here</a>.</p><p>It’s essential to understand that this blog and the associated code were developed with a primary focus on learning and educational purposes. I believe that one of the best ways to truly grasp and internalize knowledge is by explaining it to others. In that spirit, this blog serves as a comprehensive guide to integrating React, Node.js, and MySQL to build a full-stack application.</p><h3>Find me on</h3><p><a href="https://www.linkedin.com/in/santiagobedoa/">Linkedin</a></p><p><a href="https://github.com/santiagobedoa">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad9067a8ec90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Focus Modes On Spotify]]></title>
            <link>https://medium.com/@santiagobedoa/implementing-focus-modes-on-spotify-fe728b058bae?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe728b058bae</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 02:50:50 GMT</pubDate>
            <atom:updated>2023-01-18T17:10:31.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svD6RFR5G6GCeXIp0CrVXQ.png" /></figure><p><em>Please note: This was a concept project undertaken as part of Holberton’s Advanced Full Stack Web program and is in no way affiliated with Spotify.</em></p><p>I am totally sure that the reader of this article knows exactly what Spotify is, but just in case, It is one of the largest music streaming service providers, with over 456 million monthly active users, including 195 million paying subscribers.</p><p>Founded on 23 April 2006 by Daniel Ek and Martin Lorentzon, Spotify offers digital copyright-restricted recorded music and podcasts, including more than 82 million songs, from record labels and media companies. As a freemium service, basic features are free with advertisements and limited control, while additional features, such as offline listening and commercial-free listening, are offered via paid subscriptions. Users can search for music based on artist, album, or genre, and can create, edit, and share playlists.</p><p>Spotify is available in most of Europe, as well as Africa, the Americas, Asia, and Oceania, with a total availability in 184 markets. The service is available on most devices including Windows, macOS, and Linux computers, iOS and Android smartphones and tablets, smart home devices such as the Amazon Echo and Google Nest lines of products, and digital media players like Roku.</p><h4>The Brief</h4><p>After reviewing the business goals at the end of the last quarter, the Research team wants to identify if there is an opportunity to make users stream more content. They have identified a challenge that they think is worth exploring: “Improve how Spotify users find music to listen to.”</p><p>With this in mind, the UX Research team gathered data and conducted user interviews. Here are a few personas that illustrate different chunks of the user base for this challenge:</p><ul><li>Alex, student, wants to find better focus while he studies. <a href="https://drive.google.com/file/d/1RkXjb9G24GRdhO4lbCIi9q5Zj4MoWiVk/view?usp=share_link">Persona — Alex.pdf </a>— <a href="https://drive.google.com/file/d/1fYyGbTurkpF1FZhB5BPGPuM7T2i2IRUz/view?usp=share_link">User Journey Map — Alex.pdf</a></li><li>Michelle, nurse practitioner, wants to discover new genre. <a href="https://drive.google.com/file/d/1Vm9FqbjCgJax8C7MxyMdbi33IyIixhkQ/view?usp=share_link">Persona — Michelle.pdf </a>— <a href="https://drive.google.com/file/d/1_so46janaaoVsgn3S-BwSfust7Z2Q_Z6/view?usp=share_link">User Journey Map — Michelle.pdf</a></li><li>Regina, retired, wants to build a library of saved songs based on her tastes. <a href="https://drive.google.com/file/d/1PJwYA3rkwGxzTl06msI1uGmAYF2eZypN/view?usp=share_link">Persona — Regina.pdf </a>— <a href="https://drive.google.com/file/d/18LuJ8mZ6J19OvoidNjmWfSIrJBkACXyV/view?usp=share_link">User Journey Map — Regina.pdf</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyQXmIa0bpy9ptlXc_mDfw.png" /></figure><h4>User &amp; Audience</h4><p>I am a 24-year-old software developer before getting engaged in the world of development, I studied business administration for 5 years. When I decided to change my professional career, I entered the Holberton Bootcamp, where I studied for 9 months the fundamentals of software engineering, with a weekly intensity of 60 hours, and I am currently doing the advanced program in full stack. This means that for the last 6 years, I have been a full-time student.</p><p>Whit that in mind I identify with Alex’s profile, I share many of his pain points and also his desires. On a daily basis, I surround myself with other students and most of my friends can fit into the same user category as Alex.</p><p>So with that said, let’s focus on Alex’s case.</p><h4>Who is Alex?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1_9vGuE1RMFN7RyFX45pg.png" /><figcaption>Persona</figcaption></figure><p>Now that we know the highlights of Alex’s life, his goals, needs, wants, and fears, let’s see what the search process is like when Alex sits down to study:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LpiWND0OPH8NIX_jRJy0A.png" /><figcaption>User Journey Map</figcaption></figure><h4>Pain Points</h4><p>Analyzing Alex’s journey map, we can find three major pain points:</p><ul><li><strong>Stares at results:</strong> when we want to play music at a party, the process is quite simple, we go to the search bar, put the name of the song, and bang, we get the result. It’s that simple since at a party we usually look for popular songs and hits of the moment. However, when we want to listen to songs, playlists, albums, or podcasts that are not so popular, the search process becomes a bit more complex. After a search, the first results we see on the screen tend to be what is popular, so when we search for something “unknown” we have to dig through the results, and it is no mystery that this process can be a bit confusing since we have to press more buttons than we would like to find what we are looking for.</li><li><strong>Only 3 results: </strong>when we search for a genre as specific as “electro focus”, we will get few results, unlike what happens if we search for “pop”. This adds another point of friction since you have to be very careful with the words we use when searching since they are crucial to obtaining more and better results.</li><li><strong>Read playlist titles, descriptions, play songs and iterate: </strong>here we find the most frustrating part of the process. When we want to listen to “electro focus” we are looking for a type of music without lyrics, with not very strong and moving rhythms, we are looking for beats that help us concentrate when studying, working, or even meditating. This search is general because we are not looking for a specific song, but a playlist that meets the abovementioned requirements. This is why we have to read the titles of the playlists as a first filter, then read the description to make sure that the songs are oriented to help us concentrate, finally, we play the playlist. For some reason, the pieces are not what we expected, we have to repeat the whole process and although the playlist does meet our requirements, after a few hours of study the playlist will run out and we will have to look for a new one.</li></ul><p>Repeating this process every time we want to study is annoying, isn’t it?</p><p>After talking to 10 people, of whom 7 are students and 3 work as software developers, the biggest pain point when listening to music for study/work is in the time it takes to find suitable music for this purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srjhW_pwEId4iIeWr0WZ6Q.png" /></figure><h4>Apple Ecosystem</h4><p>I am a heavy user of Apple products, my first laptop was a Macbook, the same as my first smartphone and tablet. I’m a big fan of the Apple philosophy. I love the idea of making technology simple and intuitive, tools that create the least amount of friction when using them.</p><p>Surely you must be wondering, what the heck does Apple have to do with the Spotify user experience? The key is in the little or even non-existent friction there is when using an apple product, and as we have already seen, the process of looking for a playlist that helps us concentrate on our studies/work is quite confusing and cumbersome.</p><p>This is the reason why I would like to integrate Apple’s work to solve this problem, and what better way to do it than using the Apple ecosystem.</p><h4>Focus</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCko5ooF01B_pEGYqIIWaQ.jpeg" /></figure><p>Apple in iOS 15 introduced Focus mode, an expansion of Do Not Disturb that allows you to set up different permissions for apps, contacts, and more depending on what you are doing. You can have separate tasks for when you are at work, when you are studying, when you are at home, and more.</p><p>In <a href="https://www.apple.com/ios/ios-16/">iOS 16</a>, available now, Apple has improved Focus with new features, and <a href="https://www.macrumors.com/guide/ios-16-focus/">this guide</a> covers everything that you need to know about using Focuses in ‌iOS 16‌.</p><p>I am a person who is easily distracted, my worst enemy when it comes to studying is my smartphone, I constantly check it, and one way or another I always end up on Instagram scrolling down for a long time. Before Focus came out, what I had to do was leave my cell phone in a drawer or delete all social networks when studying. Focus has been a game changer for my concentration, because now with this function, I only have to customize my “Studying” mode, specify which Apps, notifications and other things I want to limit and that’s it, now by pressing just one button, I can limit the use of my apps, like if I didn’t have them installed.</p><h4>Linking to Spotify</h4><p>Since Focus works on iPhone, iPad, Mac, and Apple Watch, we can use the metadata when this feature is active so the Spotify app knows when Focus is active and what mode it is in.</p><p>The idea is once Focus mode is activated for studying, distracting apps will be blocked. When we open Spotify with Focus mode active for the first time, the application will show us a menu to do the setup. The setup consists of choosing artists, playlist, genres and categories (such as those that do not have lyrics) that will be available for the Focus mode that we have active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GhlDVcwG4jdG1Z-kBPUADQ.jpeg" /><figcaption>Sorry for my handwriting…</figcaption></figure><p>Let’s say we have the “Studying” mode active. When we enter Spotify, a menu will open to set up the “Studying” mode, there we will be asked to add artists (eg. lofi girl), playlists (eg. Study lofi), genres (eg. Electro focus) and category (eg. Without lyrics). Once we have the “Studying” mode ready within Spotify, the Home of the application will change to show us only artists, playlists, and songs that meet the established parameters, once we start playing music, the algorithm will be restricted to only play songs that comply with the parameters and thus avoid changes of genres.</p><p>Although the initial setup of focus mode could take more work compared to performing the search as shown in the User Journey Map, the next times we enter the application with the Focus mode activated, the Home will only show us recommendations that comply with what we specified in the configuration phase, so we can play music instantly and thus concentrate on what is really important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XXufmYl7aByNagJOncd9jA.png" /></figure><p>Before I show how the focus mode would look like in Spotify, let’s recall how the interface looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JYut3t2m7uZW0ZXAqT6Hw.png" /><figcaption>Spotify Regular Home</figcaption></figure><p>With this new feature, Alex’s Journey Map would look like this:</p><ul><li>Alex turns on “Studying” Focus mode on his device. <em>Note: Studying is a predefined mode of the Focus function provided by Apple devices.</em></li><li>Alex opens Spotify, and immediately the app detects the “Studying” Focus mode and asks the user if wants to do the setup for “Studying” Focus mode. The configuration consists of this series of questions: 1) Select at least three artists or profiles that best fit the “Studying” mode. 2) Select at least three playlist that best fit the “Studying” mode. 3) Which of the following activities best describes the one you will be doing during “Studying” Focus mode?. <em>Note: for the three questions, the user will be able to select between suggested. In case none of the options fit the user needs, the user could search and select the option that better suits their needs.</em></li><li>Now, Alex will have a section to view, activate/deactivate, edit and configure his modes:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1Q6G2toFpbdqy2t5As6UA.png" /><figcaption>Focus Modes View</figcaption></figure><ul><li>Finally, when Alex opens the app again with “Studying” Focus mode active, Spotify will show him a Home that meets the needs of the moment, so Alex can start studying quickly:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x2T3eKgmuVNGAtVHtdjlkA.png" /><figcaption>“Studying” mode Home</figcaption></figure><p><a href="https://www.figma.com/file/kNDLNHwyHQ1f6Ps3EEmkar/Spotify-Focus-UI?node-id=0%3A1&amp;t=KDtrX8lXpNWbHYEi-1"><em>This link</em></a><em> will take you to the Figma design.</em></p><p>After validating the final prototype with 10 friends, of which 7 are full-time students and 3 work as software developers, I get the following comments:</p><blockquote>“Spotify definitely must implement it! This feature is helpful and convenient, and it would likely improve my experience as a user. I would likely tell my friends and family about the feature and recommend it to others. If the feature is part of a music streaming service or other product that I am paying for, I would also feel more satisfied with my purchase knowing that the company is continuously improving its offerings and adding valuable features.”</blockquote><p>.</p><blockquote>It’s always great to discover new features that make our lives easier and more enjoyable.</blockquote><p>In summary, the feedback was quite positive, all the participants found the new feature quite intuitive and convenient as it saves them time and energy, they don’t have to constantly think or search for what to listen to. Just activate Focus mode and you’re ready to get the job done.</p><h4>Next steps</h4><p>This project was designed for iOS, MacOS and iPadOS operating systems. However, Spotify could develop a new functionality following the same idea as Apple’s Focus and thus reach more devices. By having the Focus functionality native on Spotify, we could create various modes such as “Studying”, “Workout”, among others.</p><h3>Find me on:</h3><p>Linkedin: <a href="https://www.linkedin.com/in/santiagobedoa/">https://www.linkedin.com/in/santiagobedoa/</a></p><p>Github: <a href="https://github.com/santiagobedoa">https://github.com/santiagobedoa</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe728b058bae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding a Shell using C]]></title>
            <link>https://medium.com/@santiagobedoa/coding-a-shell-using-c-1ea939f10e7e?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ea939f10e7e</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[c-programming-language]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Wed, 16 Nov 2022 19:27:00 GMT</pubDate>
            <atom:updated>2023-03-02T13:37:04.434Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coding your own Shell in C</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqxZ99tyXrI3aIYW8lLoHA.png" /><figcaption>img source: <a href="https://github.com/Swordfish90/cool-retro-term">https://github.com/Swordfish90/cool-retro-term</a></figcaption></figure><p>In the movies, we see how programmers work in front of a dark screen with small green letters, which in most cases does not contain actual code or commands, except for some cases, such as the fantastic series of Mr. Robot. Still, the rest of the series or movies do not reflect how the developers really work.</p><p>Actually, most of the developers I know barely use the terminal (that dark screen with green letters you see in movies), they only use it when strictly necessary, to install a library for example. Something really sad, the more you go into it, the more you learn.</p><p>I forced myself to use Vim and the terminal as my only text editor. It wasn’t until a long time ago that I started using VS Code with a Vim extension since I stuck to the good habit of using only the keyboard whenever possible, I even have a Vim extension to navigate the web using the keyboard.</p><p>The point is that I learned a lot more things compared to my colleagues who have used a text editor from the beginning. Well, the fact that I had to use only Vim to write a considerable amount of code, sooner or later I had to customize Vim (to be more exact, go from Vim to NeoVim and the world behind it) to be more efficient at the time to write code. Thanks to this, I learned about the configuration files of my operating system, soft and hard links, aliases, and even Bash scripts to automate my work environment. I probably wouldn’t have learned as much about Linux (<a href="https://linuxcommand.org/index.php">here’s a good resource for learning the essentials</a>) if I’d jumped right into VS Code.</p><p>And this not only applies to the code editor, but also to programming languages, and really to anything in life. Python is a high-level language, but do you really understand why? My first lines of code were in python, however, it wasn’t until I learned C that I realized the level of abstraction that python handles and the many things that I take for granted when developing in this language. C allowed me to see further, C gave me the foundation to understand extremely important concepts like pointers, dynamic memory allocation, or compiled vs interpreted languages, which I probably would never have learned with just python. Now, every time I write code in Javascript or Python, I value the work behind it much more.</p><p>With this said, we are going to develop a simple shell using C. I promise you that it will be very useful even if you do not use this language in your work because I am sure that it will help you understand and realize things that you were not even aware of before.</p><h3>What is a Shell?</h3><p>Before diving into the process, we should understand what is a shell. To answer this question, a Shell is a program that takes the command inputs written from the user’s keyboard and passes them to the machine to execute them through the kernel. It also verifies if the command input from the user is correct.</p><h4>Terminals, kernels, and shells…</h4><p>It is worth clarifying that the kernel, the terminal, and the shell are different things. Here is an overview to understand the differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*vyj1fmPVJWWi8PQs8pCzWw.png" /><figcaption>One thing I want to clarify in the above image is that each box is <em>within</em> the parent box. So for example, The “Program: terminal” is interacting with a contained shell, while the shell then spawns either a “Built-in” or “Program”. source: <a href="https://www.integralist.co.uk/posts/terminal-shell/">https://www.integralist.co.uk/posts/terminal-shell/</a></figcaption></figure><h4>Differences and important concepts:</h4><ul><li><strong>Kernel:</strong> a computer has a kernel, the kernel is responsible for managing the computer’s system, the kernel has no user interface, to interact with the kernel you use an intermediary program.</li><li><strong>Program:</strong> a program is a structured collection of instructions (machine code) that a computer can execute. Your computer has many programs. One such example would be the “terminal emulator” program.</li><li><strong>Executables:</strong> executables (or executable binaries) are programs. More specifically, an executable is a file that <strong><em>contains</em></strong> a program, generally the <strong><em>result</em></strong> of a program being turned into something that can be executed by the computer.</li><li><strong>Terminal:</strong> a terminal is an input/output device. Traditionally they would have been a <strong><em>real</em></strong> hardware device that you used to interact with a computer. e.g. the computer would be a large box in a server room, and the terminal would be a monitor/keyboard connected to the computer. In modern computing, we have a “terminal emulator”. If you don’t want to use a GUI (graphical user interface) to interact with your computer, you can use a terminal emulator.</li><li><strong>Shell:</strong> a shell is a program that is accessed <strong><em>via</em></strong> a terminal emulator. The terminal accepts input, passes it to the shell, and the shell’s output is sent back to the terminal to be displayed. The shell accepts input as a set of commands.</li></ul><p>Follow this <a href="https://www.integralist.co.uk/posts/terminal-shell/">link</a> for a deeper look or visit my <a href="https://medium.com/@santiagobedoa/unix-command-line-interpreter-under-the-hood-653202ca1df8">previous</a> article if you want it in plain English.</p><h3>Let’s code the Shell…</h3><p>Now we know what is a Shell, let’s open the code editor… But before let’s take a look at how will be the lifetime of our shell:</p><ul><li><strong>Initialize:</strong> in this step, a typical shell would read and execute its configuration files. These change aspects of the shell’s behavior.</li><li><strong>Interpret:</strong> next, the shell reads commands from stdin (which could be interactive, or a file) and executes them.</li><li><strong>Terminate:</strong> after its commands are executed, the shell executes any shutdown commands, frees ups any memory, and terminates.</li></ul><p>Our shell will be simple, so the shell initialization and configuration stage will not be necessary. A Shell can work interactively or non-interactively, so the main function is responsible for determining which of the two ways our shell will work:</p><pre>//main.c<br>#include &quot;shell.h&quot;<br><br>/**<br> * main - function that checks if our shell is called<br> *<br> * Return: 0 on success<br> */<br>int main(void)<br>{<br> // determines if file descriptor is associated with a terminal<br> if (isatty(STDIN_FILENO) == 1)<br> {<br>  shell_interactive();<br> }<br> else<br> {<br>  shell_no_interactive();<br> }<br> return (0);<br>}</pre><p>issaty is a function that determines if a file descriptor (fd) is associated with a terminal. It take as argument a fd and returns 1 fi fd is referring to a terminal, otherwise 0 is returned. All the functions used will be listed at the end of the document, so if you have any questions while writing the code, I encourage you to visit the man pages or search on the web. It’s very important that you really understand how the functions work.</p><p>Don’t forget to create the header file which contains C function declarations and macro definitions to be shared between several source files.</p><pre>//shell.h<br>#ifndef SHELL_H<br>#define SHELL_H<br><br>/*---LIBRARIES---*/<br>#include &lt;stdio.h&gt;<br>#include &lt;unistd.h&gt;<br><br>/*---PROTOTYPES---*/<br>/* main.c */<br>void shell_interactive(void);<br>void shell_no_interactive(void);<br><br>#endif</pre><p>For now it is something simple, however, this file will grow along with our code.</p><h3>Shell: a RPEL process</h3><p>In a very simple way, the flow of the Shell can be considered to be of type RPEL. The first action that a Shell must complete is read a line from the stdin, R is the stand for this action (read). Once the line has been read, we should split it, since we know that the first string refers to the command. Separated by a space, we found the flags and arguments of the command, P is for parse. E refers to execute, of course, we execute the command along with its arguments. Finally, our shell should iterate (L — loop) this process until the user exit the process or the shell reaches the end of the file (EOF).</p><p>This applies to both, the interactive and no-interactive Shell.</p><h3>Shell Interactive</h3><p>This is the typical case where you type into the terminal and the Shell process and execute these commands.</p><pre>//shell_interactive.c<br>#include &quot;shell.h&quot;<br><br>/**<br> * shell_interactive - UNIX command line interpreter<br> *<br> * Return: void<br> */<br>void shell_interactive(void)<br>{<br> char *line;<br> char **args;<br> int status = -1;<br><br> do {<br>  printf(&quot;simple_prompt$ &quot;); /* print prompt symbol */<br>  line = read_line(); /* read line from stdin */<br>  args = split_line(line); /* tokenize line */<br>  status = execute_args(args);<br>  /* avoid memory leaks */<br>  free(line);<br>  free(args);<br>  /* exit with status */<br>  if (status &gt;= 0)<br>  {<br>   exit(status);<br>  }<br> } while (status == -1);<br>}</pre><p>As you can see, this function contains the, read (read_line), parse (split_line), execute (execute_arg), and loop (the mentioned functions will iterate until the status gives to us a signal to end the process). In a moment you will understand why the status is equal to -1. Now it’s time to build out function.</p><h4>Read Line</h4><p>In the shell_interactive.c file, We declare a char pointer line to allocate the string returned by read_line function. read_line function reads and allocates a string containing the line read from the stream and returns it. If it is not possible to read the line from the stream, the cause is checked. If the EOF is reached, the function is terminated successfully, otherwise, the function will exit with failure.</p><pre>//read_line.c<br>#include &quot;shell.h&quot;<br><br>/**<br> * read_line - read a line from stdin<br> *<br> * Return: pointer that points to a str with the line content<br> */<br>char *read_line(void)<br>{<br> char *line = NULL;<br> size_t bufsize = 0;<br><br> if (getline(&amp;line, &amp;bufsize, stdin) == -1) /* if getline fails */<br> {<br>  if (feof(stdin)) /* test for the eof */<br>  {<br>   free(line); /* avoid memory leaks when ctrl + d */<br>   exit(EXIT_SUCCESS); /* we recieved an eof */<br>  }<br>  else<br>  {<br>   free(line); /* avoid memory leaks when getline fails */<br>   perror(&quot;error while reading the line from stdin&quot;);<br>   exit(EXIT_FAILURE);<br>  }<br> }<br> return (line);<br>}</pre><p>Moving back to the shell_interactive function, once read_line is executed, will have the string read from the stdin allocated in the line variable. Now we must split the entire string to get the command and its arguments.</p><h4>Parse String</h4><p>The purpose of split_line is to obtain an array and thus separate each element from the original text string that was obtained with the read_line function. When we split a string into multiple elements, we call this process “tokenize” in C programming.</p><pre>//split_line.c<br>#include &quot;shell.h&quot;<br><br>/**<br> * split_line - split a string into multiple strings<br> * @line: string to be splited<br> *<br> * Return: pointer that points to the new array<br> */<br>char **split_line(char *line)<br>{<br> int bufsize = 64;<br> int i = 0;<br> char **tokens = malloc(bufsize * sizeof(char *));<br> char *token;<br><br> if (!tokens)<br> {<br>  fprintf(stderr, &quot;allocation error in split_line: tokens\n&quot;);<br>  exit(EXIT_FAILURE);<br> }<br> token = strtok(line, TOK_DELIM);<br> while (token != NULL)<br> {<br>  /* handle comments */<br>  if (token[0] == &#39;#&#39;)<br>  {<br>   break;<br>  }<br>  tokens[i] = token;<br>  i++;<br>  if (i &gt;= bufsize)<br>  {<br>   bufsize += bufsize;<br>   tokens = realloc(tokens, bufsize * sizeof(char *));<br>   if (!tokens)<br>   {<br>    fprintf(stderr, &quot;reallocation error in split_line: tokens&quot;);<br>    exit(EXIT_FAILURE);<br>   }<br>  }<br>  token = strtok(NULL, TOK_DELIM);<br> }<br> tokens[i] = NULL;<br> return (tokens);<br>}</pre><p>Basically, what split_line does is call strtok passing as arguments the string to split and the delimiters to know when to break and add the extracted element to an array. The code can be seen as tricky but if you take a look at strtok man page you will find that you need to give it the string argument only for the first call, each time you call the function again you don&#39;t need to, strtok will return the next token until the end of the initial string is reached.</p><p>This is the reason why we store in the token variable the returned string by strtok. Then we start to iterate, in each iteration, we call strtok again but with a NULL string argument, then we allocate the returned token in an array of string (char **tokens) until strtok finds no more tokens. Inside the loop, we check if the size of tokens needs to increase to store more elements. Finally, split_line returns an array with multiple tokens.</p><h4>Execute Arguments</h4><p>We know that the first element of the tokens array refers to the command to be executed and the following ones are its flags. Most of the commands that a shell executes are programs, but not all of them, some commands live in the shell itself, they are called built-ins.</p><p>For example, most shells are configured by the rules specified in the configurations scripts, like “~/.zshrc”. Those scripts use commands that change the operation of the shell, is possible because they were implemented within the shell code. So, the commands that are in “.zshrc” file are built-in commands.</p><p>We should create a function that checks if the entered command matches a builtin command and, if so, executes it. If there is no match, the program should start a new process that finds and runs the file containing the desired command. In our shell, execute_args will take care of that.</p><pre>//execute_args.c<br>#include &quot;shell.h&quot;<br><br>/**<br> * execute_args - map if command is a builtin or a process<br> * @args: command and its flags<br> *<br> * Return: 1 on sucess, 0 otherwise<br> */<br>int execute_args(char **args)<br>{<br> char *builtin_func_list[] = {<br>  &quot;cd&quot;,<br>  &quot;env&quot;,<br>  &quot;help&quot;,<br>  &quot;exit&quot;<br> };<br> int (*builtin_func[])(char **) = {<br>  &amp;own_cd,<br>  &amp;own_env,<br>  &amp;own_help,<br>  &amp;own_exit<br> };<br> int i = 0;<br><br> if (args[0] == NULL)<br> {<br>  /* empty command was entered */<br>  return (-1);<br> }<br> /* find if the command is a builtin */<br> for (; i &lt; sizeof(builtin_func_list) / sizeof(char *); i++)<br> {<br>  /* if there is a match execute the builtin command */<br>  if (strcmp(args[0], builtin_func_list[i]) == 0)<br>  {<br>   return ((*builtin_func[i])(args));<br>  }<br> }<br> /* create a new process */<br> return (new_process(args));<br>}</pre><p>We use strcmp to compare the command and built-in functions, if there is a match, we will use a pointer to a function to call the target function passing the command and its flags. execute_args function will return the returned value of the target built-in function. Otherwise, execute_args will launch a new process by calling new_process function and return the returned value of new_process.</p><h4>Execute a non-built-in command</h4><p>When our Shell is called, a new process is created and it is active (running) until we end, kill or exit the program. But what is a program? In a nutshell, a program is an executable file held in storage on your machine. Anytime you run a program, you have created a process. Since we are running our shell, it has a unique process ID and lives with some specific environment variables. As we discussed before, a non-built-in function is a program (executable file) that lives somewhere in our memory.</p><p>Let’s code a function that creates a new process and execute the file that contains the command that we want to perform.</p><pre>//new_process.c<br>#include &quot;shell.h&quot;<br><br>/**<br> * new_process - create a new process<br> * @args: array of strings that contains the command and its flags<br> *<br> * Return: 1 if success, 0 otherwise.<br> */<br>int new_process(char **args)<br>{<br> pid_t pid;<br> int status;<br><br> pid = fork();<br> if (pid ==  0)<br> {<br>  /* child process */<br>  if (execvp(args[0], args) == -1)<br>  {<br>   perror(&quot;error in new_process: child process&quot;);<br>  }<br>  exit(EXIT_FAILURE);<br> }<br> else if (pid &lt; 0)<br> {<br>  /* error forking */<br>  perror(&quot;error in new_process: forking&quot;);<br> }<br> else<br> {<br>  /* parent process */<br>  do {<br>   waitpid(pid, &amp;status, WUNTRACED);<br>  } while (!WIFEXITED(status) &amp;&amp; !WIFSIGNALED(status));<br> }<br> return (-1);<br>}</pre><p>new_process function takes as argument the array of strings that split_line function returns. Using fork function, we create a new process that has the same environment variables as the parent process, we allocate these data in a pid_t structure. Now we have two processes running concurrently.</p><p>In the child process, we want to run the command given by the user. We’re going to use execvp function that takes the name of the executable (the command for our case, that would be in the first position of the array, args[0]) and an array (vector) of string arguments (like the argument vector) which contains the flags. The ‘p’ means that instead of providing the full file path of the program to run, we’re going to give its name and let the operating system search for the program path.</p><p>The parent process needs to wait for the command (child process) to finish. We use waitpid function to wait for the process’s state to change. We use the macros provided with waitpid to wait until either the processes are exited (WIFEXITED, evaluates if the child process terminates normally) or killed (WIFSIGNALED, child process was finished by a signal). Then, the function finally returns 1 as a signal to the calling function that we should prompt for input again.</p><p>So far, we have seen how the RPEL process works for our shell and the life cycle will be completed when the user decides to exit our EOF will be reached.</p><h3>Shell no-interactive</h3><p>We have coded a simple shell that can perform basic tasks in an interactive way, which means that the shell is waiting for commands that the user will give through the terminal, and will display the output to the user.</p><p>But what if we want to perform some actions from a bash script or run commands through some automated process? This is when the no-interactive shell hits the floors.</p><pre>//shell_no_interactive.c<br>#include &quot;shell.h&quot;<br><br>/**<br> * shell_no_interactive - unix command line interpreter<br> *<br> * Return: void<br> */<br>void shell_no_interactive(void)<br>{<br> char *line;<br> char **args;<br> int status = -1;<br><br> do {<br>  line = read_stream();<br>  args = split_line(line); /* tokenize line */<br>  status = execute_args(args);<br>  /* avoid memory leaks */<br>  free(line);<br>  free(args);<br>  /* exit with status */<br>  if (status &gt;= 0)<br>  {<br>   exit(status);<br>  }<br> } while (status == -1);<br>}</pre><p>It is no coincidence that shell_no_interactive function is slightly different from shell_interactive function. In fact, the only difference occurred when we assign a value to a line variable, because we get the string that contains the command in a different way. The change is so small that there was no need to create a new function and implement it from scratch. However, I decided to split it to make the code easier.</p><h4>Read Line from the stdin stream</h4><pre>//read_stream.c<br>#include &quot;shell.h&quot;<br><br>/**<br> * read_stream - read a line from the stream<br> *<br> * Return: pointer that points the the read line<br> */<br>char *read_stream(void)<br>{<br> int bufsize = 1024;<br> int i = 0;<br> char *line = malloc(sizeof(char) * bufsize);<br> int character;<br><br> if (line == NULL)<br> {<br>  fprintf(stderr, &quot;allocation error in read_stream&quot;);<br>  exit(EXIT_FAILURE);<br> }<br> while (1)<br> {<br>  character = getchar(); /* read first char from stream */<br>  if (character == EOF)<br>  {<br>   free(line);<br>   exit(EXIT_SUCCESS);<br>  }<br>  else if (character == &#39;\n&#39;)<br>  {<br>   line[i] = &#39;\0&#39;;<br>   return (line);<br>  }<br>  else<br>  {<br>   line[i] = character;<br>  }<br>  i++;<br>  if (i &gt;= bufsize)<br>  {<br>   bufsize += bufsize;<br>   line = realloc(line, bufsize);<br>   if (line == NULL)<br>   {<br>    fprintf(stderr, &quot;reallocation error in read_stream&quot;);<br>    exit(EXIT_FAILURE);<br>   }<br>  }<br> }<br>}</pre><p>The read_stream function enters an infinite loop and reads the first character from the stdin stream using the getcharfunction, after we allocate the first byte in the character variable, we check if the byte corresponds to the EOF, if it is the case, we exit with program with success status. If the above condition is not met, we check if there is a line break, which tells us that the line has end, we allocate a null byte at the end of line and return it. Otherwise, we allocate the byte in the corresponding position of line. Finally, we check if line needs more space to store the following bytes.</p><p>Finally, the header file should look like:</p><pre>#ifndef SHELL_H<br>#define SHELL_H<br><br>/*---LIBRARIES---*/<br>#include &lt;stdio.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;sys/wait.h&gt;<br><br>/*---Macros---*/<br>#define TOK_DELIM &quot; \t\r\n\a\&quot;&quot;<br>extern char **environ;<br><br>/*---PROTOTYPES---*/<br>/* main.c */<br>void shell_interactive(void);<br>void shell_no_interactive(void);<br><br>/* shell_interactive.c */<br>char *read_line(void);<br>char **split_line(char *line);<br>int execute_args(char **args);<br><br>/* execute_args */<br>int new_process(char **args);<br><br>/* shell_no_interactive */<br>char *read_stream(void);<br><br>/*---Builtin func---*/<br>int own_cd(char **args);<br>int own_exit(char **args);<br>int own_env(char **args);<br>int own_help(char **args);<br><br>#endif</pre><p><a href="https://github.com/santiagobedoa/shell">Here</a> you can find the Github repository of the project.</p><h4>Find me on:</h4><p>Linkedin: <a href="https://www.linkedin.com/in/santiagobedoa/">https://www.linkedin.com/in/santiagobedoa/</a></p><p>Github: <a href="https://github.com/santiagobedoa">https://github.com/santiagobedoa</a></p><h3>Resources</h3><h4>main.c</h4><ul><li>isatty</li><li>fileno</li></ul><h4>read_line.c</h4><ul><li>getline</li><li>feof</li><li>perror</li></ul><h4>split_line.c</h4><ul><li>strtok</li></ul><h4>execute_args.c</h4><ul><li>strcmp</li></ul><h4>new_process.c</h4><ul><li>fork</li><li>execvp</li><li>waitpid</li></ul><h4>read_stream.c</h4><ul><li>getchar</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ea939f10e7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revealing what goes on behind the scenes of the Internet]]></title>
            <link>https://medium.com/@santiagobedoa/revealing-what-goes-on-behind-the-scenes-of-the-internet-5f6d59848002?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f6d59848002</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[full-stack]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Thu, 01 Sep 2022 21:51:54 GMT</pubDate>
            <atom:updated>2022-09-01T21:51:54.831Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Have you ever wondered what happens when you type google.com in your browser and press Enter?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58ZmdPjwBGIcYVQ9wyiXmw.png" /><figcaption>Photo by <a href="https://unsplash.com/@firmbee">firmbee</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><h4><strong>Introduction</strong></h4><p>Well, everyone already knows what happens. You go to the search bar we are all used to, or does the search bar come to you? For many people, the Internet might seem like a magical invention. You type in a website name, hit enter, and somehow the website loads. Browsing is easy, right?</p><p>Behind the scenes, however, there is a surprising amount of work being done. Today, we’re going to draw back the curtain and dive into the intricacies of this wondrous system. We’ll use <a href="https://www.google.com/">https://www.google.com</a> as an example, but the following explanation could apply to any website.</p><p>First of all, you may be wondering, what exactly is the Internet? It is a wide area network (WAN) with thousands of computers around the world, all with the ability to share information with each other. The information required to load a website is located on a server, which is a computer that has the ability to process requests and send data to other computers (clients). The server with the desired information is located somewhere on the Internet.</p><p>How does your browser know where to send a request for this information? Just as houses have addresses to make it easy for the post office to send mail, servers have what is known as Internet Protocol (IP) addresses. However, memorizing a numerical label is much more complex than memorizing a name, so IP addresses are not often used by clients. So where does your computer get the address?</p><h4>DNS request</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpKuOCODSMrpIztBk48NSA.png" /><figcaption>Photo by <a href="https://unsplash.com/@mathyaskurmann">Mathyas Kurman</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>The Domain Name System (DNS) is a decentralized, hierarchical naming system for devices connected to the Internet. Each of these devices must have an Internet Protocol address that for IPv4 is in the range 0.0.0.0 to 255.255.255.255. Each of the dotted numbers corresponds to an 8-bit integer called an octet. The four octets comprise a 32-bit IPv4 address. However, these addresses are not easy to read or remember. For this reason, each IP address is associated with a human-readable domain name like <a href="http://www.google.com./">www.google.com.</a></p><p>If you have visited this website before, the address may be stored in your browser’s cache. The cache is like your phone’s contact list, containing names (domains) associated with numbers (IP addresses). If it is not stored there, the browser will ask the operating system (OS) if it has <a href="http://www.google.com/">www.google.com</a> stored in its cache.</p><p>Otherwise, the operating system will start the process of going through the Domain Name System (DNS) to find the address. First, the operating system requests the address from the resolver, usually your Internet service provider. If it is a high traffic website, the resolver may have this value stored in its cache. Otherwise, the resolver knows the address of the root server, where it begins its search for the IP address.</p><p>The root server contains the addresses of Top-Level Domain (TLD) servers. Some common TLDs are .COM, .ORG, and .NET. Since our domain name is derived from the .COM TLD, the resolver is sent to that server, which will contain information on all .COM domain names. The resolver will also cache the address of the .COM TLD server so it won’t have to request it from the root server again. If the .COM TLD does not have the address directly, it will send the resolver to the authoritative name server.</p><p>This server is owned by the company through which the domain name was purchased. But how did the .COM TLD server know which authoritative name server is associated with <a href="https://www.google.com/">www.google.com</a> without knowing the website’s IP address? When a domain name is purchased, the domain registrar reserves the name and informs the TLD registry which authoritative name server is associated with that address. Once at the authoritative name server, the resolver is finally able to get the IP address and return it to the OS. The OS will then save this address, so the resolver will not have to go through this process again, and return the address to the browser.</p><h4>TCP/IP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iB8RA646aL2QzCh8lLvRlw.png" /><figcaption>Photo by <a href="https://unsplash.com/@bannon15">Bannon Morrissy</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>Now that your browser knows where to find <a href="http://www.google.com/">www.google.com</a>, it’s time to request the information. The way your browser and the server interact is defined by the Transmission Control Protocol/Internet Protocol (TCP/IP Protocol). TCP defines how to create communication channels over a network and how the information will be broken into smaller packets and reassembled at the destination. IP defines how to address and route these packets through the network.</p><p>Before your computer sends a request to the website, a connection will be established through the TCP three-way handshake, also known as SYN-SYN-ACK. Your computer will send a TCP to sync the packet with the server. Upon receiving the packet, the server will send a synchronized acknowledgment packet to the computer. Once the computer receives this packet, it will send an acknowledgment packet, which will establish the connection.</p><h4>Firewall</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtZdEjRjXfBrBQ8tkMt6xA.png" /><figcaption>Photo by <a href="https://unsplash.com/@jamie452">Jamie Street</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>This request will first reach a special type of server called a load balancer, whose purpose is to spread traffic across multiple servers so as not to overload any one server with requests. The load balancer is often equipped with what is known as a firewall, which can be either a software component or a hardware component. The firewall’s job is to monitor incoming traffic and highlight and decide whether or not to allow the traffic to pass through based on a custom set of security rules. Some of these rules may include restrictions on the originating IP address of the request, the frequency with which requests are made, or the type of content that is requested.</p><h4>HTTPS/SSL</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jA6gaIUAceKebDim0qDYA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio">Charles Deluvio</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>Since the protocol specified when we entered our domain name was actually HTTPS and not HTTP, an additional security measure will be taken using Secure Socket Layer (SSL). SSL will establish an encrypted link between your web browser and the load balancer using an SSL certificate located on the server.</p><p>When our request reaches its destination, the server sends a copy of its SSL certificate. Then our computer checks if the certificate is authentic. If so, our client sends an encrypted key to the web server. The web server then decrypts the key and returns the content recorded with a corresponding key to the client, which is in turn decrypted.</p><p>This ensures that all information that is passed between these two endpoints will remain private. The load balancer will then redirect your request to one of many web servers using a preset algorithm. A common load balancing algorithm is a round-robin, in which the load balancer goes down a list of servers and forwards the request to the next server in the list.</p><h4>Web Server</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLADPuZmuVP2nm16si1CJQ.png" /><figcaption>Photo by <a href="https://unsplash.com/@imgix">imgix</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>Now that the request has finally been redirected to a web server, this journey across the Internet is almost over. The purpose of the web server is to process requests over HTTP and serve files that correspond to the requested website. Sometimes the request only includes a static hypertext markup language (HTML) file, which means the file never changes. In this case, the web server can access the file from the file system and deliver it directly to the client.</p><p>However, most of the time, websites are based on dynamic content or content that changes. As a result, the content will need to be converted to a static file to be delivered to the client. An additional server, the application server, will retrieve information from a database, such as a user information, and change this information to a static file. This is then returned to the web server to fulfill the request. Once the file is sent back to the browser, it will interpret the HTML file and display the corresponding website.</p><h4>This is how the magic happens!</h4><p>It’s amazing that all this happens so fast, I think this is the reason why people tend to consider the internet as something magical. We can identify the principle of abstraction in programming on how the internet works since many complex things are happening, but the user doesn’t realize what is happening and can use the internet with ease.</p><p>If you want to investigate more about the subject, I leave you this excellent resource to understand much more about how this process works:</p><p><a href="https://github.com/alex/what-happens-when#the-g-key-is-pressed">https://github.com/alex/what-happens-when#the-g-key-is-pressed</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f6d59848002" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tools are getting smarter… A brief explanation of IoT]]></title>
            <link>https://medium.com/@santiagobedoa/tools-are-getting-smarter-a-brief-explanation-of-iot-2f11db5c3ea8?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f11db5c3ea8</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[internet-of-things]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Tue, 26 Jul 2022 01:20:30 GMT</pubDate>
            <atom:updated>2022-07-26T01:20:56.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4LW4_JLfurxQxO4mDZwcw.png" /><figcaption>taken from: <a href="https://www.apple.com/fr/macos/continuity/">https://www.apple.com/fr/macos/continuity/</a></figcaption></figure><p>Over the course of the next 20 years, more will change around the way we do our work than has happened in the last 2000.</p><p>There have been four major historical eras defined by the way we work. The Hunter-Gather Age lasted several million years, the Agricultural Age lasted several thousand years, the Industrial Age lasted a couple of centuries, and now the Information Age has lasted just a few decades. And today, we’re on the cusp of our next significant era as a species.</p><p>In this new era, your natural human capabilities are going to be augmented by computational systems that help you think, robotic systems that help you make, and a digital nervous system that connects you to the world far beyond your natural senses.</p><p>If I asked you, are you an augmented cyborg? you’d probably laugh. I would argue that we’re already augmented. Well, when you have a question, surely the first thing you do is take out your cell phone and search the internet for the answer, and surprisingly you will find a good source of information with just a few clicks. And this applies to all types of knowledge, from the most technical to general knowledge.</p><p>Undoubtedly, the four major historical eras, are considered major thanks to the tools that we used in that particular time. However, for the last three and a half million years, the tools that we’ve had have been completely passive, they do exactly what we tell them and nothing more. Our very first tool only cut where we struck it, and even our most advanced tools do nothing without our explicit directions.</p><blockquote>“We have been limited by this need to manually push our wills into our tools”…</blockquote><blockquote>Maurice Conti</blockquote><h4><strong>The tools are changing</strong></h4><p>So far we have talked about how tools have marked the course of human history, and these tools have been passive. But things are changing, we are getting closer to a future where we can have conversations with computers and ask them to perform tasks for us.</p><p>In the Information Age, we have focused on connecting people, the internet (of people) has changed the world, and we have created a great network, where nodes can exchange any type of information, from photos, videos, and comments, to scientific research and literary novels. But as we said, things are changing, there’s a new internet, and it’s changing the world again.</p><p>This new internet is not just about connecting people, it’s about connecting things. It’s called the Internet of Things (IoT).</p><h4><strong>Why</strong> <strong>connect</strong> <strong>things to the Internet?</strong></h4><p>So connecting things to the Internet big deal, right? Well, it kind of is, and here’s why, because “things” can start to share their experiences with other things (like people interact on the “Internet of people”). At this point, you are probably wondering how’s that work.</p><p>In a nutshell, you take things and then you add the ability to sense, communicate, touch and control, and there you get the opportunity for things to interact and collaborate with other things. As human beings, we interact and contribute, and collaborate with other people in our own environment through our five senses (sight, hearing, taste, smell, and touch). Imagine things with the ability to sense and touch, and then add the ability to communicate, and that’s where the Internet of people and the Internet of things intersect.</p><h4><strong>Real-world examples</strong></h4><p>Say you are asleep wearing a smartwatch, that it’s sensing your sleep cycles and it knows the most opportune moment to gracefully wake you up. When that happens, the smartwatch sends a message to other things in your home, and pretty soon a chain of events starts to occur, where your things are talking to other things. Your thermostat goes up to 80 as your house fans start up and draw all the cool morning air into your home. Your coffeemaker starts up and your bedside lamp fades too bright, and your smart speaker plays your favorite music to start the day.</p><p>After a long day at work, when you return home at night the lights in your house dim, and soft instrumental music begins to play to give a cozy feel. The curtains close and the lights go out, and you’re ready to sleep.</p><p>Then, you’re again asleep, or it seems. Turns out the sensors in your smartwatch detect something very wrong, your heart rate is going up, your breathing has become erratic, and instead of gently waking you, it vibrates aggressively to get your attention, and you roll over to reach your phone. There is a message that says you’re having high blood pressure, your breathing is erratic, and it suggests taking two aspirins. All your signs have been recorded and electronically transmitted to your medical provider.</p><p>Back at the hospital, a doctor is already evaluating your data, and in his professional opinion, you need to get to the hospital, so he electronically dispatches EMT directly to your home including pertinent data about your current medical situation. All of a sudden, you’re at the hospital and you’re put under observation. You suffered a heart attack and thanks to the timely reaction the problem did not get worse.</p><p>Another good example is the detection of strong shocks that the apple watch has. If you suffer a fall or have a car accident, and you do not answer the signal of the apple watch, it will call 911 and ask for help, all this on your own, you could be unconscious and the apple watch could save your life, if you would like to see it in action click the following link:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQJ2JiwEARFo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQJ2JiwEARFo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQJ2JiwEARFo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eaa77334b277016b7acb8be402b3265/href">https://medium.com/media/9eaa77334b277016b7acb8be402b3265/href</a></iframe><p>In addition to this example, the IoT can be found everywhere, in recent years it has had a great impact on retail, education, construction, production, and supply chain, among many others.</p><p>There is a lot of information about how IoT impacts each of these sectors and how it is revolutionizing the way we live and work. but one thing is common in all these industries, is that the tools that are used are going from being passive to being generative and increasingly have more power of decision and can do great things without our direction.</p><p>Although not everything is perfect, many companies do not care about computer security and protecting the privacy of their users, and even many companies take advantage of the ignorance of their users to collect large amounts of data and sell it and thus increasing their profits. The line between online privacy and computer security is blurred.</p><p>All changes bring with them great challenges and this is one of the most important that we face. So it is everyone’s task to worry about understanding what our devices do and to demand clear game rules from companies, online privacy must be considered a right.</p><p>Privacy and security are very relevant issues, so much so that I prefer to leave it for a future post…</p><h4>Resources:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaR5N2Jl8k14%3Fstart%3D241%26feature%3Doembed%26start%3D241&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaR5N2Jl8k14&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaR5N2Jl8k14%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24ef9ef301275be1d800434e8dd3b55f/href">https://medium.com/media/24ef9ef301275be1d800434e8dd3b55f/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpGtnC1jKpMg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpGtnC1jKpMg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpGtnC1jKpMg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/58499db4bfb869a8378c0bb85f0b7e58/href">https://medium.com/media/58499db4bfb869a8378c0bb85f0b7e58/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f11db5c3ea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion in C in a Nutshell]]></title>
            <link>https://medium.com/@santiagobedoa/recursion-in-c-in-a-nutshell-1e70e51ab5cf?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e70e51ab5cf</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Fri, 10 Jun 2022 22:03:15 GMT</pubDate>
            <atom:updated>2022-06-10T22:03:15.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*OoYvyOEDIXlzrUTapZ1Sig.jpeg" /></figure><p>If you’re familiar with functions in C programming, then you know that it’s quite common for one function to call another. In Python, it’s also possible for a function to call itself! A function that calls itself is said to be <strong>recursive</strong>, and the technique of employing a recursive function is called <strong>recursion</strong>.</p><p>It may seem peculiar for a function to call itself, but many types of programming problems are best expressed recursively. When you bump up against such a problem, recursion is an indispensable tool for you to have in your toolkit.</p><p>A function that calls itself recursively must have a plan to eventually stop (to avoid an infinite call of itself). Recursive functions typically follow this pattern:</p><ul><li>There are one or more base cases that are directly solvable without the need for further recursion.</li><li>Each recursive call moves the solution progressively closer to a base case.</li></ul><h3>How does it works?</h3><p>It is always good to see how things work with examples and graphically. So let’s take the following code as an example:</p><pre>#include &lt;stdio.h&gt;<br>float _pow_recursion(float x, float y);</pre><pre>int main() {<br>    int x, y, result;</pre><pre>    printf(&quot;Enter a positive integer (x): &quot;);<br>    scanf(&quot;%d&quot;, &amp;x);</pre><pre>    printf(&quot;Enter a positive integer (y): &quot;);<br>    scanf(&quot;%d&quot;, &amp;y);</pre><pre>    result = _pow_recursion(x, y);</pre><pre>    printf(&quot;pow = %d&quot;, result);<br>    return 0;<br>}</pre><pre>float _pow_recursion(float x, float y)<br>{<br>    if (y == 0)<br>    {<br>        return (1);<br>    }</pre><pre>    if (y &lt; 0)<br>    {<br>        return (_pow_recursion(x, y + 1) / x);<br>    }</pre><pre>    return (_pow_recursion(x, y - 1) * x);<br>}</pre><p>The two key elements of this recursive function are the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*KCZWt2f0siku2AseH3tUGA.png" /></figure><p>Let’s see what happens when we execute the compiled file and pass it x = 2 and y = 3 as arguments. Once the _pow_recursion(2, 3) function is called in from the main() function, the following happens:</p><p>To explain what happens graphically, let’s separate the flow of execution into calls and callbacks.</p><h4>Calls</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Z4Gu5IN7LyOO6edOoCF0ug.jpeg" /></figure><p>In this part, it is when the function calls itself with values that are close in each call to the base case. In each call a color was used to differentiate from other calls, and in addition, a check symbol was used to specify which part of the function is the one that is executed.</p><p>brief explanation of each call:</p><ul><li><strong>First call:</strong> x = 2, y = 3. It calls itself but this time y = 2 and goes into a standby time for the return value.</li><li><strong>Second call:</strong> x = 2, y = 2. It calls itself but this time y = 1 and goes into a standby time for the return value.</li><li><strong>Third call:</strong> x = 2, y = 1. It calls itself but this time y = 0 and goes into a standby time for the return value.</li><li><strong>Fourth call:</strong> this is where the base case is reached, since y = 0 and the return value is 1. Note that this time the “standby time” is not reached.</li></ul><h4>Callbacks</h4><p>When the base case is reached, it starts what I call the “callbacks”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0J4gqo_BOGnKP4fsCpLraA.jpeg" /></figure><p>Brief explanation of each callback:</p><ul><li><strong>First callback:</strong> In our function, when the base case is reached, the return value is 1.</li><li><strong>Second callback:</strong> this corresponds to the <strong>third call</strong> that was in “standby time”, waiting for the call to the function _pow_recursion (itself) to return a value. The returned value is 1. Which means that the second callback will return 2 since 1 * 2 = 2.</li><li><strong>Third callback:</strong> this corresponds to the <strong>second call</strong>.<strong> </strong>The returned value will be 4 since 2 * 2 = 4 and this value will be passed to the fourth callback which is waiting to multiply this value two times.</li><li><strong>Fourth callback:</strong> this corresponds to the <strong>first call</strong> of our _pow_recursion(2, 3) function. The value returned by the third callback is 4, finally the operation 4 * 2 is executed. Bang! Now, we have the final result which is 8! (2 ** 3 = 8).</li></ul><h3>But what’s going on the stack?</h3><p>Stack is a LIFO (Last In, First Out) data structure. Since _pow _recursion(2.0, 0.0) is the last one pushed (added) to the stack, it is the first one popped (removed).</p><pre>             STACK<br>___                            ___<br>   | _pow_recursion(2.0, 0.0) |                      FO<br>   |--------------------------|              ||      <br>   | _pow_recursion(2.0, 1.0) |              ||      /\<br>   |--------------------------|             \  /    /  \<br>   | _pow_recursion(2.0, 2.0) |              \/      ||<br>   |--------------------------|                      ||<br>   | _pow_recursion(2.0, 3.0) |              LI<br>   |__________________________|</pre><p>Once we get to the function call where y equals to0.0, the functions will appear one by one. First to go is y=0.0 or _pow_recursion(2.0, 0.0), then y=1.0 and y=2.0. The last to appear is y=3,0: _pow recursion (2.0,3.0).</p><h3>Stack Overflow</h3><p>What happens if we remove the base case or we use a number that will never approach the base case (y == 0)?</p><pre>float _pow_recursion(float x, float y)<br>{<br>    /* note that the base case was removed */<br>    if (y &lt; 0)<br>    {<br>        return (_pow_recursion(x, y + 1) / x);<br>    }</pre><pre>    return (_pow_recursion(x, y - 1) * x);<br>}</pre><p>A segmentation fault will occur! a stack overflow occurs when we use all available storage that has been allocated to stack memory. So, basically, this happens because our function is unable to reach the base case and calls to itself (recursive calls to _pow_recursive(x, y)) will never stop, so the program will run until our stack memory runs out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e70e51ab5cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding classes and instances in Python]]></title>
            <link>https://medium.com/@santiagobedoa/understanding-classes-and-instances-in-python-1e24d94b7412?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e24d94b7412</guid>
            <category><![CDATA[classes-and-objects]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 17:05:49 GMT</pubDate>
            <atom:updated>2022-06-07T17:05:49.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*67WfYGefoq7xF0q-3tR9lQ.jpeg" /><figcaption>source: <a href="https://realpython.com/python3-object-oriented-programming/">https://realpython.com/python3-object-oriented-programming/</a></figcaption></figure><p>If you’re reading this, it’s probably because you’re a developer. We know that computers understand instructions (opcode), we can group a bunch of instructions to create functions that perform more complex activities. However, in real life, things are more complex, and although it is attractive to try to put everything into algorithms, there is another very useful approach, object-oriented programming.</p><blockquote>In a nutshell, object-oriented programming is a programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects.</blockquote><p>For instance, an object could represent a dog with <strong>properties</strong> like a name, age, and breed and <strong>behaviors</strong> such as walking, barking, breathing, and running. Or it could represent a car with properties like a color, type of car, and type of fuel and behaviors like speed up and brake.</p><p>Put another way, object-oriented programming is an approach for modeling concrete, real-world things, like cars, as well as relations between things, like vehicles and gas stations, dogs and veterinarians, and so on. OOP models real-world entities as software objects that have some data associated with them and can perform certain functions.</p><h3>Python Classes</h3><p>Primitive <a href="https://realpython.com/courses/python-data-types/">data structures</a> — like numbers, <a href="https://realpython.com/python-strings/">strings</a>, and lists — are designed to represent simple pieces of information, such as the cost of an apple, the name of a poem, or your favorite colors, respectively. What if you want to represent something more complex?</p><p>If you would like to learn more about object types I recommend you to take a look my <a href="https://medium.com/@santiagobedoa/python-mutable-immutable-everything-is-object-83a4ca0cd802">previous article</a>.</p><p>Let’s say you work in a veterinary and you want to keep track of all the pets that enter the place. You need to store some basic information about each pet, such as their name, age, breed, and the date they entered the place.</p><p>One way to do this is to represent each pet as a list:</p><pre>puppy_1 = [&quot;Eliecer&quot;, 2, &quot;Teckel&quot;, 2022-03-06]<br>puppy_2 = [&quot;Ramon&quot;, 3, &quot;Yorkie&quot;, 2022-03-03]<br>puppy_3 = [&quot;Nube&quot;, 8, 2022-02-27]</pre><p>There are a number of issues with this approach.</p><p>For example, it can introduce errors if not every pet has the same number of elements in the list. In the puppy_3 list above, the breed is missing, so puppy[2] will return the date the dog entered the vet instead of “mongrel” let’s say.</p><p>A great way to make this type of code more manageable and more maintainable is to use <strong>classes</strong>.</p><h3>Classes vs Instances</h3><p>Classes are used to create user-defined data structures. Classes define functions called <strong>methods</strong>, which identify the behaviors and actions that an object created from the class can perform with its data.</p><p>A class is a blueprint for how something should be defined. It doesn’t actually contain any data. The Dog class specifies that a name and an age are necessary for defining a dog, but it doesn’t contain the name or age of any specific dog.</p><p>While the class is the blueprint, an <strong>instance</strong> is an object that is built from a class and contains real data. An instance of the Dog class is not a blueprint anymore. It’s an actual dog with a name, like Miles, who’s four years old.</p><p>Put another way, a class is like a form or questionnaire. An instance is like a form that has been filled out with information. Just like many people can fill out the same form with their own unique information, many instances can be created from a single class.</p><h3>How to Define a Class</h3><p>All class definitions start with the class keyword, which is followed by the name of the class and a colon. Any code that is indented below the class definition is considered part of the class’s body.</p><p>The properties that all Dog objects must have are defined in a method called .__init__(). Every time a new Dog object is created, .__init__() sets the initial <strong>state</strong> of the object by assigning the values of the object’s properties. That is, .__init__() initializes each new instance of the class.</p><p>You can give .__init__() any number of parameters, but the first parameter will always be a variable called self. When a new class instance is created, the instance is automatically passed to the self parameter in .__init__() so that new <strong>attributes</strong> can be defined on the object.</p><p>Putting all this together, the Python code would look like this:</p><pre>class Dog:<br>    def __init__(self, name, age, breed):<br>        self.name = name<br>        self.age = age<br>        self.breed = breed</pre><p>Attributes created in .__init__() are called <strong>instance attributes</strong>. An instance attribute’s value is specific to a particular instance of the class. All Dog objects have a name, an age, and a breed but the values for the name, age, and breed attributes will vary depending on the Dog instance.</p><p>On the other hand, <strong>class attributes</strong> are attributes that have the same value for all class instances. You can define a class attribute by assigning a value to a variable name outside of .__init__().</p><pre>class Dog:<br>    # Class attribute<br>    species = &quot;Canis familiaris&quot;<br><br>    def __init__(self, name, age, breed): <br>        # Instance attributes<br>        self.name = name<br>        self.age = age<br>        self.breed = breed</pre><p>In summary:</p><p>Class attributes are defined directly beneath the first line of the class name, they must always be assigned an initial value. When an instance of the class is created, class attributes are automatically created and assigned to their initial values.</p><p>Use class attributes to define properties that should have the same value for every class instance. Use instance attributes for properties that vary from one instance to another.</p><h3>Class Attributes</h3><p>Let’s see how class attributes work with the following example</p><pre>class Dog:<br>    # Class attribute<br>    species = &quot;Canis familiaris&quot;<br>    <br>    def __init__(self, name, age, breed): <br>        # Instance attributes<br>        self.name = name<br>        self.age = age<br>        self.breed = breed</pre><pre># creating an instances of Dog class<br>&gt;&gt;&gt; puppy_1 = Dog(&quot;Eliecer&quot;, 2, &quot;Teckel&quot;)<br>&gt;&gt;&gt; puppy_1.species<br>&#39;Canis familiaris&#39;<br>&gt;&gt;&gt; puppy_1.name<br>&#39;Eliecer&#39;</pre><pre># let&#39;s create another puppy<br>&gt;&gt;&gt; puppy_2 = Dog(&quot;Ramon&quot;, 3, &quot;Yorkie&quot;)<br>&gt;&gt;&gt; puppy_2.species<br>&#39;Canis familiaris&#39;<br>&gt;&gt;&gt; puppy_2.name<br>&#39;Ramon&#39;</pre><p>With the example above, you can clearly see the differences between class attributes and instance attributes. All dogs belong to canines, so this variable should be a class attribute since it is common to all instances deriving from this class and we don’t need to give it a value when we create a new instance. Rather, each dog has its own name, age, and breed. These variables can vary from dog to dog so they must be attributes of the instance and a value must be provided when creating a new instance.</p><p>You can see the dictionary representation of an instance using __dict__ like this:</p><pre>&gt;&gt;&gt; puppy_1.__dict__<br>{&#39;name&#39;: &#39;Eliecer&#39;, &#39;age&#39;: 2, &#39;breed&#39;: &#39;Teckel&#39;}</pre><pre>&gt;&gt;&gt; puppy_2.__dict__<br>{&#39;name&#39;: &#39;Ramon&#39;, &#39;age&#39;: 3, &#39;breed&#39;: &#39;Yorkie&#39;}</pre><h3>The Pythonic Way to Create a Class</h3><p>Let’s say your application has a restless user and does the following:</p><pre>&gt;&gt;&gt; puppy_2.age = &quot;hello&quot;<br>&gt;&gt;&gt; puppy_2.age<br>&#39;hello&#39;<br>&gt;&gt;&gt; puppy_2.__dict__<br>{&#39;name&#39;: &#39;Ramon&#39;, &#39;age&#39;: &#39;hello&#39;, &#39;breed&#39;: &#39;Yorkie&#39;}</pre><p>What! clearly, this cannot happen, since age must be a positive integer greater than zero, and it is okay for the owner to want to change the name of his puppy, but age and breed are things that should remain static and must comply with certain requirements.</p><p>Fortunately, Python provides us with the right method decorators to create setter and getter methods. The @property decorator defines the getter and the @attribute_name.setter defines the setter. So, let’s fix our code:</p><pre>class Dog:<br>    # Class attribute<br>    species = &quot;Canis familiaris&quot;<br>    <br>    def __init__(self, name=&quot;&quot;, age=0, breed=&quot;&quot;): <br>        # Instance attributes<br>        self.name = name<br>        self.age = age<br>        self.breed = breed<br>    <br>    @property<br>    def name(self):<br>        return self.__name<br>    <br>    @name.setter<br>    def name(self, value):<br>        if type(value) is not str:<br>            raise TypeError(&quot;Name must be a string&quot;)<br>        self.__name = value<br>    <br>    @property<br>    def age(self):<br>        return self.__age<br>    <br>    @age.setter<br>    def age(self, value):<br>        if type(value) is not int:<br>            raise TypeError(&quot;Age must be an integer greater than 0&quot;)<br>        self.__age = value<br>    <br>    @property<br>    def breed(self):<br>        return self.__breed<br>    <br>    @age.setter<br>    def breed(self, value):<br>        if str(value) not in list_dog_breeds:<br>            raise TypeError(&quot;Please enter a valid breed&quot;)<br>        self.__breed = value</pre><p>Now, if the user tries:</p><pre>&gt;&gt;&gt; puppy_4 = Dog(&quot;Sugar&quot;, &quot;hello&quot;, &quot;Border Collie&quot;)<br>TypeError: Age must be an integer greater than 0<br>&gt;&gt;&gt; puppy_4 = Dog(&quot;Sugar&quot;, 5, &quot;Border Collie&quot;)<br>&gt;&gt;&gt; puppy_4.__dict__<br>{&#39;_Dog__name&#39;: &#39;Sugar&#39;, &#39;_Dog__age&#39;: 5, &#39;_Dog__breed&#39;: &#39;Border Collie&#39;}<br>&gt;&gt;&gt; puppy_4.age = &quot;hello&quot;<br>TypeError: Age must be an integer greater than 0</pre><p>Note that instance attributes tend to be defined in the initializer method, __init__. This is so that they are defined at object instantiation and do not need to be checked for in the property getter.</p><p>By using the double underscores, __attribute_name becomes a private attribute. It cannot be accessed directly from outside the object context. This is in line with the OOP principle of data hiding. It is to prevent bad coupling of code logic which makes maintaining the code a task in futility.</p><p>Note that the property cannot be accessed directly, since it is private. Defining class and instance attributes in the Pythonic way is simultaneously good OOP design. Please enjoy reaping the benefits from these good design patterns in your own software architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e24d94b7412" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Mutable, Immutable… everything is object!]]></title>
            <link>https://medium.com/@santiagobedoa/python-mutable-immutable-everything-is-object-83a4ca0cd802?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/83a4ca0cd802</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[classes-and-objects]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Thu, 02 Jun 2022 02:55:09 GMT</pubDate>
            <atom:updated>2022-06-02T02:55:09.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3X-ICrEwomwX5Rx9eUkNg.jpeg" /><figcaption>source: <a href="https://files.realpython.com/media/Python-Metaclasses_Watermarked.67e351592b05.jpg">Python-Metaclasses_Watermarked.67e351592b05.jpg</a></figcaption></figure><p>Python is a high-level, interpreted, general-purpose programming language commonly used for developing websites and software, task automation, data analysis, data visualization, and recently machine learning. If you are new to python, you have probably designed programs around functions, i.e. blocks of statements that manipulate data. this is called the <em>procedure-oriented</em> way of programming. There is another way of organizing your program in python which is to combine data and functionality and wrap it inside something called an object. This is called the <em>object-oriented programming</em> paradigm (OOP).</p><p>Even if you are new to programming in Python, you have worked with classes all the time. In fact, everything is a class in Python. Guido van Rossum has designed the language according to the principle of <em>“first-class everything”</em>. He wrote: <em>“One of my goals for Python was to make it so that all objects were “first-class.” By this, I meant that I wanted all objects that could be named in the language (e.g., integers, strings, functions, classes, modules, methods, and so on) to have equal status. That is, they can be assigned to variables, placed in lists, stored in dictionaries, passed as arguments, and so forth.”</em> (Blog, The History of Python, February 27, 2009).</p><p>In other words, “everything” is treated the same way, everything is a class: functions and methods are values just like lists, integers, or floats. Each of these are instances of their corresponding classes.</p><pre>&gt;&gt;&gt; x = 42<br>&gt;&gt;&gt; type(x)<br>&lt;class &#39;int&#39;&gt;</pre><pre>&gt;&gt;&gt; y = 6.42<br>&gt;&gt;&gt; type(y)<br>&lt;class &#39;float&#39;&gt;</pre><pre>&gt;&gt;&gt; def f(x):<br>...    return x + 1<br>...<br>&gt;&gt;&gt; type(f)<br>&lt;class &#39;function&#39;&gt;</pre><pre>&gt;&gt;&gt; import numpy<br>&gt;&gt;&gt; type(numpy)<br>&lt;class &#39;module&#39;&gt;</pre><p>Objects are called instances of classes. And, all these objects come in two grand types, <em>mutable </em>and <em>immutable. </em>Instances of primitive built-in values such as numbers are <em>immutable</em>. The values themselves cannot change over the course of program execution. Lists on the other hand are <em>mutable</em>. Mutable objects are used to represent values that change over time.</p><p>A person is the same person from one day to the next, despite having aged, received a haircut, or otherwise changed in some way. Similarly, an object may have changing properties due to <em>mutating </em>operations. For example, it is possible to change the contents of a list. Most changes are performed by invoking methods on list objects.</p><p><strong>The id() function</strong></p><p>Before continuing, we should be clear about some Pythonic objects. First, we will use the built-in id() function. Takes any object as an argument and returns the object’s numeric id, which corresponds to the actual memory address of the object. Thus, the id is unique for each object instance loaded into memory and can be used to determine whether two variables refer to an identical object. Let’s try some examples:</p><pre>&gt;&gt;&gt; str_1 = &quot;Hello&quot;<br>&gt;&gt;&gt; id(str_1)<br>4341497392</pre><pre>&gt;&gt;&gt; str_2 = &quot;World&quot;<br>&gt;&gt;&gt; id(str_2)<br>4341497712</pre><p><strong>The type() function</strong></p><p>type() method returns class type of the argument(object) passed as parameter. take a look at the first few examples again to see the implementation.</p><h3>Mutable vs Immutable</h3><p>As we mentioned before, in Python there are two types of objects:</p><h4>Immutable</h4><p>These correspond to the more primitive/fundamental types. The most common are: integers, float, complex, strings, tuples, and booleans. We can quickly check whether an object belongs to the group of immutables by assigning a value to some variable and then trying to += to itself as follows:</p><pre>&gt;&gt;&gt; variable = &quot;Value&quot;<br>&gt;&gt;&gt; id(variable)<br>4338191792<br>&gt;&gt;&gt; variable += variable<br>&gt;&gt;&gt; variable<br>&#39;ValueValue&#39;<br>&gt;&gt;&gt; id(variable)<br>4341510320</pre><p>Even though we use the <em>compound assignment operator</em> += which is supposed to assign in place, our variable <em>id</em> has changed. This is because we have effectively assigned the string <em>“Value”</em> to it. And since strings are immutable (which means that the variable can’t be modified), we have created a completely new variable that holds <em>“ValueValue”</em>. It must be a completely new instance of the String class, with a unique <em>id</em>. Let’s see the same thing with an integer, where it might be more surprising:</p><pre>&gt;&gt;&gt; id(variable)<br>4341510320<br>&gt;&gt;&gt; integer = 5<br>&gt;&gt;&gt; id(integer)<br>4338002352<br>&gt;&gt;&gt; integer += integer<br>&gt;&gt;&gt; integer<br>10<br>&gt;&gt;&gt; id(integer)<br>4338002512</pre><p>Again, you can see how a new instance has been created because we can see that the <em>id</em> of the variable has changed. Now that we know how immutable objects work, let’s review this last example:</p><pre>&gt;&gt;&gt; a = 1<br>&gt;&gt;&gt; b = a<br>&gt;&gt;&gt; a = 2<br>&gt;&gt;&gt; b<br>1</pre><p>We are not surprised by this output, right?</p><p>When declaring and assigning the value to the variable “a”, a space in memory is allocated to store this information. When we declare the variable “b” and assign it to the variable “a”. “b” is pointing to the same memory space as “a”, this is done by Python to optimize memory.</p><pre>&gt;&gt;&gt; a = 1<br>&gt;&gt;&gt; id(a)<br>4338002224<br>&gt;&gt;&gt; b = a<br>&gt;&gt;&gt; b<br>1<br>&gt;&gt;&gt; id(b)<br>4338002224</pre><p>But when we assign another value to “a”, since it is an immutable object, another instance is created and “b” continues to point to the memory address it had initially, this is the reason why “b” does not change its value.</p><pre>&gt;&gt;&gt; a = 2<br>&gt;&gt;&gt; id(a)<br>4338002256<br>&gt;&gt;&gt; id(b)<br>4338002224</pre><h4>Mutable</h4><p>Ok. But what about this?</p><pre>&gt;&gt;&gt; l = [1, 2, 3]<br>&gt;&gt;&gt; m = l<br>&gt;&gt;&gt; l[0] = &#39;x&#39;<br>&gt;&gt;&gt; m<br>[&#39;x&#39;, 2, 3]</pre><p>What! It was not expected, right? let’s see what happened</p><pre>&gt;&gt;&gt; l = [1, 2, 3]<br>&gt;&gt;&gt; id(l)<br>4341469824<br>&gt;&gt;&gt; m = l<br>&gt;&gt;&gt; id(m)<br>4341469824<br>&gt;&gt;&gt; l[0] = &#39;x&#39;<br>&gt;&gt;&gt; m<br>[&#39;x&#39;, 2, 3]<br>&gt;&gt;&gt; id(l)<br>4341469824<br>&gt;&gt;&gt; id(m)<br>4341469824</pre><p>As we can see, the objects remain pointing to the same memory address even though we change one of their values. So as you might be imagining, this is an example of mutable objects. Mutable objects can change their state or content during the run time, unlike immutable objects, which lack these properties and therefore cannot be modified. Whereas immutable types correspond to the more primitive objects, mutable types are more dynamic structures like list, dictionaries, set, or custom classes.</p><h4>Equality vs Identity</h4><p>In Python, there is a big difference between objects that are the same and objects that are identical. Two objects, or rather two variables, are said to refer to the same objects if their values are the same. This can be tested using the == operator:</p><pre>&gt;&gt;&gt; a = 10<br>&gt;&gt;&gt; b = 10<br>&gt;&gt;&gt; a == b<br>True</pre><pre>&gt;&gt;&gt; str_1 = &quot;Hello&quot;<br>&gt;&gt;&gt; str_2 = &quot;World&quot;<br>&gt;&gt;&gt; str_1 == str_2<br>False</pre><p>Two objects, or rather two variables, are said to refer to identical objects if their id()s are the same. That is, the variables refer to the same memory address (literally the same object):</p><pre>&gt;&gt;&gt; a = 10<br>&gt;&gt;&gt; b = 10<br>&gt;&gt;&gt; a is b<br>True<br>&gt;&gt;&gt; id(a)<br>4338002512<br>&gt;&gt;&gt; id(b)<br>4338002512</pre><pre>&gt;&gt;&gt; str_1 = &quot;Hello&quot;<br>&gt;&gt;&gt; str_2 = str_1<br>&gt;&gt;&gt; str_1 is str_2<br>True<br>&gt;&gt;&gt; id(str_2)<br>4341497392<br>&gt;&gt;&gt; id(str_1)<br>4341497392<br>&gt;&gt;&gt; str_2<br>&#39;Hello&#39;</pre><h4>Big Parenthesis</h4><p>Let’s see this:</p><pre>&gt;&gt;&gt; a = [1, 2]<br>&gt;&gt;&gt; b = [1, 2]<br>&gt;&gt;&gt; a is b<br>False</pre><pre>&gt;&gt;&gt; a = 1<br>&gt;&gt;&gt; b = 1<br>&gt;&gt;&gt; a is b<br>True</pre><pre>&gt;&gt;&gt; a = 257<br>&gt;&gt;&gt; b = 257<br>&gt;&gt;&gt; a is b<br>False</pre><p>You must be struggling with this, it doesn’t have any logic. This is the result of how different objects are stored according to the Python Data Model. Python memory management comprises a private heap that stores all Python objects and data structures. The Python memory manager is responsible for the maintenance of this private heap. Python’s memory manager is made up of many components that handle various elements of dynamic memory management, such as B. sharing, segmenting, preallocating, and caching.</p><h3>Aliases and Python Data Model</h3><p>Python does some very strange things with the way it stores its data in order to optimize space and time. One is that all strings that are equal are also identical. There are no two copies of the same string. Just different aliases of the same string. Aliases refer to two different variable names, or identifiers, which reference the same identical object. Any time one variable is assigned to another it becomes directly aliased. They can also be indirect aliases if they happen to refer to the same object:</p><pre>&gt;&gt;&gt; a = [1, 2, 3]<br>&gt;&gt;&gt; b = a<br>&gt;&gt;&gt; b is a<br>True        # b is an alias of a</pre><pre>&gt;&gt;&gt; a = -5<br>&gt;&gt;&gt; b = -5<br>&gt;&gt;&gt; b is a<br>True        # b is an alias of a</pre><p>As it so happens, the integers from -5 to 256 (NSMALLNEGINTS to NSMALLPOSINTS) are all pre-allocated and any references to them are aliases. This is because they are the most commonly used integers and it makes sense to keep them “cached.” When integers outside this range are assigned they are loaded and destroyed as needed, although one copy of each newly assigned integer object will be retained in memory in case it is used again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83a4ca0cd802" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Libraries in a nutshell]]></title>
            <link>https://medium.com/@santiagobedoa/dynamic-libraries-in-a-nutshell-467e3d5dc6ab?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/467e3d5dc6ab</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[dynamic-library]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Tue, 17 May 2022 02:13:33 GMT</pubDate>
            <atom:updated>2022-05-17T02:14:17.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENH7xyui8hQbX_PsJ9DjNg.jpeg" /></figure><p>If you use C or C++, you must understand Static and Shared (Dynamic) Libraries and their main differences. If you code in any other language you can probably get by without really understanding how these things work but it’s still really good to have a basic feel of what it means.</p><h3>Why use libraries?</h3><p>Understanding how your applications use libraries is really core to how everything runs, and how pretty much how your computer operates. While you are reading this article, there is a lot running on inside your computer, you might have Safari or Chrome open up, that’s a process, and you have other os-level processes that are running.</p><p>Many of these processes share and utilize very similar routines. Let’s just pick a routine that’s really simple or a piece of code that’s highly used, for example, print something on the standard output. So, if almost every program needs to utilize printing something to the screen, do you think every single developer writes their own version of the print function? Actually, every developer could write their own version of printf but it wouldn’t really be a good use of their time.</p><p>Since many applications require similar functions to work, it would be nice to have a package where all these functions could be brought together. This is what we call a library.</p><h3>What is a library?</h3><p>Library itself is just a file persisted on your computer and consists of ones and zeros like every other file. The major separating factor that we have to understand the difference between a library and every other application, is that you can’t execute a library. If you open up the task manager there are no “libraries” that are running, everything that’s currently running is a process, those are applications. So, applications can be executed and they utilize libraries.</p><h3>How do libraries work?</h3><p>Now that we have a good idea of why we need libraries, let’s dig into how libraries work.</p><h4>Shared Libraries</h4><p>If our application utilizes a shared library, our application is going to reference that library exactly when it needs to reference that library when it is running. Let’s take an example of this.</p><p>When our application needs to print something to the screen it’s going to reference another shared library on the computer that knows how to print something to the standard output and let that handle it and none of that code that’s doing the printing actually lives in our application, it lives in that shared library. All we have to do is reference that library when we need to print something.</p><p>One major contingency for using the shared library well in order for our application to run, we need two things: we need to pass somebody the application itself and giving to them the shared library because both of them have to work together. It means that the shared library has to be available because if we don’t have that around we’re not going to know what to reference which means for our example how to print something.</p><h4>Static Libraries</h4><p>Static libraries are almost the complete opposite of shared libraries. First, we need to understand that our program is going to utilize static libraries at compile-time and remember that compile-time is before run time. We take exactly what we need from the static library and we literally copy all the code we need and move it into our application. We take that library that knows how to print, we take the function and the code that we need and we move that into our application.</p><p>if you want to dive into a little more about static libraries you can take a look at my article <a href="https://medium.com/@santiagobedoa/static-libraries-in-a-nutshell-e1ac45a08750"><strong>Static Libraries in a nutshell</strong></a>.</p><h4>The major difference between Shared and Static</h4><p>In a shared library, the program references the library when it runs, so for the program to work you have to have the library and the application at the same time or nothing is going to work. For the static library, we did a copy of the exact code we need and moved it into our application (the finally binary), so after we did the copy and pasting we don’t need the library anymore, we just can get rid of it.</p><p>One more difference is in the size of the final application. Imagine that your application depends on 100 static libraries at compile time you’re literally copying and pasting code from 100 libraries into your application, this can make your app get really big fast. The major pro with the shared libraries is since you don’t do this all you do is reference libraries when you need them and it keeps your application really small but you need to be able to reference those libraries to run your program.</p><h3>How to create a Dynamic Library in Linux</h3><p>For this example, we are going to work in the dynamic_libraries directory which contains the following files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*mpqMXCSG6-H3V5Gs14sXtQ.png" /></figure><p>First, we should generate position-independent code (PIC) suitable for use in a shared library. Simply type gcc *.c -c -fPIC. This command generates one object file .o for each .c. This means it wouldn’t matter where the computer loads the code into memory. Some operating systems and processors need to build libraries from position-independent code so that they can decide at runtime where they want to load it into memory. The -c options just ensure that each .o the file isn’t linked yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*NTApGcDFkwxwHJLrbnw_fA.png" /></figure><p>Then, type in the following command: gcc *.o -shared -o libdynamic.so (replace the dynamic part with whatever library name you want). The wildcard * tells the compiler to compile all the .o files into a dynamic library that is specified by the -shared flag. The naming convention for dynamic libraries is such that each shared library name must start with lib and end with .so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*vz9fk6WCiFhvFm-VEUYt-A.png" /></figure><p>Finally, we will need to export the path of the libraries so that programs know where to look for them by running the following command: export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH</p><h3>How to use a Dynamic Library in Linux</h3><p>The point of creating a dynamic library is to use it with other programs. So we need to compile our program:</p><p>gcc -Wall -pedantic -Werror -Wextra -L. main.c -ldynamic -o hello</p><p>The expression, -l combined with dynamic tells the compiler to look for a dynamic library called libdynamic.so, while -L flag tells the compiler to look in the current directory for the library file. Finally, the flag -o will generate an executable named hello. All in one shot will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*gO0aySvivV49kSeMvKyiGw.png" /></figure><p>In case you are wondering, the main.c file contains the following code:</p><pre>#include &quot;main.h&quot;</pre><pre>int main(void)<br>{<br>      _puts(&quot;Hello World!&quot;);<br>      return (0);<br>}</pre><p>As you can see, inside the main function a call is made to _puts:</p><pre>#include &quot;main.h&quot;</pre><pre>/**<br> * _puts - prints a str followed by a new line to stdout<br> * <a href="http://twitter.com/str">@str</a>: str to be printed<br> * Return: void<br> */</pre><pre>void _puts(char *s)<br>{<br>        int i;</pre><pre>        for (i = 0; s[i] != &#39;\0&#39;; i++)<br>        {<br>                _putchar(s[i]);<br>        }<br>        _putchar(&#39;\n&#39;);<br>}</pre><p>And finally, the function _putchar is called:</p><pre>#include &quot;main.h&quot;</pre><pre>/**<br> * _putchar - writes the character c to stdout<br> * <a href="http://twitter.com/c">@c</a>: The character to print<br> * Return: On success 1.<br> */</pre><pre>int _putchar(char c)<br>{<br>        return (write(1, &amp;c, 1));<br>}</pre><p>Outside of the files listed above, no other .c file are needed for the executable. They were simply included to simulate a larger project.</p><h3>Conclusion</h3><p>When you have tons of dependencies, static libraries are a little convenient because all of those dependencies are already compiled into your program at the compiled time. So when you give your program to somebody you just say here you go, here’s the app and that’s all you need to run it. On the other hand, if your application utilizes shared libraries, you’re going to have to be like hey, here’s my program and you have to install these libraries to use it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467e3d5dc6ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unix command-line interpreter under the hood]]></title>
            <link>https://medium.com/@santiagobedoa/unix-command-line-interpreter-under-the-hood-653202ca1df8?source=rss-30d1fd7806fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/653202ca1df8</guid>
            <category><![CDATA[unix]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Santiago]]></dc:creator>
            <pubDate>Wed, 20 Apr 2022 20:57:12 GMT</pubDate>
            <atom:updated>2022-04-20T20:57:12.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUVPU2ULf6gQURl4zC8dcw.png" /></figure><p>If you type echo &quot;hello, World!&quot;on your terminal you will get the same output of the image above. This can be quite obvious and simple, because as a programmer we have a close relationship with the terminal and surely we execute much more advanced commands than these, including long bash scripts. But have you ever wondered how all this works under the hood?</p><h3><strong>What is a Shell?</strong></h3><p>Before diving into the process, we should understand what is a shell. So answering this question, a Shell is a program that takes the command inputs written from the user’s keyboard and passes them to the machine to execute them through the kernel. It also verifies if the command inputs from the user are correct.</p><h4><strong>Terminals, kernels, and shells…</strong></h4><p>It is worth clarifying that the kernel, the terminal, and the shell are different things.</p><p>Here is an overview to understand the differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*j0XhHfWqAH6sj9cDq-bOTQ.png" /><figcaption>One thing I want to clarify in the above image is that each box is <strong><em>within</em></strong> the parent box. So for example, The “Program: terminal” is interacting with a contained shell, while the shell then spawns either a “Built-in” or “Program”. source: <a href="https://www.integralist.co.uk/posts/terminal-shell/">https://www.integralist.co.uk/posts/terminal-shell/</a></figcaption></figure><p><strong>Main differences and important concepts:</strong></p><ul><li><strong>Kernel: </strong>a computer has a kernel, the kernel is responsible for managing the computer’s system, the kernel has no user interface, to interact with the kernel you use an intermediary “program”.</li><li><strong>Program: </strong>a “program” is a structured collection of instructions (machine code) that a computer can execute. Your computer has many programs. One such example would be the ‘terminal emulator’ program.</li><li><strong>Executables: </strong>executables (or executable binaries’) are programs. More specifically, an ‘executable’ is a file that <strong><em>contains</em></strong> a program, generally the <strong><em>result</em></strong> of a program being turned into something that can be ‘executed’ by the computer.</li><li><strong>Terminal: </strong>a terminal<strong> </strong>is an input/output device. Traditionally they would have been a <strong><em>real</em></strong> ‘hardware’ device that you used to interact with a computer. e.g. the computer would be a large box in a server room, and the terminal would be a monitor/keyboard connected to the computer. In modern computing, we have a ‘terminal emulator’. If you don’t want to use a GUI (graphical user interface) to interact with your computer, you can use a terminal emulator.</li><li><strong>Shell: </strong>a shell is a program that is accessed <strong><em>via</em></strong> a terminal emulator. The terminal accepts input, passes it to the shell, and the shell’s output is sent back to the terminal to be displayed. The shell accepts input as a set of commands.</li></ul><p><em>If you want to read more about this here I leave you a good resource: </em><a href="https://www.integralist.co.uk/posts/terminal-shell/">https://www.integralist.co.uk/posts/terminal-shell/</a></p><h3>What happens when you type `ls -l *.c` in the shell</h3><p>Since we understand that it is a shell, it can receive a variety of commands to perform a task, one of those is ls -l *.c. If you have a little experience working with shell commands you know what will be the result, if you don’t know don’t worry here is the answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMmoiTzk6rBGPK6frbhvMw.png" /><figcaption>ls -l *.c</figcaption></figure><p>Let’s break this into small parts, first let’s start by reviewing the ls<strong> </strong>command. ls list information about the files in the current working directory, so if we type ls the output will be like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lv1bPD5v237yrEG5SK4lg.png" /><figcaption>ls</figcaption></figure><p>-l is a flag of ls command which means the files will be listed in long format:</p><pre><strong>-rw-------   1 me       me            576 Apr 17  2019 weather.txt<br>drwxr-xr-x   6 me       me           1024 Oct  9  2019 web_page<br>-rw-rw-r--   1 me       me         276480 Feb 11 20:41 web_site.tar<br>-rw-------   1 me       me           5743 Dec 16  2018 xmas_file.txt<br><br>----------     -------  -------  -------- ------------ -------------<br>    |             |        |         |         |             |<br>    |             |        |         |         |         File Name<br>    |             |        |         |         |<br>    |             |        |         |         +---Modification Time<br>    |             |        |         |<br>    |             |        |         +-------------  Size (in bytes)<br>    |             |        |<br>    |             |        +-----------------------       Group<br>    |             |<br>    |             +--------------------------------       Owner<br>    |<br>    +---------------------------------------------- File Permissions</strong></pre><p>So if we type ls -l the output will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vB3XbbSxAqFOWqWe1zqag.png" /><figcaption>ls -l</figcaption></figure><p>Lastly *.c is a wildcard and it is used to match any character or set of characters. So putting all this together ls -l *.c will list all the files ending in .c in long format.</p><h4>What happened under the hood?</h4><p>A shell, in a very simple way, is RPEL (Read, Parse, Execute, and Loop) process. The lifetime of a shell is summed up in a loop, which receives commands from the standard input, the shell <strong>Read</strong> a command line, <strong>Parses</strong> (tokenizes) the command, <strong>Execute</strong> the command with the corresponding flags and options, and finally, the shell waits for the user type a new command to repeat the process (<strong>Loop</strong>).</p><p><strong>Let’s look at this in a little more detail</strong></p><p>As we said before, the life time of a shell is summed up in a loop. When the shell enters the loop, the following things happen:</p><ol><li><strong>Print the Prompt: </strong>the first shell task may seem a bit obvious and that is because it is about printing the prompt. A <strong>prompt</strong> is text or symbols used to represent the system’s readiness to perform the next command. A <strong>prompt</strong> may also be a text representation of where the user is currently. The prompt is found behind the cursor and is highly customizable.</li><li><strong>Read line:</strong> once the prompt is printed and the user types a command, the shell must read the entire line from the stdin and store it in a buffer. A function that is commonly used is getline() which read a line from the stream and returns a pointer.</li><li><strong>Parse line:</strong> now that the shell has the entire line, it must separate the line into multiple elements, the reason for this is because the first element of the line refers to the command, and the following elements refer to the options and arguments. strtok() is a function that split a string into multiple tokens, it divides the initial string according to the specified delimiter. So the shell could use strtok() to split the entire command line into multiple elements.</li><li><strong>Execute arguments:</strong> we already have the command and its options and arguments. But before executing the command, we must take into account that most of the commands that a shell executes are programs, but not all of them, some commands live in the shell itself, they are called built-ins. This means there are two types of commands: built-in and non-built-in.</li><li><strong>Built-in commands:</strong> built-ins are the functions that live inside the shell itself, they are implemented within the shell code. So first the shell must check if the input command corresponds to a built-in, if so, the shell would make the call as if it were another function.</li><li><strong>Non-built-in commands:</strong> if the command is not built-in, the shell must create another process in which the executable file has to be found on the system and executed along with its options and arguments. fork() function can be used to create a new child process that runs in parallel with the parent process. Inside the child process, we use execvp() to execute the program that matches the command.</li><li><strong>Output:</strong> the output will be displayed in the terminal (suppose we are using the shell in interactive mode).</li></ol><p>So far, we have seen the <strong>RPE</strong> process, to complete the missing piece, the above steps will be repeated until the shell reaches the End Of the File (EOF) or the user exits the shell. Now we have completed the whole <strong>RPEL</strong> process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653202ca1df8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>