Story of Hope and Courage

This story is from the life of Charlie Munger, from long before he was rich and famous.

The story dates to 1953 when Charlie, then 29 years old, got divorced from his (first) wife of eight years. Divorce had a huge social stigma attached at that time and it was the first blow for Munger.
His wife also got almost everything in the separation, including the house. Charlie’s friends revealed that he moved into “dreadful” conditions after this divorce.

He, however, summoned all his courage, worked crazy all week to recover the money lost in the divorce. This was, however, just the beginning and life had to still test him out further.

A year later, Charlie’s 8-year-old son Teddy, was diagnosed with leukemia (blood cancer). He scoured the medical community but quickly discovered the disease was incurable. He and his ex-wife sat in the leukemia ward with the other parents and grandparents in different stages of watching their children waste away. Also, given that there was no medical insurance in those days, Charlie paid for everything out-of-pocket.

As per his friends, each day he would take Teddy to the hospital for checkups while taking care of his other two children and practicing law. Those months were the toughest as he saw his son growing weaker nearing his death.

According to his friend Rick Guerin, Charlie would visit the hospital when his son “was in bed and slowly dying, hold him for a while, then go out walking the streets of Pasadena crying.”

One year after the diagnosis, Teddy Munger passed away at the tender age of 9, leaving Charlie heartbroken.

Charlie was 31 years old, divorced, broke, and burying his young son. It would have been tempting to just give it all up and turn to vices (alcohol, drugs) as so many people around him had done at that time. But Charlie was not that man and he kept going.

Years later, he reflected on the inner turmoil that he could’ve given in to and said –

“Generally speaking, envy, resentment, revenge, and self-pity are disastrous modes of thought. Self-pity gets pretty close to paranoia…Every time you find your drifting into self-pity, I don’t care what the cause, your child could be dying from cancer, self-pity is not going to improve the situation. It’s a ridiculous way to behave.

Life will have terrible blows, horrible blows, unfair blows, it doesn’t matter. Some people recover and others don’t. There I think the attitude of Epictetus is the best. He thought that every mischance in life was an opportunity to behave well. Every mischance in life was an opportunity to learn something and that your duty was not to be immersed in self-pity, but to utilize the terrible blow in a constructive fashion. That is a very good idea.”

via Safalniveshak.com

The power of that speech is more memorable because Charlie never mentioned the fact that his own son died of cancer.

Read the entire speech here

Sorting Files

Here’s a common problem

You have a bunch of images in a folder and you want to sort them according to the modification or creation date so you can create gif file out of it.

How do you do that?

Or consider this common usage, your app created lot of files and you want to programmatically select the last modified file. How do you do that?

Solution:

import os

files  = os.listdir(".")
files.sort(key=os.path.getctime)

To get the last modified file

files.sort(key=os.path.getmtime)[-1]

Docs for this functions.

Signature: files.sort(*, key=None, reverse=False)
Docstring:
Sort the list in ascending order and return None.

The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
order of two equal elements is maintained).

If a key function is given, apply it once to each list item and sort them,
ascending or descending, according to their function values.

The reverse flag can be set to sort in descending order.


Signature: os.path.getmtime(filename)
Docstring: Return the last modification time of a file, reported by os.stat().


Signature: os.path.getctime(filename)
Docstring: Return the metadata change time of a file, reported by os.stat().

You Want Leverage

Yesterday was talking to a colleague going though options in his work life. Most of our discussion revolved around leverage.

Thinking about this later discovered this little gem of a snippet in my notes. Unfortunately have no reference from which book I had copied this.

-The person who creates more value has leverage.
-The person who can walk away has leverage.
-The person who is irreplaceable has leverage.
-The person who has a second option has leverage.
-The person who knows the numbers has leverage.
-The person who everyone likes and wants to work with has leverage.
-The person who asks for more, gets more

Comet Plot in Python

In the summer of 2016, while working on a project with Matlab, I discovered the cool plotting function in Matlab, comet.

comet(x,y) displays a comet plot of y versus x.

A comet is an animation of a marker (head) and a line (tail) tracing a growing line over the data points. The tail is a solid line that traces the entire function.

You have to see the plot to experience this.

Ever since wanted to recreate that plot in python, so here we go.

Here’s a code to display the above plot

t=np.arange(0, 4*np.pi, np.pi/50)
x = -np.sin(t) - np.sin(t/2)
y = -np.cos(t) + np.cos(t/2)

comet(x,y)

Here’s the code for comet

import matplotlib.pyplot as plt
import numpy as np


