Jibrans Perspective

  • Archive
  • RSS

Run Vim Macros on Selected Lines

Short Version: to run a vim macro over selected lines (in visual mode), run the following:

:'<,'>normal @q

It’s been a long time since I last had anything to post, and since I just recently discovered a new vim trick (there is an uncountable number of them) I decided that it’s time to learn markdown again and start writing.

I’m pretty sure that if you’re a programmer, you use vim (if not, I don’t like you… :P). Even if you don’t use it, you’d have to be living under a rock on a deserted island on some long forgotten planet not to have heard of it; the one editor to rule them all!

So, like most text editors, vim allows you to record powerful macros. In fact, almost anything that you can do in vim can be recorded as a macro (correct me if I’m wrong here, I’ve just started using vim a couple of months ago).

For example, I’m currently working on a django project at work and I recently had to code the signup view for the site. What I needed was something like this:

def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user_params = {}
            user_params['username'] = form.cleaned_data['username']
            user_params['email'] = form.cleaned_data['email']
            *snip*
            user = User(**user_params)

now, recording a macro to convert a list of params like this:

username, email, last_name, first_name, country

into this:

user_params['username'] = form.cleaned_data['username']
*snip*
user_params['country'] = form.cleaned_data['country']

is simple. The trick I learned was running this macro on a selection, since otherwise I would have to manually count the number of times the macro needs to be run. Simply, use Shift-v to go into visual line select mode and select the lines on which you want to run your macro and type the following command:

:'<,'>normal @q

where q is the name of the macro you recorded earlier. And that’s it!

As a side note, Stackoveflow is AWESOME! I got this trick from a SO Question as well.

    • #vim
    • #tricks
  • 2 months ago
  • Permalink
  • Share
    Tweet

jQuery is Awesome

Do you know how awesome jQuery really is? If you’re still here, I have a feeling you want to find out. Here is a simple sample from one of my freelancing projects that got me thinking about the power of jQuery, and how it has changed JavaScript programming.

The interface is very simple, but the thing I want to show you is the show/hide control. It’s those little [+/-] things at the top of each element group. The effect is quite basic, but to implement it in JavaScript will require a lot of code. I can’t say exactly how much, but you’ll have to take my word that it’s a lot. :) And that’s a lot of code just to get the page up and running without worrying about the browser compatibility issues (thinking of Internet Explorer).

Using jQuery, the entire JavaScript code to get that page up and running in almost every modern browser; including IE, is:

$(function() {
    $('.toggle_display a').click(function(event) {
        $(this).parents('.header').siblings().stop(true, true).slideToggle();
        event.preventDefault();
    });
});

Using Coffee Script (which is awesome enough to get a post of its own), the code becomes:

$ ->
  $('.toggle_display a').click (event) ->
    $(this).parents('.header').siblings().stop(true, true).slideToggle()
    event.preventDefault()
    • #programming
    • #javascript
    • #demos
  • 8 months ago
  • 3
  • Permalink
  • Share
    Tweet

JavaScript: Delete Array Elements

As part of a freelancing project on oDesk, I am currently working on a couple of simple JavaScript utilities for text processing. A common function in all these utilities is to get a list of non-blank lines from an HTML textarea. The simplest way to get a list of lines from a textarea is:

var lines = $('#textarea_id').val().split('\n');

But with this input:

Asad Jibran Ahmed

Pakistan, Lahore

Web Developer

it produces the output:

["Asad Jibran Ahmed", "", "Pakistan, Lahore", "", "Web Developer"]

which contains empty lines that need to be removed.

A Google search for ‘javascript delete array element’ led me to a post by Wolfram on his blog Pythoneer. He shows how to delete an array element using the array.splice function:

> var list = [4,5,6];
> list.splice(1, 1); // Remove one element, returns the removed ones.
[5]
> list
[4, 6]

Given that I need to remove all the empty elements from an array, my first naive attempt resulted in the following gem of JavaScript code:

$.each(lines, function (index, value) {
    if (value.length == 0) {
        lines.splice(index, 1);
    }
});

However, every time an element is removed; the array size changes. But since $.each checks the array size only once at the start, the iteration continues running beyond the array bounds; producing an exception. The fix is simply creating a new array instead of modifying the old one, like so:

var new_lines = [];
$.each(lines, function (index, value) {
    if (value.length != 0) {
        new_lines.push(value);
    }
});

