Urban pro

View My Profile

Sunday, October 21, 2012

In Linux, Kill many instances of a process with a single command .

Hi guys back to you after a long time.

However, the English that i am typing in here, might be a little murky  as i am typing this one from chennai airport and there's no space to sit on .

Today we are going to look into  a very important question which is :

Suppose you are running thousand or more instances of the VI editor process in your linux. Now you want to kill them in a single shot. How do you do it ?

Let's look at the good old grep-awk :


for pid in $(ps -ef | grep "some search" | awk '{print $2}'); do kill -9 $pid; done
There are ways to make that more efficient,
for pid in $(ps -ef | awk '/some search/ {print $2}'); do kill -9 $pid; done
and other variations, but at the basic level, it's always worked for me.
The problem with this method, however, is that you often end up killing more than you intended. Writing a reliable “some search” is tricky. 

Use Killall :
killall vi
This will kill all command named 'vi'
You might also add a signal as well, e.g SIGKILL
killall -9 vi
The  problem :
  •  Killing by file only works for executables that are kept open during execution, i.e. impure executables can't be killed this way.
  •  Typing killall name may not have the desired effect on non-Linux systems, especially when done by a privileged user.What if i am trying to delete a lot of instances of some non-linux process ?
  •  killall -w doesn't detect if a process disappears and is replaced by a new process with the same PID between scans. If processes change their name, killall may not be able to match them correctly.
But, please be aware that this only works on Linux and BSD. On Solaris and some other systems killalldoes exactly what the name suggests...it kills the init-process.

On AIX, it "cancels all processes that you started, except those producing the killall process."

Use Pkill :

pkill is available on Linux, BSD and Solaris. So it has a bigger spread thankillall. 
But, 

The problem :

pkill doesn't exist on AIX or HP-UX and despite what some people like to believe, there's still a significant based  non-Linux UNIX out in the world.

What does pkill do :