def comet(x,y=None, time=0.05):
    """
    Displays a comet plot

    by Sukhbinder
    date: 15 Feb 2021
    """
    x = np.asarray(x)
    plt.ion()
    plt.xlim(x.min(), x.max())
    if y is not None:
        y = np.asarray(y)
        plt.ylim(y.min(), y.max())
    else:
        plt.ylim(0, len(x))
    if y is not None:
        plot = plt.plot(x[0], y[0])[0]
    else:
        plot = plt.plot(x[0])[0]

    for i in range(len(x)+1):
        if y is not None:
            plot.set_data(x[0:i], y[0:i])
        else:
            plot.set_xdata(x[0:i])
        plt.draw()
        plt.pause(time)
    plt.ioff()

Have you used comet or a similar plot? Let me know.

The History of “Hello”

Photo by Negative Space on Pexels.com

A book I want to reread is “A Million Years in a Day by Greg Jenner”. It has an interesting take on history relating it to a modern day.

Here’s a small sample on how ‘Hello’ came to be.

Apparently, when Edison first witnessed a demonstration of Bell’s contraption, America’s leading inventor exclaimed ‘hullo!’ in total amazement that it actually worked. ‘Hullo’ was the nineteenth-century version of ‘fancy seeing you here!’ the kind of disbelieving greeting we’d blurt out if we met our dentist at the top of some remote volcano but, with our sceptic’s hat on, this story sounds a little too charming to be true.

However, it was definitely Edison who pushed a slightly amended version, ‘hello,’ into the public consciousness as the official telephone greeting. He thought that ‘hello’ had strong, clear syllables, and this was important because he envisaged telephones would primarily be used between businesses, and that the lines would remain permanently open rather than there being a ringing sound for each call. In short, ‘hello’ was chosen specifically because it wasn’t a familiar word used in ordinary office chat, so hearing it would immediately notify someone that there was a call for them.

While Edison’s greeting is now one of the most recognizable words on the planet, I must admit I’m slightly disappointed that Bell’s alternative suggestion, borrowed from nautical terminology, wasn’t picked up instead: just imagine the musical majesty of Lionel Richie singing: ‘Ahoy, is it me you’re looking for?

From the book A Million Years in a Day by Greg Jenner

Number Puzzle and Few learnings

In April 2013, in my quest for sharpening my python skills, I wrote the below program to replicate the numbers puzzle game I have played during my childhood.

Found this on my old hard disk which I was cleaning recently. Looking at it now I find lot of issues with it.

  • Use of global variables
  • Non Intuitive use of 2, 4, 6, 8
  • Meaningless variable and method names
  • No main
  • No user input validations

# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 08:43:50 2013

@author: Sukhbinder
"""

import random
import numpy as np
import os

x = list(range(0, 16))
y = list(range(1, 16))
y.append(0)


random.shuffle(x)
moves = 0


def pt(x):
    k = os.system("cls")
    # print np.reshape(x,(4,4))
    k = 0
    for i in x:
        print('{:>5}'.format(i), end=" ")
        k = k+1
        if k % 4 == 0:
            print("")


def checkwin():
    global x, y
    return x == y


def moveit(ch):
    global x, y
    am = list(range(3, 16, 4))
    if ch == 2:
        m = -4
    if ch == 6:
        m = -1
    if ch == 8:
        m = 4
    if ch == 4:
        m = 1

    ind = x.index(0)
    if((ind in am) and (ch == 4)):
        m = 0
    if((ind % 4 == 0) and (ch == 6)):
        m = 0
    s = ind+m
    if ((s < 0) or (s > 15)):
        return None

    temp = x[s]
    x[s] = x[ind]
    x[ind] = temp


win = False
while not win:
    pt(x)
    choice = input("2 6 8 4 :")
    choice = int(choice)
    moveit(choice)
    moves += 1
    win = checkwin()
    print(win)

print("You completed in "+str(moves))

IPO

From ET

This year Indian equity market saw launch of numerous number of IPO’s. From zomato to cartrade, its raining IPO.

I am part of a couple of whatsapp group whose name has stock in them. Most started by relatives and friends. So whenever there is a new IPO, these groups buzz like a bee.

And almost every time someone or other will ask each others opinion on an IPO, my standard response is to point them to 1993’s annual letter written by Warren Buffet.


An intelligent investor in common stocks will do better in the secondary market than he will do buying new issues…[IPO] market is ruled by controlling stockholders and corporations, who can usually select the timing of offerings or, if the market looks unfavourable, can avoid an offering altogether.

Understandably, these sellers are not going to offer any bargains, either by way of public offering or in a negotiated transaction.

It’s almost a mathematical impossibility to imagine that, out of the thousands of things for sale on a given day, the most attractively priced is the one being sold by a knowledgeable seller (company insiders) to a less-knowledgeable buyer (investors).

Warren Buffet in 1993 Annual Report

Read the entire 1993 Annual report here

Weather on Desktop with standard python

I love python mostly because of the battery included philosophy.

Here’s a personal project that I did while we went to the first lockdown in March 2020. This was a fun project and I wanted to do all this with standard python modules

The project enables changing Windows Desktop Based on the Weather of the city. It’s nice to have this installed on my laptop. I have few other projects in pipelines based on this but they are still WIP.

The code and the installation procedure is available here on my Github.

Following is the heart of the app that changes the desktop with a given image file.

def set_wallpaper(wallpaper_path=None):
    SPI_SETDESKWALLPAPER = 0x0014
    ctypes.windll.user32.SystemParametersInfoW(
        SPI_SETDESKWALLPAPER, 0, wallpaper_path, 0
    )

Such a pleasure to work with python.

Fortnite Riddle

Last week, my daughter was working on probability problem sets. This prompted me to look at her math book and I was surprised to see that how short the chapter was on this topic l. Not much has changed from what I learnt and what she is learning at least in probability chapters.

Statistics and probability are the most relevant but least-taught maths in schools. They have so many real-world consequences about how people think about everyday risk.

For her to internalize these concepts, I unusually take lunch and dinner time as an outlet to throw interesting questions to them. Here’s one that I recently found on Twitter and shared with them.

My both kids love playing fortnight so painted the question with that color.

Here’s the riddle?

Ann, Brown, and Cathy each carry a paintball gun in Fortnite. They play “ordered Mexican stand-off” according to the rules below.

First, they draw lots to pick an “order”, i.e., who goes first, second, and third. All possibilities are equally likely.

Second, they take their places at the corners of a triangle. See image. Third, they start shooting taking turns in the order chosen, cycling back if necessary, until two of them are hit and only one “survivor” remains. This eventual survivor is the winner of the game.

At each turn, the shooting player has to choose one of the other surviving players to aim at. This is a strategic choice: each player chooses whom to aim at in order to maximize his chances of winning. (And each player knows this is how the other players will behave.)

All players know that Ann always hits whomever she aims at, Brown has an 80% chance of hitting his target, and Cathy only has a 50% chance of hitting her target.

Each turn of each player is independent of all the other turns and all the other players.

Assuming that nobody is hit by a shot not intended for them, who is most likely to win this game?

One of the best decisions that I have made in 2017 was not to eat in front of a TV. This has made dinner time a good family time. This has spurred many interesting games, conversations, questions and learning for me and my kids.

Now your turn to try the riddle? Who do you think will win? Give it a try? Tell me in the comments?

Here my son’s response to this.

Pandas XLS File Read Error

Recently had an issue while reading an xls file with pandas. Pandas was complaining about corrupt excel file. Opening it in excel showed no issue.

data = pd.read_excel("stock_cons.xls")                                                                     
_locate_stream(Workbook): seen
    0  5 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 
   20  4 4 4 4 4 4 4 4 4 4 4 3 2 
....

    430             self.seen[s] = seen_id
    431             tot_found += 1

CompDocError: Workbook corruption: seen[3] == 4

Solution:

Check xlrd version. Get xlrd vers 2.0.0 or above and then use the following

workbook = xlrd.open_workbook_xls("stock_cons.xls", ignore_workbook_corruption=True)                       

data = pd.read_excel(workbook)

Explaination

pandas read_excel function takes a xlrd workbook as an input, so open the workbook with xlrd with the ignore_workbook_corruption as true.

Investing is like….

I agree with this and have expressed similar sentiment in being a gardener.

Investing is like planting an orchard

In the beginning, it’s all effort with nothing to show

After a few years, fruit starts to appear

After 10 years, you are reliably producing fruit

After 30 years, you’re producing more fruit than your family could eat in a lifetime

brianferoldi on twitter

Managing Windows Desktop Using Git

My desktop quickly becomes unwieldy, so to tame the clutter, I have been using git to take regular backup of the desktop, here’s the batch script that I have configured with schtasks on my windows system.

Posting it here with explanation so its useful for others.

@echo off
cd C:\Users\sukhbinder\Desktop

git diff --stat > test
git status >> test
git add -A
git commit -F test

Explanation

git diff –stat Gives a compact statistics on the git

git status shows the current state for the working git folder

git add -A adds all files in the folder. By all I mean all tracked and untracked files in the folder

git commit -F test commits the added files using the contents of test file as the commit message

Master the “When“

Jeff Immelt, the former CEO of General Electric, said this on decision making:

“1,000 books get written about leadership and change and all that stuff. Knowing what to do isn’t that hard, knowing how to do it isn’t that hard. Knowing when to do it is really hard”

— Leadership in a Crisis

Applies to many things in life including investing.

Good Analogies and Math

I wish I had a math teacher like Mr. Azad back in my school. I liked math because of my math Teacher Mr. Neogi, but would have loved math more if these intuitions were highlighted when it was taught to us

If you are still interested, introduce yourself and your loved ones to Kalid Azad’s awesome website betterexplained.com

Here are his few thoughts on learning….


Ideas start hard and finish simple. Complicated ideas get easier. Why? Well, the idea is the same, our thinking process has improved. Multiplication flummoxed the Romans until a number system came along. I know that math, science, business, or any topic can become intuitive after overcoming the initial complexity

The best teacher is you – after you’ve learned the subject. You, 10 minutes after learning a new idea, are the perfect tutor for your current self. You overcame the difficulties and can explain the solution in language that makes sense. We can’t go back in time, but we can capture Aha! moments as soon as they happen. Some lucky soul can avoid the pothole we just climbed out of.

Get a map, not directions. Memorization isn’t understanding: you follow the recipe, apply the formula, and get from A to B without knowing why. Directions “work”, but what about wrong turns? A new destination? Helping a friend who’s lost at point C, not A? Better explained site is about sharing maps, the intuitions that get you from any point to any other point. We’ll leave the raw details for the encyclopedias.

How to get your Windows 10 Product Key with cmd

My son got a laptop from his grandparents. It is a 2018 Lenovo model which came with windows pre-installed.

He was very happy to have a system of his own. Kept the laptop with care for three weeks and now he is bored of it and so I took over and am using it.

One thing that struck me after moving from SSD based hard disk laptop to this SATA disk is that the laptop seems and is slow. Ram and processor are better than my older mac but the hard disk is dragging the performance down.

So decided to upgrade the hard disk. The only problem is don’t have the Windows OS cd, which never came with the laptop

After talking to friends and googling found os installation is possible but you need the product key. My dad doesn’t remember saving any key so turned to google to found how to get windows 10 product key.

Here’s how

Open Command Prompt in Administrator mode.

Type the following

wmic path SoftwareLicensingService get OA3xOriginalProductKey

That’s was step zero, now will move on to the upgrading step.

Tiny Things, Big Consequences

A tiny story about how tiny things that seem inconsequential but operate in a tightly coupled system where one flaw can have big consequences.

Photo by Steve Johnson on Pexels.com

After years of tests, Lockheed engineers finally built a stealth plane. They could fly their prototype without radar picking it up. It was a miracle.

Then one day, it just stopped working.

“You lit up the radar like a goddamn Christmas tree” an engineer tells a test pilot in the book Skunkworks. “They saw him coming from 50 miles away.”

No one could figure it out. They hadn’t made any changes to the plane’s design.

The cause, they eventually discovered, highlighted the complexity of their work.

A screw hadn’t been secured tightly enough during maintenance, its heads extending less than an eighth of an inch above the plane’s surface. That was maybe half a drill spin less than ideal. It was more than tight enough for the plane to operate. But on radar, it “appeared as big as a barn door.”

There’s a lot of hidden leverage in the world – tiny things that seem inconsequential but operate in a tightly wound system where one flaw can bring everything down.

It also makes me wonder: How much incredible technology has been abandoned in frustration when we were half a drill spin away from success?

From Little Stories

Simple Gems of Python

Like last week’s post, this functionality is one I have applied in many of my pet projects and scripts. The use case is to get the string values from the user clipboard.


How to get clipboard contents only using standard python?


There are few methods, but the method shown below is the one that I have used successfully across windows, Mac, and Linux systems.

def get_clipboard():
    import tkinter as tk
    try:
        root = tk.Tk()
        root.withdraw()
        return root.clipboard_get()
    except Exception:
        return None

Here’s a quick demo. 🙂

Get clipboard contents only using standard python

Do you know of any other gems like this?

What if git apply or git am patch fails

Recently had this error while applying a patch on my local repo from the devops repo.

I have a certain patch called my_py_branch.patch.

When I try to apply it, I get following message:

$ git apply --check my_py_branch.patch
warning: src/main/python/.../api.py has type 10645, expected 100755
error: patch failed: src/main/python/.../api.py:28
error: src/main/python/.../api.py: patch does not apply

What does it mean? How can we fix this problem? After a few searched on google landed on this page and learnt about the –reject option.

git apply --reject --whitespace=fix my_py_branch.patch 

This worked for me.

Explanation


The –reject option will instruct git to not fail if it cannot determine how to apply a patch, but instead to apply the individual hunks it can apply and create reject files (.rej) for hunks it cannot apply. Wiggle can “apply [these] rejected patches and perform word-wise diffs”.

Additionally, –whitespace=fix will warn about whitespace errors and try to fix them, rather than refusing to apply an otherwise applicable hunk.

Both options together make the application of a patch more robust against failure, but they require additional attention with respect to the result.

For the whole documentation, see https://git-scm.com/docs/git-apply.