Code Snippets https://www.mohamedkadi.com/snippet/ Fast Coding without memorizing Wed, 25 Sep 2024 11:21:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 216119969 React vs. Flask: A Comparative Analysis of Frontend Technologies https://www.mohamedkadi.com/snippet/react-vs-flask-a-comparative-analysis-of-frontend-technologies/ https://www.mohamedkadi.com/snippet/react-vs-flask-a-comparative-analysis-of-frontend-technologies/#respond Sun, 30 Jun 2024 10:22:13 +0000 https://www.mohamedkadi.com/snippet/?p=159 React vs. Flask: A Comparative Analysis of Frontend Technologie In the rapidly evolving landscape of web development, choosing the right tools is crucial. For frontend developers, the choice often boils down to selecting frameworks and libraries that not only meet the project requirements but also align with their personal preferences and the team’s tech stack. […]

The post React vs. Flask: A Comparative Analysis of Frontend Technologies appeared first on Code Snippets.

]]>
  • React vs. Flask: A Comparative Analysis of Frontend Technologie
  • In the rapidly evolving landscape of web development, choosing the right tools is crucial. For frontend developers, the choice often boils down to selecting frameworks and libraries that not only meet the project requirements but also align with their personal preferences and the team’s tech stack. In this article, I’ll compare two powerful technologies: React and Flask, shedding light on their strengths, weaknesses, and ideal use case

    React: The Frontend Powerhouse

    Overview

    React, developed by Facebook, is a popular JavaScript library for building user interfaces, particularly single-page applications (SPAs). Its component-based architecture and virtual DOM make it efficient and easy to manage.

    Key Features

    1. **Component-Based Architecture**: React promotes the creation of reusable UI components, which can be easily managed and combined to form complex interfaces.

    2. Virtual DOM: React uses a virtual DOM to efficiently update and render components, enhancing performance.

    3. Strong Ecosystem: With a rich ecosystem of tools and libraries, React integrates seamlessly with various other technologies, making it a versatile choice for frontend development.

    Why React?

    In the HNG Internship, React is a staple technology. As I dive deeper into React during my internship, I anticipate leveraging its powerful features to build dynamic, responsive user interfaces. The emphasis on component reusability will allow me to create scalable applications, a skill highly valued in the industry. Having graduated from the ALX program with a focus on frontend development and React, I feel well-prepared to tackle the challenges ahead.

    Flask: The Lightweight Contender

    Overview

    Flask is a micro web framework for Python, designed for simplicity and ease of use. It’s often chosen for smaller applications but can be scaled up for larger projects with the help of extensions.

    Key Features

    1. Minimalist Design: Flask follows a minimalistic approach, providing the essentials out of the box while allowing developers to add additional functionality via extensions.

    2. **Flexibility**: With no rigid directory structure, Flask offers flexibility in how you organize your code, making it adaptable to various project needs.

    3. **Integration with Python**: Flask seamlessly integrates with Python, allowing developers to leverage Python’s robust libraries and tools.

    Why Flask?

    Flask is an excellent choice for projects where simplicity and flexibility are key. It’s particularly useful for developers who are comfortable with Python and need a lightweight framework for quick development. Its minimalist nature ensures that you only use what you need, avoiding unnecessary bloat.

    ### Contrasting React and Flask

    While React and Flask serve different purposes, comparing them provides insights into their respective strengths:

    1. Use Case:
    – React is primarily a frontend library for building user interfaces.
    – Flask is a backend framework ideal for creating web applications and APIs.

    2. **Learning Curve**:
    – React has a steeper learning curve due to its component-based architecture and state management.
    – Flask is easier to learn, especially for those already familiar with Python.

    3. **Community and Ecosystem**:
    – React boasts a vast ecosystem with numerous libraries, tools, and a large community.
    – Flask has a smaller but active community, with plenty of extensions available for added functionality.

    ### My Journey with React

    As a frontend developer specializing in React, I’m excited about the opportunities the HNG Internship offers. Working with React, I aim to create intuitive, responsive interfaces that enhance user experience. The focus on hands-on projects will allow me to apply my skills in real-world scenarios, preparing me for a successful career in frontend development.

    ### Conclusion

    Choosing between React and Flask depends on the project requirements and personal preferences. React is a robust choice for building dynamic UIs, while Flask offers simplicity and flexibility for backend development. Both have their unique strengths, making them valuable tools in a developer’s toolkit.

    For more information about the HNG Internship, visit [HNG Internship](https://hng.tech/internship) and [HNG Hire](https://hng.tech/hire). These resources provide valuable insights into the program and opportunities for budding developers.

    The post React vs. Flask: A Comparative Analysis of Frontend Technologies appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/react-vs-flask-a-comparative-analysis-of-frontend-technologies/feed/ 0 159
    React Code Snippets: A Guide to Handling Lists, Arrays, and Events https://www.mohamedkadi.com/snippet/react-code-snippets/ https://www.mohamedkadi.com/snippet/react-code-snippets/#respond Thu, 28 Mar 2024 17:29:23 +0000 https://www.mohamedkadi.com/snippet/?p=132 In this article, we’ll dive into some common React code snippets that focus on handling lists, arrays, and events. Whether you’re sorting arrays, filtering objects, or managing user interactions, these snippets will provide a clear understanding of how React handles these common tasks. 1. Working with Lists & Arrays in React Assigning an Array to […]

    The post React Code Snippets: A Guide to Handling Lists, Arrays, and Events appeared first on Code Snippets.

    ]]>
    In this article, we’ll dive into some common React code snippets that focus on handling lists, arrays, and events. Whether you’re sorting arrays, filtering objects, or managing user interactions, these snippets will provide a clear understanding of how React handles these common tasks.

    1. Working with Lists & Arrays in React

    Assigning an Array to a Variable and Sorting It

    Let’s start with a basic array of programming languages:

    // Start
    
    const languages = ['C', 'Python', 'Javascript', 'Php', 'Typescript', 'Kotlin'];
    languages.sort();  // Sorts alphabetically by default
    const listItems = languages.map(language => <li>{language}</li>);
    
    // End

    In this example, we first declare an array of programming languages. Using the sort() method, we sort the array alphabetically. We then map over the array to generate a list of <li> elements for each language.

    2. Handling Arrays of Objects in React

    Sorting an Array of Objects

    When working with arrays of objects, you might want to sort them based on object properties. Here’s how you can do it:

      // Start
    
    const frameworks = [
      {id: 0, name: 'React', tech: 'Frontend'},
      {id: 1, name: 'Angular', tech: 'Frontend'},
      {id: 2, name: 'Vue.js', tech: 'Frontend'},
      {id: 3, name: 'NodeJS', tech: 'Backend'},
      {id: 4, name: 'Express.js', tech: 'Backend'}
    ];
    
    // Sorting by framework name in ascending order
    frameworks.sort((a, b) => a.name.localeCompare(b.name));
    
    // Sorting in descending order
    frameworks.sort((a, b) => b.name.localeCompare(a.name));
    
    // Mapping sorted objects to list items
    const objectItems = frameworks.map(framework => (
      <li key={framework.id}>
        {`${framework.name}: ${framework.tech}`}
      </li>
    ));
    
    // End

    In this example, we sort the array of objects by the name property using localeCompare, which ensures that sorting works with non-English characters too. Then we map over the sorted array to create a list of items displaying both the name and tech type (Frontend or Backend).

    3. Filtering Arrays

    Sometimes you may need to filter out specific items from an array. In this case, we’ll filter out the frontend frameworks from our array:

    // Start
    
    const frontendFrameworks = frameworks.filter(framework => framework.tech === 'Frontend');
    
    const frontendItems = frontendFrameworks.map(framework => (
      <li key={framework.id}>
        {`${framework.name}: ${framework.tech}`}
      </li>
    ));
    
    // End

    Here, the filter() method filters out frameworks where tech is "Frontend", and the result is used to display only the frontend frameworks.

    4. Default Props & PropTypes

    React components can be enhanced by specifying default props and PropTypes to ensure type checking and default behavior. Here’s a quick example:

    // Start
    
    List.propTypes = {
      category: PropTypes.string,
      items: PropTypes.arrayOf(PropTypes.shape({
        id: PropTypes.number,
        name: PropTypes.string,
        tech: PropTypes.string
      }))
    };
    
    List.defaultProps = {
      category: "category",
      items: []
    };
    // End

    In this snippet, we define PropTypes to validate the type of props passed to the List component. We also set defaultProps to give default values if none are provided.

    5. Handling Events in React

    React allows us to handle events efficiently, even with parameters or changing the DOM. Let’s look at two different use cases.

    Event with Parameter

    Here’s a simple example where we track the number of clicks on a button:

    let count = 0;
    const handleClick = (name) => {
      if(count < 3) {
        count++;
        console.log(`${name}, you clicked me ${count} times`);
      } else {
        console.log(`${name}, stop clicking me`);
      }
    };
    
    const Button = () => (
      <button onClick={() => handleClick("momo")}>Click me</button>
    );

    In this example, the handleClick function takes a name as a parameter. It tracks the number of clicks and logs a different message once the count exceeds 3.

    6. Changing Properties on Event Trigger

    In this example, we modify the button’s properties based on user interaction, and we toggle the visibility of an HTML element:

    let active = false;
    
    const handleClick = (e) => {
      if (!active) {
        e.target.textContent = "I am active";
        e.target.style.backgroundColor = "green";
        e.target.style.color = "white";
        e.target.style.padding = "10px 30px";
        active = true;
    
        document.getElementById('heading3').style.display = "none";
      } else {
        e.target.textContent = "I am deactivated";
        e.target.style.backgroundColor = "red";
        e.target.style.color = "white";
        e.target.style.padding = "10px 30px";
        active = false;
    
        document.getElementById('heading3').style.display = "block";
      }
    };

    Here, we check if a button is active or not. If it’s not active, we update its text and style. We also hide a heading element by changing its display property. When the button is clicked again, the button text and style revert, and the heading is made visible again.

    Conclusion

    React makes it easy to work with arrays, objects, and events. Sorting, filtering, and mapping arrays, along with managing event-driven updates to the UI, are key skills for any React developer. These snippets provide a solid foundation for handling these tasks in your projects.

    The post React Code Snippets: A Guide to Handling Lists, Arrays, and Events appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/react-code-snippets/feed/ 0 132
    How I Tackled Auto-Generated Files Matching Page URLs in My WordPress Site https://www.mohamedkadi.com/snippet/how-i-tackled-auto-generated-files-matching-page-urls-in-my-wordpress-site/ https://www.mohamedkadi.com/snippet/how-i-tackled-auto-generated-files-matching-page-urls-in-my-wordpress-site/#respond Wed, 24 Jan 2024 09:04:43 +0000 https://www.mohamedkadi.com/snippet/?p=125 Hey there, it’s Mohamed KADI, and today I want to share with you a challenge I faced while managing my WordPress site and how I resolved it using a simple yet effective solution. The Problem: Auto-Generated Files with Page URL Names As a web developer, maintaining a WordPress site comes with its set of challenges. […]

    The post How I Tackled Auto-Generated Files Matching Page URLs in My WordPress Site appeared first on Code Snippets.

    ]]>
    Hey there, it’s Mohamed KADI, and today I want to share with you a challenge I faced while managing my WordPress site and how I resolved it using a simple yet effective solution.

    The Problem: Auto-Generated Files with Page URL Names

    As a web developer, maintaining a WordPress site comes with its set of challenges. Recently, I encountered a significant problem – auto-generated files were affecting the accessibility of my original URLs. When these files were created, attempting to access example.com/page-name/ resulted in a “Not Found” message, impacting the overall quality of my website and causing me to lose valuable visitors.

    The Solution: A Bash Script for Silent Cleanup

    To address this issue, I crafted a bash script that silently checks and deletes files matching specific names. The script is designed to run in the background, continuously checking for these auto-generated files and cleaning them up without bothering me with notifications.

    Here’s a glimpse of the script:

    #!/bin/bash
    
    # List of files to delete
    filesToDelete=(
        "www.example.com"
        "services"
        "activities"
        "contact-us"
        "apartments"
        "gallery"
        "f-a-qs"
        "team"
    )
    
    # Get the current directory
    directory="$(dirname "$0")"
    
    while true; do
        for file in "${filesToDelete[@]}"; do
            filePath="$directory/$file"
    
            # Check if the file exists before attempting to delete
            if [ -e "$filePath" ]; then
                # Attempt to delete the file
                rm "$filePath" > /dev/null 2>&1
            fi
        done
    
        # Sleep for 5 seconds before checking again
        sleep 5
    done
    

    This script operates in the background, silently removing files with names corresponding to the URLs of specified pages.

    How to Use the Script:

    1. Adjust the Configuration: Modify the filesToDelete array to include the names of files you want to delete.
    2. Make it Executable: Ensure the script has executable permissions:
      • chmod +x yourscript.sh
        
    3. Run in Background: Execute the script and run it in the background:
      nohup bash yourscript.sh > /dev/null 2>&1 &
      

      Checking Background Processes:

      Wondering how to keep tabs on the background processes? You can use the ps command:

      ps aux | grep yourscript.sh
      

      This will display information about the running process, including the process ID (PID).

      Terminating a Background Process:

      To stop the script, find its PID using the ps command, and then terminate it:

      kill -9 PID
      

      This ensures a clean termination, allowing the script to perform necessary cleanup operations.

      In summary, this bash script provides an automated and silent solution to the challenge of auto-generated files impacting the accessibility of original URLs on your WordPress site. Feel free to adapt the script to your needs, and let me know if you have any questions or improvements! Happy coding!

    The post How I Tackled Auto-Generated Files Matching Page URLs in My WordPress Site appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/how-i-tackled-auto-generated-files-matching-page-urls-in-my-wordpress-site/feed/ 0 125
    The Journey of a URL: What Happens When You Type https://www.google.com and Press Enter? https://www.mohamedkadi.com/snippet/the-journey-of-a-url-what-happens-when-you-type-https-www-google-com-and-press-enter/ https://www.mohamedkadi.com/snippet/the-journey-of-a-url-what-happens-when-you-type-https-www-google-com-and-press-enter/#respond Wed, 20 Dec 2023 15:49:04 +0000 https://www.mohamedkadi.com/snippet/?p=118 Introduction Have you ever wondered about the intricate process that takes place when you type a URL into your browser and hit Enter? The seemingly simple act initiates a complex sequence of events that involves various components of the web stack. In this blog post, we’ll explore the journey of a URL, focusing on DNS […]

    The post The Journey of a URL: What Happens When You Type https://www.google.com and Press Enter? appeared first on Code Snippets.

    ]]>
    Introduction

    Have you ever wondered about the intricate process that takes place when you type a URL into your browser and hit Enter? The seemingly simple act initiates a complex sequence of events that involves various components of the web stack. In this blog post, we’ll explore the journey of a URL, focusing on DNS requests, TCP/IP, firewalls, HTTPS/SSL, load balancers, web servers, application servers, and databases.

    1. DNS Request

    The journey begins with the Domain Name System (DNS). When you type “https://www.google.com” in your browser, the first step is to translate the human-readable domain name (www.google.com) into an IP address. The DNS resolver sends a request to the DNS server, which then responds with the corresponding IP address.

    2. TCP/IP Connection

    Once the IP address is obtained, the browser establishes a Transmission Control Protocol (TCP) connection with the server at that IP address. This connection ensures reliable and ordered communication between the client (your browser) and the server.

    3. Firewall

    As the data travels across the internet, it may encounter firewalls—security measures that monitor and control incoming and outgoing network traffic. The firewall ensures that only authorized communication is allowed, protecting against potential threats.

    4. HTTPS/SSL Handshake

    Security is paramount in web communication. The browser and the server engage in a handshake process to establish a secure connection using the Hypertext Transfer Protocol Secure (HTTPS) and Secure Sockets Layer (SSL). This encryption ensures that the data exchanged between the client and server is secure and cannot be easily intercepted.

    5. Load Balancer

    For large-scale websites like Google, multiple servers handle incoming requests. Load balancers distribute the incoming traffic across these servers to ensure optimal resource utilization and prevent overload on a single server. This enhances the website’s performance, scalability, and reliability.

    6. Web Server

    Upon reaching the designated server, the web server processes the request. It retrieves the requested web page or resource and sends it back to the browser through the established TCP connection. The server might also handle additional tasks such as caching and handling static content.

    7. Application Server

    In some cases, the web server forwards requests to an application server. This server executes specific code, processes dynamic content, and interacts with databases. It plays a crucial role in generating dynamic web pages tailored to the user’s request.

    8. Database

    If the requested content involves database interaction, the application server communicates with the database server to fetch or update data. The database server manages the storage and retrieval of information, ensuring the content presented to the user is current and relevant.

    Conclusion

    The journey of a URL from your browser to the desired web page involves a series of orchestrated steps, seamlessly executed by the web stack. Understanding these components—DNS requests, TCP/IP, firewalls, HTTPS/SSL, load balancers, web servers, application servers, and databases—provides valuable insight into the underlying infrastructure that powers the internet. As we navigate the digital landscape, appreciating the intricacies of this process enhances our understanding of the technology shaping our online experiences.

    The post The Journey of a URL: What Happens When You Type https://www.google.com and Press Enter? appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/the-journey-of-a-url-what-happens-when-you-type-https-www-google-com-and-press-enter/feed/ 0 118
    A Beginner’s Guide to Getting System Information on Linux https://www.mohamedkadi.com/snippet/a-beginners-guide-to-getting-system-information-on-linux/ https://www.mohamedkadi.com/snippet/a-beginners-guide-to-getting-system-information-on-linux/#respond Thu, 02 Nov 2023 14:02:35 +0000 https://www.mohamedkadi.com/snippet/?p=113 If you’re new to Linux, you might find it helpful to know how to check various details about your system. From the kernel version to memory usage, Linux offers a range of simple commands to help you gather key information. Whether you’re troubleshooting or just getting to know your machine better, these commands can be […]

    The post A Beginner’s Guide to Getting System Information on Linux appeared first on Code Snippets.

    ]]>
    If you’re new to Linux, you might find it helpful to know how to check various details about your system. From the kernel version to memory usage, Linux offers a range of simple commands to help you gather key information. Whether you’re troubleshooting or just getting to know your machine better, these commands can be quite handy.

    Here’s a list of the most useful Linux commands to get system information, with a brief explanation of what each does:

    1. uname -a: Get Basic System Information

    This command gives you an overview of your system’s core details, including the kernel name, version, and other basic info like the machine hardware name and processor type. Think of it as a quick snapshot of your Linux environment.

    uname -a

    2. lsb_release -a: Find Out Your Linux Distribution

    Want to know which Linux distribution you’re running? This command will tell you! It provides specifics like the distributor ID, description, release number, and codename of the distribution.

    lsb_release -a

    3. hostname: Display Your System’s Hostname

    This is a simple command to show the name of your system on the network. It’s helpful for identifying your machine when working in multi-computer environments.

    hostname

    4. cat /etc/os-release: Check Operating System Details

    For a more detailed breakdown of your operating system, this command digs deeper into specifics like the OS name, version, and the system’s overall release info.

    cat /etc/os-release

    5. cat /proc/version: Get Your Kernel Version

    If you’re looking to find out the version of your Linux kernel, this is the command to use. It displays the kernel version along with additional build information.

    cat /proc/version

    6. lsblk and df -h: Disk and Filesystem Information

    To get an overview of your disk and filesystem usage, these two commands are key.

    • lsblk shows you all available block devices on your system in a tree structure.
    • df -h gives a more human-readable format of your file system usage, showing which drives are mounted and how much space is available.
    lsblk
    df -h

    7. free -h: Check Your Memory Usage

    This command is great for checking how much memory (RAM) your system is using. The -h flag makes the output more readable by showing values in GB/MB instead of bytes.

    free -h

    8. lscpu: Get CPU Information

    Want to know more about your processor? lscpu will give you details about the architecture, cores, threads, and more.

    lscpu

    9. lspci: List PCI Devices

    This command provides a list of all PCI (Peripheral Component Interconnect) devices, like graphics cards and network adapters, attached to your system.

    lspci

    10. lsusb: List USB Devices

    To see all the USB devices connected to your system, use lsusb. This is particularly helpful when troubleshooting issues with USB peripherals like keyboards, printers, or external drives.

    lsusb

    11. ifconfig or ip a: View Network Interface Information

    Both ifconfig and ip a commands allow you to view details about your network interfaces, including IP addresses, MAC addresses, and status. While ifconfig is more traditional, ip a is the more modern option.

    ifconfig
    # or
    ip a

    12. ls /etc/*-release: View Release Information Files

    For a quick look at release-related files on your system, this command lists relevant files that contain important OS version details.

    ls /etc/*-release

    Conclusion

    These Linux commands offer a quick and easy way to gather essential information about your system. Whether you’re a beginner just getting comfortable with the terminal or need to troubleshoot system issues, knowing these commands can save you time and effort.

    So, fire up your terminal and give them a try!

    The post A Beginner’s Guide to Getting System Information on Linux appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/a-beginners-guide-to-getting-system-information-on-linux/feed/ 0 113
    Mastering File Permissions in Linux: A Comprehensive Guide https://www.mohamedkadi.com/snippet/mastering-file-permissions-in-linux-a-comprehensive-guide/ https://www.mohamedkadi.com/snippet/mastering-file-permissions-in-linux-a-comprehensive-guide/#respond Sun, 28 May 2023 19:52:29 +0000 https://www.mohamedkadi.com/snippet/?p=84 Understanding file permissions in Linux is crucial for effective system administration. In this guide, we will dive into the intricacies of file permissions and demonstrate how to manage them efficiently. Whether you’re a beginner or an experienced user, this article will help you master file permissions in Linux. Exploring File Permissions: Login with user: To […]

    The post Mastering File Permissions in Linux: A Comprehensive Guide appeared first on Code Snippets.

    ]]>
    Understanding file permissions in Linux is crucial for effective system administration. In this guide, we will dive into the intricacies of file permissions and demonstrate how to manage them efficiently. Whether you’re a beginner or an experienced user, this article will help you master file permissions in Linux.

    Exploring File Permissions:

    • Login with user:
      • To switch to a specific user, use the command: su username
    • List with Search:
      • To list files and directories and search for specific items, use the command: ls -la | grep myquery

    Understanding Permission Notations:

    • Change permission:
      • To modify file permissions, use the chmod command followed by the desired permission notation. For example:
        • chmod 777 myFile sets the file permissions to read, write, and execute for the owner, group, and others.
        • chmod u+xwr,g+xwr,o+xwr myFile grants the owner, group, and others execute, write, and read permissions respectively.
    • Permission Notations:
      • Numeric representation:
        • 1: execute
        • 2: write
        • 4: read
      • Symbolic representation:
        • x: execute
        • r: read
        • w: write
      • Owner, group, others, and all:
        • u: owner
        • g: group
        • o: others
        • a: all
      • Modifying permissions:
        • +: add
        • -: remove
        • =: assign

    Copying and Managing Permissions:

    • Copying permissions:
      • To copy permissions from one file to another, use the command: chmod --reference=myfile myfile2
    • Creating Directories with Permissions:
      • To create directories and assign permissions simultaneously, use the command: chmod -m 777 myNewDir
    • Creating Symbolic Links:
      • To create symbolic links (shortcuts) to files, use the command: ln -s /root/mydir/myfile mySymbolicLink
      • Use the -f flag to forcefully override existing links: ln -sf /root/mydir/myfile mySymbolicLink
    • Removing Symbolic Links:
      • To remove a symbolic link, use either the unlink or rm command followed by the link name. For example:
        • unlink mySymbolicLink
        • rm mySymbolicLink

    Advanced Techniques:

    • Creating Nested Directories:
      • To create a directory along with its children and grandchildren, use the command: mkdir -p granFather/father/son/grandSon
    • Changing Group:
      • To change the group ownership of a file, use the command: chgrp groupname myFile
    • Changing Owner:
      • To change the owner of a file, use the command: chown username myFile
    • Changing Owner and Group:
      • To change both the owner and group of a file simultaneously, use the command: chown username:groupname myfile

    Conclusion: Understanding and managing file permissions is essential for maintaining the security and integrity of a Linux system. With the knowledge gained from this comprehensive guide, you can confidently navigate the world of file permissions and ensure proper access control. Remember to exercise caution when modifying permissions to prevent unintended consequences. Happy file management in Linux!

    The post Mastering File Permissions in Linux: A Comprehensive Guide appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/mastering-file-permissions-in-linux-a-comprehensive-guide/feed/ 0 84
    Mastering VIM: Essential Commands and Features for Efficient Text Editing https://www.mohamedkadi.com/snippet/mastering-vim-essential-commands-and-features-for-efficient-text-editing/ https://www.mohamedkadi.com/snippet/mastering-vim-essential-commands-and-features-for-efficient-text-editing/#respond Sun, 28 May 2023 18:47:19 +0000 https://www.mohamedkadi.com/snippet/?p=72 Welcome to our code Snippets post on VIM, the powerful text editor. Uncover essential commands, navigation tips, and advanced features to boost your productivity. From mastering command mode to efficient buffer management and precise text selection with visual mode, we’ve got you covered. Explore window splitting, handling of suspended jobs, executing Linux commands, and optimizing […]

    The post Mastering VIM: Essential Commands and Features for Efficient Text Editing appeared first on Code Snippets.

    ]]>
    Welcome to our code Snippets post on VIM, the powerful text editor. Uncover essential commands, navigation tips, and advanced features to boost your productivity. From mastering command mode to efficient buffer management and precise text selection with visual mode, we’ve got you covered. Explore window splitting, handling of suspended jobs, executing Linux commands, and optimizing settings. Upgrade your text editing skills with this comprehensive VIM guide.

    Command Mode:
    Shift + a: Enters insert mode at the end of the line.w: Write (save changes)
    q: Quit
    wq: Write and quit
    q!: Quit and discard changes
    r: Replace character
    x: Delete current character
    dd: Delete entire line / cut line to be pasted if desired
    i: Enters insert mode at the current cursor location
    Ctrl + a: Enters insert mode at the end of the file
    r file: Places the content of the specified file at the cursor position
    %s/old/new/g: Find and replace (g: replace every occurrence of the given word)

    Buffers:
    e file: Opens the file in a buffer
    bp: Moves to the previous buffer
    bn: Moves to the next buffer
    bd: Deletes the current buffer
    badd: Opens a new buffer while staying in the current buffer
    enew: Opens a new buffer
    ls: Lists all open buffers
    b number (e.g., :b 1): Takes you to the buffer with the specified number

    Visual Mode:
    v: Enters visual mode
    yy: Copies the highlighted text
    d: Cuts the highlighted text
    p: Pastes the copied or cut text
    sort u: Sorts the highlighted text in alphabetical order

    Navigation:
    0: Moves to the beginning of the line
    $: Moves to the end of the line
    gg: Moves to the top of the file
    G: Moves to the bottom of the file

    Splits:
    split file-name: Splits the window horizontally
    sp: Shortcut for split
    vsplite file-name: Splits the window vertically
    vs: Shortcut for vsplit
    Ctrl + w: Switches between two files in command mode

    Jobs:
    Ctrl + z: Suspends Vim and returns to the terminal
    fg: Brings the suspended Vim process to the foreground
    fg number (e.g., fg 1, fg 2): Brings the specified suspended process to the foreground

    ! linux-command: Executes a Linux command in command mode and returns to Vim.

    Miscellaneous:
    set number: Displays line numbers on the left of each line
    set nonumber: Hides line numbers
    vim + number file name: Opens the file and moves the cursor to the specified line
    vim -o file1 file2: Opens two files with a horizontal split
    vim -O file1 file2: Opens two files with a vertical split

    The post Mastering VIM: Essential Commands and Features for Efficient Text Editing appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/mastering-vim-essential-commands-and-features-for-efficient-text-editing/feed/ 0 72
    Mastering Time Travel in Git: Returning to a Previous Commit with Finesse https://www.mohamedkadi.com/snippet/mastering-time-travel-in-git-returning-to-a-previous-commit-with-finesse/ https://www.mohamedkadi.com/snippet/mastering-time-travel-in-git-returning-to-a-previous-commit-with-finesse/#respond Tue, 23 May 2023 11:27:55 +0000 https://www.mohamedkadi.com/snippet/?p=54 Master the art of revisiting past commits with our three essential tips. Learn how to locate the desired commit, navigate your local environment, and efficiently manage branches. Harness the power of Git to streamline your development workflow and maintain control over your project’s history. Tips for Going Back to a Previous Commit in Git: Find […]

    The post Mastering Time Travel in Git: Returning to a Previous Commit with Finesse appeared first on Code Snippets.

    ]]>
    Master the art of revisiting past commits with our three essential tips. Learn how to locate the desired commit, navigate your local environment, and efficiently manage branches. Harness the power of Git to streamline your development workflow and maintain control over your project’s history.

    Tips for Going Back to a Previous Commit in Git:

    1. Find the desired commit either by using the command git log --oneline in your terminal or by reviewing the commit history on the GitHub website.
    2. Return to the selected commit on your local environment using the command git checkout <commit-id> ..
    3. Keep in mind that after going back to a previous commit, you will be in a “detached HEAD” state. Create a new branch using git checkout -b <new-branch-name> to continue working from there.
    4. If you want to abandon the changes and return to the latest commit, use git checkout <branch-name> to switch back to the desired branch.
    5. Remember that going back to a previous commit discards any changes made after that commit, so exercise caution and have backups if needed.

    More Info (After you switch to commit-id):

    You are in ‘detached HEAD‘ state. You can look around, make experimental
    changes and commit them, and you can discard any commits you make in this
    state without impacting any branches by switching back to a branch.

    If you want to create a new branch to retain commits you create, you may
    do so (now or later) by using -c with the switch command. Example:

    git switch -c <new-branch-name>

    Or undo this operation with:

    git switch -

    The post Mastering Time Travel in Git: Returning to a Previous Commit with Finesse appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/mastering-time-travel-in-git-returning-to-a-previous-commit-with-finesse/feed/ 0 54
    How to Test and Improve Your Email Deliverability with Mail-Tester.com https://www.mohamedkadi.com/snippet/mail-tester/ https://www.mohamedkadi.com/snippet/mail-tester/#respond Wed, 17 May 2023 08:56:28 +0000 https://www.mohamedkadi.com/snippet/?p=49 In the digital age, email deliverability plays a vital role in effective communication. Mail-Tester.com serves as a valuable online tool for evaluating and improving email deliverability. Step 1: Access Mail-Tester.com: Open your web browser and go to http://www.mail-tester.com/. Step 2: Sending an Email: Find the unique email address provided on the mail test page. Compose […]

    The post How to Test and Improve Your Email Deliverability with Mail-Tester.com appeared first on Code Snippets.

    ]]>
    In the digital age, email deliverability plays a vital role in effective communication. Mail-Tester.com serves as a valuable online tool for evaluating and improving email deliverability.

    Step 1: Access Mail-Tester.com:

    Step 2: Sending an Email:

    • Find the unique email address provided on the mail test page.
    • Compose a new email using your preferred email client.

    Step 3: Addressing the Test Email:

    • Enter the unique email address from Mail-Tester.com as the recipient.

    Step 4: Sending the Test Email:

    • Click “Send” in your email client to send the email to the Mail-Tester.com address.

    Step 5: Checking Your Score:

    • Return to Mail-Tester.com and click “Then check your score” after sending the test email.

    Step 6: Understanding the Evaluation:

    • Mail-Tester.com generates a detailed report and assigns a score to your email.
    • The report highlights strengths, weaknesses, and areas for improvement.

    Step 7: Improving Your Email Deliverability:

    • Utilize the report’s recommendations to enhance your email’s deliverability.
    • Optimize subject lines, formatting, and email server settings as suggested.

    By leveraging the power of Mail-Tester.com, you can confidently send engaging and effective emails, ensuring they reach the intended recipients’ inboxes. Take advantage of this valuable tool to optimize your email deliverability and enhance your communication strategy

    The post How to Test and Improve Your Email Deliverability with Mail-Tester.com appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/mail-tester/feed/ 0 49
    Mastering Git Repository Initialization: Simplifying the Process to Begin with Your Current Commit https://www.mohamedkadi.com/snippet/mastering-git-repository-initialization-simplifying-the-process-to-begin-with-your-current-commit/ https://www.mohamedkadi.com/snippet/mastering-git-repository-initialization-simplifying-the-process-to-begin-with-your-current-commit/#respond Sun, 12 Mar 2023 03:36:32 +0000 https://www.mohamedkadi.com/snippet/?p=37 In short, here are the steps to make the current commit the only (initial) commit in a Git repository: Backup your repository: Ensure you have a backup of your repository’s current state as the following steps cannot be reverted. Remove all history and configuration: Execute the following commands: Save your <github-uri> by running cat .git/config. […]

    The post Mastering Git Repository Initialization: Simplifying the Process to Begin with Your Current Commit appeared first on Code Snippets.

    ]]>

    In short, here are the steps to make the current commit the only (initial) commit in a Git repository:

    1. Backup your repository: Ensure you have a backup of your repository’s current state as the following steps cannot be reverted.
    2. Remove all history and configuration: Execute the following commands:
      • Save your <github-uri> by running cat .git/config.
      • Delete the .git directory using rm -rf .git.
    3. Reconstruct the Git repository with the current content:
      • If you haven’t set up the init.defaultBranch configuration, use git config --global init.defaultBranch <branch-name>. For example, set main as the <branch-name>.
      • Initialize a new Git repository with git init.
      • Add all files to the repository using git add ..
      • Create the initial commit with git commit -m "Initial commit".
    4. Push to GitHub:
      • Add the remote origin by executing git remote add origin <github-uri>.
      • Push the changes with git push -u --force origin main.

    Remember that this method is considered a brute-force approach and should not be used if your repository contains submodules. In such cases, it is recommended to use alternative methods like interactive rebase.

    The post Mastering Git Repository Initialization: Simplifying the Process to Begin with Your Current Commit appeared first on Code Snippets.

    ]]>
    https://www.mohamedkadi.com/snippet/mastering-git-repository-initialization-simplifying-the-process-to-begin-with-your-current-commit/feed/ 0 37