Vinit Kumar

Blog about Web & Programming

Instagram

© 2014. Vinit Kumar All rights reserved.

Better Time Management At Work

Time management is a key quality of any successful person. I have been working pretty hard these days to improve me efficiency. Today, I have decided to follow this pattern while at work.

Here is the breakdown. Let's assume the net hour spent at work is 8.

  • 50% Time (4 hrs) - Writing Code.
  • 5% Time (24 min) - Documentation of the Code I wrote.
  • 5% time (24 min) - Writing test on the Code I wrote.
  • 10% time (48 min) - QA and testing the work I produced.
  • 20% time (96 min) - Planning and Studying about the topic I need to work on.
  • 5% Time (24 mins) - Working with colleagues and helping out in case they need any assistance.

I felt the need to this timetable because it is really necessary to control the time when you are on tight deadlines. I like giving my all to the work and definitely have very limited time to execute that. So only if my planning and time management is solid I would be able to produce quality work on time.

I will produce a analysis of how this goes and how much success I achieve using this methodology. Also, today I have completed my 41 day streak at GitHub.

On Writing Good Code

Whether you are working for a big software company or a small sized startup, writing good code is pretty much critical to your success. But the catch is it is not very easy to achieve without proper motivation from your side.

I have been coding professionally for almost 4 years now. First two years were as a freelancer and I mostly followed Get Things Done mode during that time. It was okay then because it was mostly a one time gig and once done you didn't had to do anything with it. Though I never wrote really bad code even at that time but the amount of maturity and knowledge required to write code that is maintainable, DRY and has some documentation was clearly not there.

While I joined my first company back in 2013, I really struggled against my bad habits. I was able to solve tough technical problems as problem solving is always close to my heart but there were serious issues with my code quality. Sometimes there was some indentation issue and something there were some code repetition. I was lucky to have my Mentor "Ruben" to closely look at my code and review it sharply and give his most honest feedback. Upon pondering about the review I realized most of the issues were coming because a certain amount of thinking and carefulness that was missing from my workflow. I didn't had my editor configured properly. Mix of tabs and spaces will obviously come back to bite you and code will look ugly on browser even though it looked fine on your editor. (Sublime Text, I am looking at you).

Now, after almost an year later I am a improved and mature programmer than what I was at this point of time last year. So what changed?

Here is a short summary of things I did in order to get better at writing code:

  • I started reading classic books on programming. Understanding programming and computer science is pretty much vital to your growth as a software developer. Dreaming about making big in this field without having solid basics is a fools errand.
  • Read a lot of good code. Discuss about it, blog about it and finally incorporate those into your own code. This is pretty much most important to improve the code you are writing. I started reading a lot of good code, on an average of 1 hour daily. With loads of Open Source projects available on Github and bitbucket it is pretty easy to do so.
  • Follow strict mode in almost every language your code on. Use Pep-8, JSHINT, CSSLint, Grunt. This might be painful at beginning but it would cover a lot of ground that you might not know as you are not an experienced developer.
  • Learn and use Travis CI and Jenkins system that would automate a lot of these things in your code.
  • Write a lot of code and open source it. Also, contribute to a good number of OSS projects. I have done a lot of this in the past year and believe me it has really helped in improving.
  • Read the f**king documentation - This is kind of most important if you want to really use the power the language or the framework provides. Otherwise, you will keep writing shitty code because you were never aware better way exists.

  • Use version control- Version control gives you an opportunity to look at your code before committing. Use this powerful feature. Always review your code before your commit. Always review a pull request and merge.

How To Get Readonly Mode In Django

Last week, I came across an interesting problem at work. The problem was:

To get read only users in a Django based application.

But doing so was not very simple because there is no read only mode for users in Django. In order to solve this, I first started reading answers on stack overflow. Some of those links did pointed me to a correct route. Here, I will document the whole process so that it could help others and serve as a reminder for me as well.

First of all, the whole system of authentication in any system originates from permissions. The basis permissions are. Read, Write, Execute. in Unix (chmod is used to set permissions).

Django has a cool way of adding the permissions in the meta class. Let's say we have a model class named Cars.

class Cars(model.Model):
  name = models.Charfield()
  year = models.DateField()

  class Meta:
    permissions  = (
      ('readonly', 'Can Read Only Cars')
    )

Just like this, Any permission could be added to the Model. Now in order to get these permissions in the database. You need to run syncdb management command.

python manage.py syncdb --all

