Search This Blog

Thursday, August 9, 2012

Ruby Introduction

Ruby is an object oriented , dynamic programming language which is designed in a way to use it easily. It's created with an aim of making programmers more productive by allowing them to concentrate on logic rather than implementation and syntax.
By object oriented i mean everything is object in Ruby. Even primitive data types of other languages like numbers are objects in ruby.
For example, you can actually do,
5.to_s
It returns "5" which is a string. 'to_s' is a method which acts on the number(object) 5 and returns a string!!
You can verify what am saying by typing the following command,
5.class
It returns the class name of 5, which is 'Fixnum'
"hello".class would return class name as 'String'

By the way did i tell you to use irb(interactive ruby shell) for trying out these commands? 
It's very helpful in exploring ruby as a beginner.
There are tons of websites providing you tutorials on Ruby.

Most programmers are strong only with the syntax of C. Sadly , Ruby's syntax is very different from C's. Today i was just trying out variable initialization, getting and setting values, arrays, loops, conditional statements in Ruby. It will take some time for getting used to the syntax. I will work with some interesting program and keep posting more about Ruby in coming days.
See you in next post! 

Tuesday, August 7, 2012

Javascript more concepts

Javascript engines:
    I hope you have read my post about browser engines earlier. Modern browsers have separate javascript engine(for rendering Javascript)  and rendering engine (for rendering html content).
Latest Javascript engines are,

  • Carakan -- used with Presto , developed by Opera for its browser
  • V8 -- used with webkit in Chrome, developed by Google
  • Nitro -- used with webkit in Safari, developed by webkit developers and apple
  • SpiderMonkey --used with Gecko in Firefox developed by Mozilla

IE has always lagged behind in its performance when compared with other browsers. It had no separate JS engine before release of IE9 which uses a JS engine called Chakra.
It is to be noted that each engine’s implementation varies and it directly affects the speed and performance of the browser. Read more about browser wars. They are very interesting.

Objects in Javascript:
    You might have used arrays,strings,date in Javascript. Those are built in javascript objects. Javascript supports object oriented programming. But it is somewhat different from other object oriented programming languages. Here i will explain the reason with a simple program, see the picture below for code.

Code demonstrating basic object usage

  • The function Human is like a class
  • Parameters passed to the function are like parameters to constructors.
  • name,age,sex are data members of the class
  • show is a method of the class

Note:

  • Human is an object and human1, human2 etc are instances of the object
  • In the above example we can declare an instance of an object even without specifying parameters. For example, human3=new Human(); Now name,age,sex will be undefined for this instance.
  • You need to associate a method to an object (Here look at the code, this.show=show )
  • You can access datamembers and menmber functions using dot operator (for example, human1.age=40 )
  • The keyword “this” refers to the owner of the particular object/function.

Timers:
    Events can be executed based on timing in javascript. This is a core functionality of javascript.
we have two functions helping us out,

  1. setInterval(function,time in milliseconds)
  2. setTimeout(function,time in milliseconds)
first one executes the given function after every time interval you have given.
second one executes the given function only ONCE after the time interval you have specified.
Stopping a timed event is pretty simple.
    clearInterval(timerVariable)
    clearTimeout(timerVariable)
timerVariable is the variable in which return value of setInterval or setTimeout is stored.
For example,

myTimer=setInterval(function{ alert(“hello”);} , 1000); //alerts ‘hello’ every second
clearInterval(myTimer); //stops alerting

JS libraries:
First i will list some popular JS libraries

  • jquery (the most popular one !!)
  • prototype
  • script.aculo.us
  • MooTools
  • underscore.js
  • backbone.js

A JS library has collection of functions (written in javascript.. understand that the libraries are nothing but JS files!!) which help you achieve some complex task(when you code it yourself in JS..) easily.

jquery has many functions that allow you to decorate your page or make it more fancy
backbone.js allows you to implement mvc architecture in large javascript files
backbone.js uses underscore.js
underscore.js has many functions which allows you to write functional code in JS very easily.


