Record Screen With Python

There a tons of screen recording software available in the market, but you don’t want to install one more software for just one usage. Or sometimes installing a freeware or a paid ware is not allowed.

What to do? you improvise. If you know and have python on your system, you are in luck.

This is what I did, when I had few occasions where I wanted to show my work. A quick gif or a small movie goes a long way, so created this app using python to records shot clips .

Here’s a demo of the same using the tool.

The entire code and tool is available at my gihub here

Git Hooks

Photo by Steve Johnson on Pexels.com

Have been using git since 2012, but during the summer of 2015, my mind was blown away when I discovered git hooks..

Git’s most useful configuration options are its hooks. A hook is a script that Git executes every time a particular event occurs in a repository.

I remember doing lot of crazy stuff with this then but they are really useful tool for any team of developers.

What are Git hooks?
Git hooks are scripts that Git executes before or after events such as: commit, push, and receive. Git hooks are a built-in feature – no need to download anything.

These hook scripts are only limited by a developer’s imagination. Some example hook scripts include:

pre-commit: Check the commit message for spelling errors.
pre-receive: Enforce project coding standards.
post-commit: Email/SMS team members of a new commit.
post-receive: Push the code to production.

How do git hooks work?
Every Git repository has a .git/hooks folder with a script for each hook you can bind to. You’re free to change or update these scripts as necessary, and Git will execute them when those events occur.

learn more https://githooks.com

Enable Syntax Highlighting of Python in Vim

VIM, I have seen a colleague use it. Its powerful. Using just the keyboard he is so productive editing code in it. I don’t have much experience with it except few instances when I am logged to a remote linux cluster via ssh and have no option but to use VIM.

Last year during a debugging session learnt a neat trick from him.

Add the following lines to your ~/.vimrc file:

syntax on
filetype indent plugin on

Thomas Edison and Teaching

In 1877, Edison was working a machine to transcribe telegraphic messages through the indentation on paper, which could be repeatedly sent over the telegraph. This development led Edison to speculate that a telephone message could also be recorded in a similar fashion. He experimented with a diaphragm which had an embossing point and was held against rapidly-moving paraffin paper. The speaking vibrations made indentations in the paper.

Edison later changed the paper to a metal cylinder with tin foil wrapped around it. The machine had two diaphragm-and-needle units, one for recording, and one for playback. When one would speak into a mouthpiece, the sound vibrations would be indented onto the cylinder by the recording needle in a vertical (or hill and dale) groove pattern.

Edison gave a sketch of the machine to his mechanic, John Kruesi, to build. Edison immediately tested the machine by speaking the nursery rhyme into the mouthpiece, “Mary had a little lamb.” To his amazement, the machine played his words back to him.

When Edison built his first phonograph in 1877, he published an article proposing ten uses to which his invention might be put to use. They included preserving the last words of dying people, recording books for blind people to hear, announcing clock time, and teaching spelling.

This teaching spelling reminded me of the way I use winsay and Mac’s say command in the spelling app. It was fun to discover this connection.

Another thing that this story reminded me was how working on something else, we stumble upon other uses. This always happens in work life, the key is to attend to that fleeting connections when they happen.

What are you working on and how does this connect to something else?

An Example of Model View Controller Design Pattern with Tkinter Python 3

MVC with tkinter is by the most popular post on this blog and that post was written in 2014, so i thought of updating it for python 3, Here’s the code in case someone is still looking for.

import tkinter as Tk

from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np


class Model():

    def __init__(self):
        self.xpoint = 200
        self.ypoint = 200
        self.res = None

    def calculate(self):
        x, y = np.meshgrid(np.linspace(-5, 5, self.xpoint),
                           np.linspace(-5, 5, self.ypoint))
        z = np.cos(x**2*y**3)
        self.res = {"x": x, "y": y, "z": z}


