Search This Blog

Monday, January 9, 2012

firebug - Console Tab

Overview of Console Tab
This tab is mainly used for logging. It also can be used as CommandLine window (like immediate window in Microsoft Visual Studio) while you are debugging the Javascript. It can be used for monitoring the execution of Javascript code by using Profiling service.
The following topic will be covered in this section.
  • Logging in Firebug (with String Substitution pattern )
  • Grouping the logs or messages
  • console.dir and console.dirxml
  • Assertion ( console.assert() )
  • Tracing ( console.trace() )
  • Timing ( Measuring the time of your code)
  • Javascript Profiler (An introduction in this tutorial, the details will be covered in next tutorial.)
#1. Logging in Firebug
Firebug supports logging in Console tab. So, you don’t need to use alert(‘something’) or document.write(‘something’) anymore.
There are five types of logging in Firebug.
  • console.log : Write a message without icon.
  • console.debug : Writes a message to the console, including a hyperlink to the line where it was called
  • erroricon.png console.error() : Writes a message to the console with the visual “error” icon and color coding and a hyperlink to the line where it was called.
  • infoicon.png console.info() : Writes a message to the console with the visual “info” icon and color coding and a hyperlink to the line where it was called.
  • warningicon.png console.warn() : Writes a message to the console with the visual “warning” icon and color coding and a hyperlink to the line where it was called.
Example Code:
  • Open the htm file called “Plain HTML” or create one HTML file.
  • Paste the following code with <body> tag.
1
2
3
4
5
6
7
<script language="javascript" type="text/javascript">
console.log('This is log message');
console.debug('This is debug message');
console.error('This is error message');
console.info('This is info message');
console.warn('This is warning message');
</script>
You will get the following output. If you click on hyperlink (“test.htm” in this case), it will take you to script tab and will highlight the line that wrote this message.
basic-logging-concept.jpg
String Substitution Patterns
String substitution parterns can be used in console.log, console.info, console.debug, console.warn and console.error . You can use the same way that we used in C/C++.
%sString
%d, %iInteger (numeric formatting is not yet supported)
%fFloating point number (numeric formatting is not yet supported)
%oObject hyperlink
Example :
Note: I will use console.log in the example below even all console objects (console.log, console.info, console.debug, console.warn and console.error ) support string substitution.
  • Remove “script” tag that we pasted for the previous example.
  • Paste the code below within <body> tag.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script language="javascript" type="text/javascript">
 
//This is for normal string substitution " %s, %d, %i, %f".
console.log("My Name is <strong>%s</strong>. My Date of Birth is <strong>%dth %s, %i</strong>. My height is <strong>%f</strong> m.", "Nicolas Cage", 7, 'January', 1964, 1.8542);
 
function Foo(){
this.LeftHand = function(){
return "Left Hand";
}
this.RightHand = function(){
return "Right Hand";
}
}
 
//This is for object "%o".
var objFoo = new Foo();
console.log('This is <strong>%o</strong> of Foo class.', objFoo);
 
</script>
console-string-substitution1.jpg
If you are using %o in your log, the object will be shown as a hyperlink in green color. This hyperlink is linked to the DOM tab. So, If you click “object” in second line, you will see the list of properties of that object (LeftHand and RightHand in this case.)
#2. Grouping
Firebug allows you to group the message or log in Console tab. If you have some many logs in your code, you can probably divide your log into small group or subgroup
Example ~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<script language="javascript" type="text/javascript">
 
var groupname = 'group1';
console.group("message group : %s " , groupname);
console.log("log message 1 from %s", groupname);
console.log("log message 2 from %s", groupname);
console.log("log message 3 from %s", groupname);
console.groupEnd();
 
groupname = 'group2';
console.group("message group : %s " , groupname);
console.log("log message 1 from %s", groupname);
 
var subgroupname = 'subgroup1';
console.group("message group : %s " , subgroupname);
console.log("log message 1 from %s", subgroupname);
console.log("log message 2 from %s", subgroupname);
console.log("log message 3 from %s", subgroupname);
console.groupEnd();
 
