Implementing nested loops with dynamic step in Python3

Introduction

The other day, my son asked me about the result of evaluation of program in Java that he had in his AP Computer Science A (APCSA) course. This course is as a part of his high school senior curriculum. The problem was quite simple of nested for loops in the control flow section. The code is as below.

    a = 0;
        for (i = 0; i < 10; i++) {
            for (k = 0; k <= 5; k++) {
                for (z = 1; z <= 16; z = z * 2) {
                    a++;
                }
            }
       }
    print a

The problem

As you can see, the problem is simple enough. I had done this kind of for loop in shell scripting and in C language when I was learning it a long time ago and somehow I thought that this was the same way you run a for loop in Python as well. Of course I know Python quite well, so I thought I would quickly port this code in Python and run it to verify the answer of the problem (My son had gotten it right by the way and through a very simple mechanism, I must add).

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object. However, Python doesn't allow the developer to define both the iteration step and halting condition. Instead Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

The syntax for a for loop in Python is very simple and intuitive like so:

    for i in some_list:
        <do something>

Most common use case is to iterate some operation a certain number of times. And the easiest way to do it is to use the range function. In the range function, the structure contains the start point, end point and the step. The step takes an integer as an input and it does not accept an expression as a step. Similarly as Python doesn't allow the developer to define the iteration step in the for loop, it posed a problem for me as I the program above required to have the step in the powers of 2 for each loop.

The research

I tried various combinations and options to change the step size in range function, but as the step is a positional argument and doesn't accept either keyword argument or an expression, the choices were limited to only integers (Range also accepts floats but it for another day). I searched far and wide for a solution but to no avail. Finally I hit on the a possible solution on (where else) Stack Overflow.

The person who asked the question had a similar goal as me. The answer to the question was kind of cryptic, but I was able to figure it out as the answer pointed me in the right direction.

The solution

The solution in the end was embarrassingly simple. Here's the final code for this: There are certain commented statements here which I have left here that I used to debug and understand what was going on.

    #########################################
    # Implement nested for loops in Python  #
    # Programmer: Mukul Dharwadkar          #
    # Date: 24 September 2021               #
    #########################################

    a = 0
    for i in range(10):
        for j in range(6):
            c=1
            for k in range(1, 17, c):
                while c < 17:
                    # print(f'Index c is {c}')
                    c = c * 2
                    #print(f"Index i is {i}")
                    #print(f"Index j is {j}")
                    a += 1
                #print(f"The value of a when is i, j, k and c is {i}, {j}, {k}, {c} is {a}")
    print(f'The value of a is {a}') 

As you can see, I needed to initialize a new counter c that would then be used as the step size. In the innermost for loop, I needed to create a stop condition as the counter was completely independent of all other variables. The while loop above creates that stop condition. Inside the while loop, I am incrementing the counter by the powers of two.

The actual operation of interest is the value of a which is incremented by one everytime the loop is executed. So essentially, the easy way once you figure out how many times each loop is executing is to multiple all those values (5 times 6 times 10 in this case) and arrive at the final answer of 300.

    The value of a is 300

I’m here for you – By Nandini Dharwadkar

Be kind to all

A brand new day. A brand new life. Only ten cars were zooming on the streets, which was the only noise left in the city of Fremont. At least, outside. Inside of hospitals and clinics, the only sound that could be heard was the moaning and groaning of suffering patients, and the soothing voices of the nurses and doctors that worked hard to cure the sick. Everyone noticed this change. Everyone knew. But not everyone cared. The rich were just taking this as a chance to relax.

Coronavirus was taking over people’s lives. And taking them away. And no one could be more affected by this than 15-year old Lily. She wanted some way to help the underprivileged people who couldn’t provide for themselves, the ones without a job because of the lockdown, because they are the ones who need help the most. Lily watched out of her window as she observed a man stuffing his trunk to its maximum capacity with cans of food. Corona Virus

Food, she thought, there will never be enough. For the the higher class with a lavishly decorated home, and the ones with a plain blanket and hard, cement bed. I need to make it enough, especially now.

And watching the man with his cans, Lily knew exactly how to help...