pkill is  available in  (LinuxFreeBSDNetBSDOpenBSDSolaris). You can specify processes by the command name, by the full command line or other criteria. For example,pkill vi kills all programs whose command name contains the substring vi. To kill only processes called vi, use pkill -x vi. To kill only processes called vi with a last argument ending in .conf, use pkill -fx 'vi.*\.conf'.
To see the list of PIDs that pkill would send a signal to, use pgrep, which has exactly the same syntax except that it doesn't accept a signal name or number. To see more information about these processes, run
ps -p "$(pgrep …)"
Under Linux, you need ps -p $(pgrep -d, …) instead (that's a bug: Linux's ps isn't POSIX-compliant).
Another common way to identify processes to kill is the processes that have a certain file open (which can be the process's executable). You can list these with fuser; use fuser -k to send them a signal. For example, fuser -k /usr/bin/find kills all running isntances of find.
If there's a runaway process that keeps forking, you may need to kill the whole process group at once. A process group is identified by the negative of its leader, which is the ancestor process of all the processes in the group. To see the process group that a process belongs to, run ps -o pgid (plus any option to select which process(es) to display). If you determine that you want to kill the process group leader 1234 and all its children, run kill -1234 or kill -HUP -1234 or any other signal.
If you can't find a better way, use ps with proper options to list all processes and filter it with grep or some other text filtering command. Take care not to accidentally match other processes that happen to be running a command with a similar name, or with an argument that contains that name. For example:
kill $(ps -o pid -o comm | awk '$2 == "vi" {print $1}')
Remember that your grep or awk command itself may be listed in the ps output (ps and the filtering command are started in parallel, so whether it will show up or not is dependent on timing). This is particularly important if the command arguments are included in the ps output.
All right that's all guys, i have to get my boarding pass now, or i will miss my flight .

See you next time .



Sunday, October 7, 2012

How to create a modal window ?

All right, so i was working with modal , modal overlay and some other stuffs, when it came to my notice that till now no good tutorial is available for beginners to make them understand the whole process sequentially. So, yours truly took the initiative to write about the process to create a basic modal window .

NOTE : This entire effort has been implemented on a JSP but users can use it anywhere else .

Let me first give you some important information. I was configuring my tomcat 7 with my eclipse indigo, when i found  a lot of problems while trying to figure it out. I had not done this since the college days and it seems few things have changed. People who are interested in doing it can follow this link : http://www.coreservlets.com/Apache-Tomcat-Tutorial/tomcat-7-with-eclipse.html  for configuring eclipse with tomcat 7(This is the best tutorial there is for that at present in www).

What is a dialogue ?

A dialog is a  default built-in behavior , but few methods are needed to control it pro-grammatically,  making this an easy to use widget that is also highly configurable and powerful.

What is a modal window ?

When your dialog box prevents the user from interacting  with the layout of the rest of your web page  if they don't close it manually, then it becomes your modal window.

So, how do we go about making it . Let me first give you the screen snaps for the code i had written :






Beware :

Whenever you are importing jquery.js and jquery-ui.js, remember to import jquery.js before jquery-ui.js, other wise you will get these errors :

jquery -- not recognized
('#id').dialog()  is not a function




Now let us understand the code that matters, shall we !

When you write :

$("#id").dialog(); -> you are actually trying to open a dialogue box and not a modal window, as you can still interact with the rest of the lay out of the page .

So how do i make it a modal window ?

Simple, to do this inside the dialog() method you have to provide --> modal : true. This tells the browser that you want the dialogue to be opened within a modal window to prohibit the user from interacting with the rest of the page.

But nobody will believe me if i don't show what it actually does . Okay, so let's see the screen shots below :

screen 1 : Before clicking on the blue date time link :


screen 2 : After clicking on the blue date time link :





Look at how the rest of the web page has become blurred and any attempt at trying to interact with the rest of the page will be a failure .

That's it for today folks.

I will see you all next time. Good bye .

Friday, October 5, 2012

Why using onload() in a body tag is a bad idea ?

                                         Let's go back to our innocent  years :

Keep Javascript unobtrusive :

To keep our Javascript unobtrusive we can keep it in a single file to avoid messing up the markup of the page. To execute the functions in our .js file, we need to call them when the page has loaded. This can be achieved in various ways and each has it's advantages and disadvantages  .

I am feeling a little nostalgic :

Back when we had just started messing around with Javascript  we used to add the onload to the body element, like this :

body onload = "callMyFunction();"

But, this is bad , real bad .

Why ? --> If we call the script(s) in the body element, we really achieve nothing, since we are still mixing markup and event calls.What we need to do is to separate the call out into a .js file.

I am all grown up :

Now the better way is to attach  the call to the onload event of the window object.

When we only use one function, we don't use the parenthesis at the end of the function name, as that would send back the result of the function rather than trigger the function.

If we have more than one function, we have to use an anonymous function that calls the others, this time with parenthesis.

This is achieved as :


window.onload=callMyFunction; //Notice that there is no ()

or

window.onload=function(){  //Here you need to give () as you are calling an anonymous       // function
 callMyFunction1();
 callMyFunction2();
 callMyFunction3();
}

This will prevent us from messing up our mark up of the page rendered .



Thursday, October 4, 2012

javascript - JQuery TypeError : Type Error

            

                                                               TYPE  ERROR

Most people face this error when they use an outdated jquery.js . Sometimes this error also comes up when someone tries to use jquery in jsp.

The most important thing here that a person must do is first use an upto date version of jquery.js . Don't worry u don't even have to download this stuff.

Just have this :



Now what else can be done, if you still get this error. Well, may be you can replace all the '$' symbols with 'jQuery'. Voila, your application will now start making use of all the jquery api s from its library perfectly.
Hence, instead of :
$('#id').click()
you will have :
jQuery('#id').click()
And everything will fall in place .

Wednesday, September 26, 2012

What is GOD OBJECT and RAVIOLI CODE ?

Hi friends,

The other day , i was going through the basic concepts of OOPS(I am a bit rusty , i fear). It's at that point of time, that i came across two mind boggling terms : GOD object and RAVIOLI code. I will try to emulate here what i have understood .

                                                            THE GOD OBJECT

                                                     

Normally :

The basic idea behind object-oriented programming is that a big problem is broken down into several smaller problems (a divide and conquer strategy) . Then, solutions are created for each of them. Once the small problems have been solved, the big problem as a whole is automatically solved. Therefore, there is only one object about which an object needs to know everything: itself. Likewise, there is only one set of problems an object needs to solve: its own.

The all knowing, all encompassing object : 

In object-oriented programming, a god object is an object that knows too much or does too much. Here, most of a program's overall functionality is coded into a single "all-knowing" object, which maintains most of the information about the entire program and provides most of the methods for manipulating this data. Because this object holds so much data and requires so many methods, its role in the program becomes god-like (all-encompassing). Instead of program objects communicating amongst themselves directly, the other objects within the program rely on the god object for most of their information and interaction.

An Example :

Let us consider a banking scenario. Let us consider, K is customer of the bank ABC . K has a savings account. Subsequently, he has an account number. He can withdraw and deposit and can view his yearly statements. Also, he has a credit card  CC  and a debit card DC. 

So a stray piece of code will look like this :
if(user is customer)
{
acctNumber = getCustmerAccountNumber();
amountWithdrawn = getAmountWithdrawn();
depositMade = getDepositMade();
yearlyStatements = getYearlyStatements();
cerditCardNumber = getCreditCardNumber();
debitCardNumber = getDebitCardNumber();
creditExpense = getCreditExpense();
debitExpense = getDebitExpense();
creditStatement = getCreditStatement();
debitStatement = getDebitStatement();
}

if(customer is highNetWorth)
{
customer.setCustmerAccountNumber(acctNumber);
customer. setAmountWithdrawn ( amountWithdrawn);
customer. setDepositMade ( depositMade);
customer. setYearlyStatements ( yearlyStatements);
customer. setCreditCardNumber ( cerditCardNumber);
customer. setDebitCardNumber ( debitCardNumber);
customer. setCreditExpense ( creditExpense );
customer. setDebitExpense ( debitExpense);
customer. setCreditStatement (  creditStatement);
customer. setDebitStatement (  debitStatement);
}

So here , the object customer becomes a GOD object. Any subsequent change in some part of the existing structure, will require a change here in the customer object as it contains every item related to the user's account .

Advantage of this approach :

In micro controllers, performance efficiency and control are two very important aspects. Here, the use of this technique is very frequently seen.

Disadvantage of this approach :

This object is referenced almost every time within the project hierarchy. Hence, maintainability becomes a problem .

                                                          RAVIOLI CODE 

                                                         

It looks delicious :

Yes, we all know it is delicious. But get a grip on yourself and look at it closely. What do you see ? Can you see what is inside the outer covering ? It's very difficult . isn't it ? Well, that's encapsulation(hiding the contents).

What is this ?

This is the opposite of the GOD object.

Ravioli code consists of very small and  loosely coupled code fragments. The term stems from the analogy of ravioli (small pasta pouches containing cheese, meat, or vegetables) to modules (which ideally are encapsulated(hidden), consisting of both code and data).

Advantage:

Places where we want to have a loosely coupled code structure(which can be changed without butting head against the wall), this is very useful.

Disadvantage :

Too much separation and hiding of the code(encapsulation) makes maintenance very difficult .

Well friends, that's it for today. Hope you found it informative.

Goodbye.

Monday, September 24, 2012

STEPPING INTO PYTHON - CHAPTER 3 (Part 1)

All right i am back again with a little bit of a dose of python . Let us start looking  into loops and conditions from today. Since this is a vital and integral part of any programming language , this chapter will be split-ted in smaller sub chapters to provide the unassuming  user a better understanding of how loops , conditions and decisions work in python .

YOU  GOTTA MAKE THE CORRECT DECISIONS IN LIFE :

Some great guy correctly said what i mentioned above . Decisions are very important in life and they have at least the same importance in the programming world,  if not more .

The If  condition :

Let's see the syntax first :
In python , one can comment using : hash operator(#).


kNumeric = int(raw_input("Please enter an integer: ")) # kNumeric is the variable chosen here . It's upto you. 
if kNumeric < 0:
     kNumeric = 0
     print 'Negative changed to zero'
elif kNumeric == 0:
     print 'Zero'
elif kNumeric == 1:
     print 'Single'
else:
    print 'More'

O/P : If i input here 42 , i get the output as More .

Here the key word elif stands for else if and is very widely used to get rid of repetitive indentation . However, the else part is optional here . This conditional flow is a kind of a substitute for switch and case statements found in other languages .

The  for loop :

The for statement in Python is different from what we may be used to in other languages. Rather than always giving the user the ability to define both the iteration step and halting condition, Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

For example in Java :



In Python :

# Let us find out length of individual items of a list
kList = ['item1', 'item2', 'item3']
for k in kList:
     print k,"-->", len(k)

O/P : 
item1 --> 5
item2 --> 5
item3 --> 5

Question : One question that is being repeatedly asked in interviews is : how can you modify a list on the fly and insert an element of the list in another location of the list depending on a condition given ?

Answer : The answer is slice copy . Let's see how to do it .


kList = ['item11', 'item2', 'item3333333']
for k in kList:
     print k,"-->", len(k)
for k in kList [:]: # in this way we can make a slice copy of the entire list on
                         # the fly
    if len(k) > 9: kList.insert(0, k)
print "Now the first element is ::",kList[0]

O/P :

item11 --> 6
item2 --> 5
item3333333 --> 11
Now the first element is :: item3333333

That's it for today friends . Next time we will have a look in the next sub chapter which will contain many other loops and conditions and constructs . Have a good day .



Saturday, September 22, 2012

My webpage

Hi friends,

Just launched my web page today to be  in more contact with you all. It's  not much but as time will fly, it will come up . You guys can personally reach me here :

http://kunalbhowmick.page.tl

See you next time .

Friday, September 21, 2012

Why building IOS apps if you don't have an i phone and a MAC is a bad idea ?

Hi friends,

I am sure many of us has come across this Question but we do not know what the answer to it is . I am not going to explain about this to you in a lot of detail right now(I will give detailed explanations later) . Rather I wanted to share with you this thread, which does shed some light in this dark area . Find the link to the thread below : :

http://programmers.stackexchange.com/questions/165644/is-there-a-way-to-publish-ios-app-from-windows-linux

I will come up with a much detailed explanation later .

Adios .

Monday, September 17, 2012

DEBUGGING

Hi guys/gals,

Back to you after a long hiatus . Sorry about that, i was so busy, could not even pick up the laptop and open face book. However, today i took some time out to speak about something perennially important, namely : DEBUGGING .

Let me start by telling you that in the context of what i am speaking , there are two kinds of debuggers :

  1. People who like to use the all important SYSTEM.OUT.PRINTLN().
  2. People who like to use the inbuilt java debugger and the magical breakpoints .
Now i have been using RAD for sometime and it contains WAS6.1 to publish and deploy my web application . Let me come to my main point here. Since i was fully new to the application and i had to first know, how the code flows and so on and so forth, i tried using the java debugger . Now the problem here is that, coupled with WAS6.1 the debugger works really badly. It at times used to stop when i had not reached the break point which was supposed to show me the values for a particular variable, sometimes the WAS server used to stop by itself and would not start for 15-20 mins. All this heartache and i needed to find out many things very quickly. So, what did i do ? I went back to our very special friend system.out.println().

Now kindly bear in mind that i am not saying that you must not use java debugger. It's just that sometimes you may be short of patience and time to effectively  reap all the benefits of it. All those times, i suggest that you start using the sysout().It acts both as a tracer and debugger for the application.

You can , however use the log() method as well .One just  needs to import log4j.jar and log4j.xml and properties file where the logfile name and path is specified and voila you can start logging your information .

A little demonstration will not hurt, huh :

// In you base class :
public static log(String s) {
// Point to the appropriate trace level :
public Static DEBUG_LEVEL = "ERROR";
switch (DEBUG_LEVEL) {
case: ERROR
System.out.println(s);
case : TRACE
writeToYourFile(s);
case : PRODUCTION
prod(s);
}
}

Hope you liked it. Will be back next time, with something else . Keep in touch to see my next upcoming tutorial on Objective C  and the upcoming chapters on stepping into python and JS-OOPS .








Sunday, July 8, 2012

STEPPING INTO PYTHON - CHAPTER 2

Hi Friends,

Here I am again  with you guys after a long time . Sorry for the delay, but i was caught up in office work for a long time and was extremely busy.

So, let us delve further into python, without waiting any further .

LISTS :

Think about arrays (feisty little boxes i call them) . Lists are very much like them . They can contain any and all types of variables and as many as you wish.

Consider this scenario :

We will declare a list first . Let's call it Klist .

Klist = [] ; //declaring a list

//Let's  build the  list

Klist.append(K);
Klist.append(B);
Klist.append(C);  

So the list now contains 3 elements A,B,C . 

Lets  print the elements inside the list now :

for i in Klist :
     print  i    // Prints  K, B C

Now beware . This  is  very important .

This list contains 3 elements . So if you  try to print an index, for which there is no element in the list .

Hence,

print  Klist[12] ; // This  generates an error as, for  the index 12 , there is no element in the list .


OPERATORS  :

All arithmetic operations are supported in python .
Addition, Subtraction , multiplication you name it , everything's there .

To return  remainder from a division you can use the modulo operator (%) .

To make a squared relationship , you can use double  * operators.

a = 7 ** 2 ; // that's actually  49

To concatenate strings  you can add them up .

kunalBhowmick = "Kunal" + "Bhowmick" ;

To concatenate a string multiple times :

Kstring =  kunalBhowmick * 10 ;

That makes  the list Kstring  contain 10 repetitive sequences of the string "kunalBhowmick " .

To join two lists you can use addition (+)  operator .

New lists can be made with a repeating sequence using the multiplication operator (*)  .

For example:

print  Klist * 3 ;

This prints the elements of the list Klist 3 times .


That's it friends for today . Next we will go through loops and conditions .


Wednesday, May 23, 2012

STEPPING INTO JS OOPS - CHAPTER 2

Hi Friends,

In this chapter we are going to delve deeper into inheritance and objects. I will suggest you here that you install firebug for your mozilla . Because a lot of this will be done using firebug script editor and console .

If you have mozilla 3.0 uptill 8.0 , i suggest you use firebug 1.7.3 xpi .

Install it from this link :  http://getfirebug.com/releases/firebug/1.7/



If you have mozilla 9 and above , i suggest you download firebug 1.8 xpi .

These are the most stable versions of firebugs  for the above versions of mozilla.

Now, Let's get started , shall we ?

I WILL INHERIT MY DAD'S  PROPERTY (Probably) :

Suppose I have an object 'x'  and it inherits all the properties of the object 'y', then in this jargon we shall say that y is the prototype of the object x and  the properties of x override the properties of  y .

I know, i know ... you are going to say what every one else said to me : "I DON'T BELIEVE  YOU" .

Well, what if i give you live examples here .

Inside the script - editor of firebug :

var alpha = {firstName: 'Kunal', lastName: 'Bhowmick'} ;
var beta = {firstName: 'Anirban'};
beta.__proto__ = alpha ; // Making beta inherit everything from alpha

beta.lastName; // O/P : Bhowmick--> in the console .

Whoa, what is this ??
Well, this is actually nothing but inheritance at it's mischievous best .

alpha is my JavaScript variable which contains firstName and lastName .
beta ,however, consists of only the firstName.

Now , to make alpha the parent of beta, we have used  '__proto__'. This is like the 'extends' keyword used in java .

Hence beta.lastName takes the lastName of alpha since it does not have a last name of it's own.
Still, you don't believe me , do yah ?
If so, then have a look at the screen shot below :

EDITOR :



CONSOLE :



 But what happens , when you try to print the firstName of beta :

beta.firstName;
O/P : Anirban

This is because, the properties of the child , present in the child overrides that of the parent .

What if we introduce last name for beta :

beta.lastName = 'Bhattacharjee';
beta.lastName;
O/P : Bhattacharjee

So , it again overrides its parent alpha .

Let's delete the lastName of beta :

delete beta.lastName;
beta.lastName;

O/P : Bhowmick

Since, we have deleted the last name of beta, it inherits the last name of alpha again.

Now, what if try to find the prototype of alpha, the parent .
Ok, so let's have :

alpha.__proto__;

This gives the output as :
This in actuality represents the object Object.prototype --> which is the godfather of all objects .




I HAVE GOT  BAD  NEWS  AND BAD NEWS :




Well, the problem is __proto__ cannot be used in internet explorer and some other browsers because it is not in the ECMA script specification .


But, hang on, before you guys curse my head off, let me tell you that, even though it cannot be used in those browsers, it does not mean that it does not exist there . It is still there, however we deal with it in a roundabout way .


So that is prototype inheritance in a nutshell. 
That is why, though java script does not contain classes, yet still it uses inheritance in this way and hence it is an OOP construct.


HOW DOES THIS INHERITANCE WORK :

 


Alright, alright i am getting into it . 
Have  a  little patience, yea of little faith .


Let us describe an ordinary function :

function Apple(name){ 
    this.name = name;  
}



var apple1 = new Apple('White Apple'); // create an object for Apple


Apple.prototype.greet = function(){
    console.log('Eat me, I am a : ' + this.name);
}


As a result of this, Apple.prototype becomes the prototype of each object that's created via new Apple() such as : apple1 .


So, we have used this prototype to define the function greet() and we will call it in this way :


apple1.greet();


O/P : Eat me, I am a : White Apple

In this way , we can create any number of  methods like greet() and they will be available for all the instances  of the apple object created there of .


This is exactly how, inheritance is used  in java script .


Hope you enjoyed this one .


Good bye .


LEAKING GLOBAL VARIABLE IN JAVASCRIPT

Hi Friends ,

This post is about a very common mistake that is made by the JS programmers who are caught unaware of what they are trying to accomplish.

The most common mistake with a java script variable  is sometimes programmers use them as global variables and as such their values persist for the entire program and does not work the way it is supposed to .


Yesterday, while i was working with a piece of JS code , i encountered this problem .

I had this piece of code :

function FUNC()
{
   K = 100;
}

FUNC();

console.log("K is :" +K); // O/P : 100

But the expected output is undefined since the variable 'K' is a local variable and hence must not be visible else where except the method where it is used .

This is the screen shot that came up in my console :

Now this is called accidental leaking of global variable .
I wanted to have my variable K as a local variable but i have used it as a global variable.
Hence , all this fuss .

So , the important thing that needs to be done is, if we intend to use a variable as a local variable , then we must use the 'var' statement .


function FUNC()
{
  var  K = 100;

}


FUNC();



console.log("K is :" +K);

As a result, this is what i got :


And this is the correct and expected result.

This small mistake messed up my application big time . So remember to use VAR in such cases.

Goodbye,

Have a good day .



STEPPING INTO PYTHON - CHAPTER 1

Hi friends,

This is the first chapter in the stepping into python series. This series will be updated from point of view of the beginners and gradually more advanced features will be published .
So without any further ado, let us delve into the language at hand .

 How to install Python :

FOR WINDOWS USERS : There are a lot of  python interpreters available. Download them and get started. However i vehemently oppose it. Python is a free software available in Linux. So download any flavor of Linux and  get started(My personal favorite is Ubuntu).

FOR LINUX USERS : Just type python in your shell and the interactive mode opens and you are good to go .

OOP : Python is an object oriented language and any variable that you use here acts as an individual object .

SOME IMPORTANT TID BITS :
                                                     help(obj) --> this gives you info on the object
                                                     dir(obj)   --> this gives you the internal structure of the object being used .

BASIC VARIABLES :

INTEGER : An integer is defined in this way :
                   kint = 8
FLOATING POINT NUMBER : kfloat = 7.0

STRINGS : When it comes to strings, you can use single quotes and double quotes both .
kstring = 'kunal'  //valid
    or
kstring = "kunal" //valid

Note double quotes are useful when you are using a string with a single quote in it .

kstring = 'kunal's not home .' // Not valid

This is not valid because the single quote which is there at the beginning of the string in 'k'  ends when it  encounters the single quote after 'l' , hence you have another single quote after stop(.) which is unaccounted for and hence the termination of the string will take place at a time much before than actually expected .

So we use double quotes in such situations :

kstring = "kunal's not home ." // valid

Concatenation  and simple operation is very easy in python :

five = 5
ten = 10

fifteen = five + ten


Hi = "hi"

Ganesh = "ganesh"
HiGanesh =Hi + Ganesh

ASSIGNMENTS :

Assignment can be done in more than one variable and in the same line .

a=2,b=3

BEWARE :

But  for all this cool tricks, do not forget one important thing .
DON'T MIX YOUR OPERATORS OR IT WILL BE THE DEATH OF YOU .

print  five + Hi  // Not Valid --> don't try to concatenate a number with a string .

That is all for today, next we will be looking into chapter 2 of this series which will deal with lists and operators .

Goodbye to you,

All the free thinking souls .


Monday, May 21, 2012

Java Script Error : Error: Expected 'j'


Java Script Error : Error: Expected 'j' :

Hi friends,

Here i am again with another piece of error that i encountered while scripting in java script .

Once I was using an alert and I got this error :  Error: Expected 'j' .

My alert statement was :

alert("Don't  skip but read the whole paragraph .");

Reason : This happened because, the apostrophe is a special character and as such to treat it as a normal character we need to escape it using back slash --> "\" .

So, the alert was re written as :

alert("Don\'t  skip but read the whole paragraph  .");

And voila, it started working properly .

Goodbye .
Have a nice day .

Sunday, May 20, 2012

Stepping into JS OOPS - Chapter 1

I was asked yesterday by my friend : why Java Script supports OOP (Object Oriented Programming).

I told him, it is because Java Script  can use inheritance and  objects .

His next Question was : How so ?

So let us see how java script is related to OOP .

JS (java script) can use Objects and objects are very important because they have attributes which can be used

As in java , we can create objects with the new operator.

CREATING OBJECTS :

Inside script-tag :

kObject = new Object(); // creating objects with new operator

kObject.name = "kunal"; //using object attribute name

End of script-tag .

CONSTRUCTOR :

Java uses constructors . Similarly JS can also use constructors .
Inside script-tag :

fruit : function(name) // My function name is fruit, which can have a name and color as its attribute
{
   this.name = name;
   this.typeOfFruit = function();
{
console.log("This is an" +this.name); // console.log is my favorite way of printing a //statement, it is like println() of java and is used in firebug console. you can also use //alert() here .
}
}


fruit1 = new fruit("Apple");
fruit1.typeOfFruit(); // O/P: This is an Apple


End of script-tag .

Here, the method fruit is an object constructor with its own set of attributes and functions.
Objects for this object constructor can be written using the "new" keyword .
Here we did so and inserted the string parameter Apple and then called the function typeOfFruit(), which in turn gets passed on to the function fruit and we get the o/p : This is an Apple.

WHAT  IS THIS ? : 

A lot of times I have been asked : why do we use this inside a  constructor ?

Here let me  take help of Java to explain this :

Consider a  class rectangle. It has its own attributes like height and width .

public  class Rectangle
{
int height = 10;
int width =    5;

// Now here comes my constructor :

public Rectangle(int Height, int Width)
{

 height = Height;
 width = Width;






/* I can describe my constructor in this way as well :


public Rectangle(int height, int width)
{

 this.height = height;
 this.width = width ;




*/
 
}

You can see that I have used the this keyword in my second description of constructor Rectangle.
The first argument of my constructor is height. 
Inside the constructor, a local copy of the same argument needs to be created. 
Hence , we use the keyword this to point to  the field : height .
If i would have used :
height = height ;
I would have got a warning that : this assignment does nothing.
Because we need to assign the variable : height in the constructor to the class attribute : height .

If we are to think of a real time example , consider that you have a very cool looking laptop. But your friend does not know that this laptop is yours . So what do you do ?

You tell him , in front of your dad that , this laptop is yours and he cannot have it .
Here your dad is the class, you are the constructor , who has the object laptop and you want to make sure that you assign it to yourself .


 
 

 


Saturday, May 19, 2012

Firebug Error --> Variable out of range

Hello friends,

I have thought of sharing this very important piece of info with you guys today .

Its mainly about this error which you might get while debugging  your web application in Firebug in mozilla :

"Varibale out of range (30 of 292)" or something like that.

Do understand that it is mainly because your variable is getting called somewhere else before its actual place where it must be called.

This mainly happens in a scenario where you have getters and setters for this variable and you are returning a value.

In such a case, let me give an example here :

var kVaraiable; // my variable

get kVariable();
set kVariable()
{
    return something;
}

Here , if you see kVariable out of range, then go ahead and take a peek in your firebug console and give special notice to the response and JSON part. You will see that some variable is giving an undefined value there.

Hence, to fix this you need to prevent the setter from returning anything , so you do this :

set kVariable()
{
    if(kVariable != undefined)  // this will prevent the variable from returning anything if it gets called          unexpectedly .
    return something;

}


ADIOS Freinds,
Think Free .


Difference Between Normal Java script and OOP Java Script


Hi friends,

I am sure many of us have troubles differentiating between these two. Well not to fear , in the coming days i will share some info that will shed light on both these two things, which will help us in understanding which is what.

But first,  let me give a simple example of both of them to clear doubts about these two from the mind of us, who are still new bees.



NORMAL JAVASCRIPT :
I know, many of you know how to write normal java script.
For those who are unaware of this , it is written in your html in this way :


Your normal script-tag goes here where you call your function , let us assume you do this in this way :
(button) onclick = callfunction();



//Then add your function :
callfunction()
{
//Do your operation
}

OOPS JAVASCRIPT :
Now the structural flow of a oops java script is very similar to your normal flow of a java program.

Here you have a class and its objects.
There is a syntactical difference also with normal javascript :


Your normal script-tag goes here where you call your function , let us assume you do this in this way :
(button) onclick = callfunction();


//your function call syntax will be a little different here :
callfunction : function()
{
//Do your operation
}

Hence you see the function is added as:

functionName : function(your parameters)
{

}

This is the end of article 1.

Be sure to visit my blog later so that you can see article 2 in detail and other interesting tips and techniques .