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;
};

The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.

NodeList or collection of nodes are normally returned by methods like : getElementsByTagName, getElementsByTagNameNS, Node.childNodes , querySelectorAll, getElementsByClassName etc.

It's important to note that the items in a NodeList are accessible via an integral index, starting from 0.

So one would general write a normal loop like below to access the elements of a NodeList, but when we try to apply a forEach() on it, we will get an error because it has no method but that name!

for (var i = 0; i < Nodes.length; ++i) {
  var item = Nodes[i]; 
}

Simple trick to iterate NodeList is to define use Array's forEach() on NodeList, like below :

var forEach = Array.prototype.forEach;
var hrefs = document.querySelectorAll('a');
forEach.call(hrefs, function(link){ consol.log(link.src)});

If that is more, how about the below ;)

[].forEach.call( document.querySelectorAll('a'), 
function  fn(elem){ 
    console.log(elem.src);
});

Converting NodeList to List :

myList = Array.prototype.slice.call(myNodeList);

Do let me know, if with your tricks of doing the same! Happy Hacking!

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

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.

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 :

<

div class="javascript" style="font-family:monospace;color: #006; border: 1px solid #d0d0d0; background-color: #f0f0f0;">/*

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

Instant upload images to imgur from android

Python needs to be embraced for it's capacity to gel with android so well and make things easier with simple and fun scripts.

After installing G+ android app, /me was curious about instant upload of images that the app provides, so decided to make a simple script to emulate the same, but as imgur is one my favs, used the same.

Instant upload images to imgur is a simple script that does :

<

ul>

  • Invoke camera to take a picture.
  • Upload the picture to imgur.
  • SMS the link to the img.
  • Copies the link to the cilpboard.
  • Figlr ASCII art on fly

    Figlr is a simple fun tool to generate FIGlet text. Those are normally used to make ASCII art banners.

    It makes use of Figlet-JS which is a JavaScript implementation of a FIGdriver and is also available as a Node module and a jQuery plugin.

    The code :
    The code is a simple javascript trick, to listen on the paste and keyup events from a text area and populate a pre tag with the FIGlet text.

    <

    pre style='color:#000000;background:#ffffff;'>$(function(){

    Programmatically delete SMS in android using python

    Deleting SMS text has been on of issues with default SMS clients of Andriod OS. Issue 5669 talks a lot about it.

    The most common alternative is to use different SMS clients, that allows bulk delete.

    But using some simple python script, deleting SMS from inbox is just a click away, provided one has SL4A installed on the device.

    Simple python script to delete SMS from inbox in Android devices :

    Yoda talks to XMPP, Twitter and Identi.ca

    This is more a tribute to Master Yoda rather than coding!

    The idea was to use a simple python script to update my gmail, tiwtter and identi.ca with a random saying from Master YODA from Star Wars!

    Yoda for me is not a mere character for a movie, but he is a philosopher, motivator and indeed the renowned Jedi master.

    Python modules needed :

    <

    ul>

  • XMPP
  • Wikipedia search summary API

    After Random images from wikipedia I made another simple API to get the summary for a search term using PHP.

    It's a JSONP API that queries the DNS of wikipedia to fetch the TXT records, which also includes a short URL to the complete corresponding Wikipedia entry. As cross-domain requests are possible with this API, one can easily integrate it to search boxes or widgets.

    Monkey code :

    Random images from wikipedia

    After Random images from xkcd as wallpaper it was time for some more fun, this time did a simple script to get Random images from