togist chrome plugin

This is a simple chrome plugin that /me managed to build which helps to create public gists on github.

All you need to do is :

1. Select some text/code on any webpage.

2. Right click on the selection.

3. Click on togist as you see in the screenshot 

4. Enjoy! 

INSTALL IT

JavaScript one liner extracting unique words from webpages

Unlike JSON parsing with ruby one-liner ? this is indeed a very strong raw JavaScript one liner that /me managed to frame last weekend.

So what's the deal?

Extracting all the words in a given webpage, which later can be used to parse or search!

The whole idea is to collect all the words in the page and create a set() out of it.

Javascript ReferenceError: Invalid left-hand side in assignment

So lately was trying some silly syntax with javascript, logically it seems to work, but throw away your dry logic!

Most of us who have been pawing at some raw JS knows  undefined || "hi" would result in "hi", on the same lines, /me tried :

Hitchhikers guide to npm

Hello hackers, this post is just a simple hello-world packing tutorial for packing nodejs with npm.

P.S : This does not talk about how npm works in depth, but gets one started with npm and assumption is you have dealt with some nodejs and npm installs before!

First up, if you have not installed node.js and npm (which is bundled with latest version) please do :

$ bash < <(curl h3manth.com/njs)

7 ruby gems in 7 days

So /me managed to write 7 silly ruby gems in 7 days, the below is a simple video demo of those 7 ruby gems :

DEMO

LInk to the gems:

Notes from Build Awesome Command-Line apps

Lately I was going through book and talks on "Build Awesome Command-Line Applications in Ruby: Control Your Computer, Simplify Your Life" by David Bryant Copeland.

Major stuff /me noted down from it are as below :

The UNIX Way

  • grepable (One "record" perline)
  • cutable (delimited "fieIds")
  • exit codes! (O for success, nonzero for failure)
  • messaging (stderr) vs. output (stdout)

TypeError: Object #<NodeList> has no method 'forEach' in javascript?

Iterating a NodeList in javascript using forEach due to temptation, you have defiantly come across TypeError: Object # has no method 'forEach'

Before digging into the error, let's try to understand what a NodeList is!

IDL Definition of NodeList is as below :

interface NodeList {
  Node               item(in unsigned long index);
  readonly attribute unsigned long   length;
};

JSON parsing with ruby one-liner ?

Parsing JSON is one of the most common tasks that any web developer does in his daily activities.

Parsing JSON with ruby with is fun and the fun multiples n.times when the code is a one-liner

Indeed some gems are needed along with ruby and rubygems, you shall need :

gem install rest-client

Native JS like jQuery

