<?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 SLEEPS on Medium]]></title>
        <description><![CDATA[Stories by SLEEPS on Medium]]></description>
        <link>https://medium.com/@mohcin.ghalmi?source=rss-3c9f7f4b3a26------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SHxQGCcvbHKYMW-ZLPEzZA.jpeg</url>
            <title>Stories by SLEEPS on Medium</title>
            <link>https://medium.com/@mohcin.ghalmi?source=rss-3c9f7f4b3a26------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:29:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohcin.ghalmi/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[Solving the N-Queens Problem in C++]]></title>
            <link>https://medium.com/@mohcin.ghalmi/solving-the-n-queens-problem-in-c-5a594e70edea?source=rss-3c9f7f4b3a26------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a594e70edea</guid>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[SLEEPS]]></dc:creator>
            <pubDate>Wed, 21 May 2025 15:40:46 GMT</pubDate>
            <atom:updated>2025-05-21T15:40:46.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/722/0*HMqsHGBPQZVR0gJ2.jpg" /></figure><p>The <strong>N-Queens problem</strong> is a classic backtracking challenge: Place N queens on an N x N chessboard such that <strong>no two queens attack each other</strong>. Queens can move horizontally, vertically, and diagonally so yeah, this ain&#39;t checkers.</p><h3>Problem Breakdown</h3><p>The challenge is to place the queens such that:</p><ul><li>No two queens share the same <strong>row</strong></li><li>No two queens share the same <strong>column</strong></li><li>No two queens share the same <strong>diagonal</strong></li></ul><p>Each row has exactly one queen, and no two threaten each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*6M7xPkX2u32Py_x2.png" /></figure><h3>Algorithm Approach</h3><p>We’re going full <strong>backtracking</strong> mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*NVSgPBLz2kQramJ6RuB_SA.png" /></figure><ol><li>Place a queen row by row.</li><li>For each cell in the current row, check if it’s safe to drop a queen.</li><li>If safe, place the queen and recurse for the next row.</li><li>If a placement leads to no solution, backtrack (remove the queen) and try the next cell.</li></ol><p>Repeat this till you hit the bottom of the board. When a queen is safely placed in every row, you’ve found a valid solution.</p><h3>C++ Implementation</h3><pre>bool checkSafe(vector&lt;vector&lt;string&gt;&gt; &amp;vec, int posx, int posy) {<br>    int i, j;<br>    <br>    // Check column<br>    for (i = 0; i &lt; posx; i++) <br>        if (vec[i][posy] == &quot;Q&quot;)<br>            return false;<br><br>    // Check top-left diagonal<br>    for (i = posx - 1, j = posy - 1; i &gt;= 0 &amp;&amp; j &gt;= 0 ; i--, j--)<br>        if (vec[i][j] == &quot;Q&quot;)<br>            return false;<br><br>    // Check top-right diagonal<br>    for (i = posx - 1, j = posy + 1; j &lt; vec.size() &amp;&amp; i &gt;= 0; i--, j++)<br>        if (vec[i][j] == &quot;Q&quot;)<br>            return false;<br><br>    return true;<br>}</pre><p>This checkSafe() function isn&#39;t being used right now, but it can be swapped into the main logic for readability.</p><h4>The Recursive Solver</h4><pre>void QueenPlace(int r, vector&lt;string&gt;&amp; board, vector&lt;vector&lt;string&gt;&gt;&amp; res) {<br>    int n = board.size();<br>    if (r == n) {<br>        res.push_back(board);<br>        return;<br>    }<br>    for (int i = 0; i &lt; n; i++) {<br>        bool safe = true;<br>        for (int j = 0; j &lt; r; j++) {<br>            int q_col = board[j].find(&#39;Q&#39;);<br>            if (q_col == i || abs(q_col - i) == abs(j - r)) {<br>                safe = false;<br>                break;<br>            }<br>        }<br>        if (safe) {<br>            board[r][i] = &#39;Q&#39;;<br>            QueenPlace(r + 1, board, res);<br>            board[r][i] = &#39;.&#39;;<br>        }<br>    }<br>}</pre><h4>Entry Point</h4><pre>vector&lt;vector&lt;string&gt;&gt; solveNQueens(int n) {<br>    vector&lt;string&gt; board(n, string(n, &#39;.&#39;));<br>    vector&lt;vector&lt;string&gt;&gt; res;<br>    QueenPlace(0, board, res);<br>    return res;<br>}</pre><h3>Final Thoughts</h3><p>N-Queens is a gateway drug to backtracking. It’s a mix of logic, recursion, and spatial reasoning. If you’re grinding for interviews or building muscle for constraint-solving problems, mastering this is a must.</p><p>Drop a comment if you think this can be optimized further (spoiler: it can with hashing), or hit me up if you’ve got a funky N-Queens variant you’re playing with.</p><h3>Resources</h3><p><a href="https://github.com/Mohcine-Ghalmi/LEET_CODE/tree/master/51.%20N-Queens">CODE</a> || <a href="https://leetcode.com/problems/n-queens/description/">PROBLEM</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a594e70edea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IRC(Internet Relay Chat)SERVER]]></title>
            <link>https://medium.com/@mohcin.ghalmi/irc-server-internet-relay-chat-bd08e4f469f8?source=rss-3c9f7f4b3a26------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd08e4f469f8</guid>
            <dc:creator><![CDATA[SLEEPS]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 13:39:44 GMT</pubDate>
            <atom:updated>2024-12-29T14:16:56.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*q3oP74xPQE7gokc_" /></figure><p>IRC (Internet Relay Chat) is one of the earliest forms of online communication, enabling real-time text-based interactions between users in chat rooms or private messages. In this blog, we’ll guide you through creating your custom IRC server in C++ and connecting to it with an IRC client like irssi.</p><p>This project was developed as part of a team effort:</p><ul><li><a href="https://github.com/Mohcine-Ghalmi/"><strong>Mohcine Ghalmi</strong></a><strong> (</strong><a href="https://medium.com/@mohcin.ghalmi"><strong>medium</strong></a><strong>)</strong>: Focused on server implementation and client communication.</li><li><a href="https://github.com/Mohamedsarda"><strong>Mohamed Sarda</strong></a><strong> (</strong><a href="https://medium.com/@mohamedsarda2001/ft-irc-channels-and-command-management-ff1ff3758a0b"><strong>medium</strong></a><strong>)</strong>: Specialized in implementing and managing IRC channels.</li></ul><p>github project page <a href="https://github.com/Mohcine-Ghalmi/ft_irc"><strong>IRC</strong></a></p><h3>Understanding IRC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*Q5WjRFYDBF1P3tk_" /></figure><p>IRC is a protocol defined in RFC 1459. Here’s a breakdown of its core components:</p><ul><li><strong>Server</strong>: The backbone of IRC, handling client connections, managing channels, and relaying messages.</li><li><strong>Clients</strong>: Users connect to the server using IRC client software (e.g., irssi).</li><li><strong>Channels</strong>: Public or private chat rooms where users can communicate.</li><li><strong>Commands</strong>: Text-based instructions like /join, /msg, and /nick.</li></ul><h3>Building the Server</h3><p>To create a server we need to use socket programming.</p><h4><strong>What is Socket Programming:</strong></h4><p>A socket is an endpoint for communication between two machines over a network. In network programming, a socket allows you to establish a connection between a client and a server, enabling them to send and receive data. Sockets provide the interface for both network communication protocols (such as TCP and UDP) and local interprocess communication (IPC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*glkJwKD2V-4P63I-" /></figure><h4><strong>Basic steps for creating a socket:</strong></h4><ol><li>Create a socket with <strong>socket().</strong></li><li>Bind the socket to an address and port using <strong>bind()</strong>.</li><li>Listen for incoming connections with <strong>listen()</strong>.</li><li>Accept connections with <strong>accept()</strong>.</li><li>Use <strong>send()</strong> and r<strong>ecv() </strong>to communicate with clients.</li></ol><h3><strong>Create a Socket:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*8TSoftz4HLTqLNSv.png" /></figure><p>In C++, the socket is created using the <strong>socket()</strong> system call. It returns a <strong>file descriptor</strong> (an integer) that represents the socket. The <strong>socket() </strong>function takes three arguments:</p><pre>int socket(int domain, int type, int protocol);</pre><ul><li><strong>sockfd:</strong> The file descriptor of the socket you want to bind. This is returned from the socket() system call.</li><li><strong>addr:</strong> A pointer to a sockaddr structure that contains the IP address and port to which the socket should be bound.</li><li><strong>addrlen:</strong> The size of the sockaddr structure.</li></ul><p>befor filling this variables we need to <strong>Prepare the Address Structure (sockaddr_in)</strong> To bind the socket, you need to fill in an appropriate <strong>address structure</strong> that specifies the IP address and port number where you want the socket to listen for incoming connections or data.</p><p>The structure you’ll commonly use for IPv4 is sockaddr_in, which is specific to the Internet (IPv4) address family (AF_INET). The structure looks like this:</p><pre>struct sockaddr_in {<br>      sa_family_t sin_family; // Address family (AF_INET)<br>      in_port_t sin_port; // Port number in network byte order<br>      struct in_addr sin_addr; // IP address (32-bit)<br>};</pre><p>the <strong>sin_port</strong> filled with the function <strong>htons() (host-to-network short) </strong>is used to ensure the port is in the correct byte order (big-endian format).</p><h3><strong>Listen for incoming connections:</strong></h3><p>The <strong>listen()</strong> function is used on the <strong>server side</strong> to mark a socket as <strong>passive</strong>, meaning it will listen (wait for connection attempts from clients) for incoming connection requests from clients. It allows the server to queue incoming connections and handle them one by one.</p><p><strong>Listen for incoming connections:</strong></p><p>The <strong>listen()</strong> function is used on the <strong>server side</strong> to mark a socket as <strong>passive</strong>, meaning it will listen (wait for connection attempts from clients) for incoming connection requests from clients. It allows the server to queue incoming connections and handle them one by one.</p><pre>int listen(int sockfd, int backlog);</pre><ul><li><strong>sockfd:</strong> The file descriptor of the socket that was created with socket() and bound using bind().</li><li><strong>backlog:</strong> The maximum number of connection requests that can be queued for acceptance.</li></ul><h3><strong>Accept connections:</strong></h3><p>The <strong>accept() </strong>function is used on the server side to accept incoming client connection requests. When a client connects to a server’s listening socket (set by <strong>listen()</strong>), <strong>accept() </strong>creates a new socket dedicated to that connection, allowing the server to communicate with the client. The original listening socket (sockfd) remains in listening mode, allowing the server to continue accepting additional connections.</p><pre>int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);</pre><ul><li><strong>sockfd:</strong> The file descriptor of the listening socket (the one that was created using socket(), bound with bind(), and set to listen with listen()).</li><li><strong>addr:</strong> A pointer to a sockaddr structure where the client’s address information will be stored. It can be NULL if you don’t care about the client’s address.</li><li><strong>addrlen:</strong> A pointer to a variable that initially contains the size of the addr structure. Upon return, it will hold the actual size of the client address structure. Can also be NULL.</li></ul><h3><strong>Communication with clients:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*znVI6aU808KI2urh.png" /></figure><p>To communicate with a server, once a connection is established between a client and server, the primary functions used for data exchange are <strong>send()</strong>, <strong>recv()</strong>, <strong>read()</strong>, and <strong>write()</strong>. These functions allow the client and server to send and receive data over the network.</p><h4>1. <strong>send()</strong> — Sending Data to the Server</h4><p>The send() function is used to send data from a client (or server) to the other side of the connection over a socket. It is typically used in TCP (SOCK_STREAM) sockets.</p><pre>ssize_t send(int sockfd, const void *buf, size_t len, int flags); </pre><ul><li><strong>sockfd:</strong> The file descriptor of the socket (either the client’s connected socket or the server’s accepted socket).</li><li><strong>buf:</strong> A pointer to the buffer containing the data to send.</li><li><strong>len:</strong> The length of the data in bytes to send.</li><li><strong>flags:</strong> Usually set to 0. Flags can modify how the function behaves (e.g., MSG_DONTWAIT to make the function non-blocking).</li></ul><h4>2. <strong>recv()</strong> — Receiving Data from the Server</h4><p>The recv() function is used to receive data from the other side of a connected socket. It reads data sent by the remote peer and stores it in a buffer.</p><pre>ssize_t recv(int sockfd, void *buf, size_t len, int flags);</pre><ul><li><strong>sockfd:</strong> The file descriptor of the socket (either the client’s or server’s connected socket).</li><li><strong>buf:</strong> A pointer to the buffer where the received data will be stored.</li><li><strong>len:</strong> The maximum number of bytes to receive (size of the buffer).</li><li><strong>flags:</strong> Usually set to 0. Flags can modify how the function behaves (e.g., MSG_WAITALL to wait for the full data).</li></ul><p>for the other functions we’re not going to use theme because <strong>write() </strong>and <strong>read() </strong>designed for writing data to files (but it can be used with sockets as well).</p><h3>IRC CLIENT:</h3><p>For the IRC client we have to setting up a TCP connection to the IRC server, sending and receiving messages. to do this we have to follow this steps :</p><ul><li><strong>Create a Socket.</strong></li><li><strong>Specify Server Address:</strong></li></ul><pre>struct sockaddr_in {<br>    sa_family_t sin_family; // Address family (AF_INET)<br>    in_port_t sin_port; // Port number in network byte order<br>    struct in_addr sin_addr; // IP address (32-bit)<br>};</pre><p>use same struct as the server but we can add</p><pre>int inet_pton(int af, const char *src, void *dst);</pre><ul><li><strong>af (address family): </strong>Specifies the address family of the IP address. It can be:</li><li>AF_INET for IPv4 addresses.</li><li>AF_INET6 for IPv6 addresses.</li><li><strong>src (source): </strong>A <strong>string</strong> containing the IP address in text format (e.g., “127.0.0.1” for IPv4 or “::1” for IPv6).</li><li><strong>dst (destination): </strong>A <strong>pointer</strong> to sockaddr_in struct.</li></ul><h4><strong>Connect to the Server:</strong></h4><p>The <strong>connect() </strong>function is used by a client to establish a connection to a server. It is typically used after creating a socket with socket(), and before sending or receiving data. Once a connection is established, the client can communicate with the server over the socket.</p><pre>int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);</pre><ul><li><strong>sockfd: </strong>This is the <strong>file descriptor</strong> of the socket that was previously created using the socket() function. The socket must be of the SOCK_STREAM type for TCP connections.</li><li><strong>addr: </strong>A pointer to a <strong>sockaddr structure</strong> that contains the <strong>server’s address and port</strong>. This structure can be of type sockaddr_in for IPv4 or sockaddr_in6 for IPv6. It stores the IP address of the server and the port number to which the client is connecting.</li><li><strong>addrlen: </strong>The size of the address structure (usually sizeof(sockaddr_in) for IPv4 or sizeof(sockaddr_in6) for IPv6).</li></ul><p>Here is a small server created using c++</p><pre>Server::Server(int argc, char **argv) {<br>    checkArgs(argc, argv);<br><br>    struct addrinfo hints, *res;<br>    memset(&amp;hints, 0, sizeof(hints));<br>    hints.ai_family = AF_INET;<br>    hints.ai_socktype = SOCK_STREAM;<br>    hints.ai_protocol = IPPROTO_TCP;<br>    hints.ai_flags = AI_PASSIVE;<br><br>    if (getaddrinfo(NULL, port.c_str(), &amp;hints, &amp;res) != 0) {<br>        std::cerr &lt;&lt; &quot;getaddrinfo error&quot; &lt;&lt; std::endl;<br>        exit(1);<br>    }<br><br>    serverSocket = socket(res-&gt;ai_family, res-&gt;ai_socktype, res-&gt;ai_protocol);<br>    if (serverSocket &lt; 0) {<br>        std::cerr &lt;&lt; &quot;Socket error&quot; &lt;&lt; std::endl;<br>        exit(1);<br>    }<br><br>    int opt = 1;<br>    setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &amp;opt, sizeof(opt));<br><br>    if (bind(serverSocket, res-&gt;ai_addr, res-&gt;ai_addrlen) &lt; 0) {<br>        std::cerr &lt;&lt; &quot;Bind error&quot; &lt;&lt; std::endl;<br>        exit(1);<br>    }<br><br>    freeaddrinfo(res);<br><br>    if (listen(serverSocket, SOMAXCONN) &lt; 0) {<br>        std::cerr &lt;&lt; &quot;Listen error&quot; &lt;&lt; std::endl;<br>        exit(1);<br>    }<br><br>    LOG_SERVER(&quot;Server started on port &quot; &lt;&lt; port);<br>    LOG_SERVER(&quot;Server started with the password &quot; &lt;&lt; &quot;&lt;&quot; &lt;&lt; password &lt;&lt; &quot;&gt;&quot;);<br>}</pre><p>plsu the connection that get accepted to create the client in our server</p><pre>void Server::acceptConnection() {<br>    int newClientSocket = accept(serverSocket, NULL, NULL);<br>    if (newClientSocket &lt; 0) {<br>        std::cerr &lt;&lt; &quot;Accept error&quot; &lt;&lt; std::endl;<br>        return;<br>    }<br><br>    clients.push_back(Client(newClientSocket)); // Add client to the server&#39;s client list<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd08e4f469f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction To Reverse Engineering]]></title>
            <link>https://medium.com/@mohcin.ghalmi/introduction-to-reverse-engineering-fdb9612c4c13?source=rss-3c9f7f4b3a26------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdb9612c4c13</guid>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[SLEEPS]]></dc:creator>
            <pubDate>Wed, 25 Dec 2024 14:24:13 GMT</pubDate>
            <atom:updated>2024-12-25T14:24:13.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*oU9n1IT1QM40Xf2bGd0ygA.png" /></figure><h3>The Purpose of Reverse Engineering</h3><p>Reverse engineering is like taking something apart to figure out how it works and how it was made. You can reverse-engineer almost anything, from software to physical machines like hardware. Here are some common reasons for reverse engineering:</p><h3>1. Repair or Replace Parts</h3><p>Think of an old gaming console that the manufacturer no longer supports. If you need a replacement part that’s no longer being made, you can reverse-engineer the hardware to create your own custom replacement or upgrade. This idea also works for software! For example, if you need an old driver for an outdated device, you can reverse-engineer the original driver to understand how the device communicates and then create a new one.</p><h3>2. Product Security and Vulnerability Analysis</h3><p>Reverse engineering is often used to analyze software for issues like crashes, security flaws, or hidden vulnerabilities. By breaking down and studying how a system works, you can find ways to fix these problems or protect sensitive data. It’s also sometimes used to bypass things like copy protection or access restrictions (though keep in mind that ethical and legal boundaries are important here!).</p><h3>3. Making Systems Work Together</h3><p>Sometimes, you need two systems to talk to each other, but they weren’t designed to do so. Reverse engineering can help you figure out how each system works and how to create a connection between them. This is especially useful for making old and new systems work together or ensuring compatibility. Reverse engineering is a fascinating way to understand, improve, or fix things — and it’s widely used in tech, engineering, and beyond!</p><h3>When reverse engineering saves industries</h3><p>Malicious software, or malware, is software created with harmful intentions. It’s designed to disrupt devices or networks, steal private information, or compromise the user’s security and privacy. To combat malware and minimize its impact, reverse engineering is essential. By taking apart the malware, we can learn what it does, how it spreads, and what vulnerabilities it exploits. Some of these exploits might be familiar, but others could be entirely new, making reverse engineering a crucial step in understanding and stopping the threat.</p><h3>WannaCry Case: How Reverse Engineering Saved the Day</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gQhD9-akCShsE6hyl6NlDw.png" /></figure><p>In May 2017, a massive ransomware attack called <strong>WannaCry</strong> hit over 300,000 Windows computers worldwide. The ransomware locked users out of their data by encrypting it and demanded a ransom in Bitcoin to unlock it.</p><p>To find a way to stop the attack, security researcher <strong>Marcus Hutchins</strong> turned to reverse engineering. By analyzing the malware’s code, he discovered a “<strong>kill-switch</strong>” hardcoded into the program. The malware checked if a specific domain name existed, if it did, WannaCry would stop encrypting data. Marcus quickly registered the domain, effectively halting the attack for machines connected to the internet and preventing it from spreading further.Other researchers, diving deeper into the program’s memory, found that the encryption key remained in memory as long as the WannaCry process hadn’t been stopped or the computer hadn’t been rebooted. This discovery led to tools like <strong>Wannakey</strong> and <strong>Wanakiwi</strong>, which allowed victims to decrypt their data without paying the ransom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*BqA9QS_XxuEGaHIYEsjuBw.png" /></figure><p>This incident is a great example of how reverse engineering can help fight cyber threats and minimize damage.</p><h3>Stuxnet: A Landmark in Cyber Warfare</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-s0BZRPgzmWRCcDDQp8EgA.png" /></figure><p><strong>Stuxnet</strong> is a highly sophisticated malicious worm discovered in 2010, designed specifically to target <strong>SCADA (Supervisory Control and Data Acquisition) systems</strong>. It is believed to have caused significant damage to Iran’s nuclear program by sabotaging the centrifuges used to enrich nuclear material.</p><p>This operation, reportedly developed under the Bush and Obama administrations, showcased the power of cyber warfare. Stuxnet was tailored to exploit vulnerabilities in industrial control systems, making it the first known malware to target physical infrastructure.</p><p>Security firm <strong>Symantec</strong> played a critical role in reverse-engineering Stuxnet. Their work helped unravel how the worm operated, including its ability to spread undetected and manipulate industrial systems. By understanding its mechanisms, researchers were able to devise strategies to contain and prevent further spread of the malware.</p><p>Stuxnet set a precedent for cyberattacks on critical infrastructure, highlighting the importance of reverse engineering in understanding and defending against such advanced threats.</p><h3>Building an application: lifecycle</h3><p>To understand the process of reverse engineering, it helps to compare it with the normal cycle of creating an application. Below is a schema that shows the standard cycle of creating an application alongside the cycle involved in reverse engineering it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*zTKZjE4pFGTR8rx59vlvYA.png" /></figure><p>To build an application, the first step is to decide what type of application you want to create and then choose a suitable programming language. While you technically can use any language, the choice should be based on the functionality required for your application and the libraries available to simplify development. For example:</p><ul><li><strong>Web Application</strong>: A web app typically has a front-end, which is often written in JavaScript using libraries like React or Vue. The back-end can be written in languages like PHP, Python, or Node.js, depending on your requirements.</li><li><strong>Desktop Application</strong>: For desktop apps, languages like C++ or C are commonly used because they provide direct access to the operating system, allowing for more efficient handling of system resources through system calls.</li><li><strong>Mobile Application</strong>: Mobile apps are generally written in Java (for Android), Swift (for iOS), or Kotlin (also for Android), depending on the platform you’re targeting.</li></ul><p>The key is to choose the language that aligns with your app’s needs and makes the development process as smooth and efficient as possible.</p><h3>Basic Concepts</h3><p>There are two main types of programming languages: compiled and interpreted.</p><ul><li><strong>Compiled languages</strong>, like <strong>C</strong>, require you to first write the source code, and then compile it using a <strong>compiler</strong> and <strong>linker</strong>. After compilation, the code is transformed into a binary executable that can be run by the operating system.</li></ul><blockquote><strong><em>Compiler</em></strong><em>: A tool that converts the source code into an intermediate object code that the CPU can’t execute directly.</em></blockquote><blockquote><strong><em>Linker</em></strong><em>: This tool combines object files and libraries to create the final executable file.</em></blockquote><blockquote><strong><em>Loader</em></strong><em>: The loader reads the executable file into memory and prepares it for execution. Once loaded, the operating system begins running the program.</em></blockquote><ul><li><strong>Interpreted languages</strong>, like <strong>Python</strong>, don’t require a separate compilation step. Instead, the code is executed directly by an <strong>interpreter</strong>, which reads and runs the source code without converting it into machine language first.</li></ul><p>When it comes to reverse engineering, a web application written in JavaScript (an interpreted language) is generally easier to reverse since you can directly access and examine the source code. The code may be obfuscated (with random variable names or functions), but it’s still readable. On the other hand, reversing a desktop application written in C++ (a compiled language) involves disassembling the binary executable and reading assembly code, which is a more complex and challenging process.</p><h3>Assembling &amp; Disassembling</h3><p>When you write a program in a compiled language, like <strong>C</strong>, the source code is typically compiled into a binary file, which is what gets distributed. Since compiling is a one-way process, you usually don’t have access to the original source code. Instead, what you get is a machine-readable file that consists of assembly language instructions — low-level code that the computer’s <strong>CPU</strong> can execute directly.</p><h4>Disassembling</h4><p>To understand what the program does, we can <strong>disassemble</strong> the binary file. Disassembling is the process of converting the binary executable back into assembly language, which gives us insight into the program’s behavior. Although it’s not the same as the original source code, disassembly can help you figure out the logic and flow of the program by examining the assembly instructions.</p><p>Example: Disassembling a Simple “Hello World” Program</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*OeDU8wKcUpnYBz71DZ3Tew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*jox3I47-vRuJwRURIBlxAw.png" /></figure><p>This assembly code represents a sequence of low-level instructions that the CPU can execute.</p><p>Understanding the Behavior</p><p>By analyzing this disassembled code, you can infer the program’s behavior, like how it prints “Hello, World!” to the screen. The actual text string (“Hello, World!”) is often stored in the binary or linked externally and accessed during runtime.</p><p>Disassembling allows reverse engineers to gain insight into how the program works, identify potential vulnerabilities, or reverse-engineer malicious software, despite not having access to the original source code.</p><h4>Compiling &amp; Decompiling</h4><p>While compilation is a one-way process, meaning the original source code is lost after being compiled into a binary, we can often make an educated guess about what the source code looked like using a tool called a <strong>Decompiler</strong>. A decompiler tries to reverse the compiled binary back into a high-level programming language that resembles the original source code.</p><p>Popular decompilers include tools like <strong>Ghidra</strong> and <strong>IDA Pro</strong>, which are widely used for reverse engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*fpE_dTQz-0oe6z1QNBbByQ.png" /></figure><p>Some information is lost during compilation, such as variable and function names. Additionally, certain structures like switch cases might be transformed into if conditions, or vice versa. As a result, decompiling isn’t an exact process, but it can still give you a clearer understanding of what’s happening. For someone with a solid programming background, reading decompiled source code is much easier than reading assembly.</p><h4>How Decompilers Work</h4><p>Decompilers analyze the binary’s assembly code, trying to map it back to higher-level code. They can identify common patterns and recognize functions and structures, such as loops and conditionals, based on the assembly instructions. Though not perfect, decompilers make reverse engineering much easier by providing a higher-level view of the code compared to raw assembly.</p><p>In the case of malicious software or analyzing vulnerabilities, decompiling can be extremely helpful as it gives us a readable version of the program that we can inspect and understand, even without the original source code.</p><h3>Analysis context</h3><p>Before starting any reverse engineering project, it’s important to define the framework and understand what information is available about the binary. There are two main types of analysis in reverse engineering:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*d0ih1LN4hQZ3kInd3toifA.png" /></figure><ol><li><strong>Black Box Analysis</strong>: This is when we only have access to the behavior of the program — meaning, we can observe the inputs and outputs — but we don’t have access to the executable or the internal code. In this case, we have to deduce how the program works purely based on its interactions and results.</li><li><strong>White Box Analysis</strong>: This occurs when we have access to the program’s binary or executable. With this level of access, we can directly analyze the code, whether through disassembling, decompiling, or inspecting the program’s internal structure, to understand its functionality. In short, black box analysis is about analyzing a program from the outside, while white box analysis involves studying the internals of the program.</li></ol><p>White box and black box analysis are not the only contexts in reverse engineering. We also encounter the concepts of <strong>static</strong> and <strong>dynamic</strong> analysis. To fully grasp these ideas, we need to explore both the black-box and white-box analysis contexts, along with the underlying concepts of static and dynamic analysis.</p><h3>BlackBox Context</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Kq-Yh5wiLSrRqptN2Vf4oQ.png" /></figure><p>A <strong>black box analysis</strong> means that we don’t have access to the binary or program we’re trying to study. Instead, we focus on exploring the behavior of the program while it’s running.</p><p>Since we don’t have access to the internal code in a black box scenario, <strong>static analysis</strong> doesn’t apply. Static analysis would involve studying a program without running it, which is not possible in a black box situation.</p><p>We can break down <strong>dynamic black box analysis</strong> into two types:</p><ol><li><strong>Passive Analysis</strong>: In this case, we study the program without interacting with it. We only observe the inputs and outputs of the program without influencing its behavior.</li><li><strong>Active Analysis</strong>: Here, we interact with the program by providing specific inputs and observing how the program responds. This allows us to control the inputs and analyze the resulting outputs.</li></ol><h3>WhiteBox Context</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*nyHjCAnf7Lc89bN1JsSxZQ.png" /></figure><p>A <strong>white box analysis</strong> means that we have access to the binary or program we want to study. This allows us to explore its behavior during execution. A white box analysis can be divided into two types:</p><ol><li><strong>Dynamic Analysis</strong>: Similar to black box dynamic analysis, this involves studying the program while it’s running. We can categorize dynamic analysis as either active or passive.</li><li><strong>Static Analysis</strong>: In static analysis, we study the program without executing it. This involves disassembling or decompiling the program to examine the generated source code. Static analysis can be broken down into two main areas:</li></ol><ul><li><strong>Syntactic Analysis</strong>: Focuses on the structure and form of the program’s code.</li><li><strong>Semantic Analysis</strong>: Examines all the possible behaviors of the program, analyzing how it might operate under different conditions.</li></ul><h3>Abstraction levels</h3><p>In reverse engineering, a key concept is the level of abstraction at which the analysis is performed. Depending on the focus of the analysis, it can be conducted at different levels. The main levels include:</p><ol><li><strong>Application Level</strong>: At this level, we aim to understand the overall purpose and field of application of the product. This involves analyzing the high-level functionality of the program, such as whether it is management software, a data exchange protocol, or something else.</li><li><strong>Structure and Data Level</strong>: Here, the goal is to understand the internal structures and data types used by the product. This could include examining the software’s architecture, design patterns, and the types of data it handles.</li><li><strong>Implementation Level</strong>: At this level, we focus on how the product was implemented. This involves analyzing:</li></ol><ul><li>The <strong>symbol table</strong>, which contains information about types, scope, and visibility of variables and functions, created during compilation.</li><li>The <strong>used character strings</strong>, which can provide clues about library calls and specific functionalities like input/output manipulation or mathematical operations.</li></ul><p>It is essential to understand the <strong>application domain</strong> before delving into the implementation details. This gives you a broader view, helping you better interpret the structures and implementation specifics of the software.</p><h3>Assembly basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*myerp00wyXWxV4f_oYQygA.png" /></figure><p><strong>Assembly Language</strong> is a low-level programming language designed to interact directly with computer hardware. It is essential for binary reverse engineering because it lets you understand and manipulate the internal structure of a program or system at the most basic level.</p><p>Learning Assembly language is key in reverse engineering. While it might seem straightforward, it’s not necessarily easy. Assembly consists of simple instructions that perform basic operations, such as copying values to or from memory, performing arithmetic operations like addition or multiplication, and handling conditionals like comparisons. These basic instructions form the building blocks for more complex processes within a program.</p><h3>Memory representation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*zTgNKEUVg9gHxgmEXGxTZQ.png" /></figure><p>When reverse engineering a program, it’s essential to understand how the program’s data is stored in memory during execution. The most basic unit of computer memory is the <strong>bit</strong>, which can hold a value of either 0 or 1.</p><ul><li><strong>Byte</strong>: 8 bits make up a byte, which can store values ranging from 0 to 255.</li><li><strong>Word</strong>: A word consists of 4 bytes or 32 bits.</li><li><strong>Double Word</strong>: A double word is 8 bytes or 64 bits.</li></ul><p>For example, a string like “Hello World” is stored in memory with each character taking up 1 byte, and each character is stored in its ASCII form. In the case of the letter <strong>‘H’</strong>, its ASCII value is 72.</p><p>To see this in memory, each character of the string would be represented by its corresponding ASCII value in binary. For example, “Hello” in binary would look like this:</p><ul><li><strong>H</strong>: 72 (ASCII) → 01001000</li><li><strong>e</strong>: 101 (ASCII) → 01100101</li><li><strong>l</strong>: 108 (ASCII) → 01101100</li><li><strong>l</strong>: 108 (ASCII) → 01101100</li><li><strong>o</strong>: 111 (ASCII) → 01101111</li></ul><p>So, the memory for “Hello” would look like this (in binary form):<br>01001000 01100101 01101100 01101100 01101111</p><p>Understanding how data like strings are represented in memory helps you decode and manipulate the program’s behavior during reverse engineering.</p><p>Here’s what an area of memory containing a string would look like in binary (1’s and 0’s)(Base 2):</p><pre>01011001 01101111 01110101 00100000 01100001 01110010 01100101 00100000 01101100 01100101 01100001 01110010 01101110 01101001 01101110 01100111 00100000 01110110 01100101 01110010 01111001 00100000 01100110 01100001 01110011 01110100</pre><p>In reverse engineering, it’s common to encounter different memory representations, such as <strong>octal</strong> and <strong>hexadecimal</strong>. Each representation shows the same information but in different bases.</p><ul><li><strong>Octal Representation</strong> (Base 8):<br>131 157 165 40 141 162 145 40 154 145 141 162 156 151 156 147 40 166 145 162 171 40 146 141 163 164</li><li><strong>Hexadecimal Representation</strong> (Base 16):<br>59 6f 75 20 61 72 65 20 6c 65 61 72 6e 69 6e 67 20 76 65 72 79 20 66 61 73 74</li></ul><p>Each element, separated by a space, represents the value of a byte in different bases. For example, the byte at address 0x0 has the value 59 in hexadecimal, 131 in octal, and 01011001 in binary, which corresponds to the ASCII value for the character <strong>&#39;Y&#39;</strong>.</p><p>Now, let’s decode the <strong>hexadecimal</strong> string to see what string is stored in memory:</p><ol><li>59 → &#39;Y&#39;</li><li>6f → &#39;o&#39;</li><li>75 → &#39;u&#39;</li><li>20 → &#39; &#39; (space)</li><li>61 → &#39;a&#39;</li><li>72 → &#39;r&#39;</li><li>65 → &#39;e&#39;</li><li>20 → &#39; &#39; (space)</li><li>6c → &#39;l&#39;</li><li>65 → &#39;e&#39;</li><li>61 → &#39;a&#39;</li><li>72 → &#39;r&#39;</li><li>6e → &#39;n&#39;</li><li>69 → &#39;i&#39;</li><li>6e → &#39;n&#39;</li><li>67 → &#39;g&#39;</li><li>20 → &#39; &#39; (space)</li><li>76 → &#39;v&#39;</li><li>65 → &#39;e&#39;</li><li>72 → &#39;r&#39;</li><li>79 → &#39;y&#39;</li><li>20 → &#39; &#39; (space)</li><li>66 → &#39;f&#39;</li><li>61 → &#39;a&#39;</li><li>73 → &#39;s&#39;</li><li>74 → &#39;t&#39;</li></ol><p>When decoded, the string reads:<br><strong>“You are learning very fast”</strong></p><p>This illustrates how data is stored and represented in memory at different levels, and how understanding these representations is crucial for reverse engineering and decoding programs.</p><h3>CPU Registers</h3><p>In addition to <strong>RAM</strong> (Random Access Memory because it allows you to access any memory area, using its address), the CPU also has <strong>registers</strong>, which are the smallest data-holding elements built directly into the processor. Registers provide extremely fast access to data, much faster than accessing data from RAM. They can hold various types of information, such as:</p><ul><li>Instructions that the CPU is currently processing</li><li>Memory addresses</li><li>Any kind of data like numbers or characters</li></ul><p>Registers are used to store the data that the CPU is actively working with. For example, if the CPU needs to calculate the sum of two numbers, the process would go like this:</p><ol><li>The two numbers are copied from <strong>RAM</strong> into <strong>registers</strong>.</li><li>The CPU performs the addition operation on the numbers stored in the registers.</li><li>The result is then placed back into a register.</li></ol><p>Because registers are located within the CPU itself, accessing data from them is much faster than retrieving data from memory (RAM), making them essential for efficient processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*mST76tSI1dXHG-99MQJgvA.png" /></figure><p>The number and size of registers vary depending on the CPU architecture. Let’s take the Intel x86 architecture as an example. The x86 architecture includes 8 General-Purpose Registers (GPR), 6 Segment Registers, 1 Flag Register, and an Instruction Pointer. Below are the identifiers used to access these registers and their components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*ZhKi-6GzGCXi4yqT6t-WAw.png" /></figure><p>You will get to understand registers more once you practice writing assembly, but you should note for now that they are just areas where you can store data, like numbers, before doing operations like addition.</p><h3>The Stack</h3><p>A stack is an abstract data structure that operates on a Last In, First Out (LIFO) principle. You can add items to the stack and remove them in reverse order. The two primary operations for a stack are <strong>push</strong> and <strong>pop</strong>:</p><ul><li><strong>Push</strong>: Adds a value to the top of the stack.</li><li><strong>Pop</strong>: Removes and retrieves the value from the top of the stack.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Jzo06ES-LHfRnLjMHe9zcw.png" /></figure><p>A <strong>program stack</strong> is a specific stack in memory utilized during a program’s execution. It typically has a fixed size allocated for each program and is commonly used to store local variables, function parameters, and return addresses for functions. Below is a diagram illustrating the typical memory layout of a program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*Jt_idDg3TwfqAkWTsERynQ.png" /></figure><ul><li>A <strong>Text area</strong> that contains the machine instructions of the current program</li><li><strong>Initialized</strong> and <strong>Uninitialized</strong> data areas contain global variables and static data</li><li><strong>The heap</strong> contains variables and data dynamically allocated, using malloc for example in C</li><li><strong>The Stack</strong> contains local variables and information about the functions the program calls, like arguments and returns addresses</li></ul><p>The following diagram shows an example of the stack contents when running this simple program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*kz8mCVj0ZZtmERCn8O_LtQ.png" /></figure><p>When a program runs, the first function to execute is main(). At this point, a new stack frame is pushed onto the stack, containing details about the main() function, such as its parameters and local variables. When reWriteString() is called, another stack frame is pushed onto the stack. Similarly, when strcpy() is invoked, yet another stack frame is added.</p><p>Once strcpy() completes and returns, its stack frame is destroyed and popped from the stack, making reWriteString() the active function at the top. When reWriteString() finishes, its stack frame is also destroyed, and execution resumes with main().</p><p>It is important to note that the stack grows downwards, meaning the top of the stack has a smaller memory address than the bottom.</p><p>Two key registers, ESP (Stack Pointer) and EBP (Base Pointer, also known as the frame pointer), play essential roles in managing the stack:</p><ul><li>ESP contains the address of the top of the stack.</li><li>EBP contains the address of the bottom of the current stack frame.</li></ul><p>When a byte is pushed onto the stack, ESP is decreased by 1 to reflect the updated top of the stack.</p><h3>Basic Instructions</h3><p>There are two widely used assembly syntax styles: <strong>AT&amp;T (GAS)</strong> syntax and <strong>Intel (NASM)</strong> syntax. Here’s an example to illustrate the differences between the two:</p><h3>AT&amp;T (GAS) Syntax</h3><ul><li>Operands are ordered as <em>source, destination</em>.</li><li>Instructions often include a suffix to indicate the operand size (e.g., movl for a 32-bit move).</li><li>Registers are prefixed with %, and immediate values are prefixed with $.</li><li>Memory addresses are specified with a base, index, and scale enclosed in parentheses.</li></ul><pre>movl $10, %eax    # Move the immediate value 10 into the EAX register<br>addl %ebx, %eax   # Add the value in EBX to EAX<br>movl (%ecx), %edx # Move the value at the memory address stored in ECX into EDX</pre><ul><li><strong>Intel (NASM) Syntax</strong></li><li>Operands are ordered as <em>destination, source</em>.</li><li>Instructions do not require suffixes for operand size (size is implied by the operands or specified explicitly).</li><li>Registers and immediate values are written without prefixes.</li><li>Memory addresses are written in square brackets.</li></ul><pre>mov eax, 10       ; Move the immediate value 10 into the EAX register<br>add eax, ebx      ; Add the value in EBX to EAX<br>mov edx, [ecx]    ; Move the value at the memory address stored in ECX into EDX</pre><h3>Preferred Syntax</h3><p>We will adopt <strong>Intel syntax</strong> because it is easier to read and write, with a cleaner and more intuitive operand order.</p><p>The <strong>current x86–64 architecture</strong> supports 981 unique mnemonics and 3,684 instruction variants. Covering all of them is impractical, so we will focus on the basics and most frequently used instructions.</p><p>For advanced exploration, I recommend consulting the <em>Intel® 64 and IA-32 Architectures Software Developer’s Manual</em>. Specifically, <strong>Volume 2</strong>, which provides the full instruction set reference. Although intimidating at first, this reference is manageable if approached in a <strong>random-access fashion</strong>, rather than sequential reading.</p><h3>Categories of Basic Instructions</h3><h4>Copying Data:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*fsxCrJSy0781MmG6sad8Xw.png" /></figure><h4>Arithmetic:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*NX7u4jZtvfCX9Drckj-JEw.png" /></figure><h4>Function Calls:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*p2Nq7n_k9dsC5m1YyBB7Dg.png" /></figure><h4>Bitwise Operations:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*CV_thuF-jrY-thsKjzusCg.png" /></figure><h4>Conditionals and Jumps:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*TRqZ-VPqCz1BIffhs2XrYg.png" /></figure><h4>Miscellaneous:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*q2ihHFKDUcPtPlKQyvqMag.png" /></figure><h3>Notes:</h3><ul><li><strong>Size Specifiers:</strong><br>Instructions without memory references must include a size specifier such as byte, word, or dword.</li><li><strong>Instruction Arguments:</strong><br>Both src and dest cannot be memory addresses simultaneously.</li><li><strong>Defining Values in Intel Syntax:</strong></li></ul><blockquote><strong>Constant (decimal or hex):</strong> 10 or 0xff</blockquote><blockquote><strong>Register:</strong> eax, ebx, ecx, edx, esi, edi, ebp, esp</blockquote><blockquote><strong>Fixed Address:</strong> [200] or [0x1000+53]</blockquote><blockquote><strong>Dynamic Address:</strong> [eax] or [esp+16]</blockquote><h3>Example Programs</h3><p>Let me show you how to write a simple program in asm and run it on Linux, we are going to focus on x86 and the 32-bit architecture for now:</p><h4>The classic Hello World</h4><p>In C language:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*E5cNPr3L1A2XH1eZYHkolA.png" /></figure><p>We can compile it and get an executable using the command:</p><ul><li>gcc –m32 hello.c -o hello: this command will compile the source and link it into an elf file “hello”, the –m32 flag is to compile this source into a 32-bit executable.<br>Here is the same program in intel x86 asm syntax:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GHvRXpWBbkei1UJ3v2HSg.png" /></figure><p>We can assemble this and link it into an executable in two steps:</p><ul><li>nasm –f elf hello.asm -o hello.o: this command will assemble the hello.asm into an elf object file “hello.o”, but it’s not executable yet</li><li>ld -m elf_i386 -s hello.o -o hello: this command will link the elf object file hello.o, into an elf_i386 (32-bit) executable named “hello”.*</li></ul><p>When running the two programs we get absolutely the same text “Hello World!” followed by a new line, on the standard output.<br>The way we make system calls in assembly depends on the operating system. This example is from Linux, each system call has a number, 1 is for sys_exit, 3 is for sys_read, 4 for sys_write, you can search online for “Linux System Call Table” for more information.<br>The register EAX contains the number of the syscall we want to perform, and then the following registers, EBX, ECX, EDX, ESX, and EDI contain arguments.<br>The write syscall takes 3 arguments, the file descriptor, pointer to the string, and the number of bytes to write, you have to fill the registers accordingly, and then do an “Interrupt” which will transfer the control to the kernel.<br>Imagine the call as sys_call(ebx, ecx, edx) with what syscall to use, being determined by the content of eax.</p><h3>Reverse Engineering Tools</h3><p>There are multiple ways to understand the functionality of a binary or to extract data from it. These methods can be categorized into two main types: <strong>Static Analysis</strong> and <strong>Dynamic Analysis</strong>.</p><ul><li><strong>Static Analysis</strong> involves examining the binary without running it. Tools used in static analysis parse the executable to extract information about its structure, symbols, sections, and strings. This can help you understand the internal workings of the program, identify vulnerabilities, or retrieve embedded data.</li><li><strong>Dynamic Analysis</strong>, on the other hand, involves running the binary and observing its behavior in real-time. This includes monitoring the contents of memory, registers, and other runtime characteristics. By executing the program in a controlled environment, such as a debugger or virtual machine, you can track how the binary interacts with its environment, which can reveal information like function calls, data manipulation, or network activity.</li></ul><p>In this chapter, we will explore several tools that can be used for both <strong>Static</strong> and <strong>Dynamic Analysis</strong> of binaries.</p><h3>Static Analysis</h3><ul><li><strong>strings</strong>: The strings command in Linux extracts literal strings from any file, whether executable or not. It can be useful for discovering domain names, IP addresses, or any strings embedded within the code, such as error messages, configuration data, or hardcoded values.</li></ul><p>-<strong> Example :</strong></p><pre>   strings /bin/bash  </pre><p>This will print all the human-readable strings within the bash binary, including error messages, version numbers, or other hardcoded strings.</p><ul><li><strong>nm</strong>: The nm tool is used to display the symbol table of executables, object files, or libraries. Symbols can include function names, variable names, labels, or even debug information that was retained during compilation and linking.</li></ul><p><strong>- Example :</strong></p><pre>       nm /bin/ls</pre><p>This will show a list of symbols in the ls binary, which could include function names, variable names, and any other linked symbols. The output will look something like this:</p><pre>0000000000400510 T _start<br>0000000000400530 T main<br>00000000004005e0 T printf</pre><ul><li><strong>strace</strong>: The strace command traces system calls and signals. It runs a program and records all system calls the process makes, along with the signals it receives. This can help in analyzing how a program interacts with the operating system by showing system call names, their arguments, and return values.</li></ul><p><strong>- Example :</strong></p><pre>       strace ls</pre><p>This will print out all the system calls made by the ls command as it runs. You might see output like this:</p><pre>openat(AT_FDCWD, &quot;/etc/ld.so.cache&quot;, O_RDONLY) = 3<br>fstat(3, {st_mode=S_IFREG|0644, st_size=41773, ...}) = 0<br>mmap(NULL, 8192, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f90e2f97000 </pre><ul><li><strong>ltrace</strong>: The ltrace tool intercepts and records calls to dynamic libraries, including signals the process receives. It also captures system calls, similar to strace, making it useful for analyzing a program&#39;s interactions with shared libraries and external resources.</li></ul><p><strong>-Example :</strong></p><pre>       ltrace ls</pre><p>This will show the dynamic library calls made by the lscommand:</p><pre>__libc_start_main(0x400530, 1, 0x7ffd7509e3a8, 0x7ffd7509e340, 0x7ffd7509e320, 0x7ffd7509e300) = 0<br>fopen64(0x7f5f8fd11028, 0x0)          = 0x7f5f8fc0d200</pre><h3>Disassemblers and Debuggers</h3><p>Disassemblers and debuggers are essential tools in reverse engineering. Disassemblers convert binary code into assembly language, which provides insights into the structure of a program. Debuggers, however, offer a more interactive approach, enabling the examination and manipulation of the program’s execution in real-time.</p><h3>Key Concepts:</h3><ul><li><strong>Disassemblers</strong>: Read binary bytecode and output assembly instructions.</li><li><strong>Debuggers</strong>: Halt execution, examine variables, step through instructions, and manipulate memory or registers during runtime.</li></ul><p>Debuggers, being more powerful, allow precise control over a program’s execution and can help understand its behavior in detail. Many debuggers even provide the ability to modify memory values, registers, or function return values to manipulate the program flow.</p><h3>Common Debuggers:</h3><h4>1. GDB (GNU Debugger)</h4><p>GDB is a highly versatile command-line debugger for binaries compiled with or without debugging symbols.</p><p><strong>Key Features</strong>:</p><blockquote>Disassembling binaries.</blockquote><blockquote>Step through code line-by-line.</blockquote><blockquote>Examine and modify variables, registers, and memory.</blockquote><blockquote>Set breakpoints at specific instructions or functions.</blockquote><blockquote>Supports extensions for various editors like VSCode, CLion, or Vim.</blockquote><pre>gdb /path/to/binary</pre><p>In GDB, you can set breakpoints with:</p><pre>break main</pre><h4>2. <strong>LLDB</strong></h4><p>LLDB is the default debugger on macOS, often used with Xcode.</p><p><strong>Key Features</strong>:</p><blockquote>Supports C, C++, Objective-C, and Swift.</blockquote><blockquote>Used for debugging on macOS and iOS.</blockquote><blockquote>Integrated with IDEs like Xcode.</blockquote><pre>lldb /path/to/binary`</pre><p>You can inspect a variable with:</p><pre>frame variable</pre><h4>3. <strong>Radare2 (r2)</strong></h4><p>Radare2 is a command-line tool with broad functionality, designed for low-level analysis, disassembly, and debugging.</p><p><strong>Key Features</strong>:</p><blockquote>Powerful disassembler and debugger.</blockquote><blockquote>Remote debugging capabilities.</blockquote><blockquote>Scripting support.</blockquote><blockquote>Wide support for architectures.</blockquote><pre>r2 /path/to/binary</pre><p>To start debugging:</p><pre>r2 -d /path/to/binary</pre><h3>Graphical Interface Debuggers:</h3><p>For those who prefer a GUI, these debuggers are based on the command-line tools but provide a more user-friendly interface.</p><h4>4. <strong>Cutter</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hydmIc5xsQU28t27lwIwVA.png" /></figure><p>Cutter is a graphical user interface for Radare2 (r2), providing advanced reverse engineering features.</p><ul><li><strong>Key Features</strong>:</li></ul><blockquote>User-friendly GUI for Radare2.</blockquote><blockquote>Supports disassembly, analysis, debugging, and scripting.</blockquote><blockquote>Open-source and free.</blockquote><ul><li><strong>Command Example</strong>: Simply open Cutter and load your binary file to start analyzing.</li></ul><h4>5. <strong>IDA Pro</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*UJyH5g8RPkrT1b0nXgDYTg.png" /></figure><p>IDA Pro is a well-known disassembler and debugger with a powerful GUI.</p><ul><li><strong>Key Features</strong>:</li></ul><blockquote>Automated code analysis.</blockquote><blockquote>Cross-referencing between code sections.</blockquote><blockquote>API call parameter analysis.</blockquote><blockquote>Supports many architectures and formats.</blockquote><blockquote>Available in both free and professional versions.</blockquote><ul><li><strong>Command Example</strong>: After launching IDA Pro, you can load a binary for automatic disassembly and analysis. Use the graphical interface to set breakpoints, step through code, and inspect program flow.</li></ul><h4>Decompilers</h4><p>In reverse engineering, <strong>decompilers</strong> play a crucial role in attempting to reconstruct source code from the disassembled binary. However, this process is inherently imprecise, as decompilers must make educated guesses about variable names, functions, and logic flow, which can lead to different results across tools. Additionally, code constructs like multiple if-else statements might be restructured into a switch-case, further complicating the decompilation accuracy. Despite these challenges, decompilers are useful for gaining insights into the structure and behavior of a program. here are some of the most useful ones:</p><h4>1. <strong>Binary Ninja</strong> (<a href="https://binary.ninja/">Binary Ninja</a>)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x60_Umovj2MhNZtQwdcv_Q.png" /></figure><p>Binary Ninja is a powerful, interactive disassembler, decompiler, and binary analysis platform designed for reverse engineers, malware analysts, vulnerability researchers, and software developers. It supports a wide range of architectures and formats and provides an intuitive user interface for analysis.</p><h4>2. <strong>Ghidra</strong> (<a href="https://ghidra-sre.org/">Ghidra</a>)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjhSsaeZYPEuWcgifRqU8A.png" /></figure><p>Ghidra is a software reverse engineering suite developed by the NSA’s Research Directorate. It is a comprehensive tool for decompiling, disassembling, and debugging binaries, and is open-source and free to use.</p><h3>Hex Editors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*L8Z7RgAnlXy3yMU-YRzqVA.png" /></figure><p>Hex editors are crucial tools in the field of <strong>reverse engineering</strong> and <strong>binary analysis</strong> because they allow direct interaction with the binary code of a program. They enable users to inspect and manipulate the raw contents of a file at the byte level, providing insights into the structure and behavior of the program that are not visible through higher-level abstractions like source code or disassembly. Here’s why hex editors are important and how they are used: Hex editors are essential for reverse engineering because they provide a direct view and manipulation of the underlying binary code. Whether you’re analyzing a program’s structure, patching an executable, debugging low-level issues, or modifying the program’s behavior, a hex editor is a powerful tool for understanding and altering how a binary works.</p><h3>Network Analysis</h3><p>When reverse engineering applications that involve network communication, analyzing and manipulating network traffic is a critical aspect of understanding how the application works. Several tools are available that allow you to capture, sniff, and even modify network packets. These tools are essential for inspecting the data being sent or received and can be extremely useful for identifying vulnerabilities or testing the behavior of network protocols. Here are some key tools that can assist with network traffic analysis and modification:</p><h3>1. Wireshark</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*Evd_jraEdSbJWm-xoA1rjw.png" /></figure><p><strong>Wireshark</strong> is one of the most popular and powerful network protocol analyzers. It captures and analyzes network packets in real-time. Used by network administrators, security professionals, and reverse engineers, Wireshark can decode numerous protocols and display the contents of each packet in a human-readable format.</p><h3>TcpDump</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*496nmgGzYSdXfgcUpyAzEg.png" /></figure><p><strong>Tcpdump</strong> is a command-line packet analyzer that captures network traffic and displays it in a readable format. It is widely used for packet-level inspection and analysis of TCP/IP traffic.</p><h3>Scapy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJWNsmbKr-_qAzfD1XQEiQ.png" /></figure><p><strong>Scapy</strong> is a powerful Python-based tool that can be used for network packet crafting, sending, sniffing, and analysis. Unlike Wireshark and Tcpdump, Scapy gives you the ability to manipulate packets at a very low level, making it an excellent choice for reverse engineers and penetration testers who need to interact with custom network protocols.</p><h3>BlackBox Techniques</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*twyTsICf3oqKKhlCsyjJGw.png" /></figure><p>The <strong>Blackbox reverse engineering</strong> technique is a method used to analyze a system without having access to its source code, internal structure, or design documentation. In this approach, the system is treated as a “black box,” meaning that the focus is on observing the system’s <strong>inputs</strong>, <strong>outputs</strong>, and how it behaves during interactions, without any knowledge of its inner workings. Blackbox reverse engineering is a powerful technique for understanding and analyzing systems where internal knowledge is unavailable. It enables the discovery of system behavior, vulnerabilities, and interaction patterns, making it a valuable tool in both security analysis and system design. Whether for analyzing software, hardware, or protocols, blackbox techniques are crucial for investigating and understanding complex systems from an external perspective.</p><h3>WhiteBox Techniques</h3><p><strong>White box reverse engineering</strong> involves analyzing and understanding the internal structure of an application, often focusing on its <strong>source code</strong>. Unlike <strong>black box analysis</strong>, where only the system’s inputs and outputs are studied, white box reverse engineering provides insights into the actual code that drives the application, its logic, and its underlying design. White box reverse engineering allows for an in-depth understanding of how an application works internally. By gaining access to the source code (or decompiled code), reverse engineers can find errors, improve performance, enhance security, and even create derivative products. This method is crucial in software development and security, helping engineers optimize and maintain applications while addressing vulnerabilities before they become issues.</p><h3>Protection mechanisms against RE</h3><p>There are several reasons why developers or companies may want to hide what their software is doing, ranging from protecting intellectual property to ensuring security. Here are the key reasons:</p><h4>1. Protection of Intellectual Property (IP)</h4><p>Companies that create outstanding products or innovative software need to protect their <strong>intellectual property (IP)</strong>. If a competitor can reverse engineer their software, they could gain access to the proprietary algorithms, business logic, or code that forms the core of the product. This can lead to direct copying or the creation of competing products. To prevent this, companies implement <strong>anti-reverse engineering techniques</strong> like code obfuscation, encryption, and licensing mechanisms to make it difficult for others to understand how the software works.</p><h4>2. Malware Concealment</h4><p>Malware developers intentionally hide the behavior of their malicious programs to avoid detection and analysis by security researchers or anti-virus software. By using various <strong>obfuscation</strong> and <strong>encryption techniques</strong>, malware can be made harder to reverse engineer, which helps evade detection by security tools. This allows malware to remain undetected for longer periods, maximizing its impact, such as stealing data or taking control of compromised systems. The more difficult it is to understand how the malware works, the harder it is to create effective countermeasures.</p><h4>3. Software Protection and Anti-Piracy</h4><p><strong>Paid software</strong> or commercial applications need to be protected against piracy. If a program’s code is not sufficiently protected, it can be cracked by attackers, allowing them to bypass licensing restrictions or use the software without paying. To prevent this, software developers often incorporate <strong>anti-tampering techniques</strong> (e.g., checksums, licensing checks, or hardware dongles) and <strong>obfuscation</strong>. This makes it much harder for crackers to figure out how to disable the protection mechanisms and use the software without authorization.</p><h4>4. Preventing Tampering and Manipulation</h4><p>In some cases, the software’s behavior might need to be hidden or protected to prevent tampering. For example, financial applications or software dealing with sensitive information need to make it difficult for users to manipulate the code to change their data or gain unfair advantages (e.g., cheating in games, manipulating financial transactions, or altering game scores). By hiding the inner workings, these applications are more resilient to tampering and manipulation.</p><h4>5. Compliance and Security</h4><p>Certain industries require software to maintain a high level of confidentiality and security. For instance, software used in government, healthcare, or military applications might need to hide specific operations to ensure compliance with security standards. Making the software difficult to reverse engineer helps protect sensitive data, maintain confidentiality, and prevent exploitation by malicious actors.</p><h3>Basic principles</h3><h4>1. Never Unencrypt Protection-Related Strings</h4><p>Do not store unencrypted strings related to protection (e.g., license checks, error messages) in your code. If these strings are easily accessible, attackers can modify or bypass protection mechanisms. Keep these strings encrypted or obfuscated to prevent them from being easily read or modified.</p><h4>2. Don’t Implement Disabled Features in Trial Versions</h4><p>If you release a trial version of your software with some features disabled, do not include the unimplemented features in the code. Use <strong>conditional compilation</strong> or similar techniques to ensure that the features do not exist in the trial version at all, so there’s no way for attackers to simply re-enable them by reverse engineering.</p><h4>3. Avoid Simple Conditional License Checks</h4><p>Simple checks like:</p><pre>if (Check_License() == TRUE) {<br>    Carry_on();<br>} else {<br>    Stop();<br>}</pre><p>should be avoided. Such straightforward checks are easy to identify and bypass through tools like debuggers. Instead, integrate protection more deeply into the program so that it cannot be easily bypassed.</p><h4>4. Integrate Protection with Critical Program Functions</h4><p>Protection mechanisms should be tied to <strong>vital parts</strong> of the program. Don’t separate the protection code from the main functionality, as this makes it easier to identify and disable. The protection should be embedded in such a way that its removal would impact the core functionality.</p><h4>5. Use Weak Sections of Protection as Part of the Key</h4><p>If you use weak sections (like conditional jumps) in your protection mechanism, incorporate them into a <strong>key calculation</strong> related to your protection. This adds complexity to the reverse engineering process, as simply modifying the weak section won’t be enough to bypass the protection.</p><h4>6. Perform Checksum Validation on Critical Sections</h4><p><strong>Checksums</strong> should be used to detect if the executable has been modified. When performing checksums, do it on critical sections of the code (including code in memory) rather than the executable file. If the checksum fails, do not just print a “checksum error” message. Instead, <strong>interrupt the program immediately</strong> to prevent the attacker from continuing.</p><ul><li><strong>Example for Pentium Processors</strong>: Interrupt the program using the instruction sequence F0 0F C7 C8 to stop execution if the checksum is invalid.</li></ul><h4>7. Perform Memory-based Checksum</h4><p><strong>Do not</strong> rely solely on file-based checksums. Attackers can use techniques like creating a launcher with write access to the program’s memory to patch the executable while it is running. Perform checksums on the program’s code <strong>in memory</strong>, making it more difficult for attackers to modify and bypass protection.</p><h3>Using Serial Numbers and Nag Screens for Software Protection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*sFq8TxwDTgNiI_g49Hohrw.png" /></figure><p>To prevent piracy and unauthorized use of paid software, many companies implement serial number-based protection and nag screens. These methods are designed to restrict access to the full version of the software until the user provides a valid serial number or activates the software. Nag screens are message prompts that inform users when their trial period has expired or remind them to activate the software.</p><h3>Code Obfuscation</h3><p>Obfuscation is a technique used to make code harder to understand, even if the source code is available. While interpreted languages like JavaScript provide direct access to the source code, obfuscation makes it more difficult for someone to reverse-engineer the logic behind the code. The goal of obfuscation is not only to hide the function and logic of the code but to also add complexity that slows down the process of understanding or modifying it.</p><p>For example, The following image shows a JavaScript code, before and after Obfuscation, can you tell which is more complex to understand?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*M841Tu7ZlxDhgC8SWyjcxQ.png" /></figure><h3>Packers</h3><p>Packers are tools used to protect software from reverse engineering by encrypting or compressing parts of the executable, making it difficult to analyze the program statically. When a packer is used, the code is often stored as encrypted data within the binary, with only a small decryptor or stub visible. This decryptor is responsible for unwrapping the actual program code at runtime, allowing the program to execute as intended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9z1VJdXw7k5hw9fcamYs6Q.png" /></figure><h3>Antidebug techniques</h3><p>When debugging a program, it’s common for the software to attempt to detect the presence of a debugger in order to prevent reverse engineering or tampering with its behavior. Programs may use various techniques to detect whether they are being analyzed, and once detected, they may alter their behavior or even terminate the execution. Programmers use a variety of techniques to protect their software from reverse engineering and debugging, such as API calls for debugger detection, detecting breakpoints, and fuzzing the code to confuse disassemblers. These techniques can significantly increase the difficulty of debugging, but by understanding these protections, reverse engineers can develop methods to bypass them and analyze the software.</p><h3>VM Detection</h3><p>Malware creators use various methods to detect whether their code is running inside a virtual machine (VM), as VMs are commonly used for analysis and reverse engineering. Detecting the presence of a VM can help malware avoid analysis or alter its behavior to evade detection by researchers. There are multiple VM detection techniques, and malware often combines several of these strategies to accurately determine whether it’s running in a virtualized environment.</p><p>VM detection techniques employed by malware serve as an effective countermeasure to prevent analysis and debugging within virtual environments. By using a combination of these detection techniques, malware can accurately determine if it is running inside a virtual machine and adjust its behavior accordingly. As virtual machines are crucial tools for reverse engineers and malware analysts, understanding these detection techniques is essential for avoiding detection and bypassing VM-specific evasion strategies during the analysis process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdb9612c4c13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Solve Sudoku Using C++: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@mohcin.ghalmi/how-to-solve-sudoku-using-c-a-step-by-step-guide-f98c81b8ade3?source=rss-3c9f7f4b3a26------2</link>
            <guid isPermaLink="false">https://medium.com/p/f98c81b8ade3</guid>
            <category><![CDATA[sudoku-puzzles]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[sudoku-solver]]></category>
            <dc:creator><![CDATA[SLEEPS]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 10:52:39 GMT</pubDate>
            <atom:updated>2024-11-17T10:52:39.094Z</atom:updated>
            <content:encoded><![CDATA[<p>Sudoku is a puzzle that has enjoyed worldwide popularity since 2005. also it is one of the most popular logic-based number puzzles. Solving it programmatically is a great way to sharpen your skills in <strong>recursion</strong> and <strong>backtracking</strong>. In this article, I’ll show you how to solve a Sudoku puzzle using C++ from scratch.</p><h3>Understanding the Problem</h3><p>The standard version of Sudoku consists of a 9×9 square grid containing 81 <strong>cells</strong>. The grid is subdivided into nine 3×3 <strong>blocks</strong>. Some of the 81 cells are filled in with numbers from the set {1,2,3,4,5,6,7,8,9}. These filled-in cells are called <strong>givens</strong>. The goal is to fill in the whole grid using the nine digits so that each row, each column, and each block contains each number exactly once. We call this constraint on the rows, columns, and blocks the <strong>One Rule</strong>.</p><p>A Sudoku of <strong>rank n</strong> is an <strong>n^2 × n^2</strong> square grid, subdivided into <strong>n^2</strong> blocks, each of size <strong>n × n</strong>. The numbers used to fill the grid in are <strong>1, 2, 3, …, n^2</strong>, and the <strong>One Rule </strong>still applies.</p><p>Here is an example of a Sudoku puzzle and its solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*EWKBUSEdNMrZqy8N.JPG" /></figure><h3>Solving Strategy (The Math Behind Sudoku)</h3><p>When one hears that no math is required to solve Sudoku, what is really meant is that no arithmetic is required. The puzzle does not depend on the fact that the nine placeholders used are the digits from 1 to 9. Any nine symbols would serve just as well to create and solve the puzzles. In fact, mathematical thinking in the form of logical deduction is very useful in solving Sudokus.</p><p>The most basic strategy to solve a Sudoku puzzle is to first write down, in each empty cell, all possible entries that will not contradict the One Rule with respect to the given cells. If a cell ends up having only one possible entry, it is a <strong>“forced”</strong> entry that you should fill in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ODXvr4-qKGiMipoVTCKVQ.png" /></figure><p>Another way to proceed is to pick a number and a row, column, or block. Note all the cells in the row, column, or block in which the number can be placed without violating the One Rule. If the digit can only be placed in one cell in the neighborhood, you should fill that cell in. Once you’ve done this, the chosen number can be eliminated from being a possibility for any other cell in the neighborhood.</p><p>These two strategies are usually not enough to completely fill in a Sudoku grid. You often need more complicated analysis methods to make progress, and sometimes you need to <strong>make a guess</strong> and proceed, <strong>backtracking</strong> if the guess results in a conflict. One more complicated strategy is to look at pairs or triples of cells within a row, column, or block. You might find that a pair of cells has only two options of entries, but don’t know which goes where. What you can still gain from this observation is that those pair of numbers cannot occur anywhere else in the neighborhood. This will decrease the number of possibilities for the other cells in the neighborhood and help you get closer to a solution. Similarly, a triple of cells having only three possibilities of entries between them will eliminate these entries in all other cells in a neighborhood of this triple.</p><p>If no entries are forced, try to pick a box with the fewest number of possibilities and pick one of them. Continue playing, using the strategies above and any other ones you discover. If you reach a contradiction (a repeated digit in a row, column, or block), you should retrace your steps and undo what you’ve done until you have no contradiction.</p><h3>Approach: Backtracking</h3><p>Backtracking is a powerful problem-solving technique that involves exploring all possible solutions and discarding those that don’t lead to a valid solution. Here’s how we can apply it to Sudoku:</p><ol><li><strong>Find an Empty Cell:</strong></li></ol><ul><li>Iterate through the grid to find an empty cell (represented by a dot ‘.’ in the code or ‘0’).</li></ul><pre>for (int row = 0; row &lt; 9; row++)<br>        for (int col = 0; col &lt; 9; col++)<br>            if (board[row][col] == &#39;.&#39;) {<br>                //the empty cell</pre><p>2. <strong>Try Possible Numbers:</strong></p><ul><li>For each possible number (1 to 9), check if it’s valid for the current cell:</li><li>Ensure the number doesn’t exist in the same <strong>row</strong>,<strong> column</strong>, or <strong>subgrid(3 x 3)</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/0*e3ePX-jMHmGp_VuT.png" /></figure><pre>bool isValidPos(vector&lt;vector&lt;char&gt; &gt; &amp;board, int row, int col, char num) {<br>    for (int i = 0; i &lt; 9; i++) {<br>        if (board[row][i] == num) // is it valid in this col ??<br>            return false;<br>        if (board[i][col] == num) // is it valid in this row ??<br>            return false;<br>        if (board[row / 3 * 3 + i / 3][col / 3 * 3 + i % 3] == num)<br>            return false; // is it valid in this 3x3 grid ?? <br>    }<br>    return true;<br>}</pre><p>Checks if a given number is valid for a specific cell by verifying it doesn’t conflict with the rules of Sudoku.</p><ul><li>If the number is valid, place it in the cell and recursively call the sudokuSolve function to solve the rest of the puzzle.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*yJWoCqg9LdT4djJKOrD-xA.gif" /></figure><pre>bool sudokuSolve(vector&lt;vector&lt;char&gt; &gt; &amp;board) {<br>    for (int row = 0; row &lt; 9; row++)<br>        for (int col = 0; col &lt; 9; col++)<br>            if (board[row][col] == &#39;.&#39;) {<br>                for (char num = &#39;1&#39; ; num &lt;= &#39;9&#39;; num++) {<br>                    if (isValidPos(board, row, col, num)) {<br>                        board[row][col] = num;<br>                        if (sudokuSolve(board)) // recursive<br>                            return true;<br>                        board[row][col] = &#39;.&#39;;<br>                    }<br>                }<br>                return false;<br>            }<br>    return true;<br>}</pre><p>Implements the backtracking algorithm. It recursively tries different numbers for empty cells and backtracks if a dead-end is reached.</p><ol><li><em>Finds the next empty cell.</em></li></ol><p><em>2. Attempts to place each digit from </em><em>1 to </em><em>9.</em></p><p><em>3. If a digit works, it continues solving the rest of the board.</em></p><p><em>4. If a digit doesn’t work, it backtracks and tries the next.</em></p><h3>Complete Code</h3><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;unordered_set&gt;<br><br>using namespace std;<br><br>bool isValidPos(vector&lt;vector&lt;char&gt; &gt; &amp;board, int row, int col, char num) {<br>    for (int i = 0; i &lt; 9; i++) {<br>        if (board[row][i] == num)<br>            return false;<br>        if (board[i][col] == num)<br>            return false;<br>        if (board[row / 3 * 3 + i / 3][col / 3 * 3 + i % 3] == num) <br>            return false;<br>    }<br>    return true;<br>}<br><br>bool sudokuSolve(vector&lt;vector&lt;char&gt; &gt; &amp;board) {<br>    for (int row = 0; row &lt; 9; row++)<br>        for (int col = 0; col &lt; 9; col++)<br>            if (board[row][col] == &#39;.&#39;) {<br>                for (char num = &#39;1&#39; ; num &lt;= &#39;9&#39;; num++) {<br>                    if (isValidPos(board, row, col, num)) {<br>                        board[row][col] = num;<br>                        if (sudokuSolve(board))<br>                            return true;<br>                        board[row][col] = &#39;.&#39;;<br>                    }<br>                }<br>                return false;<br>            }<br>    return true;<br>}<br><br>void solveSudoku(vector&lt;vector&lt;char&gt;&gt;&amp; board) {<br>    sudokuSolve(board);<br>}<br><br>int main() {<br>    vector&lt;vector&lt;char&gt;&gt; board = {<br>        {&#39;5&#39;, &#39;3&#39;, &#39;.&#39;, &#39;.&#39;, &#39;7&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;},<br>        {&#39;6&#39;, &#39;.&#39;, &#39;.&#39;, &#39;1&#39;, &#39;9&#39;, &#39;5&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;},<br>        {&#39;.&#39;, &#39;9&#39;, &#39;8&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;6&#39;, &#39;.&#39;},<br>        {&#39;8&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;6&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;3&#39;},<br>        {&#39;4&#39;, &#39;.&#39;, &#39;.&#39;, &#39;8&#39;, &#39;.&#39;, &#39;3&#39;, &#39;.&#39;, &#39;.&#39;, &#39;1&#39;},<br>        {&#39;7&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;2&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;6&#39;},<br>        {&#39;.&#39;, &#39;6&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;2&#39;, &#39;8&#39;, &#39;.&#39;},<br>        {&#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;4&#39;, &#39;1&#39;, &#39;9&#39;, &#39;.&#39;, &#39;.&#39;, &#39;5&#39;},<br>        {&#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;8&#39;, &#39;.&#39;, &#39;.&#39;, &#39;7&#39;, &#39;9&#39;}<br>    };<br><br>    solveSudoku(board);<br><br>    for (const auto&amp; row : board) {<br>        for (char c : row) {<br>            cout &lt;&lt; c &lt;&lt; &quot; &quot;;<br>        }<br>        cout &lt;&lt; endl;<br>    }<br><br>    return 0;<br>}</pre><h3>Output</h3><p>For the given input, the output will be:</p><pre>5 3 4 6 7 8 9 1 2 <br>6 7 2 1 9 5 3 4 8 <br>1 9 8 3 4 2 5 6 7 <br>8 5 9 7 6 1 4 2 3 <br>4 2 6 8 5 3 7 9 1 <br>7 1 3 9 2 4 8 5 6 <br>9 6 1 5 3 7 2 8 4 <br>2 8 7 4 1 9 6 3 5 <br>3 4 5 2 8 6 1 7 9</pre><h3>Conclusion</h3><p>By following these steps and understanding the C++ implementation, you can effectively solve Sudoku puzzles using programming. Remember, practice makes perfect, so experiment with different Sudoku puzzles to hone your skills! also you can extend it further by optimizing the empty cell search or adding additional checks to make the solution faster. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f98c81b8ade3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Basics]]></title>
            <link>https://medium.com/@mohcin.ghalmi/computer-basics-e7b8f545cb0b?source=rss-3c9f7f4b3a26------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b8f545cb0b</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[os]]></category>
            <category><![CDATA[devlopment]]></category>
            <category><![CDATA[information-technology]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[SLEEPS]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 18:00:52 GMT</pubDate>
            <atom:updated>2024-08-28T18:00:52.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When learning to code, you’ll spend a lot of time on a computer. So, it’s important to know how to use it well. In this document, we’ll show you a resource to help you quickly learn some computer basics.</p><h3>1- What is a computer?</h3><p>A <strong>computer</strong> is an electronic device that handles <strong>information</strong>, or <strong>data</strong>. It can store, <strong>retrieve</strong>, and <strong>process</strong> data. You probably know that you can use a computer to type documents, send emails, play games, and browse the internet. You can also use it to edit or create spreadsheets, presentations, and videos.</p><h4><strong>Hardware vs. software</strong></h4><p>Before we discuss different types of computers, let’s talk about two things all computers have: hardware and software.</p><blockquote><strong>Hardware</strong> is any part of your computer that you can <strong>touch</strong>, like the keyboard or mouse. It also includes all the internal parts of the computer, which you can see in the image below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JuUa5Ze_twUH66csSUMSA.png" /></figure><blockquote><strong>Software</strong> is a set of <strong>instructions</strong> that tells the hardware <strong>what to do</strong> and <strong>how to do</strong> it. Examples of software are web browsers, games, and word processors.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxdPIVlttUlj-0OxC4h-Zw.png" /></figure><p>Everything you do on your computer uses both hardware and software. For example, you might be viewing this blog in a <strong>web browser</strong> (software) and using your <strong>mouse</strong> (hardware) to click from page to page. As you learn about different types of computers, think about the differences in their hardware. You’ll also notice that different types of computers often use different types of software.</p><h3><strong>2- What are the different types of computers?</strong></h3><p>When people think of a <strong>computer</strong>, they usually think of a <strong>desktop</strong> or <strong>laptop</strong>. But computers come in many forms and sizes and are used for many different tasks in our daily lives. For example, <strong>ATMs</strong>, grocery store scanners, and calculators are all types of computers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVtBOU9yu-kAILZVkNAoQw.png" /></figure><blockquote><strong>Desktop computers!</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lWEk821TKRT8V-RNxumjQ.png" /></figure><p>Many people use <strong>desktop computers </strong>at work, home, and school. Desktop computers are meant to be placed on a desk and usually have several parts: the computer case, monitor, keyboard, and mouse.</p><blockquote><strong>Laptop computers</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyY0enMAeJiOIDcEJNtd-Q.png" /></figure><p>The second type of computer you might know is a <strong>laptop</strong>. Laptops are battery-powered and <strong>more portable</strong> than desktops, so you can use them almost anywhere.</p><blockquote><strong>Tablet computers</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvwOTn7z4aes1wS44GOkCQ.png" /></figure><p><strong>Tablet computers</strong>— or <strong>tablets</strong> — are handheld computers that are even more portable than laptops. Instead of a keyboard and mouse, tablets use a <strong>touch-sensitive screen</strong> for typing and navigation. The <strong>iPad</strong> is an example of a tablet.</p><blockquote><strong>Servers</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Gvb8YFhZhWM64aG3GqlLw.png" /></figure><p>A <strong>server</strong> is a computer that gives information to other computers on a network. For example, when you use the Internet, you’re looking at something stored on a server. Many businesses also use local servers to <strong>store and share files</strong> within their organization.</p><blockquote><strong>Other types of computers</strong></blockquote><blockquote>Many of today’s electronics are <strong>specialized computers</strong>, even if we don’t think of them that way. Here are some common examples:<br> — <strong>Smartphones:</strong> These are cell phones that can do many things computers can, like browsing the Internet and playing games.<br> — <strong>Wearables:</strong> This is a term for devices like <strong>fitness trackers</strong> and <strong>smartwatches </strong>that you wear all day. They are often just called <strong>wearables</strong>.<br> — <strong>Game consoles:</strong> These are special computers used to play <strong>video games</strong> on your TV.<br> — <strong>TVs:</strong> Many TVs now have apps that let you access online content, like streaming video from the Internet directly to your TV.</blockquote><h3><strong>3- What is an operating system?</strong></h3><p>An <strong>operating system</strong> is the <strong>most important software</strong> on a computer. It manages the computer’s <strong>memory</strong>, <strong>processes</strong>, <strong>software</strong>, and <strong>hardware</strong>. It also lets you interact with the computer without needing to know how to speak the computer’s language. <strong>Without an operating system</strong>, a <strong>computer can’t work</strong>.</p><ul><li><strong>The operating system’s job</strong><br> Your computer’s <strong>operating system</strong> (<strong>OS</strong>) handles all the <strong>software</strong> and <strong>hardware</strong> on the computer. Since multiple programs often run at the same time and need to use the <strong>CPU</strong> (<strong>central processing unit</strong>), <strong>memory</strong>, and <strong>storage</strong>, the OS makes sure that each program gets the resources it needs.</li><li><strong>Types of operating systems</strong><br> Operating systems usually come <strong>already installed</strong> on any computer you buy. Most people stick with the operating system that comes with their computer, but you can upgrade or change it if you want. The three most common operating systems for personal computers are <strong>Microsoft Windows</strong>, <strong>macOS</strong>, and <strong>Linux</strong>.</li></ul><p>Modern operating systems use a graphical user interface, or <strong>GUI</strong> (pronounced <strong>“gooey”</strong>). A GUI allows you to use your mouse to click <strong>icons</strong>, <strong>buttons</strong>, and <strong>menus</strong>, and everything is shown clearly on the screen using a mix of graphics and text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVF6L1QgprreS_289ul0Fg.png" /></figure><p>Each operating system’s GUI looks and feels different, so if you switch to a new one, it might seem unfamiliar at first. However, modern operating systems are made to be <strong>user-friendly</strong> (<strong>easy to use</strong>), and most basic features work in similar ways.</p><blockquote><strong>Microsoft Windows</strong><br> Microsoft created the <strong>Windows</strong> operating system in the mid-1980s. There have been many different versions of Windows, but the most recent ones are <strong>Windows 11</strong> (released in 2021), <strong>Windows 10</strong> (2015), <strong>Windows 8</strong> (2012), <strong>Windows 7</strong> (2009), and <strong>Windows Vista</strong> (2007). Windows comes <strong>pre-loaded</strong> on most new PCs, making it the <strong>most popular operating system</strong> in the world.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8y-FX_ySAEjwuiJezop3w.png" /></figure><blockquote>macOS<br> <strong>macOS</strong> (previously called <strong>OS X</strong>) is a line of operating systems created by Apple. It comes preloaded on all Macintosh computers, or Macs. Some of the specific versions include <strong>Ventura</strong> (released in 2022), <strong>Monterey</strong> (2021), <strong>Big Sur</strong> (2020), <strong>Catalina</strong> (2019), <strong>Mojave</strong> (2018), <strong>High Sierra</strong> (2017), and <strong>Sierra</strong> (2016).<br> According to <strong>StatCounter Global Stats</strong>, macOS users account for less than <strong>10%</strong> of global operating systems — much lower than the percentage of Windows users (more than <strong>80%</strong>)<strong>. </strong>One reason for this is that Apple computers tend to be more expensive. However, many people do prefer the look and feel of macOS over Windows.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30c3oJAfY-SY7E9qOsV91w.png" /></figure><ul><li><strong>Linux</strong><br> <strong>Linux</strong> (pronounced <strong>LINN-ux</strong>) is a family of <strong>open-source</strong> operating systems, meaning anyone around the world can modify and distribute them. This is different from <strong>proprietary software</strong> like Windows, which can only be modified by the company that owns it. The advantages of Linux include that it is <strong>free</strong> and offers many different distributions — or versions — to choose from.<br> According to <strong>StatCounter Global Stats</strong>, Linux users account for less than <strong>2%</strong> of global operating systems. However, most <strong>servers</strong> run Linux because it is relatively easy to customize.</li><li><strong>Operating systems for mobile devices</strong><br> The operating systems we&#39;ve discussed so far are designed for <strong>desktop</strong> and <strong>laptop computers</strong>. <strong>Mobile devices</strong> like <strong>phones</strong>, <strong>tablets</strong>, and <strong>MP3 players</strong> are different, so they use operating systems made specifically for mobile devices. Examples of mobile operating systems include <strong>Apple iOS</strong> and <strong>Google Android</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O33ZxysNzPK0zQ1BDkTc7A.png" /></figure><p>Operating systems for mobile devices usually have fewer features than those for desktop and laptop computers and can’t run all the same software. However, you can still do many things with them, such as watch movies, browse the web, manage your calendar, and play games.</p><h3>4- What is an application?</h3><p>You might hear people refer to using a <strong>program</strong>, an <strong>application</strong>, or an <strong>app</strong>. Essentially, an app is a type of software that helps you <strong>perform specific tasks</strong>. Applications for desktop or laptop computers are often called <strong>desktop applications</strong>, while those for mobile devices are called <strong>mobile apps</strong>.</p><p>When you open an application, it runs within the <strong>operating system</strong> until you close it. Often, you’ll have more than one application open at the same time, which is called <strong>multi-tasking</strong>.</p><p>The term <strong>“app”</strong> is commonly used for <strong>applications</strong>, especially for simple ones that can be downloaded <strong>cheaply</strong> or for <strong>free</strong>. Many apps are available for <strong>mobile devices</strong> and even some <strong>TVs</strong>.</p><ul><li><strong>Desktop applications<br></strong> There are countless desktop applications, and they come in various categories. Some are <strong>very feature-rich</strong> (like <strong>Microsoft Word</strong>), while others may only perform <strong>one or two functions</strong> (like a <strong>clock</strong> or <strong>calendar app</strong>). Here are a few types of applications you might use:</li></ul><blockquote><strong>Word processors:</strong> These are programs that let you write letters, design flyers, and create various types of documents. The most well-known word processor is <strong>Microsoft Word</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nm1DPKDMuWnxo_eVwo1q3g.png" /></figure><blockquote><strong>Web browsers:</strong> A web browser is a tool you use to access the Internet. Most computers come with a web browser already installed, but you can download a different one if you prefer. Examples of web browsers include Internet Explorer, Mozilla Firefox, Google Chrome, and Safari.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98eM_nURaju51lBmVI3u-A.png" /></figure><blockquote><strong>Media players:</strong> If you want to listen to <strong>MP3s</strong> or watch <strong>movies</strong> you’ve downloaded, you’ll need a media player. Popular <strong>media players</strong> include <strong>Windows Media Player</strong> and <strong>iTunes</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3sckUpKh5r_qjMSfz9PMQ.png" /></figure><blockquote><strong>Games:</strong> You can play many types of games on your computer, from card games like <strong>Solitaire</strong> to action games like <strong>Halo</strong>. Some action games need a lot of computing power, so they might not work well on older computers.</blockquote><ul><li><strong>Mobile apps</strong><br> Desktop and laptop computers aren’t the only devices that can run applications. You can also download apps for mobile devices like <strong>smartphones</strong> and <strong>tablets</strong>. Here are a few examples of mobile apps:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3AMQ4C8U8ox3eBzI0xc-og.png" /></figure><ul><li><strong>Gmail:</strong> This app lets you view and send emails from your mobile device. It’s available for both Android and iOS.</li><li><strong>Instagram:</strong> Use Instagram to quickly share photos with friends and family. It’s available for Android and iOS.</li><li><strong>Duolingo:</strong> This app helps you learn new languages through quizzes, games, and other activities. It’s available for Android and iOS.</li><li><strong>Installing new applications</strong><br> Every computer and mobile device comes with some built-in applications, like a web browser and media player. However, you can also purchase and install new apps to add more features and functionality.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LomYv6Kqz9Yqea1uNFEZbQ.png" /></figure><h3>5- Open source vs. closed source software</h3><p>Almost every piece of computer software is created using <strong>source code</strong>, which is the detailed set of instructions that tells a program how to work. When creators release their software, they choose whether to make its code open source (freely available for anyone to view and modify) or closed source (not accessible to the public).</p><ul><li><strong>What is open source and closed source?</strong><br> With <strong>closed source software</strong> (also known as proprietary software), the public does not have access to the source code. This means people cannot view or modify the code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*J9nfhXqYXFitW99bZhoJ1Q.png" /></figure><p>With open source software, the source code is available to anyone who wants it, allowing programmers to read or modify the code if they choose. However, you don’t need to read or modify the code to use an open source product.</p><ul><li><strong>Which type is more common?</strong><br> Most apps, games, and popular software are closed source. However, there are many open source alternatives available. For example:<br> — <strong>LibreOffice:</strong> An open source alternative to Microsoft Office.<br> — <strong>Linux: </strong>An open source operating system you can use instead of Windows.<br> — <strong>Firefox:</strong> A popular open source web browser.<br> — <strong>WordPress:</strong> An open source blogging platform.</li><li>What are the pros and cons?<br> One of the biggest advantages of open source software is that it’s <strong>usually free</strong>, though some features or technical support might cost extra. Additionally, because the source code is available to everyone, the <strong>public can collaborate</strong> to fix bugs, add features, and improve performance quickly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EIEOBrnZsWaZN2iogj4Exw.png" /></figure><p>However, open source software isn’t perfect. <strong>It may not be as user-friendly</strong> as closed source software, and finding technical support can be challenging, especially for less popular programs.</p><p>Closed source software is generally more <strong>stable</strong> and <strong>focused</strong>, and customer service is usually easier to access if you need support. However, it <strong>often costs money</strong>, and if it has bugs or missing features, you’ll need to wait for the creator to fix them.</p><p>Now that you understand the difference between open and closed source software, you can choose the type that best meets your needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b8f545cb0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OPTIMIZE YOUR DEPLOYMENT WITH DOCKER CONTAINERS]]></title>
            <link>https://medium.com/@mohcin.ghalmi/optimize-your-deployment-with-docker-containers-419d5c9edb70?source=rss-3c9f7f4b3a26------2</link>
            <guid isPermaLink="false">https://medium.com/p/419d5c9edb70</guid>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[dcoker]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[SLEEPS]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 18:02:29 GMT</pubDate>
            <atom:updated>2024-03-01T16:40:38.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*baqfUx1D1UYUJbTo.jpg" /></figure><p><strong>Unleashing the Power of Docker: A Comprehensive Guide</strong></p><p>Welcome to the realm of Docker! If you’ve ever grappled with compatibility issues in your coding endeavors, Docker offers a transformative solution. This blog delves into Docker containers and their role in streamlining application deployment. Get ready to explore the benefits and possibilities of Docker!</p><p><strong>Getting Started with Docker: A Step-by-Step Guide</strong></p><p><strong><em>Part One: </em></strong>Introduction to Containers and Docker Installation In this section, we’ll cover the basics of containers, what Docker is, and how to set it up on your computer.</p><p><strong><em>Part Two: </em></strong>Running Your First Container and Creating Custom Images Next, you’ll learn how to run your very first container and make it work with Docker images from the Docker Hub. Plus, we’ll guide you through writing your own Dockerfile to create personalized Docker images.</p><p><strong><em>Part Three:</em></strong> Managing Containers with Docker Compose Finally, we’ll explore Docker Compose, a tool for managing multiple containers at once. You’ll learn how to use the <strong>docker-compose.yaml</strong> file to run several containers simultaneously, making your development process smoother and more efficient.</p><h3>Discover Containers</h3><p><strong>Part One</strong> will be your introduction to<strong> containers</strong> and Docker. But before all that, we need to go back over some important concepts:</p><ul><li>What is a <strong>virtual machine</strong>?</li><li>What is a <strong>container</strong>?</li><li><strong>Why </strong>use containers?</li></ul><blockquote>In the past, when we needed servers, we had to buy physical ones with a set quantity of CPU, RAM, or disk storage space.</blockquote><blockquote>However, we would regularly need additional power for periods of high load (e.g., popular holidays), so you’d have to buy additional servers to handle peak usage. A solution was created to respond to this problem: the <strong><em>virtual machine</em></strong>.</blockquote><h4>Understand What a Virtual Machine is :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XGPBBbLNwpgIMokw.png" /></figure><p>When you use a virtual machine (VM), you’re doing what is known as <strong><em>heavy virtualization</em></strong>. You’re actually recreating a complete system in the host system so that it has its own resources.</p><p><strong>This gives you complete isolation from the host system</strong>, but it does have a few drawbacks:</p><ul><li>❌ A virtual machine takes <strong>time</strong> to start up.</li><li>❌ A virtual machine <strong>reserves resources</strong> (CPU/RAM) on the host system.</li></ul><p>However, there are also various advantages to this solution:</p><ul><li>✅ A virtual machine is completely <strong>isolated</strong> from the host system.</li><li>✅ The resources allocated to a virtual machine are completely <strong>reserved</strong> for this VM.</li><li>✅ You can install <strong>different operating systems</strong> (Linux, Windows, etc.).</li></ul><p>Often, though, the application the VM is running doesn’t use up all of the available resources, which gave rise to a new, more lightweight virtualization system: <strong>containers</strong>.</p><h4>Understand What a Container is :</h4><p>A Linux container is a <strong>lightweight process </strong>or set of processes that are isolated from the rest of the system.</p><p>A container allows for <strong><em>lightweight virtualization</em></strong>, which means that it doesn’t virtualize the resources, it just <strong>isolates the processes</strong>. Containers therefore share resources with the host system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mMBmmdwNXhvTZhsR.png" /></figure><p>Containers like OpenVZ and LXC provide <strong>good isolation of system processes</strong>; however, the CPU, RAM, and disk resources are fully shared with the whole system. Containers share the Linux kernel, so it isn’t possible to run a Windows or BSD system.</p><p>Let’s take a look at a few advantages of containers.</p><h4>Only Reserve Necessary Resources</h4><blockquote>Another considerable way in which containers are different to virtual machines is that they <strong>don’t reserve</strong> the entirety of CPU, RAM, and disk resources attributed to the host system. This means that we can allocate 16 GB of RAM to our container, but if it only uses 2 GB, the rest will not be locked.</blockquote><h4>A Speedy Start</h4><blockquote>As containers only need isolation and not virtualization of resources, they can <strong>be started much more quickly and frequently </strong>than a virtual machine on our host servers, allowing for a slight reduction in infrastructure costs.</blockquote><h4>Increased Developer Autonomy</h4><blockquote>Beyond financial concerns, containers can also be run on developer workstations, thereby reducing the differences between the production environment and the local environment on developer workstations.</blockquote><h4>Understand Why We Use Containers :</h4><p>With containers, we can <strong>reduce costs</strong> and increase <strong>infrastructure density</strong> while improving the deployment cycle.</p><p>Containers appear in different contexts. For example, continuous integration (CI) tools used by large companies use containers. Netflix uses containers to rapidly create and isolate application tests/builds.</p><p>As containers can be started very quickly, they are often used in production to add available resources, helping to meet sizing or scalability requirements. However, they also respond to pre-production requirements. As they are lightweight and quick to start, they allow for the creation of dynamic environments, thereby responding to business needs.</p><p>You should be aware, though, that while containers and virtual machines work in a very similar way, <strong>one does not replace the other</strong>! To run a container, you always need a machine (whether that’s virtual or not). The two tools are complementary, and you’ll need to make informed decisions about how and when to use them.</p><h4>Let’s Recap!</h4><ul><li>You now know how a container differs from a virtual machine. You’ve also seen the differences between <em>heavy virtualization</em> and <em>lightweight virtualization</em>.</li><li>Containers should always be lightweight. They should be free of unnecessary content so that they can be started quickly, however they do provide less isolation. Virtual machines, on the other hand, provide very good isolation but are generally slower and much heavier.</li></ul><h3>Discover Docker</h3><p>Docker was initially created to respond to the needs of a Platform as a Service (PaaS) company called <strong>DotCloud</strong>. Later down the line, in March 2013, this company created a new structure called <strong>Docker, Inc.</strong> and made its product available as open source. That product was <strong>Docker</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*AuQwzJdq1ubU_84T.png" /></figure><p>Docker entered the world of containers with a fresh way of thinking. In the Docker vision, a container should only run <strong>a single process</strong>. This means that in a scenario where we have a LAMP stack (Linux, Apache, MySQL, PHP), we would have to create <strong>three different containers</strong>: one for Apache, one for MySQL, and one for PHP. In an LXC or OpenVZ container, on the other hand, we’d be able to run all three services in one single container.</p><h4>Understand Why we Use Docker :</h4><p>Docker responds to a significant problem in the development world.</p><blockquote>Let’s take two examples: you’ve developed your Twitter Lite project locally. Everything’s working well, but when the time comes to put it into production, you realize that you don’t know how to <strong>deploy your project</strong>. Another example: you’re in a team of 10 people where everyone is using a different OS (Ubuntu, macOS, Windows, CentOS, etc.). How do you achieve a <strong>unified and functional environment</strong> for the whole development team?</blockquote><p>Docker solves both of these problems with containers. Thanks to Docker, you’ll no longer have any issues with different environments. Your code will work everywhere!</p><h4>Use Docker in All Your Environments</h4><p>Docker is used by many companies in a variety of different ways. One of the key uses of Docker is <strong>creating local environments</strong>. It’s easier to use Docker locally when working with lots of different versions of software, as it means you avoid any compatibility issues between them.</p><p>We also find Docker in the field of CI (<strong>Continuous Integration</strong>) and CD (<strong>Continuous Delivery</strong>), where it can be used to rapidly create isolated spaces for running tests.</p><p>Watch out, though. <strong>You can’t use Docker everywhere</strong>. Say, for example, you want to persist large quantities of disk memory and ensure a high level of service continuity. Docker isn’t really designed to be used in situations like this.</p><h4>Docker: an Improved Version of LXC (LinuX Containers)</h4><p>Docker started out as a layer of the LXC container, providing various changes to make containers more flexible and portable.</p><p>Docker containers also provide the possibility of <em>stateless</em> and <em>immutable </em>infrastructure.</p><h4>Stateless and Immutable</h4><p><strong><em>Stateless</em> vs. <em>Stateful</em></strong></p><p>In the world of Docker, you’ll frequently come across the words “<strong>stateless</strong>” and “<strong>stateful</strong>,” which are two different categories of containers. It’s important to know what each category is.</p><p>A <strong>MySQL database</strong>, for example, would be <strong>stateful</strong> as it stores a state. So, if you shut down and then restart your database, you’ll find it in the same state of operation.</p><p>Stateless is the opposite: the application does not store state.<strong> HTTP</strong>, for example, is <strong>stateless</strong>. For each new HTTP request, the same series of actions will be carried out.</p><p><strong>A Container is Immutable</strong></p><p><strong>A container’s immutability </strong>is also important. A container should not store data that you need to be preserved, as it will lose it (unless you’ve persisted your data). If you do want to locally put a database in a Docker container, you need to create a volume to store your data so that it is persisted.</p><h4>Select the Right Version of Docker</h4><p>There are two different versions of Docker distributed by Docker, Inc.:</p><ul><li>Docker Desktop (Mac, Windows or Linux)</li><li>Docker Community Edition (Linux only)</li></ul><p>Docker Desktop can be installed on <a href="https://docs.docker.com/desktop/install/windows-install/">Windows</a>, <a href="https://docs.docker.com/desktop/install/mac-install/">macOS</a> and <a href="https://docs.docker.com/desktop/install/linux-install/">Linux</a> and is available via a free (Personal) or different paid Docker subscriptions (Pro, Team or Business) depending on your environment.</p><p>A comparison of the different subscriptions available is outlined <a href="https://www.docker.com/pricing/">here</a>.</p><p>If you use Linux, use the Community Edition (CE). You’ll also use this version for your servers.</p><h3>Let’s Recap!</h3><p>In this chapter, you’ve been introduced to Docker and what sets it apart from other containers:</p><ul><li>Docker containers are different from Linux containers (LXC) as they are — by definition — immutable and stateless.</li><li>Docker is used at all infrastructure levels (CI, Development, and Production).</li><li>There are a number of differences between the available versions of Docker — Free (Personal) and paid for (Pro, Team and Busine</li></ul><h3>Install Docker on Your Workstation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*nEah46a-dXuVunMR.png" /></figure><p>In the last chapter, we saw the different versions of Docker that we might find ourselves using. We’re now going to take a closer look at two of those: <strong>Docker for Mac/Docker for Windows</strong>, and <strong>Docker Community Edition</strong> (CE).</p><h4>Install Docker for Mac and Docker for Windows</h4><p><strong><em>Docker Hub</em></strong></p><p><strong>Docker Hub</strong> is a service provided by Docker, Inc. Think of it like GitHub, but specialized in <strong>storing images for Docker</strong>.</p><p>To download and use Docker (and for the purposes of the rest of this course), you’ll need to create an account on <a href="https://hub.docker.com/">Docker Hub</a>.</p><h4>Stable vs. Edge Version</h4><p>Docker, Inc. distributes two versions of Docker for Mac and for Docker Windows clients.</p><p>There is a Stable version which is updated quarterly, and an Edge version containing beta features, which is available every month.</p><p>We’re going to go for the Stable version, as it will give us a functional and stable environment while you’re learning all about Docker.</p><p>Now that you have a working Docker Hub account and we know which version we want to use, we can install Docker for Windows and Docker for Mac</p><h4>Docker for Windows</h4><p>To run Docker on Windows, there are various steps to go through. Luckily, Docker, Inc. has created a tool that makes all of these tasks automatic, meaning you can quickly have Docker up and running on Windows.</p><p>The tool created by Docker, Inc. will create a Hyper-V virtual machine on Windows, and then install Docker within this.</p><p>Head to <a href="https://docs.docker.com/desktop/install/windows-install/"><strong>this page</strong></a> and download the latest version of Docker for Windows.</p><p>Note that you’ll need to follow the setup instructions for your version of Windows 10 (Home or Pro). Make sure you follow the steps outlined in the “System Requirements” section for the version you are using.</p><p>Once the download is complete, you can run the tool and go through its installation procedure. Note that you’ll need to restart your PC.</p><p>Once the installation is complete, you’ll be prompted to connect the Docker Hub account you created earlier.</p><p>Docker for Windows is now ready to go on your PC!</p><h4>Docker for Mac</h4><p>nstalling Docker for Mac works in the same way as Docker for Windows.</p><p>You need to download the application from <a href="https://docs.docker.com/desktop/install/mac-install/"><strong>the Docker website</strong></a>.</p><h3>Install Docker Community Edition</h3><p>For the <strong>Docker Community Edition</strong> version, you don’t need to create an account on Docker Hub. However, just to keep things the same, we’re also going to create an account on Docker Hub here and log in.</p><p>We’re assuming that you’re using a Linux machine running Debian, onto which you’ll be installing Docker CE. To see how to install Docker on another Linux distribution, take a look over <a href="https://docs.docker.com/desktop/install/linux-install/">the Docker documentation</a>.</p><p>Start by updating your system and installing the prerequisites for Docker installation:</p><pre>sudo apt-get update &amp;&amp; sudo apt-get install apt-transport-https ca-certificates curl gnupg2 software-properties-common</pre><p>Once that’s done, add the Docker repository:</p><pre>curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg –dearmor -o /etc/apt/trusted.gpg.d/docker.gpg</pre><pre>sudo add-apt-repository &quot;deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable&quot;</pre><p>You can now install Docker on your machine:</p><pre>sudo apt update &amp;&amp; sudo apt-get install docker-ce docker-ce-cli containerd.io</pre><p>You now have Docker on your computer. However, you don’t have the required access to be able to talk with the daemon. To resolve this issue, use the following command:</p><pre>sudo usermod -aG docker your-user</pre><p>After restarting your user session, you’ll be able to communicate with the Docker daemon and use Docker normally.</p><p>As we said before, to keep things the same, we’re also going to connect to Docker Hub with the</p><pre>docker login</pre><p>command. Use the account that you’ve just created on Docker Hub.</p><h3>Let’s Recap!</h3><ul><li>You now know how to install the relevant version of Docker for your OS.</li><li>You also know how to connect to Docker Hub.</li></ul><h3>Run Your First Local Container</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*9cX2mcqMAnmA960w.png" /></figure><p><strong>In Part Two</strong>, it’s time to get to <strong>grips with Docker</strong>. We’ll start by looking at the <strong>command-line interface, </strong>which we use with the Docker daemon we installed earlier.</p><h3>Understand Docker Hub</h3><p>Before starting your first Docker container, think back to when you created your account on Docker Hub to download your version of Docker. This is also <strong>Docker’s official registry</strong>.</p><p>What is a registry?</p><p>A <strong>registry</strong> is a piece of software for sharing images with other people. It is a major component of the Docker ecosystem, allowing:</p><ul><li><strong>developers</strong> to <strong>distribute ready-to-use images</strong> and use a tag system to label <strong>versions</strong>.</li><li>continuous integration <strong>tools</strong> to run a suite of <strong>tests</strong> without needing anything other than Docker.</li><li><strong>automated systems</strong> to <strong>deploy these applications</strong> in your development and production environments.</li></ul><h3>Start Your First Docker Container</h3><p>To start your first container, you need to use the docker run hello-world command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ha34mCCD9YOf8pZ6BKrSTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irHpMo031P6s_mt60lcXMA.png" /></figure><blockquote>When you use this command, the <strong>Docker daemon</strong> looks to see whether the image hello-world is <strong>available locally</strong>. If not, it will go and <strong>get it from the official Docker registry</strong>.</blockquote><p>In our case, the container started up, displayed the content, and then shut down. If you want <strong>your container to stay running until you shut down the service it contains</strong>, you’ll also need to add the --detach (-d) argument. This means you don’t have to remain attached to the container, allowing you to run several containers. In the next section, we’ll see how to use the -d argument.</p><h3>Run a Nginx Server With a Docker Container</h3><p>You now know how to run a container, and you’ve understood the actions carried out by the Docker daemon when using the docker run command.</p><blockquote>Now let’s take that a bit further. We’re going to run a container that starts a Nginx server using two options: docker run -d -p 8080:80 nginx.</blockquote><p>In this command, we’ve used two options:</p><ul><li>-d to <strong>detach the container</strong> from the console’s main process. This allows you to carry on using the console while your container works on another process.</li><li>-p to define <strong>the use of ports</strong>. In our example, we’ve asked it to transfer the traffic<strong> from port 8080 to port 80 of the container</strong>. So, if you head to the addresshttp://127.0.0.1:8080, you’ll see the default Nginx page.</li></ul><p>You may also need to “get into” your Docker container to carry out actions there. To do this, you’ll use the docker exec -it &lt;container name&gt; bash command. In this command, the -it argument gives you a fully operational bash shell. Once you’re in your container, you can use the cd /usr/share/nginx/html command to go into the directory that contains the index.html file to modify its content and see the result live athttp://127.0.0.1:8080.</p><h3>Stop Your Docker Container</h3><blockquote>You’ve created a container with the --detach option, so at some point you’re going to have to stop it! To do this, we’ll use the docker stop &lt;container name&gt; command.</blockquote><blockquote>Now that your Docker container has been stopped, you can delete it with the docker rm &lt;container name&gt; command. This will destroy the container and its contents, however you can always recreate your container with the docker run command that we saw earlier.</blockquote><h3>Get an Image From Docker Hub</h3><p>You may also need to <strong>get images from Docker Hub </strong>without actually running your container. To do this, you’ll need to run the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j__rc1F05ywvizaLfWTQyg.png" /></figure><p>By running this command, you’re downloading an image directly from Docker Hub and storing it locally on your computer.</p><h3>Show All Existing Containers</h3><p>When you create containers with the --detach argument, you may need to know whether the containers are still active. To do that, you’ll need to use the docker ps command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYfCVoae9g7cRUadUDmVyQ.png" /></figure><p>You can also see all of the images locally present on your computer, with the docker images -a command.</p><h3>Understand How to Clean My System</h3><p>After having run several tests on your computer, you may need to do a bit of housework. To clean things up a bit, you can delete all of the manual resources in Docker.</p><p>Or you can let Docker do the clearing up for you! Here’s the command to use for “pruning”: docker system prune.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*pYKw4HBphbxTYcwOP1LRrg.png" /></figure><p>This will delete the following data:</p><ul><li>All Docker <strong>containers</strong> that do not have <em>running</em> status</li><li>All <strong>networks</strong> created by Docker which are not used by at least one container</li><li>All unused Docker <strong>images</strong></li><li>All <strong>caches</strong> used to create Docker images</li></ul><h3>Let’s Recap!</h3><p>You now know how to download, start, and stop containers. You’re also able to define a Docker registry, and you know why we use them.</p><p>Let’s recap the important points in this chapter:</p><ul><li>Starting a container with docker run</li><li>Using the arguments -d and -p when starting a container</li><li>Pulling an image from the registry with the docker pull command</li><li>Cleaning the system with docker system prune</li></ul><h3>Create Your First Dockerfile</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*j5khedobX9sY-9ux.png" /></figure><p>You now know how to use the Docker command interface and pull images from the Docker Hub. But how do you create your own image?</p><p><strong>In this chapter</strong>, we’re going to create a Docker image together, in which we’ll install <strong>Node.js</strong> as well as the different <strong>dependencies for our project</strong>.</p><p>We’ll start by creating <strong>a file named “Dockerfile.”</strong> In this file, you’ll find the whole <strong>recipe</strong> describing the Docker image that you need for your project.</p><p>If it helps, you can imagine the Dockerfile to be the equivalent of a <strong>package.json</strong> file in <strong>Node.js</strong>, or <strong>composer.json</strong> in <strong>PHP</strong>.</p><p>Every <strong>instruction</strong> that we give in our Dockerfile will create a new <strong><em>layer</em></strong> corresponding to each <strong>stage</strong> in the image build or the recipe.</p><p>If we stick with the cooking analogy, Dockerfile gives us our recipe for making <strong>a layer cake</strong>. So each argument creates a <strong>new “</strong>layer”<strong> for our cake</strong>. Our goal is to keep <strong>the number of layers to a minimum</strong> so that our cake is as <strong>lightweight</strong> and <strong>high-performing</strong> as possible.</p><p>The first thing you need to do is create a file named “Dockerfile,” and then within this file, define the <strong>image that you’re going to use as a base</strong>, using the FROM instruction. For our example, we’re going to use a Debian 11 base image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*LGDGZAkvf1celL-lt6Msiw.png" /></figure><p>FROM is an instruction that can only be used once in a Dockerfile.</p><p>After that, use the RUN instruction to run a command in your container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*dbYnZ0defvloCoU1CAJSKA.png" /></figure><p>You should try to keep the number of RUN instructions to a minimum, so that you keep down the number of layers you’ve created and reduce the size of your Docker image.</p><p>Then use the ADD instruction to copy or download files into the image. For our example, we’ll use it to add the <strong>sources of our local application</strong> in the /app/ image folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*cgRHPWL1sDZKo2IWi2h_wg.png" /></figure><blockquote>Next, we’ll use the WORKDIR instruction to modify the current directory. This command is equivalent to a cd in the command line. All of the following commands will be executed from the defined directory.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*KPJ5q9-fySTsuFak0XoE_A.png" /></figure><p>Then, the next RUN instruction will install the Node.js project package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*BJK0pyDTG5uRbqdJXQEv3Q.png" /></figure><p>You could’ve used ADD twice, allowing your image to add the package.json file first of all and then, once the npm install had been carried out, add a second ADD . /app/ . This would reduce the reliance between the dependencies present in the package.json file and the app code, which would save time when building the image.</p><p>Now that you have the source code and dependencies present in your container, we need to give our image some final pieces of informatio</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*PcEb5I9k5vJRq16iUaPx7g.png" /></figure><p>The EXPOSE instruction describes which port your app is listening on. The VOLUME instruction describes which directory you want to share with your host.</p><p>We don’t need the EXPOSE and VOLUME instructions for our Docker image to work properly, but adding them helps the user understand the expected listening ports and shareable volumes.</p><p>Finally, we have an instruction that should always be present, which we’ll place on the final line to make it as clear as possible: CMD. This lets our container know which command it should run once it starts up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*DBh8Eh36g2Dfn2LoyAoo6g.png" /></figure><p><strong>So that leaves us with the following for our complete Dockerfile:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8Wmyc3jVCgmCcnCmGmwVSQ.png" /></figure><h3>Create Your .dockerignore File</h3><p>Our Dockerfile is now in working order! However, there are still a few adjustments we need to make.</p><p>On Git projects, we use the .gitignore file. On Docker, it’s a similar thing. This prevents the copying of certain files and/or folders into our container when executing the ADD instruction.</p><p>At your project root (so next to your <strong>Dockerfile</strong>), create a .dockerignore file that contains the following lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*BU1NpMXgGNXqoCx-O9ikcw.png" /></figure><h3>Enjoy Optimized Docker</h3><p>One final thing: when you execute the docker build command, <strong>Docker will create a container for each instruction</strong>, and the result will be saved in a layer. The end result is a collection of layers that create a complete Docker image.</p><p>There are various advantages to this. If a layer doesn’t move between two builds, <strong>Docker will not rebuild it</strong>. Only layers located after a layer that is rebuilt will be rebuilt in turn.</p><p>This means you can create new images very quickly, without having to wait a long time for your image build.</p><p>In our example, if we add a dependency in the package.json file, and then re-run our image build, you’ll see that it’s only the layers located after the ADD package.json /app/ that are rebuilt. The Node.js installation remains in the cache.</p><h3>Run Your Personalized Container!</h3><p>You’re now ready to create your first Docker image!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*_AfCgEdGHIApGkygRoNV1w.png" /></figure><p>The -t argument is for <strong>naming your Docker image</strong>. This makes it easier to find your image later down the line.</p><p>The . is the directory where the Dockerfile is located. In our example, it’s at our project root.</p><p>You can now run your container with the docker run command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*RvxERri1oX18XlNnf__FdQ.png" /></figure><p>In the logs folder, you’ll find your application logs. Access this folder on port 2368, via the URL <a href="http://127.0.0.1:2368/">http://127.0.0.1:2368</a>.</p><h3>Let’s Recap!</h3><p>You now know how to use the following instructions to create a Docker image:</p><ul><li>FROM for setting the source image</li><li>RUN for running commands in your container</li><li>ADD for adding files to your container</li><li>WORKDIR for defining your working directory</li><li>EXPOSE for defining the default listening ports</li><li>VOLUME for defining usable volumes</li><li>CMD for defining the default command when executing your Docker containers</li></ul><h3>Use Images With Sharing on Docker Hub</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*oMnFT0GceqoWE_eW.png" /></figure><p>Now that you’ve created your own image using a Dockerfile, you want to share this image with your colleagues. To do this, you have two options:</p><ul><li>Either you share your Dockerfile with each of your colleagues in turn, and you ask them to create their own image with a docker build.</li><li>Or, you send your image on your own <strong>registry</strong>.</li></ul><p>The first option will work perfectly well, but will mean your colleagues have to <strong>recreate each of the images themselves</strong>, and that can be pretty time-consuming</p><p>You can get around this by using a <strong>Docker registry</strong>, through which you can share your image directly.</p><h3>Create Your Image on Docker Hub</h3><p>You’re going to <strong>create your Docker image on Docker Hub</strong> to make it publicly accessible to your whole community.</p><p>To get started, head to <a href="https://hub.docker.com/">https://hub.docker.com/</a> and log in with the account you created when installing Docker.</p><p>Next, click on <em>Create a Repository</em>. This will take you to a page where you type in your <strong>image name</strong> along with a description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*G66zYwFNuKP6PNKyBAxLKQ.png" /></figure><p>For the remainder of this blog, we’ll call this image ocr-docker-build. You can use the same name for your repository in Docker Hub.</p><p>Last chapter, you created a Docker image using the docker buildcommand. We’re now going to <strong>publish this image on Docker Hub</strong>. We’ll need to use a few different commands to do this.</p><blockquote>Here’s the first one: docker tag ocr-docker-build:latest YOUR_USERNAME/ocr-docker-build:latest. This will create a <strong>link</strong> between the image we’ve created ( ocr-docker-build:latest ) and the image that we want to send to Docker Hub ( YOUR_USERNAME/ocr-docker-build:latest ).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TihTUT6sttZg_cjJm15VA.png" /></figure><p>If the container you want to use doesn’t have a name, use its container <em>id</em>, which you can get from the docker build command.</p><p>You can now execute the final command required to <strong>send your image</strong> to Docker Hub: docker push YOUR_USERNAME/ocr-docker-build:latest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*TdkVRSu3OtU8J7agC8L2uQ.png" /></figure><p>If you now go back to the Docker Hub page for your image, you’ll see that there’s an initial version of it.</p><p>You can create other versions of your image, replacing :latest with another string. Watch out, though, the default image used will always be the :latest image.</p><h3>Find the Image You Want</h3><p>You may need to search for images in Docker Hub, so you should be aware that there are two different types of images:</p><ul><li><strong>Official</strong> images</li><li><strong>Personal</strong> images</li></ul><p>To date, Docker has over 150 official images that it keeps continuously updated, which you can find here on <a href="https://hub.docker.com/search/?type=image&amp;image_filter=official">Docker Hub</a>.</p><p>There are also lots of personal images <strong>created by different members of the community</strong>, some of which are even created by editors of open source solutions.</p><p>There are two ways to search for an image:</p><ul><li>The <strong>command-line</strong> option</li><li>The <strong>web interface</strong> option</li></ul><p>For option one, you’ll need to use the docker search command. So, if we’re searching for an Nginx image, it would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6IpaR2x1qg5pq1OTPx1pg.png" /></figure><p>As you can see, the Docker CLI <strong>returns a list of available Docker images</strong>.</p><p>You can carry out the same action via Docker Hub. If we’re searching for an image there, <a href="https://hub.docker.com/search?q=nginx&amp;type=image">here’s the search URL</a>. Here again, we’ll find a <strong>list of images</strong> along with the filters required to <strong>sort the images</strong> in the way you want to.</p><h3>Let’s Recap!</h3><p>You now know how to send your image to Docker Hub, and you also know how to search the Hub for images.</p><p>Remember these key commands:</p><ul><li>docker push for sending your local images to a directory</li><li>docker search for searching for an image in your directory</li></ul><h3>Discover and Install Docker Compose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*FH8QmKfqIk-NY1PL.png" /></figure><p>You’re working on a new website project with <a href="https://wordpress.org/">WordPress</a>. To <strong>simplify management of the infrastructure</strong>, you want to deploy all of your components in Docker containers. To do this, we’re going to need two containers:</p><ul><li>A <strong>MySQL</strong> container</li><li>And a <strong>WordPress</strong> container</li></ul><p>Docker Compose helps you orchestrate your containers, simplifying deployment across multiple environments. With this tool, which is written in Python, you can describe several containers within a <strong>YAML file</strong> as a <strong>set of services</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*nvsDw_U18m3cVjKV.png" /><figcaption>Docker Compose lets you manage several containers</figcaption></figure><h3>Install Docker Compose</h3><p>If you’ve used Docker for Mac or Docker for Windows, you already have the latest version of Docker Compose installed on your system.</p><p>On a Linux computer, that won’t be the case, so you’ll have to download and then install it with this command line (yes, it’s a bit long!):</p><pre>sudo curl -L https://github.com/docker/compose/releases/download/v2.12.2/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose &amp;&amp;chmod +x /usr/local/bin/docker-compose</pre><p>You can check which version of Docker Compose is installed on your computer with:</p><pre>docker-compose --version</pre><h3>Discover the Docker Compose CLI</h3><p>To use the Docker Compose CLI (Command-Line Interface), we’ll need a docker-compose.yml file, which we’ll create in the next chapter. But before we do, let’s start by taking a look at the CLI that lets us use docker-compose.yml.</p><p><strong>The Docker Compose and Docker CLIs are pretty similar</strong>. For instance, if you want to pull all images described in your docker-compose.yml file and download them from Docker Hub, you’ll run docker-compose pull. For Docker, the command would be docker pull.</p><p>The good thing about both CLIs being very similar is that you don’t have to learn two. If you know the Docker CLI, you basically know how to use the Docker Compose CLI as well!</p><p>However, we’re still going to take a look over the <strong>key commands</strong> that you might need to use and know when it comes to Docker Compose.</p><h4>Start a Docker Compose Stack</h4><p>If you want to run the creation of all of your containers, you need to run the docker-compose up command (remember, you use docker run to run a single container). You can add the -d argument to <strong>run the containers as a background task</strong>.</p><p>A <strong><em>stack</em></strong> is the name given to a set of Docker containers run using a single Docker Compose file.</p><h4>See the Status of a Docker Compose Stack</h4><p>After starting a Docker Compose stack, you’re going to have to check whether all of the containers are operating as they should and are ready to provide a service.</p><p>To do this, use the docker-compose ps command, which will return the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3uZYDiv36b3ySJjcK-GJWw.png" /></figure><h4>See the Logs for a Docker Compose Stack</h4><p>Your Docker Compose stack is now operational and all services are responding well, but you may at some point need to see your container <strong>logs</strong>. To do this, you’ll need the following command: docker-compose logs -f --tail 5</p><p>This will give you a continuous display of the logs for the different containers, limiting the display to just the first five lines.</p><p>This way, if our containers have been operating for a long time, we won’t have any waiting time or have to look at lots of logs that we’re not interested in.</p><h4>Stop a Docker Compose Stack</h4><p>If you want to <strong>stop</strong> a Docker Compose stack, you’ll need to use the docker-compose stop command. However, this will not delete the different resources created by your stack.</p><p>This means that if you run docker-compose up -d again, your whole stack will immediately return to being operational.</p><p>if you want to delete a whole Docker Compose stack, you’ll need to use the docker-compose down command, which will <strong>destroy all of the resources</strong> created.</p><h4>Check a Docker Compose Stack</h4><p>When writing a docker-compose file, there’s always the possibility that <strong>errors</strong> may arise. To avoid them as much as possible, you’ll need to use the docker-compose config command to <strong>check your file’s syntax</strong> and be sure it’ll work properly.</p><p>If we introduce an error into our stack, by replacing “image” with “images,” for instance, we’ll get the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*4a-nZX2Vee7tVhy6F4_HTw.png" /></figure><h3>Let’s Recap!</h3><p>You now know the key commands for using a Docker Compose stack. Here’s a recap of the most important commands:</p><ul><li>docker-compose up -d for starting all of your containers in the background</li><li>docker-compose ps for seeing the status of your whole stack</li><li>docker-compose logs -f --tail 5 for seeing the logs for your stack</li><li>docker-compose stop for stopping all of a stack’s services</li><li>docker-compose down for destroying all of a stack’s resources</li><li>docker-compose config for checking the syntax of your docker-compose.yml file</li></ul><h3>Create a Docker Compose File to Orchestrate Your Containers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*8omg1XiKxj6VTMCa.png" /></figure><h3>Create Your docker-compose.yml File</h3><p>In the last chapter, we saw how to use the command-line interface for Docker Compose. Now it’s time to learn how to create a docker-compose.yml file.</p><p>Remember, you’re working on a new website with <a href="https://wordpress.org/"><strong>WordPress</strong></a> and you want to simplify infrastructure management. The time has come for your production deployment, where all of the components are in Docker containers. For this, you’re going to need several components:</p><ul><li>A <strong>MySQL</strong> database</li><li>The <strong>WordPress</strong> file system</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*ljvqj7SogYVG8FxL.png" /><figcaption>Our Docker Compose structure</figcaption></figure><p>Start by creating a docker-compose.yml file at your project root. In this, describe all of the resources and services required to create your POC.</p><h3>Describe Your First Service: db</h3><h4>Define the Version of Docker Compose</h4><p>A docker-compose.yml file always starts with the following information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*Y5FB8T-cxHkl_SDu2IS_jw.png" /></figure><p>The version argument tells Docker Compose which <strong>version</strong> we want to use. Here we’re using version three, which is currently the most widely-used version.</p><h4>Declare the First Service and Its Image</h4><p>We’re now going to declare our first service, which will create our WordPress stack!</p><p>All of the containers to be created should be defined under the services argument. Each container should start with a unique name. For our example, our first container will be called db.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*XCI0ZEYHzaWF6q_pX6RwJw.png" /></figure><p>Next, you need to <strong>describe your container</strong>. Here, we’re using the image argument which defines the Docker image that we want to use.</p><p>We could also have used the build argument, specifying the route to our Dockerfile. This way, when executing Docker Compose, it would have built the container via the Dockerfile before executing it.</p><h4>Define the Volume in Order to Persist Your Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*y_Iivry5MCcHH4hdBk2_ng.png" /></figure><p>Remember, earlier we saw that <strong>Docker containers are not created to run stateful services</strong>, and that a database is by definition a stateful service. However, you can use the volumes argument, which lets you store all of the contents of the /var/lib/mysql folder in a persistent disk, thereby locally storing our data on our host.</p><p>This description is present in the line db_data:/var/lib/mysql. db_data is a volume created directly by Docker which lets you write data to the host disk without specifying the exact location. You could also have used /data/mysql:/var/lib/mysql, which would have worked just as well.</p><h4>Define a Restart Policy for the Container</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*iIYUPw0nLqtdEFr822gJOA.png" /></figure><p>Since a container is, by definition, single-process, if it encounters a fatal error, it might just stop. In our example, if the MySQL server stops, it will restart automatically using the restart: always argument.</p><h4>Define Environment Variables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*moHBz00P0M6NsVUrlfcKUA.png" /></figure><p>The MySQL image provided has <strong>several environment variables</strong> that you can use. For our example, we’re going to give the container the values of different passwords and users that should exist on this base. When you want to give environment variables to a container, you should use the environment argument, just like we have done in the docker-compose.yml file above.</p><h3>Describe Your Second Service: WordPress</h3><p>In the second service, we create a container that will contain everything we need to run our website with <strong>WordPress</strong>. This allows us to introduce two additional arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*b8sRVgrg3Od_hy4WwhhVTQ.png" /></figure><p>The first argument ( depends_on ) is for creating a <strong>dependency</strong> between two containers. This means that Docker will start the db service before starting the WordPress service. We want this to happen, as WordPress depends on the database to work correctly.</p><p>The second argument ( ports ) tells Docker Compose that we want to expose a <strong>port</strong> from our host machine to our container, making it externally accessible.</p><p>Here is the <strong>docker-compose.yml</strong> file in its final version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*lys9OKpWA1uBLsLDB6IQmg.png" /></figure><h3>Run Your Docker Compose Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*fvIspB6-Z9S1n64Lr2GCWg.png" /></figure><p>When executing this command, Docker Compose starts by checking if we have the images required to run the stacks available locally. If not, it will download them from a registry, or build them via docker build.</p><p>It will then launch two containers on your system. For our example, you can see the result by opening the following URL in your browser: <a href="http://127.0.0.1:8000.">http://127.0.0.1:8000.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmUqEvRlY6j8goSkjmhxQw.png" /></figure><h3>Let’s Recap!</h3><p>You now know how to use the basic commands in Docker Compose, and create a docker-compose.yml file to manage your Docker containers.</p><p>Here’s a recap of the arguments we’ve looked at in this chapter:</p><ul><li>image for specifying the source image for the container</li><li>build for specifying the source Dockerfile to create the container image</li><li>volume for specifying the mountpoints between the host system and the containers</li><li>restart to define how the container behaves if the process is stopped</li><li>environment to define the environment variables</li><li>depends_on to state that the container depends on another container</li><li>ports to define the available ports between the host machine and the container</li></ul><p>As we conclude our Docker blog journey, you now possess a comprehensive understanding of Docker, its functionality, and how to effectively navigate and manage it</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=419d5c9edb70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LuxMancer: Mastering Light and Shadow- MINIRT: PART 7]]></title>
            <link>https://medium.com/@mohcin.ghalmi/luxmancer-mastering-light-and-shadow-minirt-part-7-e7124c1ff206?source=rss-3c9f7f4b3a26------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7124c1ff206</guid>
            <category><![CDATA[rat-race]]></category>
            <category><![CDATA[geometry]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[SLEEPS]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 12:30:03 GMT</pubDate>
            <atom:updated>2024-02-03T12:30:03.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-jzgESdxgt3MxELh.png" /></figure><h3>Collaborative Authors:</h3><p>Welcome to an exciting exploration of geometric marvels in the realms of ray tracing! In this collaborative venture by two passionate minds, <strong>RIDWANE EL FILALI </strong>and <strong>MOHCINE GHALMI</strong>, we embark on a journey to unravel the mysteries behind the calculations of fundamental shapes the <strong>triangle</strong>, <strong>Cylinder.</strong> As we delve into the intricate dance of mathematics, vectors, and graphics, our aim is to illuminate the underlying principles that power the world of ray tracing. This joint endeavor takes us through the fascinating applications of this cutting-edge technology, particularly in mapping scenarios.</p><p>We bring our unique perspectives and expertise to this project, guiding you through the complex terrain of shape calculations. Whether you’re a seasoned enthusiast or a curious learner, this blog promises to shed light on the interplay of geometry and visualization in the world of ray tracing. Join us on this collaborative exploration, where we decode the secrets behind these foundational shapes. Check out <a href="https://github.com/RIDWANE-EL-FILALI/MiniRT"><strong>RIDWANE EL FILALI’s GitHub</strong></a> for hands-on insights into ray tracing project. Engage with RIDWANE EL FILALI on <a href="https://medium.com/@ridwaneelfilali"><strong>Medium</strong></a> to dive deeper into his perspectives on this fascinating subject. <a href="https://github.com/Mohcine-Ghalmi"><strong>Mohcine Ghalmi’s GitHub Account</strong></a> you can read <a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-1-3aeced5d91ce?source=user_profile---------4----------------------------"><strong>PART1</strong></a> <a href="https://medium.com/@mohcin.ghalmi/luxmancer-mastering-light-and-shadow-minirt-part-2-67528e57b831"><strong>PART2</strong></a> <a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-3-731cb991f5cd"><strong>PART3</strong></a> <a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-4-3473e9dbbe2e"><strong>PART4</strong></a> and<strong> </strong><a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-5-e8d2c6a72bbb?source=user_profile---------1----------------------------"><strong>PART5</strong></a><strong> and </strong><a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-6-4a5b22ea50a4"><strong>PART6</strong></a><strong>.</strong></p><h3>Implementing Shapes in Ray Tracing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*y3yGmE8Osc6svuU9DUzb6Q.gif" /></figure><h4><strong>1- </strong>Ray-Cylinder Intersection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*JXCVunePsB9a_xTkMRR_Rg.png" /></figure><p>In the realm of ray tracing, determining the intersection of a ray with a cylinder involves solving geometric equations and employing vector mathematics. This process is essential for rendering realistic three-dimensional scenes. Here, we’ll delve into the mathematical intricacies behind ray-cylinder intersection.</p><p><strong>Equation of a Ray </strong>Consider a ray represented by the origin <strong>(Pa) </strong>and direction <strong>(Va) </strong>and <strong>(t)</strong> is parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*kAni0SRM8q3o6mbYPEGWhg.png" /></figure><p><strong>Equation of a Cylinder</strong> A cylinder is defined by its center <strong>(c)</strong>, axis direction (<strong>n)</strong>, radius <strong>(r)</strong>, and height <strong>(h)</strong>. The points on the surface of the cylinder can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*rbt0dsZjwTCxULKF0THklg.png" /></figure><p>Infinite cylinder along <strong>y </strong>of radius <strong>r</strong> axis has equation <strong>x2 + z2 — r2 = 0</strong>. The equation for a more general cylinder of radius <strong>r</strong> oriented along a line</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*MVMGCINLbQKPGxrPtvQmvQ.png" /></figure><p>where <strong>q = (x,y,z)</strong> is a point on the cylinder.</p><p>To find intersection points with a ray <strong>p + vt</strong>, substitute <strong>q = p + vt</strong> and solve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SwQwbdAMvnUdmxf9WTl2A.png" /></figure><p>reduces to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*Wk-fivn_5zQl4tT4UamWtg.png" /></figure><p>with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QX7-83jbJ5Ti89USHmoqQ.png" /></figure><p>where <strong>∆p = p- pa</strong></p><p>In the equations provided earlier, our objective is to identify the solutions, <strong>T1</strong> and <strong>T2</strong>, for the given equation.</p><pre>T1 = (-b + sqrt(pow(b, 2) - 4 * a * c)) / (2 * a);<br> T2 = (-b - sqrt(pow(b, 2) - 4 * a * c)) / (2 * a);</pre><p>We need to ascertain the values of <strong>A</strong>, <strong>B</strong>, and <strong>C</strong>, and if they exist, mark those solutions as potential intersections. Specifically, we are interested in solutions that are nonnegative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*3DLA6vi437GJX2bMt3JOFQ.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*NlskS28ew4jVcEkDSGkfVg.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*F_ahTXzjh9Ek2IjjOP3AvQ.png" /></figure><p>after finding <strong>T1</strong> and <strong>T2</strong> we Checks if intersections are within cylinder height.</p><pre>lst-&gt;fig.cy.dist1 = dot(lst-&gt;fig.cy.nv, vsubstr(scal_x_vec(x2[0], d), \<br>            vsubstr(lst-&gt;fig.cy.c, o)));<br> lst-&gt;fig.cy.dist2 = dot(lst-&gt;fig.cy.nv, vsubstr(scal_x_vec(x2[1], d), \<br>            vsubstr(lst-&gt;fig.cy.c, o)));<br> if (!((lst-&gt;fig.cy.dist1 &gt;= 0 &amp;&amp; lst-&gt;fig.cy.dist1 &lt;= lst-&gt;fig.cy.h \<br>     &amp;&amp; x2[0] &gt; EPSILON) || (lst-&gt;fig.cy.dist2 &gt;= 0 \<br>     &amp;&amp; lst-&gt;fig.cy.dist2 &lt;= lst-&gt;fig.cy.h &amp;&amp; x2[1] &gt; EPSILON)))<br>  return (INFINITY);</pre><p>Updates the normal vector based on the intersection point. and Returns closest intersection distance.</p><pre>*normal = calc_cy_normal(x2, o, d, lst);</pre><h4>Checks for intersections with cylinder caps (top and bottom)</h4><p>A finite cylinder with caps can be constructed as the intersection of an infinite cylinder with a slab between two parallel planes, which are perpendicular to the axis.</p><p>To intersect a ray with a cylinder with caps:</p><p>■ intersect with the infinite cylidner</p><p>■ check if the intersection is between the planes</p><p>■ intersect with each plane (check the <a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-6-4a5b22ea50a4"><strong>plan intersection</strong></a>)</p><p>■ determine if the intersections are inside caps</p><p>■ out of all intersections choose the on with minimal t</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*Gk7ZU0Uc1RiRBH38GPFpRQ.png" /></figure><p>cap centers at <strong>p1</strong> and <strong>p2</strong>, radius <strong>r</strong>.</p><p>Infinite cylinder equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*M1xh93PL9ZT1Ff7emFWNgQ.png" /></figure><p>The finite cylinder (without caps) is described by equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXjztgWUtaAKB2bsVy17Aw.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*YCAbSFJGU63Kl6DDTbmDPw.png" /></figure><p>The equations for caps are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLMLbFFkqf79HTa7_M-b_w.png" /></figure><p>Compute t3 and t4, the parameter values for which the ray intersects the upper and lower planes of the caps. If these intersections exists, mark as intersection candidates those that are nonegative</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UGYy7hG6EN5ttCT6ggCEA.png" /></figure><p>In the set of candidates, pick the one with min. t</p><p>t3 and t4</p><pre>id1 = solve_plane(o, d, lst-&gt;fig.cy.c, lst-&gt;fig.cy.nv);<br> id2 = solve_plane(o, d, c2, lst-&gt;fig.cy.nv);</pre><p>and the distance for the intersection to take the lower intersection:</p><pre>ip1 = vadd(o, scal_x_vec(id1, d));<br>  ip2 = vadd(o, scal_x_vec(id2, d));</pre><p>at the end we compare the side intersections and the caps so we take the lower value to render.</p><h4>2- Ray-Triangle Intersection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*NS645GCiyNgryGhU.png" /></figure><p>In this handout, we explore the steps needed to compute the intersection of a ray with a triangle, and then to compute the barycentric coordinates of that intersection. First, we consider the geometry of such an intersection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*Oygso79IlHZOot3h69Wt3Q.png" /></figure><p>where a ray with origin P and direction d intersects a triangle defined by its vertices, A, B, and C at intersection point Q. The square region diagrammatically surrounding triangle ABC represents the supporting plane of the triangle, i.e., the plane that the triangle lies on.</p><p>To perform ray-triangle intersection, we must perform two steps:</p><p>1. Determine the point of intersection, Q.</p><p>2. Determine if Q lies inside of triangle ABC.</p><p>Finally, we’ll compute the barycentric coordinates of Q with respect to ABC.</p><h4><strong>Determining Q</strong></h4><p>Determining the point of intersection Q in turn requires us to take two more steps:</p><ol><li>Determine the equation of the supporting plane for triangle ABC.</li><li>Intersect the ray with the supporting plane.</li></ol><p>We’ll handle these steps in reverse order.</p><h4><strong>Ray-plane intersection</strong></h4><p>you can check the plan intersection in <a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-6-4a5b22ea50a4">PART6</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*QG4UaGiH_7FAmosjai6jkg.png" /></figure><pre> id = solve_plane(o, d, lst-&gt;fig.tr.p1, lst-&gt;normal);</pre><h4><strong>Solving for the supporting plane</strong></h4><p>To intersect with a triangle, we need to solve for the equation of its supporting plane. As noted above, we need only solve for the normal n to the plane and the coefficient d. The figure below illustrates how we might solve for the normal using cross products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*temINCMlrcusT93hBXCXKA.png" /></figure><p>In particular, we can construct the vectors B-A and C-A and compute their normalized cross product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*UzzYLjZcpnwMQSf_dDcIAg.png" /></figure><p>[Strictly speaking, n does not need to be normalized (i.e., of unit length) in order for ray-plane and ray-triangle intersection to work; however, for shading purposes, a normalized normal is necessary anyway, so we present the normalized result.]</p><p>Earlier we stated the plane equation as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*lbllv8QJpHDmS1_eoyIA3w.png" /></figure><p>Any x that satisfies this equation must lie on the plane. Thus, if we pick a point that lies on the plane, and plug it into the equation, then the equation must be satisfied. Clearly, the vertices of the triangle lie on the supporting plane, so we just need to pick one — any one — of them. We’ll pick A. Now we find that, simply:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*5ZrbUtPgFN775DuW-oFD0A.png" /></figure><pre> ip = vadd(o, scal_x_vec(id, d));</pre><p>At this point, we have now computed all the coefficients needed to describe the supporting plane of the triangle and can go ahead and compute the intersection Q.</p><h4><strong>Triangle inside-outside</strong></h4><p>Now we’ve got the situation where we have a triangle ABC and an intersection point Q, but we don’t know if Q actually lies inside the triangle. To determine this, we need to perform an “inside-outside” test. In particular, Q lies inside of triangle ABC if it lies on the inside of all of the lines determined by edges AB, BC, and CA. Below, on the left, we see that Q satisfies this requirement. On the right, we see that Q is inside of edges CA and BC, but not AB, and is therefore outside the triangle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*U29VV5EVxV-Wa2p2bDenFg.png" /></figure><p>We can now use cross products to determine which side of each edge Q is on. Consider the edge AB. If we form the vectors B-A and Q-A, then their cross product should point in the same direction as the normal. In other words, Q is on the inside of AB if:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*e6QwnhPDrATHNwKMwKRs6g.png" /></figure><p>The figure below, on the left, illustrates this idea for the two cases where Q is inside and outside of the edge AB. In the second case, the cross product will point in the opposite direction of the normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*gaiyFCgErK9XLlQLUnWlMA.png" /></figure><p>We can develop similar conditions for the other edges. As a result, Q is inside of ABC if all of the following conditions are met simultaneously</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*Ob8Anz8CxFqOqZ4RDr9_wA.png" /></figure><pre>if (p_is_outside(lst-&gt;fig.tr.p1, lst-&gt;fig.tr.p2, lst-&gt;fig.tr.p3, ip))<br>  return (INFINITY);<br> if (p_is_outside(lst-&gt;fig.tr.p2, lst-&gt;fig.tr.p3, lst-&gt;fig.tr.p1, ip))<br>  return (INFINITY);<br> if (p_is_outside(lst-&gt;fig.tr.p3, lst-&gt;fig.tr.p1, lst-&gt;fig.tr.p2, ip))<br>  return (INFINITY);</pre><p>If any one of these tests fails, then Q is not inside of ABC, and the result is no intersection.</p><p>Note that we used the “greater than or equal to” comparison here. We do this in order to insure that the vertices A, B, and C and the edges AB, BC, and CA are all considered to be part of the triangle. For instance if Q were equal to A, then the first test would return a value of zero. Or, if Q were along the edge BC, then the second test would return a value of zero (parallel vectors have a cross product of zero). In both cases, however, we would want to declare Q to have intersected with the triangle; thus, the tests must have the “greater than or equal to” comparisons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7124c1ff206" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LuxMancer: Mastering Light and Shadow- MINIRT: PART 2]]></title>
            <link>https://medium.com/@mohcin.ghalmi/luxmancer-mastering-light-and-shadow-minirt-part-2-67528e57b831?source=rss-3c9f7f4b3a26------2</link>
            <guid isPermaLink="false">https://medium.com/p/67528e57b831</guid>
            <category><![CDATA[parsing]]></category>
            <category><![CDATA[rat-race]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <category><![CDATA[rendering-3d-animation]]></category>
            <dc:creator><![CDATA[SLEEPS]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 16:43:11 GMT</pubDate>
            <atom:updated>2024-01-29T14:42:43.786Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Decoding 3D Worlds: A Guide to Parsing Maps for Ray Tracing</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Lig8mDVIy1X4Ndn.png" /></figure><h4><strong>Collaborative Authors:</strong> Unraveling Map Parsing in Ray Tracing</h4><p>This blog post is a joint endeavor by <strong><em>RIDWANE EL FILALI</em></strong> and <strong><em>MOHCINE GHALMI</em></strong>, as we navigate the intricacies of map parsing within the realm of ray tracing. Together, we explore the nuanced interplay of vector mathematics, graphics, and ray tracing to shed light on the applications of this technology in mapping scenarios.</p><p>Check out <a href="https://github.com/RIDWANE-EL-FILALI/MiniRT"><strong>RIDWANE EL FILALI’s GitHub</strong></a> for more on map parsing in ray tracing.</p><p>Connect with <strong><em>RIDWANE EL FILALI</em></strong> on <a href="https://medium.com/@ridwaneelfilali"><strong>Medium</strong></a> to dive deeper into his perspectives and insights on map parsing in ray tracing.</p><ul><li><a href="https://github.com/Mohcine-Ghalmi"><strong>Mohcine Ghalmi’s GitHub Account</strong></a></li><li>you can read <strong>PART1</strong> in<strong> </strong><a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-1-3aeced5d91ce"><strong>LuxMancer: Mastering Light and Shadow- MINIRT: PART 1</strong></a></li><li>for <a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-3-731cb991f5cd"><strong>PART3</strong></a> and <a href="https://medium.com/@ridwaneelfilali/luxmancer-mastering-light-and-shadow-minirt-part-4-3473e9dbbe2e"><strong>PART4</strong></a></li></ul><h4>Introduction</h4><p>In the mesmerizing realm of computer graphics, the art of creating virtual worlds relies heavily on the ability to interpret and process intricate scene descriptions. In the context of ray tracing, where each pixel is meticulously calculated to simulate the interplay of light and materials, the foundation lies in parsing maps.</p><h4><strong>Understanding the Basics</strong></h4><p>Before delving into the parsing intricacies, let’s establish a solid understanding of the core components that constitute a scene description. In the context of ray tracing, a map typically contains details about the camera, lights, and various objects populating the virtual environment.</p><pre>R 1024 720 (resolution)<br><br>A 0.2  255,255,255 (Ambient light)<br><br>c 0,1.8,-1  0,-0.15,1 70 (Camera)<br><br>l 0,3.8,3.8  0.4   255,0,0 (Light)<br><br>pl 0,0.3,0  0,1,0  255,255,255 (Plane)<br><br>cy 0,3.2,3.8 0,1,0 1 0.3 255,255,255 (Cylinder)<br><br>sp 0,3.5,3.8 1  255,255,255 (Sphere)</pre><p><strong>1-resolution: </strong>This line is specifying the resolution of an image height and width</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*h_ZZj7Ev34KbRNYJ.jpg" /></figure><p><strong>2-Ambient lightning: </strong>non-directional light that helps illuminate a scene globally, simulating the indirect light that comes from all directions. The specified intensity and color will contribute to the overall lighting of the scene, providing a base level of illumination.</p><p><strong>3- Camera Settings:</strong> Define the viewpoint and perspective through parameters such as position, orientation, and field of view (FOV). The camera acts as the eye through which the virtual world is observed. is the source where we shoot rays</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*O7MPr0xITgskb1KX" /></figure><p><strong>4- Lights:</strong> Specify the light sources that illuminate the scene. This includes ambient lighting for overall illumination and point lights for localized brightness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*X50TsgvlPQSe5R9u.jpg" /></figure><p><strong>5- Objects:</strong> Describe the geometry present in the scene spheres, planes, cylinders, and more along with their respective attributes such as position, size, and material properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*yvLfqT6t2I-PI358" /></figure><h4>Setting the Stage:</h4><ul><li>The code begins by initializing key variables, clearing any previous scene data, and announcing its intent to parse the scene. It eagerly opens the scene file, ready to devour its contents.</li><li>The scene file is read into a string, ensuring a tasty meal for the parsing functions.</li></ul><pre>str = line(str, fd);</pre><ul><li>Dissecting the Elements The</li></ul><pre>parse_elems()</pre><p>function takes center stage, leading the systematic analysis of the scene description. It diligently checks each character in the string, seeking meaningful patterns and clues. checking new lines and commented lines.</p><p><strong>Identifying Key Components expertly distinguishes between essential scene elements, such as:</strong></p><ul><li>Resolution (R)</li><li>Ambient light (A)</li><li>Camera (C)</li><li>Various geometric shapes (cylinders, cubes, spheres, squares, planes, pyramids, triangles) For each element, it calls upon specialized parsing functions to extract and store their specific properties.</li></ul><p><strong>Enforcing Scene Integrity:</strong></p><p>It acts as a vigilant gatekeeper, ensuring the scene description contains all necessary elements for rendering. If any crucial components are missing, it raises an error, preventing a subpar rendering experience.</p><pre> parse(mlx, scene, list, &amp;str);</pre><p>Assembling the Scene As it processes each element, it meticulously constructs a comprehensive representation of the 3D scene within the program’s memory. This intricate model forms the foundation for subsequent rendering steps.</p><h4>Let’s break down the parsing logic for each relevant function:</h4><pre>void parse(t_mlx *mlx, t_scene *scene, t_obj **list, char **str)<br>{<br>    char *ret;<br>    ret = *str;<br>    if (*ret == &#39;R&#39; &amp;&amp; *(ret++))<br>        parse_res(scene, &amp;ret);<br>    else if (*ret == &#39;A&#39; &amp;&amp; *(ret++))<br>        parse_ambient_light(scene, &amp;ret);<br>    else if (*ret == &#39;c&#39; &amp;&amp; (*(ret + 1) == 32 || *(ret + 1) == 9) &amp;&amp; *(ret++))<br>        parse_camera(mlx, scene, &amp;ret);<br>    else if (*ret == &#39;c&#39; &amp;&amp; *(ret + 1) == &#39;y&#39; &amp;&amp; *(ret++) &amp;&amp; *(ret++))<br>        parse_cylinder(list, &amp;ret);<br>    else if (*ret == &#39;c&#39; &amp;&amp; *(ret + 1) == &#39;u&#39; &amp;&amp; *(ret++) &amp;&amp; *(ret++))<br>        parse_cube(list, &amp;ret);<br>    else if (*ret == &#39;l&#39; &amp;&amp; (*(ret + 1) == 32 || *(ret + 1) == 9) &amp;&amp; *(ret++))<br>        parse_light(&amp;scene, &amp;ret);<br>    else if (*ret == &#39;s&#39; &amp;&amp; *(ret + 1) == &#39;p&#39; &amp;&amp; *(ret++) &amp;&amp; *(ret++))<br>        parse_sphere(list, &amp;ret);<br>    else if (*ret == &#39;s&#39; &amp;&amp; *(ret + 1) == &#39;q&#39; &amp;&amp; *(ret++) &amp;&amp; *(ret++))<br>        parse_square(list, &amp;ret);<br>    else if (*ret == &#39;p&#39; &amp;&amp; *(ret + 1) == &#39;l&#39; &amp;&amp; *(ret++) &amp;&amp; *(ret++))<br>        parse_plane(list, &amp;ret);<br>    parse2(list , ret);<br>    *str = ret;<br>}</pre><h4>1- Resolution Parsing:</h4><pre>typedef struct  s_scene<br>{<br> int    res_init;<br> int    xres;<br> int    yres;<br> int    cam_nb;<br> t_light   *l;<br> int    al_init;<br> double   ambient_light;<br> int    al_color;<br> int    bgr;<br>}     t_scene;</pre><ul><li>Initialization:</li></ul><p>Check if resolution (R) has already been initialized <strong>(int res_init)</strong>. If yes, display an error. If not, mark resolution as initialized</p><ul><li>Parsing:</li></ul><p>Move the string pointer to the next character.<br>Parse and set the (<strong>int xres</strong>)(X Resolution) and (<strong>int yres</strong>) (Y Resolution) values.<br>Check if the parsed values are within a valid range.</p><h4>2- Ambient Light Parsing:</h4><pre>typedef struct  s_scene<br>{<br> int    res_init;<br> int    xres;<br> int    yres;<br> int    cam_nb;<br> t_light   *l;<br> int    al_init;<br> double   ambient_light;<br> int    al_color;<br> int    bgr;<br>}     t_scene;</pre><ul><li>Initialization:</li></ul><p>Check if ambient light (A) has already been initialized (<strong>int al_init</strong>). If yes, display an error. If not, mark ambient light as initialized</p><ul><li>Parsing:</li></ul><p>Move the string pointer to the next character.</p><pre>next(str);</pre><p>Parse and set the ambient light intensity (<strong>double ambient_light</strong>). <br>Check if the parsed value is within a valid range.<br>Parse and set the ambient light color (<strong>int al_color</strong>).</p><p><strong>3- Camera Parsing:</strong></p><pre>typedef struct  s_scene<br>{<br> int    res_init;<br> int    xres;<br> int    yres;<br> int    cam_nb;<br> t_light   *l;<br> int    al_init;<br> double   ambient_light;<br> int    al_color;<br> int    bgr;<br>}     t_scene;<br><br>typedef struct s_mlx<br>{<br>    void *mlx;<br>    void *win;<br>    t_cam *cam;<br>    t_cam *begin;<br>}   t_mlx;<br><br>typedef struct s_cam<br>{<br> int    idx;<br> t_point   o;<br> t_point   nv;<br> int    fov;<br> void   *img_ptr;<br> int    *px_img;<br> int    bits_per_pixel;<br> int    size_line;<br> int    endian;<br> struct s_cam *next;<br>}   t_cam;</pre><ul><li>Initialization:</li></ul><p>Create a new camera element. <br>Track the previous camera index to assign a unique index (<strong>int idx</strong>)to the new camera.</p><ul><li>Parsing:</li></ul><p>Move the string pointer to the next character.<br>Parse and set the camera position (o) (<strong>t_point o</strong>).<br>Parse and set the camera normalized view (nv) (<strong>t_point nv</strong>).<br>Parse and set the camera field of view (fov) (<strong>int fov</strong>).<br>Check if the parsed field of view is within a valid range.<br>Assign a unique index to the camera. Update the camera list.</p><pre>typedef struct  s_scene<br>{<br> int    res_init;<br> int    xres;<br> int    yres;<br> int    cam_nb;<br> t_light   *l;<br> int    al_init;<br> double   ambient_light;<br> int    al_color;<br> int    bgr;<br>}     t_scene;<br><br>typedef struct  s_light<br>{<br> t_point   o;<br> double   br;<br> int    color;<br> struct s_light *next;<br>}     t_light;</pre><p><strong>3- Light Parsing:</strong></p><ul><li>Initialization:</li></ul><p>TCreate a new light element. <br>Track the initial light list pointer.</p><ul><li>Parsing:</li></ul><p>Move the string pointer to the next character. <br>Parse and set the light position (o) (<strong>t_point o</strong>).<br>Parse and set the light brightness (br) (<strong>double br</strong>).<br>Check if the parsed brightness is within a valid range.<br>Parse and set the light color (<strong>int color</strong>).<br>Update the light list.</p><pre>union   u_figures<br>{<br> t_sphere sp;<br> t_plane  pl;<br> t_square sq;<br> t_cylinder cy;<br> t_triangle tr;<br>};</pre><p><strong>4- Figure Parsing:</strong></p><ul><li>Initialization:</li></ul><p>Create a new figure element.<br>Track the initial figure list pointer.</p><ul><li>Parsing:</li></ul><p>Move the string pointer to the next character.<br>Parse and set figure-specific properties (position, size, color, etc.).<br>Check if the parsed values are within valid ranges. <br>Update the figure list.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67528e57b831" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>