Usage of these libraries should be avoided whenever possible, because they make your code slow.. you can’t tweak little things and i personally think it makes you feel that you are not in control of your own code.
Always remember that native javascript functions can achieve whatever you have done using some JS library.
See you in next blog!

Monday, August 6, 2012

Javascript solutions to day2's questions

Today i would discuss about the solutions i came up with for the 3 problems i discussed in previous blog,
Crashing a browser:
The first idea i got is to write a simple recursion and crash the browser. This technique works great for C programs. But it never worked for me in crashing browsers. May be the javascript engines were too clever to avoid crashing!
Then i tried infinite loop .. which worked well in crashing the browser. In case of firefox the browser crashed, whereas in chrome only the tab running the code crashed. Other tabs were working fine. This is because chrome uses different threads for each tab.
However both firefox and chrome gave me the option to stop the script running as it is crashing the browser !!

Pattern:
Animation using sprites ! I have coded that already and that seemed a perfect answer for pattern problem. In addition to that i tried working with ‘canvas’ which is a new functionality added in html5.
It allows you to draw beautiful patterns.
What i decided to do was allow the user to draw his own pattern in the canvas.I used event handlers to find the mouse position and then draw line tracing the pointer. Event handling is an area which has many cross browser compatibility issues. It took some time to find suitable functions that worked well both in chrome and firefox.
Finally i put the animation and this canvas on the same page and did little coding which makes the animation to stop whenever the user draws and resumes when user stops drawing and comes out of canvas.

My own programming language:
It turned out to be my most favorite question after i finished it. I decided to create a language similar to assembly language. Remember x86 language? which uses instructions like mov,add,sub etc...
I used js object which allows you to store key-value pairs for storing variables and their values.
I consciously put effort to improve code-reusability and modularity. But then realised that without conscious efforts too, i would have done the same refactoring. I still firmly believe designing code is all about the programmers instincts. Good programmers do it in a better way !
will upload codes in a separate post.
See you in next post !

Solutions (programming language)


File: proglang.html