An hour later, Lily had persuaded her sister and had gathered a few friends with her to help other people during this time of distress and were walking around the streets carrying large trash bags. Filled with food and supplies in it that they had pooled out of their own homes. It wasn’t much, but it was worth it. And everyone around the world knew that.

They walked down Thornton Avenue, where they saw an old lady sitting at the edge of a gas station, who was watching them nervously. Her eyes said it all. But as they approached, the woman’s gaze fell to the sidewalk, but Lily knew what the lady’s heart wanted.

Lily kneeled in front of her, and tried to ignore the deadly smell circling the woman. Trying not to scrunch her nose and be rude, Lily said benignly, “How are you doing, Ms….?”

The old woman seemed to trust the teenagers who were silently watching, and said in a croaky voice, “Gibson. Ms. Gibson. What are you doing here? And why are you outside?”

Lily pulled out six large cans of beans, tomatoes, vegetables, and chicken that her mom had saved up. She lined them up in front of the woman. “For you,” she said, and took the old woman’s hand and squeezed it. “We’ll get through this. Coronavirus will be kicked away by vaccines that our doctors will discover. Stay strong. You’re not alone. We’re here for you. I’m here for you.”

Ms. Gibson was speechless. “You’re here for me,” she repeated. “You’re here for me.”

For two hours Lily and the other teenagers walked around Fremont passing out food to homeless and needy people. Other residents noticed the group with large bags as they passed out food. Soon, almost everyone in Lily’s community had joined in the heroic act, and were chanting, “We’re here for you. I’m here for you” to everyone they provided supplies.

Lily looked back at the size of her group and grinned. It took one small act of kindness to prove that the coronavirus could not kill off the kindness people felt for each other, despite the lockdown. All people had to do to prove that was to say four simple words: “I’m here for you.”

Updating a DynamoDB attribute with a hyphen or dash (-) in the name using CLI or SDK

Background

As a part of my personal growth plan and work commitments, I am working on the AWS Certified Developer - Associate certification using the Linux Academy platform. In one of the lab exercises that I was doing on DynamoDB, there were requirements for updating DynamoDB attribute using SDK and perform conditional updates and atomic counters on the tables. Being what I am, I did not use the examples they had provided, but created by own table to create a database of books I own and proceeded to create my own attribute names for the items.

The problem

As it happened, I created attributes like book-title, book-author, book-price, etc. which in itself is not a problem. However, the lab exercise had me perform the item updates using the BOTO3 Python SDK which got me excited to learn new things. I used the example files that the trainer had provided and modified it to suit my environment and ran the script.

UpdateExpression='SET book-price = :val',
ExpressionAttributeValues={
    ':val': {'N': '15.37'},  
    ':currval': {'N': '0'} 
},
ConditionExpression='book-price = :currval',
ReturnValues="ALL_NEW"

To my dismay, I started encountering errors.

Traceback (most recent call last):
  File "conditional_write.py", line 18, in 
    ReturnValues="ALL_NEW"
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 626, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Syntax error; token: "-", near: "book-price"

The Solution

I reviewed my code to ensure that I had not introduced any bugs myself. After ensuring that I had not introduced any bugs by adding new attributes to an item without any dashes and running the script successfully, I starting practicing my Google-Fu. There I found this awesome post on stackoverflow along with a link to official AWS documentation. The official documentation however only talks about a dot being a special character and it doesn't list a dash (-). After following the instructions from the stackoverflow post, my new code looked like this:

UpdateExpression='SET #bp = :val',
ExpressionAttributeValues={
    ':val': {'N': '15.37'},  # Make sure we keep this line the same
    ':currval': {'N': '0'}  # What was the current value?
},
ExpressionAttributeNames={
    "#bp": "book-price"
    },
ConditionExpression='#bp = :currval',
ReturnValues="ALL_NEW"

And once I implemented this code it all started working correctly. I have left a feedback for the AWS documentation team and hopefully they will update the documentation. I just want to make sure that all the cases are at listed and documented so that developers and wannabes like me are not stuck.

Thumbs up to Apple on Inclusion and Diversity

