I recently ran into an interesting problem with one of my AWS EC2 instances. I had a small Ubuntu server running on an EC2 t3.micro instance with an 8 GB EBS volume. Everything was working perfectly, and I could connect to the server using SSH and my private key. I decided to increase the EBS storage from 8 GB to 16 GB. This seemed like a straightforward operation, and I didn’t expect it to cause any problems. However, shortly afterward, I discovered that I could no longer connect to my server. Initially, I suspected that increasing the disk size had somehow broken the instance. After investigating, I discovered something much simpler: I had enabled the firewall, i.e., UFW (Uncomplicated Firewall) without allowing SSH connections first. This blog post documents how I diagnosed the problem and recovered access to my original Ubuntu installation without losing data or rebuilding the EC2 instance.
1. The Initial Problem
My original EC2 configuration was:
Component
Configuration
Cloud provider
AWS
Instance type
t3.micro
Operating system
Ubuntu
Original EBS volume
8 GB
Updated EBS volume
16 GB
Connection method
SSH with private key
SSH username
ubuntu
After increasing the EBS volume size, I attempted to connect as usual:
ssh -i your-key.pem ubuntu@EC2_PUBLIC_IP
But the connection never completed. I checked the AWS EC2 console and found that:
The instance was running.
Both EC2 status checks passed (3/3).
The EBS volume had been successfully increased to 16 GB.
This suggested that the instance itself was healthy from AWS’s perspective.
2. Diagnosing the SSH Connection Problem
The next step was to enable verbose SSH logging. I ran:
ssh -vvv-i your-key.pem ubuntu@EC2_PUBLIC_IP
The output ended with:
OpenSSH_9.6p1 Ubuntu-3ubuntu13.20, OpenSSL 3.0.13
debug1: Connecting to EC2_PUBLIC_IP port 22.
debug3: set_sock_tos: setting socket options
The important detail was that SSH was hanging while attempting to establish a TCP connection to port 22. It hadn’t even reached the authentication stage. This suggested a networking or firewall problem rather than an incorrect SSH key. I also checked the AWS security group to ensure that inbound TCP traffic on port 22 was allowed from my public IP address. That was fine. But then I remembered something important. I had enabled UFW before I terminated my earlier SSH session!
3. Understanding How UFW Can Block SSH
UFW stands for Uncomplicated Firewall. It is a frontend for managing Linux firewall rules and is commonly used on Ubuntu servers. One important thing to understand is that enabling UFW without first allowing SSH can block incoming SSH connections. For example, this command enables the firewall:
sudo ufw enable
But if SSH hasn’t been allowed, incoming connections on port 22 may be blocked. The correct sequence should be:
For better security, restrict access to your own IP address:
sudo ufw allow from YOUR_PUBLIC_IP to any port 22 proto tcp
Unfortunately, I had already enabled UFW and lost SSH access. Hmmmm. I needed another way to access the server.
4. Attempting to Recover Access Through EC2 Serial Console
AWS provides a feature called EC2 Serial Console. It allows administrators to access an instance through a serial connection, independently of its normal network connectivity. I tried:
Opening the EC2 console.
Selecting my instance.
Clicking Connect.
Choosing EC2 Serial Console.
However, I received this error:
Failed to connect to your instance
SendSerialConsoleSSHPublicKey failed.
Try again later.
This was a separate problem: AWS couldn’t establish the serial console session. EC2 Serial Console requires several prerequisites:
Serial Console access must be enabled at the AWS account level.
The IAM user or role must have the required permissions.
Any applicable AWS Organizations restrictions must permit access.
The AWS Region and instance must support the feature.
I cleared all the above prerequisites. But then stumbled on another issue.
5. Understanding the Ubuntu EC2 Default Credentials
Even if the serial connection succeeds, Ubuntu may still require an operating-system username and password. A common question when using EC2 Serial Console is: What are the default Ubuntu credentials? For standard Ubuntu EC2 images: Username:
ubuntu
Password: There is no default password. Normally, Ubuntu EC2 instances use SSH key authentication rather than password authentication. This was exactly how I had configured my server. I had never created a password for the ubuntu user. Therefore, even if I managed to establish a serial console connection, I would potentially need to recover or configure a password before logging in. That is, default username is known but password was not set and I could not login. I needed a different recovery method.
6. Recovering the Instance Using a Temporary EC2 Instance
The solution was to use another EC2 instance as a recovery machine. This approach allows you to access the original Ubuntu filesystem by attaching its EBS volume to another Linux instance. The advantage is that you don’t need to reinstall Ubuntu or delete your existing data.
Step 6.1: Create a temporary Ubuntu EC2 instance
I created a new EC2 instance with the following configuration:
Setting
Value
Name
ubuntu-recovery
AMI
Ubuntu Server
Instance type
t3.micro
Availability Zone
Same as original instance
SSH access
Restricted to my public IP
The recovery instance was used only to access and repair the original disk.
Step 6.2: Stop the original instance
Before detaching its root EBS volume, I stopped the original EC2 instance. I then opened: AWS Console → EC2 → Volumes. I identified the original 16 GB EBS volume. As an additional precaution, I created an EBS snapshot before modifying anything. This provided a recovery point in case something went wrong.
Step 6.3: Detach the original EBS volume
I selected the original volume and chose: Actions → Detach volume. Once the volume was detached, I attached it to the temporary Ubuntu recovery instance. Both instances needed to be in the same Availability Zone for this attachment. I selected a secondary device name, such as /dev/sdf. An important detail: AWS device names and Linux device names don’t always match. On Nitro-based instances, an attached EBS volume commonly appears as an NVMe device.
Step 6.4: Identify the original disk
After connecting to the temporary instance through SSH, I executed:
/dev/nvme0n1: The temporary recovery instance’s own disk.
/dev/nvme1n1: The original EC2 instance’s disk.
The original root filesystem was located on:
/dev/nvme1n1p1
Step 6.5: Mount the original filesystem
I tried mounting the disk:
sudo mkdir-p /mnt/recovery
sudo mount /dev/nvme1n1p1 /mnt/recovery
I then checked the mounted filesystem:
ls /mnt/recovery
The expected output included directories such as:
bin
boot
dev
etc
home
lib
root
usr
var
This confirmed that I had successfully accessed the original Ubuntu installation.
7. Using chroot to Access the Original Ubuntu Installation
Another useful Linux feature is chroot. It allows you to change the apparent root directory of a process. In this situation, it allowed me to execute commands within the original Ubuntu filesystem while running the recovery instance. Before entering the chroot environment, I mounted the necessary virtual filesystems:
sudo mount --bind /dev /mnt/recovery/dev
sudo mount --bind /proc /mnt/recovery/proc
sudo mount --bind /sys /mnt/recovery/sys
sudo mount --bind /run /mnt/recovery/run
Then I entered the original installation:
sudo chroot /mnt/recovery
At this point, commands such as:
cat /etc/ufw/ufw.conf
were accessing the original installation’s configuration rather than the recovery instance’s configuration. This distinction is very important. Without chroot, commands must reference the original filesystem explicitly, for example:
cat /mnt/recovery/etc/ufw/ufw.conf
Note that: inside chroot, the original filesystem becomes /.
8. Disabling UFW on the Original Installation
Once inside the chroot environment, I checked the UFW configuration:
cat /etc/ufw/ufw.conf
The configuration contained:
ENABLED=yes
I have disabled it using:
ufw disable
Alternatively, I could have modified the configuration file directly:
Note: The volume should only be detached after the unmount succeeds.
10. Reattaching the Original Volume
Once the original filesystem is safely unmounted:
Open EC2 → Volumes.
Select the original 16 GB EBS volume.
Detach it from the temporary recovery instance.
Attach it to the original EC2 instance.
Restore its original root device mapping.
Start the original EC2 instance.
Note: The root device mapping is important. Make sure the volume is attached as the original root volume, not as an additional data disk.
11. Testing SSH Again
After the original instance starts, check its current public IPv4 address. If the instance was stopped and started, its public IP may have changed unless it uses an Elastic IP. That was the case. Then try:
ssh -i your-key.pem ubuntu@EC2_PUBLIC_IP
Assumption is that if UFW was the only problem and the AWS security group and networking are configured correctly, SSH should work again. That was the case and it worked! Security Note: For a public-facing server, restricting SSH to trusted IP addresses is preferable.
12. Lessons Learned
This experience taught me several useful lessons about AWS EC2 and Linux server administration. Let me mention a few here:
A) Always allow SSH before enabling UFW
This is probably the most important lesson. Before enabling UFW again, explicitly allow SSH. No, I am not talking about enabling SSH in SecurityGroup. I am talking about UFW. It is like making sure, when you leave home, you have your house keys before you slam the door behind you. To enable UFW, use:
sudo ufw allow from YOUR_PUBLIC_IP to any port 22 proto tcp
sudo ufw enable
B) EBS volume resizing and filesystem resizing are different operations
Increasing an EBS volume from 8 GB to 16 GB does not automatically mean that Ubuntu will use all the additional space.
C) AWS status checks don’t guarantee SSH connectivity
This sounds obvious but important and I overlooked it. An instance can pass all AWS status checks and still be inaccessible over SSH. Status checks primarily monitor the health of the instance and its underlying infrastructure. They don’t guarantee that your firewall, SSH daemon, or network configuration is correct.
D) Keep an alternative recovery method available
AWS provides several ways to recover an inaccessible EC2 instance:
EC2 Serial Console.
AWS Systems Manager Session Manager.
EBS volume attachment to another instance.
Knowing how to use these tools can save considerable time and, most importantly, your data! …… and may be your job too :D
E) Never modify an EBS volume without a backup
This is also somewhat obvious but important. Before making significant changes to an instance’s root disk, create an EBS snapshot. It provides an additional layer of protection if a recovery operation goes wrong.
Conclusion
What initially looked like a problem caused by increasing an EBS volume turned out to be a firewall configuration issue. The recovery process involved creating a temporary Ubuntu instance, attaching the original EBS volume, mounting the original root partition, entering the installation using chroot, and checking the UFW configuration. Even when the original operating system is inaccessible, AWS’s EBS architecture gives you a practical way to recover the filesystem and repair the installation without rebuilding the server. And, most importantly, always remember: Allow SSH before enabling firewall on a remote Ubuntu server! Read more
You can add both Google AdSense (to display advertisements and earn revenue) and Google Analytics 4 (GA4, to track website visitors and traffic) to your website hosted on GitHub Pages using the AcademicPages template. The good news is that AcademicPages is built with Jekyll, so you generally don’t need to modify the template’s core code. You can add Google’s tracking and advertising scripts through the Jekyll layout files. I’ll explain how to do both.
1. Add Google Analytics 4 (GA4)
GA4 / Google Analytics 4 Migration & Transition by Tinderpoint* Google Analytics Tracks visitors, page views, traffic sources, geographic statistics, and user engagement. Free service
Enter your website URL, for example: https://yourusername.github.io
Google will provide a Measurement ID similar to: G-XXXXXXXXXX
Keep this ID. You will need it in your website configuration.
Step 2: Find the correct AcademicPages file
In your GitHub repository, locate: _config.yml AcademicPages normally supports Google Analytics configuration through this file. Look for a section similar to: yaml
Replace G-XXXXXXXXXX with your actual Measurement ID. Save and commit the changes. Important: If your version of AcademicPages has a different analytics configuration, check its _includes/analytics/ directory and existing configuration before adding another tracking script. You don’t want Analytics installed twice.
Step 3: Verify that Analytics works
Wait a few minutes after deploying your website.
Open Google Analytics.
Navigate to Reports → Realtime.
Open your website in another browser tab.
You should see your visit in the Realtime report.
2. Add Google AdSense (to earn money from advertisements)
Monetize Your Content with Google AdSense
Earn Revenue from Ads
Google AdSense Displays advertisements on your website and can generate revenue from eligible ad impressions and clicks. Requires Google approval
Your website will need to pass Google’s review before you can display ads. Review can take a few days or, in some cases, 2–4 weeks. Google AdSense Help +1
Step 2: Add the AdSense code to AcademicPages
In your GitHub repository, look for: _includes/head/custom.html If this file doesn’t exist, create it. Paste the AdSense code provided by Google into this file. It will look similar to: HTMLWrap linesCopy codePreview
Replace the publisher ID with the one provided by Google. AcademicPages includes custom head functionality, so this is a convenient place to add the code without changing the main theme files.
Step 3: Enable automatic advertisements
Once Google approves your website:
Open your AdSense account.
Go to Ads → By site.
Select your website.
Enable Auto ads.
Save your settings.
Google can then determine suitable places to display advertisements.
Step 4: Add ads.txt
Google may ask you to publish an ads.txt file. Create a plain-text file named: ads.txt Place it in the root directory of your GitHub repository, alongside files such as index.html and _config.yml. It will contain a line similar to: text
Use the exact line supplied by AdSense. After deployment, it should be accessible at: https://yourusername.github.io/ads.txt
3. Important: A correction for AcademicPages Analytics configuration
After checking the AcademicPages repository, I found that its configuration supports google-analytics-4 as the provider. So, for the standard AcademicPages template, I recommend using this configuration in _config.yml instead of the google-gtag example I gave earlier: yaml
4. Important considerations for a website hosted in Germany
Since your website may receive visitors from Germany and other EU countries, pay attention to privacy requirements.
Add a privacy policy (Datenschutzerklärung) explaining your use of Google Analytics and AdSense.
Configure appropriate cookie consent before activating non-essential tracking technologies.
For personalized advertising to EEA visitors, Google requires a Google-certified consent management platform (CMP) integrated with the IAB Transparency and Consent Framework. Google AdSense Help +1
On one lazy Sunday, I started contemplating how smartphones (dis)connected us at home, i.e., connected the far but disconnected the near. While exploring how this could be reversed, I came to know that generative AI can offer something truly special for people looking to enhance their time together. In this article, I am going show you how you can dive into a world of creativity, learning, and fun together, with just a voice command. It is a low-cost system that can blend technology and imagination, transforming everyday moments into extraordinary memories. First, let us see a hypothetical scenario that elucidates what I meant by dis(connected).
Let us have a look at a scenario where this project could be applied to – a family evening lost in their devices.
It’s a cozy Friday evening, and the living room of the Johnson household is filled with soft, warm lighting. The smell of freshly popped popcorn drifts through the air as the TV is playing quietly in the background, almost unnoticed. Instead of gathering together to chat, watch a movie, or share stories, each family member is lost in their own digital world.
Dad, sitting on the comfy armchair, is absorbed in his tablet, scrolling through news articles and checking work emails. Despite it being the weekend, he’s still glued to his device, trying to catch up on things he missed during the week. Every now and then, he taps the screen to close a notification or reply to a message, his eyes never leaving the glowing device.
Mom, lounging on the sofa, is deep into an online shopping spree. She’s comparing prices for the latest home décor and reading reviews for a vacuum cleaner she’s been eyeing. Every so often, she pauses to flick through social media, liking photos from friends and catching up on posts. Her focus is so intense that she doesn’t even notice the cat jumping up beside her, meowing for attention.
Teenage Daughter, sitting cross-legged on the rug, is hunched over her phone, scrolling through TikTok videos. She occasionally bursts out laughing or grins at a funny meme but doesn’t engage with anyone else in the room. Her phone seems like an extension of her hand, and the world around her, including her family, fades into the background.
Young Son, in the corner, is glued to his gaming console. With headphones on, he’s navigating a virtual world, immersed in a fast-paced game where he’s battling enemies and leveling up. He occasionally mutters under his breath, reacting to the game’s challenges, but not once does he look up to see what’s happening in the room around him.
The soft hum of technology fills the room as each person stays wrapped in their digital bubble. The TV, once the centerpiece of family evenings, is now a mere background noise, occasionally offering up scenes that no one is paying attention to. The sound of the popcorn popping seems like a distant memory, drowned out by the constant ping of notifications and the quiet clicks of fingers on touchscreens. There’s a sense of disconnect, even though everyone is physically in the same room. The cozy atmosphere and shared space feel almost hollow as each person retreats into their own digital world. While the furniture is filled, the space feels eerily empty. Conversation has been replaced by the flicker of screens, and the family, in this moment, is scattered, mentally and emotionally, across the vast internet instead of together in the living room. It’s the perfect example of how technology, while useful and entertaining, can also create a subtle divide between people—turning shared family time into isolated moments, even when everyone is physically present. The living room, once a place for gathering and connection, is now more like a silent digital sanctuary for each family member. In today’s fast-paced world, finding ways to connect and bond with our loved ones is more important than ever. While technology often gets a bad rap for isolating us, there’s a shining example of how it can actually bring us closer together: the marriage of Generative AI, Your TV and Raspberry Pi to create a fun, interactive experience in the living room. Imagine this: you issue a voice command, and within seconds, a unique image generated by AI appears on your TV screen. Sounds exciting, right? Everyone in the room can be mesmerized by the stunning image and scenery generated by AI and displayed on TV. One can also see some flaws after a deeper look into the generated image. Then laughter errupts. Let’s dive into how this setup can redefine family time and spark creativity in every household. With the power of Generative AI at your fingertips, you can now create and experience personalized images at the mere sound of their voices. Using a Raspberry Pi, this project turns everyday moments into extraordinary ones, in an affordable way. The AI listens to your voice command, interprets it, and generates an image on the spot. Want to see a majestic sunset over a mountain range? Just ask! Curious about how a spaceship would look flying through a galaxy made of candy? It’s on the screen in seconds! This voice-controlled interaction is more than just a gimmick—it’s an entirely new way for people to engage with technology. Whether you’re huddled around the TV after dinner, enjoying a lazy weekend morning, hosting a family get-together, or a party, this system provides an experience that’s both fun and unique in that it offers:
A) Endless Possibilities for Creative Fun
Generative AI opens up a world of creative possibilities that can bring families together in new and exciting ways. Here are a few ways families can use this system to spark their imagination:
Personalized Artwork: Whether you’re looking to see a family portrait recreated as a painting or an abstract piece of art that represents the spirit of your family, the AI can generate one-of-a-kind images based on simple descriptions. Imagine a family member describing their favorite memory—like a summer trip to the beach—and the AI visualizing it in an artistic style.
Interactive Storytelling: Kids and adults alike can come together to create stories. By simply providing a prompt, such as “a dragon flying over a city,” the AI can generate images that illustrate the story. As you watch the AI bring these scenes to life, you can continue building the narrative, turning it into a collaborative storytelling adventure.
Family Games and Challenges: Take family game night to the next level! Use voice commands to generate riddles, puzzles, or even trivia challenges, with the AI producing images or clues based on each family member’s input. AI can also create custom word puzzles or visual challenges to keep everyone entertained and engaged.
B) Building Deeper Connections
In an age where many of us are caught up in the digital world, it’s easy to forget the power of shared experiences. The generative AI system provides a unique opportunity to reconnect with each other. Here’s how it fosters deeper bonds:
Hands-On Fun: The ability to control the system with voice commands gives everyone in the family a chance to participate, no matter their age. Parents, kids, and even grandparents can get involved, making it a great way to build stronger connections across generations.
Shared Creativity: As you collaborate to create stories, images, or games, everyone in the family contributes their ideas, which fosters creativity and teamwork. This shared process helps bond family members through shared goals and fun.
Accessible for Everyone: The simplicity of voice commands makes this system accessible for all ages and abilities. Even younger children or older relatives who aren’t as tech-savvy can easily interact with the system, ensuring everyone can join in on the fun.
C) Bringing Fun into Learning
Learning together as a family doesn’t have to be a dull experience. With AI-generated content, your family can enjoy educational activities that are as engaging as they are informative. Imagine learning about history by having AI generate visual depictions of historical events or creating scientific experiments with AI-generated diagrams and illustrations. Here are some ways you can turn learning into a shared family experience:
Interactive Learning: Ask the AI to explain complex topics like the solar system, dinosaurs, or ancient civilizations, and let it generate images that help illustrate the concepts. This can make learning more interactive and visually exciting.
Creative Problem Solving: Use the AI to generate visual challenges or brainteasers that stimulate critical thinking. This encourages family members to work together, think creatively, and come up with solutions in a collaborative way.
D) Simple Setup with Raspberry Pi
One of the most exciting parts of this project is that it runs on a Raspberry Pi—a low-cost, energy-efficient computer that’s incredibly versatile. Not only does this make the setup affordable for anyone, but it also ensures that the system is easy to maintain and can run without consuming a lot of energy. The Raspberry Pi serves as the perfect platform for this project, offering enough power to run the necessary software while remaining compact and portable.
So, what are you waiting for? Start generating and let the family fun begin! Clone the project from the GitHub repository, follow the steps and enjoy it! Read more
Programming is the process of giving a set of instructions to a computer to perform a specific task. Programming languages are used to write these instructions. Python is one of the most popular programming languages due to its:
Readable Syntax: Python’s syntax is simple and easy to understand, making it ideal for beginners.
Versatility: Python is used in web development, data analysis, artificial intelligence, machine learning, automation, and more.
Large Community: Python has a vast community, providing plenty of resources for learning.
Flow control refers to the order in which individual statements, instructions, or function calls are executed in a program. There are three main types of flow control:
Linear flow means the program runs from the top to the bottom, executing one instruction after another without any branching or looping as show in the example below:
# Linear Flow Example
print("Start of program")x=10y=5sum=x+yprint("The sum is:",sum)
In this example, the program runs from top to bottom, executing one statement after another.
Conditional statements allow a program to make decisions based on whether a condition is true or false. The most common conditional statements are if, elif, and else.
A for loop is used to iterate over a sequence (like a list, tuple, or string). It executes a block of code for each item in the sequence. For loop is a powerful tool for automating repetitive tasks.
# Iterating through a list using a for loop
fruits=["apple","banana","cherry"]forfruitinfruits:print(fruit)
In this example, fruits is the name of the variable containing the list above whereas fruit is the name of the variable that will hold the items in the list during the iteration.
Now that you understand for loop and while loop, you may have a question: “when is for loop preferred over while loop? when is while loop preferred over for loop?” A for loop is typically preferred over a while loop when:
Number of Iterations is Known or Finite: If you know in advance how many times you need to iterate, a for loop is often more appropriate. For example, iterating over a list or a fixed range of numbers as in the example below:
foriinrange(10):# Iterates 10 times
print(i)
Iterating Over a Sequence or Collection: When you need to iterate over items in a sequence like a list, tuple, string, or dictionary, the for loop is cleaner and more readable.
my_list=[1,2,3,4]foriteminmy_list:print(item)
Clear Loop Boundaries: When the loop has well-defined start and end conditions, for loops help make the boundaries explicit, improving readability and reducing the chance of infinite loops.
foriinrange(0,100,10):# Looping from 0 to 90 in steps of 10
print(i)
Iteration with Known Step Size: When you need to iterate through a range with a specific step size (e.g., incrementing or decrementing by a set number), a for loop is typically easier to use.
foriinrange(0,20,2):# i goes 0, 2, 4, 6, ..., 18
print(i)
If the number of iterations is unknown or dependent on a condition that might change during the loop (e.g., waiting for user input or processing data until a certain condition is met), a while loop is preferred. For example:
# Continue until a valid user input is provided
whileTrue:user_input=input("Enter a number: ")ifuser_input.isdigit():break
The range() function is commonly used to generate a sequence of numbers. It provides an easy way to iterate a specific number of times or over a defined sequence of values. The basic syntax of range() is as follows:
range(start,stop,step)
start: The starting value of the sequence (inclusive). If not specified, it defaults to 0.
stop: The ending value of the sequence (exclusive). This value is not included in the sequence.
step: The difference between each number in the sequence. This is optional, and if not specified, it defaults to 1. Have a look at the following examples on the use of range() function:
Basic range without start or step:
foriinrange(5):# This will loop from 0 to 4 (not including 5)
print(i)
Output:
0
1
2
3
4
Range with start and stop:
foriinrange(2,6):# This will loop from 2 to 5 (not including 6)
print(i)
Output:
2
3
4
5
Range with step:
foriinrange(1,10,2):# This will loop from 1 to 9, with a step of 2
print(i)
Output:
1
3
5
7
9
Negative step:
foriinrange(10,0,-2):# This will loop from 10 to 2 (not including 0), stepping by -2
print(i)
Output:
10
8
6
4
2
Key points about range() function:
start is inclusive, but stop is exclusive. So, the loop will stop just before reaching the stop value.
If start is greater than stop and the step is positive, the loop won’t run. Similarly, if the step is negative and start is less than stop, the loop won’t run.
In python, there are three statements that are used to change the behavior of loops:
break: Exits the loop prematurely. It is used to end the loop when some condition is satisfied. For example, if a loop is searching an item in a list, it should exit as soon as it gets the time.
continue: Skips the rest of the current iteration and moves to the next one.
pass is a statement that does nothing. It is often used as a placeholder or to intentionally ignore certain code blocks.
# Using break and continue
foriinrange(10):ifi==5:break# Stop the loop when i equals 5
ifi%2==0:continue# Skip the rest of the loop if i is even
print(i)
Nested loops
There is also another variant of loop where you have loops inside loops (called nested loops). In Python, you can nest any type of loop (like a for loop or a while loop) inside another loop. Nested loops are commonly used when you need to perform more complex iterations, like working with 2D arrays, matrices, or iterating through multiple dimensions. Basic Structure
forouter_iteminouter_sequence:forinner_itemininner_sequence:# Do something with outer_item and inner_item
The outer loop runs first and controls how many times the inner loop will execute.
The inner loop will complete all of its iterations for each single iteration of the outer loop. Have a look at the examples below:
1: Nested for Loop with a List of Lists (2D list) Imagine you have a 2D list (a list of lists), and you want to loop through each row and each element in the row.
matrix=[[1,2,3],[4,5,6],[7,8,9]]forrowinmatrix:# Outer loop (iterates over each row)
forelementinrow:# Inner loop (iterates over each element in the row)
print(element,end=" ")print()# Move to a new line after each row
Output:
1 2 3
4 5 6
7 8 9
As you can see from the output,
the outer loop goes over each row of the matrix.
the inner loop goes through each element in that row and prints it.
the end=" " keeps the output on the same line, and print() without arguments moves to the next line after completing one row.
Example 2: Nested Loops for Multiplication Table
A common example of a nested loop is generating a multiplication table. Here’s how you can do it with two nested for loops:
foriinrange(1,6):# Outer loop for the first number (1-5)
forjinrange(1,6):# Inner loop for the second number (1-5)
print(f"{i} x {j} = {i*j}",end="\t")print()# Move to a new line after each row
Output:
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15
4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16 4 x 5 = 20
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25
Example 3: Nested Loops with a Condition
You can also combine nested loops with conditions. For example, let’s print the elements of a 2D list but only if they are even:
matrix=[[1,2,3],[4,5,6],[7,8,9]]forrowinmatrix:forelementinrow:ifelement%2==0:# Check if the element is even
print(element,end=" ")print()# Move to a new line after each row
Output:
2
4 6
8
Example 4: Nested while Loop
You can also nest while loops. Here’s an example of nested while loops that print a pattern:
i=1whilei<=3:# Outer while loop
j=1whilej<=3:# Inner while loop
print(f"i={i}, j={j}")j+=1i+=1
Outer loop runs once for each item in its sequence, and for every iteration, the inner loop runs through its entire sequence.
Performance considerations: Nested loops can become slow if the sequences you’re iterating over are large because the time complexity increases with the depth of nesting. For example, two nested loops over lists of length n result in a time complexity of O(n^2).
Indentation: In Python, proper indentation is critical. The body of each loop must be indented.
Conclusion:
Nested loops are a powerful tool when dealing with multi-dimensional data structures or when you need to perform repetitive tasks with multiple layers of iteration. Just remember that the deeper you nest loops, the more computationally expensive it becomes!
Functions are reusable blocks of code that perform a specific task. Functions allow you to avoid repetition of codes and make your code more organized and readable. Functions allow you to break your program into smaller, manageable pieces, making it easier to read, maintain, and test.
You define a function in Python using the def keyword.
# Defining a function
defgreet(name):print(f"Hello, {name}!")# calling the function
greet("Alice")greet("Bob")
In this example, greet is the name of the function and name is the parameter. The function prints greeting text for the given parameter. The output of the above code will be:
Basic programming concepts: What programming is, why Python is a great language to start with.
Flow control: Linear flow, decision making with if, elif, and else, and iterations using for and while loops.
Functions: How to define and use functions for reusable code blocks.
Data structures: Working with lists, tuples, dictionaries, and sets to store and organize data.
To revise the concepts, implement the following practical examples to help reinforce your learning: Example 1: Simple Calculator
defadd(x,y):returnx+ydefsubtract(x,y):returnx-ydefmultiply(x,y):returnx*ydefdivide(x,y):returnx/yify!=0else"Cannot divide by zero!"# Test the calculator
print("Addition:",add(10,5))print("Subtraction:",subtract(10,5))print("Multiplication:",multiply(10,5))print("Division:",divide(10,5))
Example 2: Odd/Even Checker
defcheck_even_odd(number):ifnumber%2==0:return"Even"else:return"Odd"num=7print(f"{num} is {check_even_odd(num)}.")
QR codes have become an essential part of many digital interactions, offering an easy way to link offline and online worlds. Whether for business, marketing, or personal use, their ability to store information quickly and be easily scanned makes them a valuable tool.
This article provides an overview of QR Code and a simple python application to generate a QR Code. The first part offers inroduction to QR code and the second part walks you through the steps to the implementation of QR generator in python. If you are interested only to the implementation, you can directly jump to the section Generating QR Code. The full code is available here.
What exactly are QR Codes? A QR code (short for Quick Response code) is a type of two-dimensional barcode that can store a variety of data such as text, URLs, contact information, and other data types. Unlike traditional barcodes, which are one-dimensional and only store information in a single line, a QR code can store much more data due to its two-dimensional structure, allowing for both horizontal and vertical information storage. Key Features of QR Codes
Matrix Barcode: A QR code consists of a grid (matrix) of black and white squares arranged in a square shape. This grid can vary in size, with larger grids storing more data.
Data Capacity: QR codes can store much more data than traditional barcodes. For example: A basic QR code can hold around 3,000 characters or 7,000 numeric digits. Depending on the error correction level, it can store text, URLs, phone numbers, or even binary data.
Error Correction: QR codes incorporate error correction techniques that allow them to remain readable even if they are partially damaged. This is achieved by using a feature known as the Reed-Solomon error correction algorithm. Different levels of error correction can be applied (from L to H), with higher levels allowing for more damage but reducing the data capacity.
Speed and Efficiency: QR codes are designed for quick scanning. Unlike traditional barcodes, which require a scanner to move along the code to read it, QR codes can be scanned from any angle and can be read almost instantly.
Static QR Codes: These are QR codes whose data cannot be changed once they are created. They can store URLs, text, or other types of information.
Dynamic QR Codes: These allow for the data to be changed after the code has been printed or distributed. For example, a dynamic QR code might redirect to different URLs based on the context or tracking information.
Positioning Patterns: A QR code has three large squares at three corners, which are used to help the scanner locate and orient the code.
Alignment Patterns: These help the scanner read the QR code even when it’s tilted or distorted.
Timing Patterns: These help the scanner detect the size of the QR code matrix and ensure it’s scanned correctly.
Data and Error Correction Area: The majority of the QR code consists of data and error correction bits. This is where the actual information is encoded.
Quiet Zone: A quiet zone is a border of white space surrounding the QR code, ensuring that the scanner can correctly identify the edges of the code.
Now that you understand what a QR code is, let us go through a python application that generates it. We will use a simple Flask application that generates QR codes using the qrcode library along with Flask. Below is a step-by-step guide to creating the app: Step 1: Install dependencies First, you need to install the necessary libraries. Open your terminal or command prompt and run the following commands: pip install Flask qrcode[pil] Flask is the web framework and qrcode[pil] is the library used to generate QR codes with support for images (Pillow is included in this package). Step 2: Create the Flask application Now, let’s write the Flask application. Create a file called app.py and paste the following code inside it:
from flask import Flask, render_template, request, redirect, url_for
import qrcode
from io import BytesIO
from flask import send_file
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate', methods=['POST'])
def generate_qr():
# Get the data from the form input
qr_data = request.form.get('qr_data')
# Generate the QR code
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(qr_data)
qr.make(fit=True)
# Create an image from the QR Code instance
img = qr.make_image(fill='black', back_color='white')
# Save the QR code to a BytesIO object
img_io = BytesIO()
img.save(img_io, 'PNG')
img_io.seek(0)
# Return the image as a response
return send_file(img_io, mimetype='image/png')
if __name__ == '__main__':
app.run(debug=True)
The '/' route displays the homepage where users can input data for the QR code. The '/generate' route is where the QR code is generated when the form is submitted. It uses the qrcode library to generate the QR code, then returns the image as a PNG file. The qrcode.QRCode class is used to create a QR code object, and we add the data to be encoded using add_data(). We generate the QR code image using make_image(), which we then save to a BytesIO object and send back as an image response. Step 3: Create the HTML template Create a folder named templates in the same directory as your app.py, and inside it, create a file named index.html. This will be the homepage where users can input the data to generate the QR code. Here is the content of index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>QR Code Generator</title>
</head>
<body>
<h1>QR Code Generator</h1>
<form action="" method="POST">
<label for="qr_data">Enter data for QR code:</label>
<input type="text" id="qr_data" name="qr_data" required>
<button type="submit">Generate QR Code</button>
</form>
</body>
</html>
This simple HTML form sends a POST request to the Flask application with the text input (the data you want to encode in the QR code). Step 4: Run the application Now, go back to your terminal and run the Flask app with this command: python app.py Your Flask application should be running at http://127.0.0.1:5000/. When you visit that URL, you will see a form where you can input some text, and the app will generate a QR code for that text when you submit the form. Congratulations! You have created a Flask application that generates QR codes! The QR code is dynamically generated and sent back as an image in response to a form submission. You want to create your QR code or connect with me, scan the QR code below. Read more
In this blog post, we will explore how to send emails using Python, with a special focus on customizing the “From” header to display a different email address or name, while the actual sender email address remains unchanged. This is useful when you want to send an email from one address but have the From field show a different email or name, creating a more personalized or professional appearance. Prerequisites Before we dive into the code, let’s make sure you have the required tools:
Python 3.x installed on your system. smtplib and email.mime libraries are included in the Python standard library, so you don’t need to install anything extra.
Access to an SMTP server. For this example, we’ll use Gmail’s SMTP server, but you can modify the code to work with any SMTP provider.
Why Would You Want to Customize the From Header? You might want to send an email from your address but show a different “From” name or email address for various reasons:
Marketing Emails: You may want the email to appear as if it’s coming from a company or a support team, even though it’s sent from your personal email.
Multiple Email Aliases: If you use aliases for different purposes (e.g., support@company.com but the email is sent from your_email@example.com), you can display the alias in the header.
Professional Appearance: Customize the display name to appear more formal or specific to your communication, like “Customer Support” or “John Doe” instead of your actual email.
Steps to Send an Email with a Different From HeaderStep 1: Set Up the Email Message We will use Python’s built-in smtplib to send the email and email.mime to construct the email message. Let us first import the necessary libraries.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Then define the sender email, receiver email, and SMTP server details as follows:
sender_email = "your_email@example.com" # Email that will send the email
receiver_email = "receiver_email@example.com"
password = "your_email_password" # TIP: security consideration
Next, set up the SMTP server (Gmail is used as an example)
smtp_server = "smtp.gmail.com"
smtp_port = 587
Step 2: Create the email message and customize the From field Now let us create the email message and customize it. Here is where you can customize the From field.
msg = MIMEMultipart()
msg['From'] = "Custom Name <your_email@example.com>" # The 'From' field will show this name
msg['To'] = receiver_email
msg['Subject'] = "Test Email from Python"
# Email body content
body = "Hello, this is a test email sent from Python!"
# Attach the email body to the message
msg.attach(MIMEText(body, 'plain'))
In the msg['From'] field, you can change both the name and the email address. By default, the From header will show the email address. If you make it show a different name or alias, the recipient will see “Custom Name” in their inbox, but the email will still be sent from your_email@example.com. Step 3: Log In to the SMTP Server and Send Now that we have set up the email message, let’s log in to the SMTP server and send the email:
try:
# Set up the SMTP server connection
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Start TLS encryption for secure email sending
# Log in to the SMTP server with your credentials
server.login(sender_email, password)
# Send the email
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {e}")
finally:
# Close the server connection
server.quit()
In this example, we used smtplib.SMTP to connect to the SMTP server. For Gmail, the server is smtp.gmail.com and the port is 587. We also use starttls() to encrypt the connection, ensuring that our credentials and email content are secure. The server.login() function logs into the server using your sender email and password. If you’re using Gmail and have two-factor authentication (2FA) enabled, you’ll need to generate an App Password instead of using your regular Gmail password. This is a security measure to prevent unauthorized access. Follow the instruction on how to create App Password to get one. The try block ensures that any issues during the email sending process are caught, and the exception is displayed if there’s a problem. Security Considerations Never hard-code your email password in your scripts. Consider using environment variables or a credentials manager to securely store your login credentials. If you’re using Gmail, remember to either enable Less Secure Apps or generate an App Password if two-factor authentication is enabled. Conclusion Sending emails programmatically with Python is a powerful feature, especially when you need to customize the header or automate the email sending process, e.g., if you are sending marketing emails, notifications, or personal messages, this approach provides you with the flexibility to display any name or email address in the header, even if the actual sender email is different. Read more
In the world of Python development, managing dependencies effectively is crucial. One of the best ways to do this is by using virtual environments. Virtual environments allow you to create isolated environments for different projects, ensuring that each project has its own set of dependencies, independent of other projects or system-wide packages. This helps avoid conflicts between different versions of libraries and ensures that your projects remain portable and reproducible. In this article, we will go through the process of creating and using virtual environments in Python, covering both venv (the built-in Python module) and virtualenv (a popular third-party tool). What is a Virtual Environment? A virtual environment is a self-contained directory tree that contains the Python installation for a particular version of Python, as well as additional packages. This isolation prevents the installed libraries in one project from affecting other projects or the system-wide Python installation. Benefits of Using Virtual Environments
Dependency Management: Each project can have its own dependencies, even if they conflict with dependencies in other projects.
Clean Development Setup: No more version conflicts or dependency issues across projects.
Reproducibility: It makes it easier to recreate a project setup from scratch on another system.
Experimentation: You can safely experiment with different versions of libraries without affecting other projects.
Creating a Virtual Environment – Step by StepStep 1: Install Python First, make sure Python is installed on your system. You can download Python from the official website. To check if Python is installed and verify its version, run:
python --version
or for Python 3: python3 --version If Python is not installed, you can follow the installation instructions for your operating system from the official Python website. A) Virtual Environment Using `venv` (Built-in Python Module)Step 2: Create a Virtual Environment Using venv Python 3.3+ includes a built-in module called venv that can be used to create a virtual environment. To create virtual environment using venv, you need to navigate to the directory, create the virtual environment and activate it.
Navigate to Your Project Directory
First, navigate to the folder where you want to store your project, or create a new folder if needed.
mkdir my_project
cd my_project
Create the Virtual Environment
Use the following command to create a new virtual environment. You can name the environment whatever you want (let us name it .venv here). I prefer .venv thank .env because I often use .env for environmet variables.
python3 -m venv .venv
This will create a directory named .venv in your project folder. The .venv directory contains a copy of the Python interpreter, along with the standard Python libraries.
Activate the Virtual Environment
To activate the virtual environment, you need to run the appropriate command based on your operating system.
OS
Code to activate virtual environment
Windows
.\env\Scripts\activate
macOS
source env/bin/activate
Linux
source env/bin/activate
After activating the virtual environment, your terminal prompt should change, indicating that the virtual environment is now active. For example, on Windows, you might see something like:
(env) C:\path\to\my_project>
Step 3: Installing Packages in the Virtual Environment Once the virtual environment is active, you can install Python packages using pip, and they will only be available within that environment. For example, to install the requests library, you use pip install requests and you can now use requests within your project, but it won’t interfere with any other projects you might be working on. Step 4: Deactivate the Virtual Environment When you’re done working in your virtual environment, you can deactivate it by running the deactivate command as follows:
(env) C:\path\to\my_project>deactivate
Your terminal prompt will return to its original state, and you will be back to using the global Python environment. Step 5: Requirements File (Optional but Recommended) To ensure that other developers (or you, on another machine) can easily recreate the virtual environment with the same dependencies, you can create a requirements.txt file. This file lists all the packages currently installed in your environment. This ensures reproduceability and portability of your application. You can generate a requirements.txt file automatically using a handy tool called freeze as follows:
pip freeze > requirements.txt
This will save all installed packages and their versions in requirements.txt. To install the same packages later (or on a different machine), use:
pip install -r requirements.txt
Step 6: Delete the Virtual Environment (Optional) If you no longer need the virtual environment, you can delete the entire .venv directory. Simply remove it like any other directory:
OS
Code to activate virtual environment
Windows
rmdir /S /Q .venv
macOS
rm -rf .venv
Linux
rm -rf .venv
This will completely remove the virtual environment and all its contents. B) Virtual Environment Using `virtualenv` (Third-Party Tool) While venv is built into Python 3, you may want to use virtualenv, a popular third-party tool that provides some additional features, like compatibility with Python 2. Step 1: Install virtualenv If you don’t already have virtualenv installed, you can install it globally using pip:
pip install virtualenv
Step 2: Create a Virtual Environment with virtualenv To create a new virtual environment, run the following command:
virtualenv .venv
This will create a new virtual environment in the .venv directory. Step 3: Activate and Deactivate the Environment The activation and deactivation steps are the same as with venv. After activation, you can install packages using pip just like before. Conclusion Creating and managing virtual environments is an essential practice for any Python developer. By using venv or virtualenv, you ensure that your projects remain isolated and that dependencies don’t conflict with each other or with the base system. This isolation simplifies the development process, allows for easier dependency management, and enhances reproducibility, making it easier to share your projects with others. Remember to use a requirements.txt file to document your project’s dependencies and make it easy to recreate the environment on another machine. If you’re working on multiple projects, adopting the practice of using virtual environments will help you maintain cleaner, more manageable codebases. Remember to also add .venv into your .gitignore file to exclude the syncronization the virtual environment to your git repository (avoid unnecessary bandwidth usage). Now that you have read the article till the end, did you find this blog post useful? Drop me your comment as a message on LinkedIn Read more
Folder management can be daunting, especially when you need to keep folders in multiple systems in sync. I have always been creating folders under subfolder in Inbox folder in outlook. As shown in the example structure below, every time I start working on a project or proposal, I create a folder in initation. As the developement process continues and its status changes, I move the folder to a corresponding folder. For example, if the proposal is in its initial discussion phase, it will have a folder under Initiation; if the proposal development continues, the folder is moved to Preparation and if it is submitted, the folder is moved to Submitted and follow up; if it is rejected, the folder is moved to Rejected; if it is accepted, it does not belong to proposal category any more and the folder is moved to Running projects. I do this in my email folder (then create rules for email routing), in my file system (to organize files) as well as browser bookmark (to organize relevant websites). Doing it manually is a bit tidious and error prone. As a result, I decided to automate the entire workflow. This blog post explains how I automate the creating of folders in my outlook mail box.
user_name@domain.com
Inbox
Projects
1_Proposal
11_Initiation
<project_names>
12_Preparation
13_Submitted and follow up
14_Rejected
2_Running
<project_names>
3_Completed
Remember, if you want to create a subfolder under an existing subfolder of the Inbox in Outlook, you need to first access the subfolder and then create a new folder under it. To create a subfolder in the “Inbox” folder of Outlook using Python, you can utilize the pywin32 library, which allows Python to interact with the Outlook application through COM (Component Object Model) automation. So, the first step is to install the pywin32 library using pip install pywin32. The code below shows the implementation of creating a subfolder under a given parent folder.
import win32com.client
def create_subfolder_under_subfolder(parent_folder_name, subfolder_name):
'''
Description: Function to create a subfolder under an existing subfolder in Inbox.
Inputs: the subfolder you want to create and the parent folder in which you want to create your subfolder
Usage: create_subfolder_under_subfolder(parent_folder_name, subfolder_name)
'''
# Initialize the Outlook application
outlook = win32com.client.Dispatch("Outlook.Application")
# Get the Namespace object (MAPI)
namespace = outlook.GetNamespace("MAPI")
# Get the Inbox folder
inbox = namespace.GetDefaultFolder(6) # 6 is the constant for Inbox
# Find the parent subfolder under Inbox
try:
parent_folder = inbox.Folders[parent_folder_name]
except KeyError:
print(f"Subfolder '{parent_folder_name}' does not exist under Inbox.")
return
# Create the new subfolder under the parent folder
subfolder = parent_folder.Folders.Add(subfolder_name)
print(f"Subfolder '{subfolder_name}' created under '{parent_folder_name}'.")
# Example usage
parent_folder_name = "subfolder_name" # Name of the existing subfolder under Inbox
subfolder_name = "NewSubFolder" # Name of the new subfolder to be created
create_subfolder_under_subfolder(parent_folder_name, subfolder_name)
The function will initialize Outlook Application with win32com.client.Dispatch("Outlook.Application"), allowing access to its functionality.
Namespace (MAPI): We access the MAPI interface, which gives us the ability to interact with Outlook data such as emails, folders, etc.
Get Inbox Folder: The GetDefaultFolder(6) method retrieves the Inbox folder (6 is the default constant for the Inbox).
Create Subfolder: The Folders.Add(folder_name) method adds a new folder with the specified name under the Inbox.
Now, you can only focus on maintaining your file containing the list of proposals/projects you work on, e.g., excel file, json file or a mere text file. I suggest you create cron job that runs on regular basis to check the content of the file you maintain and compare it with the directory structure of your mailbox, bookmark and filesystem and update if needed, relieving you from doing the same thing again and again. Assumptions:
Outlook is installed and running on your system.
The script will create the folder within the Outlook profile that is currently logged in.
If you have questions or comments, you can reach me via LinkedIn. Read more
Creating issues en mass in GitLab (using the web interface) is sometimes tidious or may require unnecessary context switching. This post is to show how you can create bulk of issues using python. The code below is for a single issue but you can easily create list of issues and iterate over them to create multiple issues.
Requirements
1) You need to install python-gitlab library in order to perform more complex logic during issue creation 2) You need to create a project and get its id. 3) You need to have personal access token. pip install python-gitlab
Steps
It takes three steps to automate the creation of issues in GitLab projects: Authentication, Project selection and issue creation.
i) Authentication
Provide your personal access token and the Gitlab instance url. You can generate a token with the necessary scopes (e.g., API) from your GitLab profile settings.
ii) Project Selection
Provide the ID of the project where you want to create the issue. You can find the project ID in the project’s URL (see screenshot below).
iii) Creating the Issue
The new issue uses dictionary and defines the title, description, and labels for the new issue. You can customize these fields as needed. Once the dictionary is populated with the necessary information, the project.issues.create(new_issue) method creates the issue and returns an Issue object. The full code for creating a new issue is shown below.
How (and from where) do you get project id? You can get project id by clicking the 3 dots next to Fork on Gitlab web interface as shown in the screenshot in Figure 1. As soon as you click the three dots, you will see the popup that reads “Copy project ID: ". Clicking on the popup will copy the project id to clipboard. You can then paste it in ```project = gl.projects.get(id='your_project_id')``` to replace the placeholder ```your_project_id```. Figure 1: Screenshot showing how to get project id You can extend the above code by incorporating the following:
Error Handling: Consider adding error handling mechanisms to handle exceptions like authentication failures, API rate limits, or network errors.
Asynchronous Operations: For large-scale operations, you might want to explore asynchronous programming techniques to improve performance.
Advanced Features: The gitlab library offers many more features, such as assigning issues to users, setting due dates, and closing issues. Refer to the library’s documentation for detailed usage.
Read more about the API here If you have questions or comments, you can reach me via LinkedIn. Read more