P.S: I just discovered underscore.js, a very useful JavaScript library that includes some killer functional language features. In the context of this post, the most useful one would be the _.select. It iterates over an array and returns a new array with only those elements which pass a test. The code I used above can thus be replaced by this much more concise piece:

var new_lines = _.select(lines, function (val) {
    return val.length != 0;
});

The official documentation for the select function can be read here.

    • #javascript
    • #notes
    • #programming
    • #string processing
    • #arrays
    • #code snippets
  • 8 months ago
  • 31
  • Permalink
  • Share
    Tweet

The coolest cat

devteam:

The coolest cat

We loved the chase!  

Good luck, Steve.

Signed,
Jailbreakers and tinkerers everywhere.

  • 8 months ago > devteam
  • 154
  • Permalink
  • Share
    Tweet

The Pheonix Blog

Until recently, I was running my blog on Word Press using my own hosting at Web Faction (awesome hosting provider). However, after looking at a couple of well designed Tumblr blogs, it struck me that Tumblr was a lot easier to use and manage, so I have decided to give it a try.

This is sort of a rise from the ashes type of thing for me because I have had a Tumblr blog for almost a complete year now, but haven’t been able to use it much. Infact, I think that I only have 1 original post on my blog. Hence the weird title.

I have just moved my blog from WP to Tumblr, set up the URL redirects (a topic for another post), and basically wasted my entire Sunday afternoon doing something that I may just undo in a couple of days.

But still, I’m excited to try out Tumblr. I have a couple of posts planned out, but if you have ever seen my other blog (which you haven’t), you’ll know that me and deadlines, we just don’t fit together. :)

    • #general
  • 9 months ago
  • 1
  • Permalink
  • Share
    Tweet

The Pakistani Problem

Hazrat Muhammad (P.B.U.H):

Whoever among you sees an evil action, then let him change it with his hand [by taking action]; if he cannot, then with his tongue [by speaking out]; and if he cannot, then with his heart – and that is the weakest of faith.

Narrated by Muslim in his Saheeh.

Elie Wiesel:

There may be times when we are powerless to prevent injustice, but there must never be a time when we fail to protest.

