Search This Blog

Monday, August 6, 2012

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




Friday, August 3, 2012

JavaScript day 2

In today's session we were given 3 interesting questions. I will share them with you now,
1.Write JavaScript code to crash a browser
2.Create a simple pattern using JavaScript
3.Write your own programming language using JavaScript


The day went in solving these 3 questions. You too try coding answers.
I will share my answers along with concepts used for coming up with the solution in next post.

Thursday, August 2, 2012

Javascript Introduction

Audio blog on JavaScript introduction


The day went away in a jiffy learning basics of javascript. I went through basic and some advanced concepts of javascript in www.w3schools.com . It was fun. 

I would now explain a popular javascript functionality of ‘handling events’ with not-so-popular functionality of html ..’maps’ !


Events -- > actions performed by user like mouse click, keystroke etc...
Here i have done a sample program which uses onmouseover and onmouseout functions of Javascript. 

Sharing screenshots of code and output with you here,
pic1 - html page containing the javascript code as well.
The code is kind of self explanatory.
pic2 - output.. the paragraph content is head because the mouse pointer was hovering over the upper part of the picture. A video would have been better. But this is a very simple program. U can very well code and see the output in your machine.



Pic 1 the html file

Output. Mouse pointer is over head of penguin :P


Will be posting more about JavaScript in coming days.
See you in next blog.

Wednesday, August 1, 2012

TDD and BDD

Audio blog on TDD and BDD


TDD:
TDD-->test driven development
Adhering to tdd means you shouldn’t write a line of code without developing test case for it first !!
For beginners this may be very difficult...sometimes we write functional code without writing test cases. That’s not correct TDD.
It’s a technique where we use unit tests to drive the design of the program or project.
Unit tests ??
    These are very small scripts which send some input to a class or method and verifies if the result is same as the predicted result.
For example , suppose we have a function to concatenate two strings, we test it like,
START TEST
    assert(concatenate(“hello”,”world”),”helloworld”,”expects helloworld as output”);
END TEST
Forget the syntaxes used above, they are invented by me now to explain testing.
There are different testing frameworks available for carrying out testing in different programming languages.
Java - JUnit
C - Check
...

How TDD works? or Motto of TDD..
RED ---> GREEN --> REFACTOR

RED --> Develop a test case and make it fail. ( a test case will obviously fail without even writing the function it is testing)
GREEN --> develop code so that the test case developed in the first step passes.
REFACTOR --> Change code to remove duplication(accept it.. there will be some sort of duplications even in experts code) , improve the design.

It's to be noted that testing is to be done after refactoring to verify everything is working correctly.
This is done for every piece of code that is going to be a part of your project.
Getting the point?
You develop test cases based on requirements and then write code to pass those test cases . This is the essence of TDD.

Why use TDD ??
You may think you are good at designing and then implementing the same. But that may not be the case. May be you are a gifted programmer and designer.. ! but that may not be the case with everyone. TDD makes sure that the code you write is good. You will understand if i explain some advantages of TDD,
Advantages:

  • It helps you in proceeding step by step. The important thing is that it gives you confident that the step you completed is perfectly working and correct. Some programmers tend to code many many lines of code and then wonder where the bugs are !! it's always better to go step by step.
  • It forces decoupling of modules or dependencies. For example , you write a program to find multiplicative inverse modulo of a number. This program in turn needs to calculate gcd of the number and the modulo involve. Normally you tend to write the code to calculate the gcd within the main module itself. So they become coupled. If you need to find gcd of two numbers in some other program you need to copy paste the code. Had you used TDD you would have developed test cases to check whether the gcd algorithm works correctly. Automatically you would have put the gcd algorithm as a separate module. Decoupling happens !!
  • The test cases are like a constant feedback to the developer that the modules are working properly. Again it's for the confidence of the developer. It helps in easily identifying and fixing bugs too.
  • It is like a documentation that never goes out of date unlike the documentation developers write !

BDD:
It stands for behaviour driven development. It involves identifying behaviour of a system and then writing test cases for that behaviour to be satisfied. It combined acceptance testing and unit testing.
People consider BDD as rephrasing the existing good testing process based on TDD. Am not going into BDD any further as i have zero experience in them.

Where TDD may go wrong? or what led to BDD when we have TDD !!
TDD may have design impacts (not always.. happens due to bad programming logic or poor design knowledge of the programmer). Sometimes design may not be clear to the coder. In those cases you need to change the test case itself which may prove very costly.
Lot of time investment is involved to get into the TDD approach. Normally you can see developers skipping test cases for some part of the code or project .

TDD approach by example:
    Let’s assume you are writing a simple 2D game... like mario.
As you are considering game as an example test cases will be innumerable. I will tell only a few here.
When mario gets a mushroom,
    if he is small he must become big
    if he is big then he must get firepower

Now you decide to put this into code, you decide to write a mushroom_got function which gets called when mario gets a mushroom.
so you start by writing test cases.

testcase 1:
input : small mario gets mushroom
result: big mario

test case 2:
input: big mario gets mushroom
result: mario with firepower

Now you begin implementing methods that does the same. You then find that becoming big or getting firepower also needs to be tested.

so you write test case for those like,
after becoming big -- is height of mario larger than his prev height etc..

for implementing this testcase you will write makemariobig as separate function and then use it inside the mushroom_got function.

This is how TDD works. You can understand how it helps in deciding the flow too.

That’s it for today. See you in next post.