console.log("log message 3 from %s", groupname);
console.groupEnd();
 
</script>
group-message.jpg
#3. console.dir and console.dirxml
  • console.dir : It can be used for getting all properties and methods of a particular object. According the example below, we can get the Model (property) and getManufactor (method) of Car object by using console.dir(); You can also pass the object of HTML element (eg: console.dir(document.getElementById(‘tbl1′)); ) instead of objCar and let’s see the result. (You will get all properties and methods of the HTML table called “tbl1″).
  • console.dirxml : print the XML source tree of HTML element.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<table id="tbl1" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
</table>
<script language="javascript" type="text/javascript">
//Create a class
function Car(){
this.Model = "Old Model";
 
this.getManufactor = new function(){
return "Toyota";
}
}
 
//Create a object
var objCar = new Car();
 
//Firebug
console.dir(objCar);
console.dirxml(document.getElementById('tbl1'));
 
</script>
console-dir.jpg
#4. Assertion ( console.assert() )
You can use console.assert() to test whether an expression is true or not. If the expression is false, it will write a message to the console and throw an exception.
Example :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script language="javascript" type="text/javascript">
function whatIsMyAge(year){
var currYear = 2007;
return currYear - year;
}
 
var yearOfBirth1 = 1982;
var age1 = 25;
console.assert(whatIsMyAge(yearOfBirth1) == age1);
 
var yearOfBirth2 = 1982;
var age2 = 11;
console.assert(whatIsMyAge(yearOfBirth2) == age2); //You should get the error here.
</script>
assertion-failure.jpg
#5. Tracing ( console.trace() )
This function is very interesting. Before I tell you the way that I understand, let’s take a look what console.trace does exactly in official website.

CONSOLE.TRACE()

Prints an interactive stack trace of JavaScript execution at the point where it is called.
The stack trace details the functions on the stack, as well as the values that were passed as arguments to each function. You can click each function to take you to its source in the Script tab, and click each argument value to inspect it in the DOM or HTML tabs.
This function will tell you about the route information from start point to end point. If you are not clear what I mean, let’s take a look at the sample code and the result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<title>Firebug</title>
<script language="javascript" type="text/javascript">
function startTrace(str){
return method1(100,200);
}
function method1(arg1,arg2){
return method2(arg1 + arg2 + 100);
}
function method2(arg1){
var var1 = arg1 / 100;
return method3(var1);
}
function method3(arg1){
console.trace();
var total = arg1 * 100;
return total;
}
 
</script>
</head>
<body>
<input type="button" value="Trace" onclick="startTrace('Result');"/>
</body>
</html>
trace.jpg
Suppose: we wanna know how “method3″ function is invoked. So, we put this code “console.trace()” in that method. then, we run the program and we got the result as picture above. If we read the result from bottom to top, we will see “onclick(click clientX=34, clientY=26)”. That means the execution of Javascript started at on click event of button. then, we got “startTrace(“Result”)” in second line. That means startTrace function is invoked after firing onclick event and the parameter is “Result”. If we keep on checking from bottom to top, we will figure out the completed route from onclick event to method3.
If you wanna test more, you can move this code “console.trace()” to method2(). then, firebug will give the new route from onclick event which is a started point to method2() which is the end point.
I think that it’s pretty useful if you are debugging the other developer’s source code and you have no idea why this function is invoked.
Let me know if you are not clear what I’m trying to explain about console.trace();.
#6. Timing ( Measuring the time of your code)
You can use console.time(timeName) function to measure how long a particular code or function take. This feature is very helpful if you are trying to improve the performance of your Javascript code.
Example :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<title>Firebug</title>
<script language="javascript" type="text/javascript">
function measuretheTime(){
var timeName = 'measuringTime';
console.time(timeName);
 
for(var i=0;i&lt;1000;i++){
///do something
for(var j=0;j&lt;100;j++){
//do another thing.
}
}
 
console.timeEnd(timeName);
}
</script>
</head>
<body>
<input type="button" value="Trace" onclick="measuretheTime();"/>
</body>
</html>
Result : measuringTime: 16ms
#7. Javascript Profiler
You can start the profiler thought code (console.profile(‘profileName’)) or by clicking “Profile” button from “Console” tag. It can be used for improving the performance of Javascript. It is similiar to the console.time() function but profiler can give your more advanced and detailed information.