Wikiquote (http://en.wikiquote.org/wiki/Elie_Wiesel)

Edmund Burke:

The only thing necessary for the triumph of evil is for good men to do nothing.

Wikipedia (http://en.wikipedia.org/wiki/Edmund_Burke#Good_men_do_nothing)

These are quotes from three different personalities, each born in different times, yet each saying the same thing; we must never fail to protest against evil. And lately, I’ve been thinking more and more about this.

It actually started a while back. It was Ramzan, and I was taking Sheri with a couple of friends. The discussion somehow turned to Pakistans current situation. Those were the days when a lot had gone wrong very quickly. Corruption scandals were being dug out, calls were being made for martial law and revolution, and then Pakistan was hit by the floods, and all the political scandals that it brought along with it. There were talks of zamindars (land lords) using their political clout to save their lands by flooding the areas where the kissan (farmers) that worked for the land lords lived. There were even talks about politicians taking money from the flood relief fund. Amidst all this were a couple of university students talking about the problems of Pakistan and what it would take to solve them.

Somehow, the discussion turned to the up coming Eid and how chilars (Police Men) standing at chowks (a traffic signal) would be gearing up to stop unsuspecting people going about their business and ask for “Eidi”. Now, Eidi is something that elders give to children on Eid as a present for the joyous occasion. But Eidi is entirely voluntary, and if you don’t give any, you’re not supposed to face any wrath. But not so with the common police man. NO! Say no to a police man and you’ll be charged with everything from not wearing a helmet to DUI (drunk driving). So the Eidi the police man is asking for isn’t voluntary at all. It’s just an epitome for a bribe. A nice way for the police to ask, nay demand, your hard earned (or otherwise) money from you.

So anyways, I was trying to make the point that you should not give in to the demands of the police man. And I was shut up quite nicely when asked what I would do if a police man stopped me on the road and demanded money from me to let me go. Either give him the money or go to jail. The perfect example of being between a rock and a hard place! And then my friend said something that I think describes the Pakistani mentality perfectly.

Bribery isn’t haram (not allowed according to Islamic rules) in Pakistan. None of the things that you have to do to survive in this country is haram. You do them because you have to, not because you want to.

All this made me think of the quotes that I put at the start of this post, that we should do whatever is in our power to stop evil. I of course understand that it is unrealistic to assume that an average guy will put his life and limb at risk just to fight a corrupt system when a police man is asking for a bribe, but that should not stop us from protesting against it, even if the protest is a simple thought that what happened is wrong and given the same power as the police man, I shall not do what he has just done. That should be enough to serve as a starting point to improve this system.

But the problem isn’t in the system itself. It’s in the people. We aren’t exactly taught from the start to protest. We are told to keep our heads down and live our lives quietly without getting into any problems. We are taught this from class 1. We are taught that money and power can save you from a lot of trouble. Got bad marks in a paper? No problem, just get your parents to talk to the teacher, give him a box of sweets, and presto, problem solved! See someone being beaten up in the streets by the police? Don’t stop to interfere, just look down and pass them by. Why should you interfere and get beaten up as well?

And this is the kind of thinking that results in the beating to death of two children in bright day light and in full view of 6 or so police men in Sialkot.

Then our discussion turned to smuggling and how it should be avoided. My friend said something that again portrays the Pakistani mentality quite nicely.

The government takes taxes and it goes into the pockets of the politicians. They fill their pockets left and right. They do whatever the hell they can to get their hands on more and more money, and most of it comes at the detriment of Pakistan and it’s people. So, if you have a chance to not give money to the government, you should take it. 

And this made me think about a saying that I hear often:

Jaisi Qom Waise Hukamran

Loosely translated, it means:

The rulers are of the same nature as the people they rule

Even logic validates this statement. Our rulers are chosen from amongst us, and if we try to take money from the government every chance we get, how can we expect our rulers to do any different. This point of view is expressed quite nicely by Hassan Nisar, a political analyst/scholar from Pakistan in this video:

http://www.youtube.com/watch?v=wrloEQ2LyDc&feature=player_embedded

This gives even more importance to protesting against the evils of the system. The form of protest doesn’t matter, as long as you continue to protest.

And finally, there’s a lot of talk going around revolution. In my humble opinion, we need evolution much more than a revolution. A revolution doesn’t really accomplish anything. The system doesn’t change magically. It never changes unless the people change. And the only way to do so it to instill the qualities we want to see in our rulers into our children, from the start. The only right way to change the system is to change ourselves. Only then can we create a better system, a better country, and perhaps even a better world.

    • #Pakistan
    • #Corruption
    • #Bribery
    • #Islam
  • 1 year ago
  • 3
  • Permalink
  • Share
    Tweet
ihatemyparents:

Just give me one inch! I will kick this punks pink ass.

Let Me At Him!!!
Pop-upView Separately

ihatemyparents:

Just give me one inch! I will kick this punks pink ass.

Let Me At Him!!!

    • #humor
    • #photography
    • #animals
  • 1 year ago > ihatemyparents
  • 57
  • Permalink
  • Share
    Tweet
ihatemyparents:

pavlovsstepson:
My diabolical plans are coming to together splendidly…I mean, Goodnight!
Pop-upView Separately

ihatemyparents:

pavlovsstepson:

My diabolical plans are coming to together splendidly…I mean, Goodnight!

    • #humor
    • #photography
    • #kids
  • 1 year ago > pavlovsstepson
  • 165
  • Permalink
  • Share
    Tweet
karmahasutra:

jhendi:

poisonedflowers:
(via everygreatcity)


I must say, gotta admit the guts of the photographer who took this photo&#8230;
Pop-upView Separately

karmahasutra:

jhendi:

poisonedflowers:

(via everygreatcity)

I must say, gotta admit the guts of the photographer who took this photo…

    • #animals
    • #photography
    • #nature
  • 1 year ago > everygreatcity
  • 481
  • Permalink
  • Share
    Tweet
It is better to have a permanent income than to be fascinating.
Oscar Wilde
iGoogle Widget: Quotes of the Day
    • #quotes
  • 1 year ago
  • Permalink
  • Share
    Tweet
← Newer • Older →
Page 1 of 2

About

I'm a programmer, mostly working on Python web apps, usually using the Django framework.

Here I write about anything and everything. Topics are diverse and include Programming, Pakistani Politics, and even a bit of religion.

Twitter

loading tweets…

  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr