Thursday, November 8, 2012

Find total number of lines recursively in terminal

Recently I need to do some analyze on code check into certain repository, and thanks to linux provide a very useful to for wc, you can get word count, number of lines types of information easily. And in order to do it recursively, here is the command you need, very handy for me :)

find . -name '*.js' | xargs wc -l

Tuesday, October 9, 2012

Web Platform Docs

If you guys didn't know, the W3C has started a project called Web Platform Docs ( currently in alpha release ) aimed at being the centralized resources for web developer.  This project has been and will continue be contributed by the main (and big) players in the web development industry.

http://docs.webplatform.org/wiki/Main_Page

If you haven't heard of that before, you can visit their "Getting Started" link,

http://docs.webplatform.org/wiki/WPD:Getting_Started

Monday, September 17, 2012

You don't need ssh-copy-id

This is what ssh-copy-id does

cat ~/.ssh/id_rsa.pub | ssh user@machine "mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys"

If you are using Mac or other *nix flavor that doesn't have ssh-copy-id, the above is what you need.  That's exactly what ssh-copy-id does :)

Thursday, September 13, 2012

Modeling and Reasoning behind DOM Events

A nice presentation on why DOM events behave in certain way.  So instead of telling you what a UI developer should know, it tells you why you have been told is true.

https://www.usenix.org/conference/webapps12/modeling-and-reasoning-about-dom-events

Here are some more good links in my reading list this month :)

Race Detection in UI
http://www.srl.inf.ethz.ch/papers/pldi12-wr.pdf

Whitepaper on Why Eval is Evil and General Misunderstanding
http://www.cs.purdue.edu/homes/gkrichar/papers/eval-ecoop-2011.pdf

Thursday, June 28, 2012

RaspberryPi mouse and keyboard do not work after startx

Setting up my recently received RaspberryPi and everything seems fine, I can get the Pi working.  However, when I try to startx, my mouse and my keyboard doesn't response at all.  At first, I thought it might be the power drained is maxed out, but after several searches, looks like it is because my firmware is not updated.  However, updating Pi firmware is a pretty tedious task itself.  Let me documented my experience here and hopefully someone might be benefited from this post.



You need to download the rpi-update script
  • wget https://raw.github.com/Hexxeh/rpi-update/master/rpi-update
Move the script to /usr/bin/rpi-update and run chmod +x /usr/bin/rpi-update

You need to do a update, since I'm using the Debian version, just run sudo apt-get update

Now you need to install ca-certificate
  • sudo apt-get install ca-certificates
Install git-core
  • sudo apt-get install git-core
Last, update your Pi firmware
  • sudo rpi-update
Reboot your Pi, and login.  Now try startx and your mouse and keyboard should response again, enjoy your Pi!




Friday, June 8, 2012

Tools to test across all browsers

http://www.browserstack.com/
BrowserStack is a web based cross browser testing tool.  Has a nice feature to let you test on development server that might not be exposed to the public.

http://browsershots.org/
BrowsersShots let you enter your URL and do a browser compatibility test across the browsers you checked. Some people prefer Adobe Browser Lab because they claimed it's faster than Browsershots, and one can save his/her own set of browsers.

http://netrenderer.com/
IE NetRenderer allows you to check how a website is rendered by Internet Explorer 10, 9, 8, 7, 6 or 5.5, as seen from a high speed datacenter located in Germany. Just type in a URL in the field above and try it out - it's free!

https://browserlab.adobe.com/en-us/index.html
Adobe BrowserLab is an online service that helps ensure your web content displays as intended. Accurately preview web pages across multiple browsers and operating systems, navigate links, and use diagnostic tools to optimize websites efficiently.

https://addons.mozilla.org/en-US/firefox/addon/adobe-browserlab-for-firebug/
Adobe BrowsersLab for Firebug

http://spoon.net/browsers/
Browser Sandbox lets you "run popular web browsers with no installs" (IE6, 7, 8, 9+, Firefox, Chrome, Safari, Opera).

http://finalbuilds.com/iecollection.htm
Multiple IE versions you can installed.

http://www.microsoft.com/en-us/download/details.aspx?id=4580
For testing in different IE versions on Windows, you can also use Microsoft Virtual PC.

Note: The above is not an exhausted list of tools you can use for browser testing.  If you have more tools you have seen and want to share, please feel free to add it in the comments, thanks!


Wednesday, May 2, 2012

SVN log by username

Currently there is native way to view svn log by username, however you can use extra command to achieve the same thing, for example the following one :

svn log | sed -n '/username/,/-----$/ p' 

Tuesday, April 3, 2012

DOM Introduction Slides

Today we covered javascript DOM in the class, here is the slide we used today.

Monday, April 2, 2012

jQuery how to scroll to particular line in textarea

Recently I was working with outputting formatted source code in a textarea, and the requirement is you have a control "sidebar", which is a list, that allow user to click on and the textarea will scroll to particular line accordingly.

In jQuery, when you use the below. the textarea will scroll to the top

$('.my_class_for_this_textarea').animate({ scrollTop: 0 });

However, in my case, the sidebar list only tells you the code is in line 100 for example.  How to make sure you tell jQuery to scroll to the correct line every time??

scrollTop  takes "pixels", and you need to find out your pixel of each line is. And the following is the formular.

$('.my_class_for_this_textarea').animate({
  scrollTop: my_relative_line_number * LINE_PIXEL
}); 

The correct way to get mouse coordinates

I still saw some developers try to use different formular / ways to find out the mouse coordinates.  Well, according to the documentation, there is always only one correct cross-browser way to find out the real mouse coordinates   relative to the browser.   (  Note: mouse coordinates relative to your computer screen is not very useful for most of our cases, so the below is mouse coordinates relative to browser. )

Here is how the recommended implementation looks like :)
function myCallBack(e) {
 var posx = 0;
 var posy = 0;
 if (!e) var e = window.event;
 if (e.pageX || e.pageY)  {
  posx = e.pageX;
  posy = e.pageY;
 }
 else if (e.clientX || e.clientY)  {
  posx = e.clientX + document.body.scrollLeft
   + document.documentElement.scrollLeft;
  posy = e.clientY + document.body.scrollTop
   + document.documentElement.scrollTop;
 }
 // posx and posy contain the mouse position relative to the document
}

Wednesday, March 28, 2012

Javascript Date return NaN in IE 8

Well, UTC suppose to be universal date-time format, but when I do Date.parse() or new Date() with UTC string in IE8, it returns null / NaN  ( while all the browser, including IE9, works ).  Well, it turns out that IE 6 - 8 doesn't understand UTC date-time format :)  Not surprise though, it is IE after-all.

This website has a metrics of javascript Date support for all browsers, pretty handy.
http://dygraphs.com/date-formats.html

One of the solutions is to override Date.parse() when the browser is an IE.

Tuesday, March 27, 2012

Javascript Constructor return rules

Tonight we have a student asked about what if we return a primitive types in a constructor function, like the below:

function Person() {
   this.name = "Roy";
   return "abc";
}

What would be the return if we instantiate this constructor?

var me = new Person();
console.log(me); // what would you expect to see??

The result is you will get an instance of "Person".  Some people may question "the return was a string, how come it still return an instance of Person?"   Well, it is all related to the "new" keyword.

Whenever you instantiate a constructor ( or a Class ) using "new" keyword.  The javascript interpreter will enforce you to return an object.  If you do not return an object ( just like the above ), the javascript interpreter will enforce this rule by returning an instance of a current constructor.

So it will be similar to the following:

function Person() {
   this.name = "Roy";
   return this;
   //return "abc";
}

However, if you define an object at the return, the javascript interpreter won't care about it.

function Person() {
   this.name = "Roy";
   return { name: "Joyce" };
}

The above code works because it is returning an object, but it won't be an instance of Person.

So, remember, if you return a "primitive types" in a constructor, when you instantiate the constructor with a "new" keyword, you will always get the instance of the Constructor back.  However, if you return an object, you won't have any issue.

Wednesday, March 21, 2012

Javascript Garbage Collection

There's a student yesterday asking about garbage collection in Javascript.  And here it is how it works from  a high level perspective.

Memory is allocated to objects when they created and reclaimed by the browser when there are no more reference to it.  A garbage collection is a mechanism that saved developer time or effort from explicitly performing memory management task and its main duty is to  determine when it is safe to reclaim the memory.   Of course, if an item is still being referenced or being used, it won't collect those memory.   It only collects the memory from objects that are no longer reachable or referenced.

But how does that works?  Well, most garbage collection is using different variants of "Mark-and-Sweep" method/algorithm.  In Javascript, it travsed periodically all the variables and objects and mark items that are still being used or referenced. And it follows with the "sweep" step, it sweep any "unmark" items and reclaim the memory back by deallocating those.

Ok, so how does those information help us?  

In Javascript, global scope variables are not garbage collectable and presenting opportunity for a memory leak, and it explains why we need to limit the usage of global variables in our program.  ( There are many reasons why you should limit the use of global variables, this is just one of the reasons ).

Whenever you create an object using a "new" statement, use a delete statement to explicitly destroy it when it is no longer needed.  This step ensures the memory of that object will be available to the garbage collection.

There is a blog post more on this topic:
http://blogs.msdn.com/b/ericlippert/archive/2003/09/17/53038.aspx

Tuesday, March 20, 2012

HTML5 Community Night


5:00 - 6:00 pm      Registration, Demo showcase, Social, food, drink
6:00 - 6:30 pm      Kick off  (Doris Chen, Ann Burkett, Kevin Nilson)
6:30 - 7:10 pm      The Graphical Web - Fostering Creativity (Adobe: Vincent Hardy)
7:10 – 7:50 pm      Dart (Google: Seth Ladd)
7:50 – 8:00 pm      break
8:00 - 8:20  pm     WebFWD (Mozilla: Diane Bisgeier)
8:20 - 9:00  pm     Behind The Scenes of Cut The Rope (Microsoft: Giorgio Sardo)
9:00 - 9:30 pm      Panel Discussion & Q&A (Kevin Neilson, Vincent, Seth, Giorgio)
9:30 - 9:40  pm     Give Away and Wrap