class View():
    def __init__(self, master):
        self.frame = Tk.Frame(master)
        self.fig = Figure(figsize=(7.5, 4), dpi=80)
        self.ax0 = self.fig.add_axes(
            (0.05, .05, .90, .90), facecolor=(.75, .75, .75), frameon=False)
        self.frame.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1)
        self.sidepanel = SidePanel(master)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame)
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        self.canvas.draw()


class SidePanel():
    def __init__(self, root):
        self.frame2 = Tk.Frame(root)
        self.frame2.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1)
        self.plotBut = Tk.Button(self.frame2, text="Plot ")
        self.plotBut.pack(side="top", fill=Tk.BOTH)
        self.clearButton = Tk.Button(self.frame2, text="Clear")
        self.clearButton.pack(side="top", fill=Tk.BOTH)


class Controller():
    def __init__(self):
        self.root = Tk.Tk()
        self.model = Model()
        self.view = View(self.root)
        self.view.sidepanel.plotBut.bind("<Button>", self.my_plot)
        self.view.sidepanel.clearButton.bind("<Button>", self.clear)

    def run(self):
        self.root.title("Tkinter MVC example")
        self.root.deiconify()
        self.root.mainloop()

    def clear(self, event):
        self.view.ax0.clear()
        self.view.fig.canvas.draw()

    def my_plot(self, event):
        self.model.calculate()
        self.view.ax0.clear()
        self.view.ax0.contourf(
            self.model.res["x"], self.model.res["y"], self.model.res["z"])
        self.view.fig.canvas.draw()


if __name__ == '__main__':
    c = Controller()
    c.run()

Winsay

The thing I like about MacBook is that it comes with simple features/apps in-built that makes life easy. And being forced to use windows at office I have tried to use python as the bridge to fix these gaps.

One of the feature I like about mac for entertaining kids, and to relax my eyes while reading content is the ease with which Mac allows the reading of text on the screen. Alt escape and it reads the selected text. I have entertained kids with the say command on many rainy days and now use it as their spelling app to revise spellings.

So created winsay, an app that uses your computer to read in text and to have the same functionality as say in Mac.

Demo shown below.

Do check it out the code and the app here on GitHub.

A Primer on Spaced Repetition

After my post on the spelling app for kids, a friend and me were discussing about Spaced Repetition.

Then by serendipity one of the author I subscribe too, sent a weekly link to this primer on Spaced Repetition.

If you’d like to learn more about the powerful spaced repetition technique, check out this article by Nicky Case, which also allows you to interact occasionally with the graphics

A Nice Interactive Graphic Article about Spaced Repetition

I did shared this with my older kids, so she could appreciate the concept of active recall which she practices with the app

Using genfromtxt instead of pandas

When reading a csv file, pandas has become my default, but most of the time, this adds pandas dependency just for reading csv, so I tend to use numpy's genfromtxt. This is a versatile and fast option to use.

To read mixed type data, the dtype=None is the a good option to use.

Using dtype=None is a good trick if you don’t know what your columns should be.

If you already know what type they should have, you can give an explicit dtype. But if that is not known and you want the data to be inferred automatically using dtype=None is a good option

qdata = np.genfromtxt("quater.csv", skip_header=1, dtype=None)

Forced to Talk

Got cable tv in the house after a long gap and I am appalled at the state of the 24/7 news channels.

This reinforced my belief that seeing daily news is something one can miss. You won’t miss anything. If something real happens it will come in your view via other means rest is just puff.

Seeing this constant chatter reminds me of something I read somewhere. Rings so true now

Imagine how much stuff you’d have to make up if you were forced to talk 24/7. Remember this when watching financial news on TV.

Numpy to Json

I don’t know why I have this snippet of code as a text file. This is something that I have used in few of the api endpoints.

A pattern so common, so putting it here as a reference.

import json
import io

import numpy as np

# Create dummy numpy data
expdata = np.random.rand(100,3)