Apple hosted their annual fall product launch yesterday in the Steve Jobs theatre in the Apple campus. The event had its regular razzmatazz of new products and self-described superlatives for its own products. There was something different about the event this time and no it was not the iPhone 11 Pro. This time, the presenters were from diverse backgrounds and were inclusive. Thumbs up to Apple on Inclusion and Diversity and making a real effort towards it.

Historically, the presenters of the events were white males (and to some extent females) who would boast the features and performances of the products. This time around though, we saw Asians doing the keynote presentations, females in actions but sadly still not blacks. I am fairly certain that it is just a matter of time where every company and organization will make Inclusion and Diversity their priority.

But for now, I think I will enjoy the launch and wait for the availability of iPhone 11 Pro. It is a great product and Apple has managed to excite me after 5 versions of the phone.

Are we becoming the mice of NIMH?

Introduction

Some time ago, I had written about people behavior and civilization. Those thoughts sparked from how people behave in less than optimal situations like a crowded train. But that's nothing compared what's happening around us nowadays. Last week there was yet another mass shooting in a public place in the US. This time the shooting was at the Gilroy Garlic Festival. There have been 248 mass shootings in US in 2019 and at this pace, it will easily surpass the 323 mass shootings that took place in 2018. Are we becoming the mice of NIMH?

Social Issue

What is the society now coming to? Are we really becoming the mice of NIMH where we are unable to handle the bounty that nature and our society is providing us? The video below is very distressing and is that a harginger for human society. All the indicators so far point in that direction only.

Will this human behavioral trend mean that all the social gatherings will cease to happen and everything will become virtual? Already the today's kids don't like to go and hang out together. Rather they choose hanging out together in virtual chat rooms like Google Hangouts, Facebook Messenger, or Discord. Messenger website even has a catch-phrase, "Be together, whenever."

Messenger Message
Is it worth it?

These kids are missing out on all the personal contacts gained by actual interaction. This kind of social interaction is not preparing them for the rigors of the real world and they become socially awkward. Will they become "The beautiful ones"? Only time will tell, but I am worried.

Already the upcoming social events like the Fremont Festival of the Arts will have enhanced security after the Gilroy incident. In that case, people immediately start viewing each other with suspicion and instead of what should be a celebration of art, culture and human interaction, the ambience becomes acidic and caustic and an ordeal. I have already made up my mind to not go to the festival.

Conclusion:

I just hope that good sense will prevail and human race will address this issue and halt the seemingly inevitable march towards doomsday.

Elections in the new world

Context:

A long running episode has just turned an important page right now. Robert Mueller finally testified in front of the congress and as I expected provided almost nothing to the lawmakers outside his report. The focus of media and most of the public was around collusion and obstruction of justice. Indeed, that was the most newsworthy story but in my opinion not the main story or threat to the democracies of the world. It was only Rep. Adam Schiff brought out the question of integrity and security of elections. Director Mueller had already highlighted it in his monologue of a press conference in May 2019. How will the elections look like in the new world?

Subtext:

It is an important aspect that all the democratically elected governments of the

Elections
Elections in India

world should be really worried about. In fact there are questions being asked of the validity of the Brexit referendum vote and even some of the assembly Elections results in India. Now defunct Cambridge Analytica is being suspected as being involved and even instrumental in altering the outcome of both the results.

Just imagine if the Pakistani intelligence agency ISI decides to engage itself in Indian politics. It can ensure a party that is sympathetic towards Pakistan comes to power. Or even worse, it can ensure that an incompetent leader becomes the prime minister of India. That would be a disaster not only for India but to the stability of the region and I daresay, even the world. I can't think of India being ruled by Congress party led by an inept leader like Rahul Gandhi.

With the world becoming more and more digital and online, governments of the world should take infinitely more care about ensuring the data security and integrity to ensure fair and correct results. We all see in day to day life how easy it is to hack any computer system and bring it down. The private companies of the world realize it and spend a fortune on securing their IT infrastructure. The governments also should realize it. The bureaucrats must eliminate of reduce bureaucracy to a large extent and actually care about the security and integrity of the election process and the integrity of the results.

Conclusion:

It is very easy to ensure the security of elections in the new world if you think about it. First of all, Government must appoint competent people to key positions with reasonable autonomy to perform their function. As a result of strong and fair oversight, it will ensure that the right policies and procedures are implemented. Politicians must be kept at more than an arms length from the entire process. State of the art technology should be implemented. Most importantly, the people involved in the process at the grass roots level should be provided training and right incentives.

This is the just the starting point. But we don't have a lot of time to get it right. The bad actors are already off the blocks and the race is on!!!

A “Brave” new browser (?)

While watching the recently concluded 2019 cricket world cup, I saw some ads for Alluva, which calls itself a prediction platform. I am not sure how it works, but that's not the point of this article. I signed up to Alluva and it had me create an account on MetaMask, to receive the Alluva tokens. There on MetaMask site, it was strongly encouraging using a new browser called Brave.

Get Brave!

The browser in itself if based on Chromium project and they state that they have "taken almost all of Google from the Chrome."

I was intrigued. I am not the one to shy away from testing out new technologies. So I decided to take it for a spin. I downloaded it and took it for a spin. The first few sites all worked fine as the browser's core code base is Chrome itself. But the moment I tried to connect to my corporate sites, it started acting up. I faced two main issues while browsing:

  1. For any SSO enabled site, it started asking for username and password instead of taking the authentication from the kerberos ticket.
  2. For any SAML federation redirects, the redirects just failed and the site failed to work.

These issues were a deal breaker for me. For all the technology evangelism I just can't see myself using two browsers for my needs. I needed to have one browser. I was about to give up and go back to tried and tested Firefox. But I refused to give up. I asked myself, if Chrome works, then why not Brave? What is different in Brave that is causing the issue. I found the answer in one of the feature request on GitHub and a Brave Community post. Looks like when the browser code was compiled the developers disabled a couple of flags that are needed for SSO integration with kerberos and SAML redirects.

  • --auth-server-whitelist
  • --auth-negotiate-delegate-whitelist

When I tried to run the browser by running from command line and passing correct arguments for these parameters, everything worked fine. But again it is not very easy to always run it from the command line and all your settings are lost. So I was looking for an answer to make the process automatic and repeatable. I searched a lot of forums and help sites and I found the answer on superuser.com. This gives a step by step explanation of how to configure command line parameters for any application.

I tried both methods, and finally settled on the second method as the best method.

I created a small application using MacOS automator. It worked well. But I always had to launch the application from wherever I had saved it. Launching it from the Dock instead of from the actual location even after pinning it to the Dock defaulted to the original application launcher. The second method modifies the application bundle so it is a little risky but with enough due diligence and case, you can do it.

You can download the brave browser by clicking here.

How to setup use NexxHome garage door opener with Google Home

After a lot of discussions and false starts, we finally took the plunge in making our home a smart home starting with smart speakers and thermostats. After we moved into our own home, we were always kind of worried about the garage door and once or twice we have left it open only for our neighbors to call us and alert us about it.

We were not sure about how to handle it when a couple of our friends told us about the smart garage door openers that operate over WiFi and are accessible over the internet from anywhere. We did some research and based on the reviews and feedback from our friends, we decided to go for the NexxHome smart garage door opener. Based on the information provided on the product page on Amazon and on the NexxHome website, the device works with Alexa as well as Google Home. While I was able to find a lot of sites that showed how it works with Alexa, I was not able to find any tutorials on how to link and enable NexxHome with Google Home. The device doesn't even come up on Google Home App when I try to add a device.

I was disappointed and stumped. But then, I found this document on the NexxHome support page that kind of gave me a direction to pursue.

Integrating NexxHome with Google Home is not very straight forward. There is a roundabout way of doing it. Before linking Nexxhome with Google Home, the Nexxhome App needs to be prepped up a little bit.

  1. Open your NexxHome App and tap on Setting (gear icon)
  2. In the next screen, tap on "Works With" menu and enable Google Assistant
  3. Once that is done, open your Google Home App and click on the user icon
  4. Tap on Explore and in the search window, type Nexx Home and select on the Nexx Home result
  5. In the next window, click on Link to link your NexxHome with Google assistant and enter your NexxHome credentials to login when prompted.
  6. Once you login, the Nexx will be linked and it will show Try it button to try the commands.

That's it. This successfully links NexxHome with your Google Home and Google assistant.

Note: Although it links successfully, the linkage is not very reliable and you may not get the desired results every time. However, for me, it has worked as expected 8 out of 10 times. Hope this helps others as well.

Troubleshooting and fixing 404 errors on a self hosted WordPress

After hosting my website on Plone and attempting to host it on plain HTML5 I decided that time has come for me to use a CMS. As I wrote in the Hello World post (i.e. the first post) I chose to use WordPress. I installed it and as my work and life made me busier and busier, I kind of ignored. It is very apparent from the irregularity of the posts and blank periods in the posting.

Anyhow, the point is that I didn't realize that the permalinks, categories and tags were not working. When I clicked on a particular post or tags or categories, it showed me a 404 error. So essentially I had a broken site on my hands. And here I was wondering why my site was not coming up in searches and why I was not getting any traffic. SEO helps Google to crawl and index the website most effectively when permalinks, tags and categories are setup correctly.

Apparently, it is a very common error in WordPress with a very straight forward solution. A simple google search most likely leads you to the right solution. My objective is not to add to the burgeoning posts of "How to fix 404 errors on WordPress". The objective of this how-to is to address one edge case that will occur when you are trying to host WordPress on your own server/computer.

I followed a lot of posts and almost all of them told me the same thing.

  • Re-save the permalink settings and
  • Ensure you have the .htaccess in your WordPress directory (some of them don't tell that you should have it in the WordPress directory though).

I was at my wits end on what to do to solve the problem. I was about to give up and try and reinstall WordPress when I came across this site and the how-to. That how-to does address the edge case of people like me who like to run their own web servers instead of buying managed hosting. In fact, I am running my site in containers. In fact re-installing WordPress would have added work and would have broken my site. Thankfully I stayed away from it.

The rewrite module of Apache is not automatically enabled. This was the "A-HA" moment for me. I checked out the modules that were loaded by running sudo apachectl -L and sure enough there was no rewrite module enabled there. I double checked that I had the rewrite module binary in the mods-available directory in my Apache distribution.

At this point, I was ready to enable the module by running sudo a2enmod rewrite and sudo service apache2 restart on my server and enable the module. After that, I was able to reset the permalinks to whatever I wanted it to be. This fix also worked tags and categories.

I hope this helps whoever is facing this issue.

I am not an ideal man

I am a man. Period. With all the fallibilities and weaknesses that accompany a man, I exist. I do not claim to be the perfect or ideal man. In the entire history of human kind, there has been only one perfect / ideal man - the supreme being if you will and that was Prabhu Sri Ramachandra.

And even he was unable to make everyone happy all the time and be ideal all the time. When he was an ideal son, he was not an ideal brother or ideal husband. When he was an ideal husband, he was not an ideal ruler... and so on.

I have never claimed to being perfect or ideal, but I do claim is that I am a good man and my heart is in the right place. Even if I am unable to convey my feelings and thoughts clearly at times, I never have bad intentions for anyone. Ever.

I have tried to be a good husband, a good father, a good son, a good son-in-law, a good brother and a good friend. But recently I have realized that I have failed miserably in everything. Possibly because, I have confused myself with the definition of good and ideal. It is OK to feel sad, angry and let down. It is also OK to not meet expectations every time as long as you are clear and upfront about it as to why you are doing what you are doing.

I always felt that I cannot let anyone down and I have to ensure that I meet everyone's expectations else, I will lose my reputation and ruin my relation with whoever had the expectation. No. That's not right. If the relation is so weak so as to break / ruin based on one transgression, then it was not a real and strong bond in the first place. I also know that all the interactions need to be transactional, but also realize that it is not possible for people to not remember earlier transgressions and treat every interaction as independent. But I think there is a limit to how long these things will be stretched and a person reminded of past errors.

As a man with fallibility, I am bound to make mistakes - To err is human - but it is also equally true that - to forgive is divine - In forgiveness, both sought and given is where we find true peace and love.

Verified by MonsterInsights