Lately was pawing at some [Selector API's][1] and really liked the raw power of native JS!

So here is some comaprsion of Native JS vs jQuery selectors

As jQuery uses "$" as a shortcut for "jQuery", lets defined a naughty $$ for making things much more easier. [ True! I can use "jQuery.noConflict()".]

As per the standards The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.

function $$(selector){
return Array.prototype.slice.call(document.querySelectorAll(selector), 0);
}

URL scrapping with javascript

Quite some time ago /me had coded a small entry on Hyperlink to URL && Extracting all the links from a site which was much of a terminal based scrapping.

Lately I was playing around with different possible ways of extracting URLs from a give webpage using plain and raw javascript, the idea was to figure out which of the different possible ways is the best and how.

A simple comparison of different methods is demonstrated in this entry.

The focus of this writeup :

  • List out the possible ways of extracting URLs.

  • Do a performance review of them.

  • Select the best out of the lot.

Download images with node.js

All of a sudden /me gets silly and crazy thoughts to do useless tasks that just pleases me only!

Here is one such task, the code below downloads images from a given URI to the filesystem.

TypeError: can't convert Regexp into String

TypeError: can't convert Regexp into String in Ruby So what?

#!/usr/bin/env ruby
"hemanth".include?(/hem/)
=begin
Exectuing the above code will result in :
TypeError: can't convert Regexp into String
=end



It so happens that the String#include? takes only a string argument not a regular expression, as the below code makes it clear.

One click duckduckgo

Check out the ONE CLICK DDG DEMO

Search any text that is selected anywhere in the OS with duckduckgo in a single click is really fun!
Yes you read it right, may the text be in a document, webpage, terminal anywhere you can imagine and select can be searched with duckduckgo with a single click, using a simple one liner and some easy GUI tricks as in the video.

Dependency : xclip - command line interface to X selections (clipboard)

Comparing Strings with variable white spacing

Stings may sound like 101 of programming, but just a glimpse of TAOCP would turn the thought inside out!

Comparing Strings is on of the most common tasks that any programmer would do, but the fun never ends with strings!

Comparing Strings with variable white spacing, is also one among the most common cases, below /me has tried to collect the most intuitive way of doing it in Ruby, Perl, Python and Javascript

Say we have two strings str1="hemanth is testing" and str2="hemanth is testing" with white spaces in consideration, these two strings are not equal, but logically handling the extra spaces would reveal that these strings are equal, which plays a very important role in fileds like : parsing, NPL, testing and so forth.

On the other hand, if we try to compare strings ignoring cases, we will end up with wrong results, say for example comparing two strings like "a book" and "ab o ok" ignoring spaces would be the same, but they are in real not!

The below are the ways to compare strings with variable strings are as below :

Ruby : Out of all the languages considered here, /me selected ruby because, none of the other languages provide such an easy way to do this with their own standard libs.

>> "a book".squeeze == "a       book".squeeze
=> true
 

Perl : Perl's R.E are always interesting.

$str1 = "hemanth is     testing" ;

$str2 = "hemanth is testing" ;

$str1 =~ tr / //s;

$str1 == $str2 ? print 1 : print 0;

 

Python: Indeed the famous "import re"

>>> s1="hemanth is testing"
>>> s2="hemanth is    testing"
>>> re.sub("[\x00-\x20]+", " ",s2) == s1
True

 

JavaScript

str1 = "hemanth is testing"
str2 = "hemanth is      testing"
str1.replace(/\s+/g, " ") == str2.replace(/\s+/g, " ")

Do let me know your ways of doing the same!

_Update 0:_

As per the comments below from Kevin, it worth to keep this is mind :

1.9.3-p327 :001 > "a book".squeeze == "a bok".squeeze
 => true 
1.9.3-p327 :002 > "a book".squeeze(" ") == "a book".squeeze(" ")
 => true 
1.9.3-p327 :003 > "a book".squeeze(" ") == "a bok".squeeze(" ")
 => false 

P.S : We are passing an empty sting to squeeze!

Watir Webdriver attach window

While porting a watir based automation framework to watir-webdriver, I came across an issue that most have come across, that being : "In Watir and Selenium Webdrivers, there is no longer an attach met

Remotely enable remote desktop on Debian

It so happened, as I was working from home last Friday, box there at office had only ssh enabled, but was in need of remote desktop badly [ But default it's not enabled ].

Android Remote Control Setup

Control your Android devices while running scripts on your computer!

Wonder can be done with ASE and an android device along with scripting languages like Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell.

Would it not be wonderful to run code on your box and the same being reflected on your android devices ?

The same is achieved with help of Scripting Layer for Android's remote control.

Before one uses the script make sure that you have a GNU/Linux box with sudo privileges and an Android device with ASE installed on it.

Tweaking Command Not Found

Most of the time in ubuntu, when we come across the message like : The program 'program_name' is currently not installed. You can install it by typing: sudo apt-get install program_name

We would end-up doing "sudo apt-get install program_name" and installing it.

This repeats so why not automate the same? Solving this question, I had to do the below :

Bash shell has a hook called command_not_found_handle

Getting server info using nodejs

Getting server information using nodejs is very easy especially using the os module.

Wrote a simple script to fetch hostname, loadavg, uptime, freemem, totalmem, cpus, type, release, networkInterfaces, arch, platform, getNetworkInterfaces from the server where the node is running.

Below is the code to get the server info using nodejs :

HTTP-request header from node.js

The message header of requests and responses in the Hypertext Transfer Protocol define the operating parameters of an HTTP transaction.

Say if you want to do a language detection in the browser : One must be aware that browser settings don't actually affect the navigator.language property that is obtained via javascript, but they do affect is the HTTP 'Accept-Language' header, but this value is not available through javascript at all!

So we need some server side help, why not use javascript itself on the server side?

Unicode symbols as function names

Unicode stings for function/method names is a very rare scenario, but who knows in the near future people might use them daily! [ Too much of an expectation aye? ;) ]

Say : one needs to convert dollars to pounds and writes a method to do so, might name it "dollar2pound", but a code monkey might name it $2£

Below is the result of such a play in few of my favorite programming languages :

To makes things silly/simple, lets assume our methods takes an integer argument and prints ❤'s those many time.

First up is BASH [ Simple, undocumented so might stop working soon! ]:

function() { yes '❤' | head -n$1 | xargs echo; }

# Invoke the function12

# Bazinga! we got 12 ❤s :)
❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤

Python's turn :

l={} 
l['❤'] = lambda x: "❤ "*x
print l['❤'](12).decode('utf8')
❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤


Perl! here it comes! [ Yes you are right, no strict ] :

use utf8;
*{'❤'} = sub { print '❤ ' x shift; }; 
${\'❤'}->(12);  
❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤


Ruby [ Don't forget -Ku ] :

#!/usr/bin/ruby -Ku
def(x)
    puts '❤ '*x;
end(12)
❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤


JavaScript FTW!?

String.prototype.repeat = function(n) { 
return (new Array(n+1)).join(this.valueOf()); 
};
this["❤"] = function (x) { return '❤ '.repeat(x); }; 
this["❤"](12)
❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤

Update :

function Σ() {return [].reduce.call(arguments, function(a,b){return a+b})};
 
Σ(1,2,3,4)
 
10

So how do you do it in your fav programming languages ;) ?

Invalid HTML in Google's homepage

When validating my homepage /me got 1Error and 1warning, was curious to paw more!

w3.org validator says : 37 Errors, 2 warning(s) on validation of google.com!
Edit 1 : It says : 39 Errors, 2 warning(s)
/me loves reading obfuscated code, with javascript in view on of the most obfuscated code can be found in the source pages of google pages, may it be gmail, g+ or even their 404 page! It's fun reading it.

Simple closure for cross browser XHR instance

Yes that is right, there are many libraries to handle XHR, but raw JS is always fun!

There are many ways of doing this, but here is a unique way of getting an XHR instance.

A simple closure, that tries to create a simple XHR instance :

typeof JavaScript tweaked

Most of the programming critters pawing at JavaScript would have used the typeof operator that returns a string indicating the type of the unevaluated operand.

But the well know confusing with typeof, is the string it returns!

  • typeof [] => "object"
  • typeof {} => "object"
  • typeof null => "object"

The below is a simple, but very effective tweak for the typeof operator

JavaScript Event tracking and management

Events play a major role in all most all the JavaScript libraries. Experimenting on the same lines, coded a simple prototype with raw JavaScript to make the basic event management and tracking easier and names it event.js.

So what does event.js do?

  • Add events to DOM elements. [Cross-Browser support]
  • Get the event type for the particular DOM element.
  • Remove a single or all events.

Simple Cookie Management with JavaScript

On of the most common things that most of the web developer would do is cookie management.

Was pawing at some JavaScript and made a simple cookie management class in JavaScript that does basic cookie management like :

  • setCookie
  • getCookie
  • removeCookie
  • getAll
  • removeAll

Okies, so now enough of talking here is the silly code :

manageCookie = {
     /*     Set a cookie's value
         
         *  @param  name  string  Cookie's name.
         *  @param  value string  Cookie's value.
         *  @param  days  int     Number of days for expiry.
    */
    setCookie: function (name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        } else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    /**     Get a cookie's value
         
         *  @param  name  string  Cookie's name.
         *  @return value of the Cookie.
    */
    getCookie: function (name) {
        var coname = name + "=";
        var co = document.cookie.split(';');
        for (var i = 0; i < co.length; i++) {
            var c = co[i];
            c = c.replace(/^\s+/, '');
            if (c.indexOf(coname) == 0) return c.substring(coname.length, c.length);
        }
        return null;
    },

    /**     Removes a cookie
         
         *  @param  name  string  Cookie's name.
    */

    removeCookie: function (name) {
        manageCookie.setCookie(name, "", -1);
    },

    /** Returns an object with all the cookies. */

    getAll: function () {
        var splits = document.cookie.split(";");
        var cookies = {};
        for (var i = 0; i < splits.length; i++) {
            var split = splits[i].split("=");
            cookies[split[0]] = unescape(split[1]);
        }
        return cookies;
    },

    /** Removes all the cookies */

    removeAll: function () {
        var cookies = manageCookie.getAll();
        for (var key in cookies) {
            if (obj.hasOwnProperty(key)) {
                manageCookie.removeCookie();
            }
        }
    }
};

Introducing the slang API

Lately was working on some slang filtering module, but for the LOLz of it made a simple JSON API.

The deal is pretty simple, the API takes in an SMS slang word and expands the acronym.

So, here is a simple jQuery code to get results :

JavaScript MapReduce One liner?!

After Word frequency using mapreduce in python
I got my paws dirty with some silly javascript, after reducing a whole chuck of code, it turned out to be a simple one liner in JavaScript.
A linear implementation of map reduce, none the less it was fun and indeed will be much useful if on node.js.

Enough of talking! The below is the one liner that would give the word frequency in JSON format.

One Liner :

Word frequency with Mapreduce in python

"MapReduce is a programming framework popularized by Google and used to simplify data processing across massive data sets. As people rapidly increase their online activity and digital footprint, organizations are finding it vital to quickly analyze the huge amounts of data their customers and audiences generate to better understand and serve them. MapReduce is the tool that is help"

The algorithm fundamentally boils down to two crisp steps, indeed they are map and reduce

  • map (k1,v1) ! list(k2,v2)
  • reduce (k2,list(v2)) ! list(v2)

Setup your own cloud in 30 seconds

Yes from past few years there is hell lot of hype for cloud. Which is the new name the enterprise gave for the old game of web-hosting.

I recently did a setup of my OwnCloud which took be 30 seconds!

It's all about FREEDOM An open personal cloud which runs on your personal server, which is licensed with GNU AFFERO GENERAL PUBLIC LICENSE