a = io.StringIO()
json.dump(expdata.tolist(), a, separators=(',',':'),indent=4)

print(a.getvalue()) 

The Medal is For the Moment

With the corona-virus raging in the world, it’s a loss that we are not having Olympics this year. This is one casualty that I have seen not many have missed.

In preparation for this Olympics, early in January, I was reading the book “A shot at history” by Indian Olympics gold winner Abhinav Bindra.

Here’s a passage that struck me when someone asked him about his gold medal..

The medal used to be in my mother’s room. Now it’s in a case with my Olympic bib (No. 1334) and score sheets in a room reserved for my trophies. People ask me if I like to touch the medal now and then. Not really. I went through the pain to get it, I won it, experienced it, felt the journey.

The medal is for the moment, reward for two hours of shooting. But for the athlete it’s not the moment of victory that matters, for it’s taken him more than two hours. It’s taken four years, probably eight, it’s taken 250 international flights, 600 moments of ‘I can’t do this,’ hundreds of technical changes, fifty tastes of defeat, four to five nervous vomits. It’s taken internal struggle, psychology books, patient coaches. It’s a dream taken and dipped into sweat to become reality.

All that is more meaningful to the athlete.

Few Not So Common but Useful git commands

Git is a versatile tool. It has lot of things that can make it productive to use. Here’s a list of few commands that I use in git on a monthly basis for my git repositories.

git fsck -> Files system check

git gc -> Garbage collection

git diff –stat -> Only stats

git bundle create -> Export an entire branch, complete with history, to the specified file.

git clean –fdx -> Clears the working directory

git archive –format=zip –output=filename.zip -> Export a single snapshot to a ZIP archive called.

Do you have any other not so common git command that you use regularly?

Life is Like a Snowball.

Last sunday was the 90th birthday of Berkshire Hathaway chairman & CEO Warren Buffett, the world’s most successful investor.

And my twitter feed had this lovely quote from him, couldn’t help but share it here.

Image
credit:Vishal @ safalniveshak.com

“Life is like a snowball. The important thing is finding wet snow and a really long hill. ” ― Warren Buffett

Git Alias for Efficient Development

The term alias is synonymous with a shortcut. Alias creation is a common pattern found in other popular utilities like bash shell. Aliases are used to create shorter commands that map to longer commands.

Aliases enable more efficient workflows by requiring fewer keystrokes to execute a command.

Git aliases are a powerful workflow tool that create shortcuts to frequently used Git commands. Using Git aliases will make you a faster and more efficient developer.

For a brief example, consider the git checkout command.

An alias can be created that maps git co to git checkout, which saves typing: git co to be typed instead.

Some alias that I use in my git workflow are shown below

git config alias.week 'log --all --oneline --decorate --graph --since="2 weeks ago"'

To only see log for last two weeks.

git config alias.plog 'log --date=short --pretty=format:"%h%x09%an%x09%ad%x09%s"'

To show pretty log

$ git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.ci commit
$ git config --global alias.st status

To use just type

git co

git week

git logp

Spellings: How to get good at it?

As my school friends will attest, spellings were never a strong suit for me. Most of this could be because I was lazy and never paid attention to it when reading. I liked reading but never looked at the spellings.

I forgot about this until few years back when I began finding my kids getting spelling tests at school. To give them extra practice, I turned to python.

This is the app that I developed which is based on the concept of spaced revision. According to wikipedia

Spaced repetition is an evidence-based learning technique that is usually performed with flashcards. Newly introduced and more difficult flashcards are shown more frequently while older and less difficult flashcards are shown less frequently in order to exploit the psychological spacing effect.

Here’s a long demo of the app being used by my older kid.

Another fun thing added to the program is voice, so my kids really do love doing this.

My kids have been using this consistently for a over a year now and they have improved their spellings.

If you want to give it a try, please download this wheel or visit this github project to download the code.

Do give it a try if you have kids and let me know how it goes?