Saturday, February 18, 2012

TSG Javascript Programming - Part I




Title
TSG Javascript Programming - Part I

Prerequisite
This class ( Part I ) does not requires any javascript background, but basic knowledge on HTML and CSS is preferred.

Location
G5 ROLCC -  Please click the logo below for more detail on TSG location.

Cost
$65 Dollars

Date & Time
Time will be 7:30 pm - 9:15 pm
  • 3/06/12 ~ Basic Introduction - Doing Javascript The Right Way
  • 3/13/12 ~ The Building Blocks of Javascript
  • 3/20/12 ~ Array and Functions
  • 3/27/12 ~ Creating Objects 
  • 4/03/12 ~ Document Object Model
  • 4/10/12 ~ Field Trip to HTML5 conference
  • 4/17/12 ~ DOM Interaction Hands on Session / Debugging Javascript






Description
This JavaScript course provides the knowledge necessary to design and develop dynamic Web pages using JavaScript. It introduces participants to JavaScript and how the language can be used to turn static pages into dynamic, interactive Web pages.  Besides learning the syntax of the JavaScript language, other additional topics may include the Document Object Model, form validation, how to create functions, and how to create your own script files.  At the end of this class, participants will have the knowledge necessary to utilize the power of JavaScript to provide dynamic content on their Web sites.  We will reserve 30 minutes each class for hands on session, so please bring your laptop when you come to the class. [Note] Feel free to leave comments or send me email if you have any questions.  Thanks. 


[ Note ]
We don't have an assigned book in this class, but if you are new to javascript, I would recommend this one.
http://www.amazon.com/Simply-JavaScript-Kevin-Yank/dp/0980285801/ref=sr_1_1?ie=UTF8&qid=1331147166&sr=8-1
...
What's Next  (Future Classes)
For Javascript Programming Level II, here is the proposed schedule.
  • Javascript Events
  • Form Handling and Validation
  • Javascript Events II
  • JSON and Ajax
  • Javascript Animation
  • Introduction to JQuery

For Javascript Programming Level III, here is the proposed schedule.
  • Closures
  • Scopes and Prototypes
  • Javascript Object Oriented Programming
  • Javascript Design Pattern - Part I
  • Javascript Design Pattern - Part II
  • Introduction to Events Driven Development
...
There will be one more class as the last of this Javascript Programming Series.  Instead of calling it Javascript Programming Level IV, let's called that "Let's start your Javascript Ninja Road Trip".

Let's start your Javascript Ninja Road Trip, here is the proposed schedule
  • Common mistakes in Javascript development
  • Understand your Javascript Engine
  • Writing high Performance Javascript
  • Dive deeper into Events Driven Development
  • Introduction to Server Side Javascript and Persistent Layer using Javascript
  • Design your custom Javascript Framework

Thursday, January 26, 2012

Twitter bootstrap popover doesn't work with click event

We were playing with the Twitter bootstrap javascript library lately,  and found out the popover doesn't play well with 'click' event in Chrome (FF works though).  I tried to find solution on the web, but didn't find what we want or the solution doesn't work. Hopefully this post might provide a solution that can help others.

The way we get around this is to wrap the popover call inside a callback which listen to click.
        // ... probably in your initialize function
        $('my-selector').bind('click', this.showPopover);

        // ... somewhere inside an object
        showPopover: function(e){
            var $popTrigger = $(e.target),
                $closeBtn = $('.popover .close-btn');

            $closeBtn.trigger("click");

            (function(that){
                $popTrigger.popover({
                    html:true,
                    placement:'below',
                    offset:8,
                    trigger:'manual',
                    title:function () {
                        return "Well, title!"
                    },
                    content:function () {
                        return that.getContent();
                    }
                });
            })(this);

            $popTrigger.popover("show");

            $closeBtn.live('click', function(e){
                $popTrigger.popover("hide");
                e.preventDefault();
            });

            e.preventDefault();
        }


You can enhance the code by checking if the elements already have desired events attached, so you don't need to trigger that twice.  And if you are designing a one page app, you may need to add function to  hide/remove the popover when the page context is changing.

Wednesday, January 4, 2012

Another good javascript interview question

I was debugging some Node.js code recently and found a bug that is so obvious but very easy to get that  to creep in if you are not careful enough. The following code is just a sample, not reflecting the real code that I'm working on.

The buggy version
Do you see the problem??  That could be one of the interview questions for my next candidate.  I can think of  three different ways to solve this scope issue, two of them are pretty standard, the other one is more elegant :)  Can you think of at least one?

(function() {
//...
for ( key in MyModules){
    if(MyModules.hasOwnProperty(key)){
        module = MyModules[key];
        // if you're not coming from Node.js, the code 
        // inside will get execute during runtime
        app.get(module.regEx ,function(req,res,next){
            module.router(req,res,next,module.collection); 
        });
    }
}
//...
}());

As a javascript developer, the basic minimal concepts we should know before going into an interview would be "prototype, scope and closure".  Because from those concepts, one can generate different patterns out from them.