So this just sets the background in place. The real job is getting this permissions to work.

Now, I began to wonder what all things were required to develop this complete functionality ?

The first thing that came to my mind naturally was to override templates and hack ground admin.py.

So, I created a new class in Admin.py that was inherited from the admin class I was earlier using:

from model import Cars


class CarAdmin(admin.ModelAdmin):
    date_hierarchy = 'date'
    list_filter = ('status', 'event_instance',)
    actions = ['accept', 'reject', 'pending']

class ReadonlyCarAdmin(CarAdmin):
    def __init__(self, model, admin_site):
      super(ReadonlyCarAdmin, self).__init__(model, admin_site)
      self.model = model

    def has_delete_permission(self, request, obj=None):
      if request.user.has_perm('car.readonly') and not
      request.user.is_superuser:
        return False
      else:
        return True

    def has_add_permission(self, request, obj=None):
      if request.user.has_perm('car.readonly') and not
      request.user.is_superuser:
        return False
      else:
        return True

     def has_change_permission(self, request, obj=None):
        if request.user.is_superuser:
            self.readonly_fields = () # make sure to remove caching.
            return True
        elif request.user.has_perm('car.readonly'):
            # make the fields readonly for only users with readonly permissions.
            self.readonly_fields = [field.name for field in filter(lambda f: not f.auto_created, self.model._meta.fields)]
            return True
        else:
            return False


     def get_actions(self, request):
        actions = super(ReadOnlyCarAdmin, self).get_actions(request)
        if request.user.has_perm('car.readonly') and not request.user.is_superuser:
            # This ensures that that user doesn't not have any actions
            if 'delete_selected' in actions:
                del actions['delete_selected']
                del actions['accept']
                del actions['reject']
                del actions['pending']
            return actions
        else:
            return actions


admin_site.register(Car, ReadonlyCarAdmin)

Okay, so now we have a robust system in place to ensure whichever user has readonly permission on Cars Model would only be able to see the model data in Readonly mode.

But this is not it. Here is the part where templates are overridden.

First of all save and cancel button on buttom needs to go as we don't need them.

For that, create a new template in templates folder.The templates name is change_form.html. Hence the full pathname is carapp/templates/admin/change_form.html.

Copy the content from the default django template (/admin/change_form.html) in django project add replace this content with this gist:

This will ensure that the selected user with this readonly only permissions won't be able get the submit button on his admin page.

Now, you have a fully functioning Django Admin with readonly mode. The main effort was to make it very easy to use and ensure that this feature could run across future versions.

Hope this post help anyone else who has to implement something similar.

Setting Up Emacs for Development

I always wanted to use Emacs. Yesterday, I wanted to have a good JavaScript/Node REPL in my editor. Though I had always used Vim since last 5 years still setting up a REPL in Vim is not very easy. So I decided to give Emacs a try and till now I am enjoying using Emacs.

Here is a guide that would help you to setup emacs.

First of all, If you are on Mac install emacs for OSX from here. you could easily install the GUI version of Emacs for other platforms too.

My Emacs config

This is my Emacs config which could be used for development in following technologies:

  • Ruby / Ruby on Rails
  • CSS / LESS / SASS / SCSS
  • HAML / Markdown / Textile / ERB
  • Clojure (via nrepl)
  • Javascript / Coffeescript
  • Python
  • PHP
  • Haskell
  • Erlang
  • Common Lisp (with Slime)

In particular, there's a nice config for tab autocompletion, and flycheck is used to immediately highlight syntax errors in Ruby, HAML, Python, Javascript, PHP and a number of other languages.

Demo

This is my emacs live in action:

Requirements

  • Emacs 23 or greater (note that Emacs 24 is required for some functionality, and will likely become the minimum required version some time soon.)

Installation

To install, clone this repo to ~/.emacs.d, i.e. ensure that the init.el contained in this repo ends up at ~/.emacs.d/init.el:

git clone https://github.com/vinitkumar/.emacs.d.git ~/.emacs.d

Upon starting up Emacs for the first time, further third-party packages will be automatically downloaded and installed.

Adding your own customization

To add your own customization, use M-x customize and/or create a file ~/.emacs.d/lisp/init-local.el which looks like this:

... your code here ...