Tuesday, November 15, 2011

SQLite format Output

The following commands can be used to get formatted output from the sqlite3 shell program.

  • .header(s) ON|OFF
  • .mode
  • .output
  • .prompt
  • .separator
  • .show
  • .width

Following are the short help strings from the command prompt for the above commands.

Code Listing 1. Short descriptions of output formatting commands from SQLite shell

.header(s) ON|OFF Turn display of headers on or off

.mode MODE ?TABLE? Set output mode where MODE is one of:
csv Comma-separated values
column Left-aligned columns. (See .width)
html HTML

code
insert SQL insert statements for TABLE
line One value per line
list Values delimited by .separator string
tabs Tab-separated values
tcl TCL list elements

.nullvalue STRING Print STRING in place of NULL values

.output FILENAME Send output to FILENAME

.output stdout Send output to the screen

.prompt MAIN CONTINUE Replace the standard prompts

.separator STRING Change separator used by output mode and .import

.show Show the current values for various settings

.width NUM NUM ... Set column widths for "column" mode

The Default Output

As you can see in the listing below, the formatting commands will be executed on a simple database with contacts and addresses.

Code Listing 2. A simple db with contacts and addresses

D:\Research\sqlite\sqlite-3_5_7>sqlite3.exe contactsext.db
SQLite version 3.5.7
Enter ".help" for instructions


sqlite> .tables
Address Contacts


sqlite> .schema
CREATE TABLE Address (_id INTEGER PRIMARY KEY, city TEXT, country TEXT, line1 TE
XT, line2 TEXT, region TEXT);
CREATE TABLE Contacts (title TEXT, email TEXT, _id INTEGER PRIMARY KEY, addrid N
UMERIC, name TEXT);


sqlite> select * from contacts;
Chairman|billg@microsoft.com|1|1|Bill Gates
CEO|steve@apple.com|2|2|Steve Jobs
Senator|hillary@senate.us.gov|3|3|Hillary Clinton
Senator|mccain@senate.us.gov|4|3|John McCain
Senator|obama@senate.us.gov|5|3|Barack Obama


sqlite> select * from address;
1|Seattle|USA|A Street||Washington
2|California|USA|B Street||Cupertino
3|Washington|USA|K Street||DC

If you look at the output from contacts and address, the output is not very pretty. It’s barely readable. And, it would be hard to understand the data without the columns (especially if the tables are non-obvious unlike contacts and address).

The Current Settings

We can see the current settings by using the command .show. Since no changes were made to the settings, these are the default settings.

Code Listing 3. The Default Settings

sqlite> .show
echo: off
explain: off
headers: off
mode: list
nullvalue: ""
output: stdout
separator: "|"
width:

Changing to Column Mode

The mode by default is list. Using the .mode command, lot of formatting can be accomplished. Setting the display to column, you will see a spread-out column display for the results.

Code Listing 4. The Column Display

sqlite> .mode column


sqlite> .show
echo: off
explain: off
headers: off
mode: column
nullvalue: ""
output: stdout
separator: "|"
width:


sqlite> select * from contacts;
Chairman billg@microsoft.com 1 1 Bill Gates
CEO steve@apple.com 2 2 Steve Jobs
Senator hillary@senate.us.g 3 3 Hillary Cl
Senator mccain@senate.us.go 4 3 John McCai
Senator obama@senate.us.gov 5 3 Barack Oba

The Column Headers

In the above output, we don’t know the column names. For obvious tables like contacts, you probably don’t need column names, but in general they will be helpful. The command ‘.headers on’ would turn on the headers.

Code Listing 4. Turning the headers on

sqlite> .headers on


sqlite> .show
echo: off
explain: off
headers: on
mode: column
nullvalue: ""
output: stdout
separator: "|"
width:


sqlite> select * from contacts;
title email _id addrid name
---------- ------------------- ---------- ---------- ----------
Chairman billg@microsoft.com 1 1 Bill Gates
CEO steve@apple.com 2 2 Steve Jobs
Senator hillary@senate.us.g 3 3 Hillary Cl
Senator mccain@senate.us.go 4 3 John McCai
Senator obama@senate.us.gov 5 3 Barack Oba

The first line from the results to the SELECT statement is the listing of columns. There is one more problem – the output (email and names) is truncated beyond the tenth character.

Width of the columns

Using the .width command, you can adjust the width of the columns so that you can see more of the data. Separate the width of the columns (in number of characters) by a space.

Code Listing 5. Specifying the width of the columns

sqlite> .width 10 25 3 6 15


sqlite> .show
echo: off
explain: off
headers: on
mode: column
nullvalue: ""
output: stdout
separator: "|"
width: 10 25 3 6 15


sqlite> select * from contacts;
title email _id addrid name
---------- ------------------------- --- ------ ---------------
Chairman billg@microsoft.com 1 1 Bill Gates
CEO steve@apple.com 2 2 Steve Jobs
Senator hillary@senate.us.gov 3 3 Hillary Clinton
Senator mccain@senate.us.gov 4 3 John McCain
Senator obama@senate.us.gov 5 3 Barack Obama

As shown in the above listing, you can see that the column headers are there, all the data is shown in a column fashion.

Other Options in Mode

The command .mode is pretty powerful. Setting it to csv will give you the results in a ‘Comma Separated Values’ format – which is good for Excel, etc. You can also generate HTML code by setting the mode to html. You can get the columns on a line by choosing line. Or separate the values by tabs. You can also generate insert statements.

Code Listing 6. Various modes of data display

sqlite> .mode csv
sqlite> select * from contacts;
title,email,_id,addrid,name
Chairman,billg@microsoft.com,1,1,"Bill Gates"
CEO,steve@apple.com,2,2,"Steve Jobs"
Senator,hillary@senate.us.gov,3,3,"Hillary Clinton"
Senator,mccain@senate.us.gov,4,3,"John McCain"
Senator,obama@senate.us.gov,5,3,"Barack Obama"


sqlite> .mode html
sqlite> select * from contacts;




sqlite> .mode line
sqlite> select * from contacts;
title = Chairman
email = billg@microsoft.com
_id = 1
addrid = 1
name = Bill Gates

title = CEO
email = steve@apple.com
_id = 2
addrid = 2
name = Steve Jobs

title = Senator
email = hillary@senate.us.gov
_id = 3
addrid = 3
name = Hillary Clinton

title = Senator
email = mccain@senate.us.gov
_id = 4
addrid = 3
name = John McCain

title = Senator
email = obama@senate.us.gov
_id = 5
addrid = 3
name = Barack Obama


sqlite> .mode tab
sqlite> select * from contacts;
title email _id addrid name
Chairman billg@microsoft.com 1 1 Bill Gates
CEO steve@apple.com 2 2 Steve Jobs
Senator hillary@senate.us.gov 3 3 Hillary Clinton
Senator mccain@senate.us.gov 4 3 John McCain
Senator obama@senate.us.gov 5 3 Barack Obama

sqlite> .mode insert
sqlite> select * from contacts;
INSERT INTO table VALUES(’Chairman’,’billg@microsoft.com’,1,1,’Bill Gates’);
INSERT INTO table VALUES(’CEO’,’steve@apple.com’,2,2,’Steve Jobs’);
INSERT INTO table VALUES(’Senator’,’hillary@senate.us.gov’,3,3,’Hillary Clinton’
);
INSERT INTO table VALUES(’Senator’,’mccain@senate.us.gov’,4,3,’John McCain’);
INSERT INTO table VALUES(’Senator’,’obama@senate.us.gov’,5,3,’Barack Obama’);































titleemail_idaddridname
Chairmanbillg@microsoft.com11Bill Gates
CEOsteve@apple.com22Steve Jobs
Senatorhillary@senate.us.gov33Hillary Clinton
Senatormccain@senate.us.gov43John McCain
Senatorobama@senate.us.gov53Barack Obama