<!DOCTYPE html>
<html>
<head>
<title>My programming language</title>
<link rel="stylesheet" type="text/css" href="proglangstyle.css"></link>
<script type="text/javascript" src="proglangscript.js"></script>
</head>
<body>
<div id="codearea">
<h3>Enter your code here</h3><br>
<textarea id="code" rows=10></textarea>
</div>
<div id="outputarea">
<h3>Output</h3><br>
<textarea id="output" rows=10></textarea>
</div>
<div>
<input type=button id="run" value="Compile and run"></input>
<input type=button id="check" value="check variable values"></input>
<input type=button id="clear" value="Clear all"></input>
</div>
<div id="rules">
<h4>Syntax rules</h4>
<p>
More like assembley language.<br>
Data types<br>
number --> integer<br>
text --> single word surrounded by single quotes<br>
<br>
Note:<br>
Variables automatically get declared if not declared already when used in destination field (eg: add a,10 //creates a variable a and stores 10 in it)<br>
Spacing is strict. only one space in a statement and it is placed between keyword and arguments.<br>
adding texts leads to concatenation<br>
<br>
Instructions:<br>
mov dest,src //dest=src<br>
mov variable,number<br>
mov variable,text<br>
mov variable,variable<br>
<br>
add dest,src //dest=dest+src<br>
add variable,number<br>
add variable,text<br>
add variable,variable<br>
<br>
similarly sub,mul,div works<br>
<br>
show varlist<br>
varlist --> variables separated by commas (eg:show a,b,c)<br>
It prints values of the variables listed<br>
</p>
</div>
<div id="sampleprogram">
<h4>Sample Program</h4>
<p>
mov a,10<br>
add a,20<br>
mov name,'raj'<br>
add name,'kumar'<br>
mov b,2<br>
mul c,8<br>
div c,b<br>
show a,b,c,name<br>
</p>
</div>
</body>
</html>

File: proglangscript.js


window.onload=initAll;
var vartable;
var output;

function initAll()
{
initialize();
document.getElementById("run").onclick=getCode;
document.getElementById("check").onclick=checkVarValue;
document.getElementById("clear").onclick=clearAll;
}

function initialize()
{
vartable={};
output="";
}

function clearAll()
{
document.getElementById("code").value="";
document.getElementById("output").value="";
}

function checkVarValue()
{
var varname=prompt("Enter variable name:","");
if(varname)
alert(vartable[varname]);
}

function getString(str) //returns string after removing quotes
{
return str.substr(1,str.length-2);
}

function whatIs(x) //returns whether x is a number or variable or text
{
var textpattern=new RegExp("\'.*\'");
if(isNaN(x))
{
if(vartable[x])
return "var";
else if(textpattern.test(x))
return "text";
}
else
return "num";
}

function move(movstmt) //code for processing move statement
{
var param=movstmt.split(",");
var dest=param[0];
var src=param[1];
switch(whatIs(src))
{
case "num":
vartable[dest]=parseInt(src);
break;
case "text":
vartable[dest]=getString(src);
break;
case "var":
vartable[dest]=vartable[src];
break;
}
}

function show(showstmt) //prints variables given
{
var variables=showstmt.split(",");
for(var i=0;i<variables.length;i++)
{
output+=variables[i]+" : "+vartable[variables[i]]+"\n";
}
document.getElementById("output").value=output;
}

function operate(stmt,operator) //code for processing div statement
{
var param=stmt.split(",");
var dest=param[0];
var src=param[1];
switch(whatIs(src))
{
case "num": //source is a number
if(vartable[dest]) //checking if source exists
{
if(isNaN(vartable[dest]))
{
alert("cannot handle number operating on text");
break;
}
switch(operator)
{
case '+':
vartable[dest]+=parseInt(src);
break;
case '-':
vartable[dest]-=parseInt(src);
break;
case '*':
vartable[dest]*=parseInt(src);
break;
case '/':
vartable[dest]/=parseInt(src);
break;
}
}
else
{
vartable[dest]=parseInt(src);
}
break;

case "text":
if(operator=='+')
{
if(vartable[dest])
{
if(!isNaN(vartable[dest]))
{
alert("cannot add text to number");
break;
}
vartable[dest]+=getString(src);
}
else
{
vartable[dest]=getString(src);
}
}
else
alert("not possible");
break;

case "var":
if(vartable[dest])
{
switch(operator)
{
case '+':
vartable[dest]+=vartable[src];
break;
case '-':
vartable[dest]-=vartable[src];
break;
case '*':
vartable[dest]*=vartable[src];
break;
case '/':
vartable[dest]/=vartable[src];
break;
}
}
else
{
vartable[dest]=vartable[src];
}
break;
}
}

function process(instructions) //main code for processing each statement
{
for(var i=0;i<instructions.length;i++)
{
var stmt=instructions[i].split(" ");
var keyword=stmt[0];
switch(keyword)
{
case "mov":
move(stmt[1]);
break;
case "add":
operate(stmt[1],'+');
break;
case "sub":
operate(stmt[1],'-');
break;
case "mul":
operate(stmt[1],'*');
break;
case "div":
operate(stmt[1],'/');
break;
case "show":
show(stmt[1]);
break;
default:
alert("something wrong with the keyword at line "+(i+1));
}
}
}


function getCode() //gets text from text area and splits them into instructions for processing
{
initialize();
var code=document.getElementById("code").value;
code=code.trim();
var instructions=code.split("\n");
process(instructions);
}


File: proglangstyle.css

body{
background-color:#EEEEFF;
}
#codearea{
float:left;
width:45%;
margin:5px;
}

#outputarea{
float:left;
width:45%;
margin:5px;
}

#rules{
width:45%;
float:left;
margin:5px;
background-color:#EEEFF5;
}

#sampleprogram{
width:45%;
float:left;
margin:5px;
background-color:#EEEEF5;
}
input{
float:left;
width:25%;
margin:3px;
}

textarea{
width:90%;
height:90%
}