(provide 'init-local)

Tips for using these emacs settings

If you want to use my settings straight out of the box, here are some things to note:

  • I recommend starting with a blank emacs + Technomancy's better-defaults package, and then dig through this repo for useful nuggets, instead of forking it directly.

  • The key bindings are optimized for a norwegian keyboard layout.

  • Start by reading up on all the cool stuff in key-bindings.el.

  • You quit emacs with C-x r q, mnemonic Really Quit.

  • Find file in project with C-x o, in dir with C-x C-f, recent with C-x f

  • Add your user- and project-specific stuff in .emacs.d/users/[machine name]/*.el

  • C-h is rebound to backspace, like in the shell. Get help on F1 instead.

  • Autocomplete with C-. (autocomplete entire lines with C-:)

  • expand-region is your friend. Find its bound key by doing F1 f er/expand-region

  • Undo with C-_ and redo with M-_. Watch the undo-tree with C-x u

  • Quickly jump anywhere in the buffer with C-ΓΈ then the starting letter of a word.

  • Indent and clean up white space in the entire buffer with C-c n

  • On a mac, the Meta key M is bound to Command.

  • I recommend rebinding Caps Lock to Ctrl and use that instead of the often badly placed Ctrl-key.

  • Watch emacsrocks.com

Survival guide for the first week of emacs

When you start using emacs for the first time, your habits fight you every inch of the way. Your fingers long for the good old familiar keybindings. Here's an overview of the most commonly used shortcuts to get you through this pain:

  • C Shorthand for the ctrl-key
  • M Shorthand for the meta-key (bound to cmd on my mac settings)
  • S Shorthand for the shift-key

Files

  • C-x C-f Open a file. Starts in the current directory
  • C-x f Open a recently visited file
  • C-x o Open a file in the current project (based on .git ++)
  • C-x C-s Save this file
  • C-x C-w Save as ...
  • C-x C-j Jump to this files' current directory
  • C-x b Switch to another open file (buffer)
  • C-x C-b List all open files (buffers)

Cut copy and paste

  • C-space Start marking stuff. C-g to cancel.
  • C-w Cut (aka kill)
  • C-k Cut till end of line
  • M-w Copy
  • C-y Paste (aka yank)
  • M-y Cycle last paste through previous kills
  • C-x C-y Choose what to paste from previous kills
  • C-@ Mark stuff quickly. Press multiple times

General

  • C-g Quit out of whatever mess you've gotten yourself into
  • M-x Run a command by name
  • C-. Autocomplete
  • C-_ Undo
  • M-_ Redo
  • C-x u Show the undo-tree
  • C-x m Open magit. It's a magical git interface for emacs

Navigation

  • C-arrow Move past words/paragraphs
  • C-a Go to start of line
  • C-e Go to end of line
  • M-g M-g Go to line number
  • C-x C-i Go to symbol
  • C-s Search forward. Press C-s again to go further.
  • C-r Search backward. Press C-r again to go further.

Window management

  • C-x 0 Close this window
  • C-x 1 Close other windows
  • C-x 2 Split window horizontally
  • C-x 3 Split window vertically
  • S-arrow Jump to window to the left/right/up/down

Help

  • F1 t Basic tutorial
  • F1 k Help for a keybinding
  • F1 r Emacs' extensive documentation

Credits & Inspiration

This config is totally based on this repo by Mr. Steve Purcell. But this might diverge with time and my personal taste.

The Survival guide has been taken from .emacs.d project of Mr. Magnar Sveen

Be Awesome

I write a lot about technical jargon even on my personal blog. For a change, this post is nowhere close to it. As time passes by my thinking and maturity level has improved. I am able to see things that were invisible to me before.

I have learned to control my anger and frustration over things I should not have been upset about in the first place. Control over our actions and anger is important. These two things are very easy to loose but with practise these can become your strength.

These days I have realized the worth of good health and fit body. Since the day, I started going to gym i could really feel the difference in my energy level and awareness. Software development is a really hard profession. There are numerous possibility of getting burnout. After working for three direct months from October, somewhere around January it hit me hard. I was shying away form hard issues, felt tired very soon. Then I realized that all I did in past three months is just code, code and code. Nothing else at all. Even on weekends I was busy with my personal projects. It gives a kick when you immerse yourself in programming. But if you ignore your body and mental health. It will come to bite you.

Since then I started paying more attention to my health and hence started making full use of my Gym Membership. Another thing that I am trying to work on these days is to work only 9-5 on normal days. It might sound strange but if I want to maintain a healthy work life balance, this is a must. Wake up early, commute to office, give solid 8 hours of disciplined work, come back up home, relax, go to gym, watch some TV. These are simple things, but with Good impact.