Thursday, June 14, 2012

New dimensions in UML2.0


  • New dimensions in UML2.0


The major difference is the enhancement and additional features added to the diagrams in UML2.0

Sequence diagram is a time dependent view of the interaction between objects to accomplish a behavioral goal of the system. The time sequence is similar to the earlier version of sequence diagram.

Communication diagram is a new name added in UML2.0. A Communication diagram is a structural view of the messaging between objects, taken from the Collaboration diagram concept of UML 1.4 and earlier versions. This can be defined as a modified version of collaboration diagram.

Interaction Overview diagram is also a new addition in UML2.0. An Interaction Overview diagram describes a high-level view of a group of interactions combined into a logic sequence, including flow-control logic to navigate between the interactions.

Timing diagram is also added in UML2.0. It is an optional diagram designed to specify the time constraints on messages sent and received in the course of an interaction.

if we analyze the new diagrams then it is clear that all the diagrams are created based upon the interaction diagrams described in the earlier versions

http://www.tutorialspoint.com/uml/uml_2_overview.htm





  • some of the new notations added to the class diagram from UML 1.x.


Instances
When modeling a system's structure it is sometimes useful to show example instances of the classes.
To model this, UML 2 provides the instance specification element, which shows interesting information using example (or real) instances in the system.

However, merely showing some instances without their relationship is not very useful; therefore, UML 2 allows for the modeling of the relationships/associations at the instance level as well

http://www.ibm.com/developerworks/rational/library/content/RationalEdge/sep04/bell/#N1031B

Monday, June 11, 2012

JavaServer Pages Standard Tag Library

JavaServer Pages Standard Tag Library (JSTL) encapsulates as simple tags the core functionality common to many Web applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags. 


JSTL 1.2 is part of the Java EE 5 platform


http://www.oracle.com/technetwork/java/index-jsp-135995.html

Friday, June 8, 2012

Denormalization


Denormalization

Denormalization on the contrary is the process of adding redundant data to speed up complex queries involving multiple table JOINS. Data is included in one table from another in order to eliminate the second table which reduces the number of JOINS in a query and thus achieves performance.

Only one valid reason exists for denormalizing a relational design - to enhance performance. The sacrifice to performance is that you increase redundancy in a database.

References:
http://www.indiabix.com/technical/dbms-basics/7
http://www.techpreparation.com/mysql-interview-questions-answers1.htm
http://www.dotnetfunda.com/interview/exclusive/showcatquestion.aspx?category=38


In computing, denormalization is the process of attempting to optimise the read performance of a database by adding redundant data or by grouping data.[1][2] In some cases, denormalisation helps cover up the inefficiencies inherent in relational database software. A relational normalised database imposes a heavy access load over physical storage of data even if it is well tuned for high performance.

http://en.wikipedia.org/wiki/Denormalization



Denormalization means allowing redundancy in a table. The main benefit of denormalization is improved performance with simplified data retrieval and manipulation. This is done by reduction in the number of joins needed for data 


Monday, June 4, 2012

string literal vs string object


when you use new String("...") you get a new string object.

In this example both string literals refer the same object:

String a = "abc";
String b = "abc";
System.out.println(a == b);  // True

Here two different objects are created and they have different references:

String c = new String("abc");
String d = new String("abc");
System.out.println(c == d);  // False
In general you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code.

Reference:
http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal









  •    the String class creates a pool of Strings

    when you create a String by using the new operator or by using the + and += operators (the string is computed at runtime) you are implicitly telling the compiler to create a new String object
    when you create a String by assigning a string literal the compiler searches the existing string pool for an exact match. If it finds one, a new string is NOT created. Instead the variable is assigned a reference to the existing pooled string.
 
    http://www.janeg.ca/scjp/oper/string.html



public class compareStrings {


public static void main(String[] args) {

/*
* string literal example
* when you create a String by assigning a string literal the compiler searches the existing string pool for an exact match.
* If it finds one, a new string is NOT created. Instead the variable is assigned a reference to the existing pooled string
*/
String str1="abc";
String str2="abc";



if (str1==str2)
{
System.out.println("str1=str2");
}
else
{
System.out.println("str1 not str2");
}



//to actually compare the contents of String objects use the String method equals()
if (str1.equals(str2)) {
System.out.println("str1=str2");
} else {
System.out.println("str1 not str2");
}



}

}




output:

str1=str2
str1=str2




public class compareStrings {


public static void main(String[] args) {




/*
* Here two different string objects are created and they have different references
* when you use new String("...") you get a new string object
* when you create a String by using the new operator or by using the + and += operators (the string is computed at runtime)
* you are implicitly telling the compiler to create a new String object
*/

String str1=new String("abc");
String str2=new String("abc");


if (str1==str2)
{
System.out.println("str1=str2");
}
else
{
System.out.println("str1 not str2");
}



//to actually compare the contents of String objects use the String method equals()
if (str1.equals(str2)) {
System.out.println("str1=str2");
} else {
System.out.println("str1 not str2");
}



}

}


output:

str1 not str2
str1=str2





  • Comparison of Objects with equals 

 
    == relational operator is used to compare primitive data types
 
int a = 5;
int b = 5;

if (a == b)
System.out.println("equal");
else
System.out.println("not equal");

Output is "equal".



"==" operator works only with primitive data types, does not work if we use wrapper classes of primitive data types

Integer a = new Integer(5);
Integer b = new Integer(5);

if (a == b)
System.out.println("equal");
else
System.out.println("not equal");

Output is "not equal".

"==" operator is not applicable for objects because it compares  references of objects not contents of objects
comparison of contents of objects there is "equals" method in each object

wrapper class example

Integer a = new Integer(5);
Integer b = new Integer(5);

if (a.equals(b))
System.out.println("equal");
else
System.out.println("not equal");

Output is "equal".


This "equals" work fine for wrapper classes but does not run correctly for custom classes because it compares two object references by default just like "==" operator.
To change behaviour of "equals" we will have to override it in our classes

http://javainnovations.blogspot.com/2008/05/comparison-of-objects-with-equals.html




  • equals method is overriden in all wrapper classes and String class as well. 

the StringBuffer class doesnt overrides it.


http://www.coderanch.com/t/241896/java-programmer-SCJP/certification/equals-Wrapper-Classes

public class TestWrapper {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Integer i=new Integer("1");
Integer j=new Integer("1");
String s=new String("1");
String s1="1";
StringBuffer sb=new StringBuffer("1");
StringBuffer sb1=new StringBuffer("1");
 
System.out.println(i==j);         //false
System.out.println(i.equals(j));   //true  
System.out.println(s==s1);          //false
System.out.println(s.equals(s1));   //true
System.out.println(sb==sb1);        //false
System.out.println(sb.equals(sb1)); //false
System.out.println(sb==sb);          //true
System.out.println(sb.equals(sb));   //true
System.out.println(sb1==sb1);        //true
System.out.println(sb1.equals(sb1)); //true


}

}





  • String and wrapper classes have override the equals method in Object class

Primitive values in Java are not objects.
In order to manipulate these values as objects, the java.lang package provides a wrapper class for each of the primitive data types
All wrapper classes are final.
The objects of all wrapper classes that can be instantiated are immutable,


Wrapper Comparison, Equality, and Hashcode

Each wrapper class (except Boolean) defines the following method:
int compareTo(WrapperType obj2)


Each wrapper class (except Boolean) also implements the Comparable interface, which defines the following method:
int compareTo(Object obj2)
This method is equivalent to the compareTo(WrapperType) method when the current object and the object denoted by the argument obj2 have the same WrapperType.




Each wrapper class overrides the equals() method from the Object class.
The overriding method compares two wrapper objects for object value equality.
boolean equals(Object obj2)


Each wrapper class overrides the hashCode() method in the Object class.
The overriding method returns a hash value based on the primitive value in the wrapper object.
int hashCode()

http://etutorials.org/cert/java+certification/Chapter+10.+Fundamental+Classes/10.3+The+Wrapper+Classes/



Sunday, June 3, 2012

Prepare Yourself Mentally and Emotionally for Your Job Search

 it’s important not to neglect the mental and emotional preparation that is also necessary

Rehearse
anticipate some of the questions the interviewer will ask, or that you think he or she will ask
Relaxation Exercises
They help you get your attention focused, centered, and calm. Deep breathing is one such exercise; meditation takes it a bit further along the preparedness scale
Remember – It’s Not Personal
So before your interview, go over how you will respond if the answer is no.
Have some steps planned out and some practical things you can do in the face of rejection.
This may make you more relaxed anyway, and you won’t appear desperate to the interviewer.
Visualization
Get a good mental picture of what your position will look like.

Reference:
http://jobstar.info/prepare-yourself-mentally-and-emotionally-for-your-job-search/?goback=.gde_1698247_member_120807357

Tuesday, May 29, 2012

perl interview questions

  • Explain the difference between 'my' and 'local' variable scope declarations?

Both of them are used to declare local variables.
The variables declared with 'my' can live only within the block and cannot gets its visibility inherited fucntions called within that block, but one defined as 'local' canlive within the block and have its visibility in the functions called within that block.




'my' creates a new variable, 'local' temporarily amends the value of a variable

There is a subtle difference.

In the example below, $::a refers to $a in the 'global' namespace.

$a = 3.14159;
{
local $a = 3;
print "In block, $a = $a ";
print "In block, $::a = $::a ";
}
print "Outside block, $a = $a ";
print "Outside block, $::a = $::a ";

# This outputs
In block, $a = 3
In block, $::a = 3
Outside block, $a = 3.14159
Outside block, $::a = 3.14159
[download]
ie, 'local' temporarily changes the value of the variable, but only within the scope it exists in.

so how does that differ from 'my'? 'my' creates a variable that does not appear in the symbol table, and does not exist outside of the scope that it appears in. So using similar code:

$a = 3.14159;
{
my $a = 3;
print "In block, $a = $a ";
print "In block, $::a = $::a ";
}
print "Outside block, $a = $a ";
print "Outside block, $::a = $::a ";

# This outputs
In block, $a = 3
In block, $::a = 3.14159
Outside block, $a = 3.14159
Outside block, $::a = 3.14159
[download]
ie, 'my' has no effect on the global $a, even inside the block.

http://www.coolinterview.com/interview/6205/






  • what is meant by a 'pack' in perl?

Pack Converts a list into a binary representation. Takes an array or list of values and packs it into a binary structure

http://discuss.itacumens.com/index.php?topic=37847.0




  • What are scalar data and scalar variables?

Scalar means a single thing, like a number or string

http://www.toppersarena.com/index.php?option=com_content&view=article&id=217:perl-interview-questions-and-answers&catid=36:blog-section&Itemid=49



  • What is a hash?

conventions remain the same - any combination of letters, numbers and the underscore characte
%special_events
A hash is also called an associative array, or an array where each value is associated with a corresponding key
%contactInfo = ('name', 'Bob', 'phone', '111-111-1111');
http://www.techinterviews.com/perl-interview-questions-and-answers
http://www.onesmartclick.com/interviews/perl-programming-interview-questions-answers.html




What does the command ‘use strict’ do and why should you use it?

#!/usr/local/bin/perl -w
use strict;

This will help you (really, it will force you) to write better, cleaner code.
Adding the -w switch to the perl interpreter will cause it to spit out warnings on uninitialized variables
'use strict' turns on the 'strict' pragma which will make you declare your variables with the my keyword
'use strict' also tosses up errors if your code contains any barewords that can't be interpreted in their current context.

http://perl.about.com/b/2006/09/21/why-you-should-use-strict.htm





  • "Use strict" is one of the pragma used for checking the variable scope and syntax


Eg: You can write a program like this:

$x=100
print $x

But if you use strict pragma, then you have to be very
specific while using variables

use strict;
my $x=100; ##look at the usage of scope like my,local,our
print $x;

http://www.allinterview.com/showanswers/16873.html






  • Explain the difference between use and require.


The use statement works at compile time, require at run time. So if you have a module that does a lot in a begin block and you don't really need it in all cases, then it's clever to "require" it there where you want to use it but don't "use" it. So you don't have to wait for all that initializations of that module in case you don't need it.

The differences are many and often subtle:
use only expects a bareword, require can take a bareword or an expression
use is evaluated at compile-time, require at run-time
use implicitly calls the import method of the module being loaded, require does not
use excepts arguments in addition to the bareword (to be passed to import), require does not
use does not behave like a function (i.e can't be called with parens, can't be used in an expression, etc), whereas require does
So they behave differently but achieve the same goal. Then there's a list of cultural differences in addition to the technical differences, but they're not so hard and fast.

http://www.perlmonks.org/?node_id=412860




  • What purpose does each of the following serve: -w, strict, - T ?

-w enables the warnings mode in perl-T is enables the Taint mode it performs some checks howyour program is using the data passed to itTurn on strict mode to make Perl check for common mistakes.

http://www.scribd.com/doc/1184228/Perl-Interview


-w:Enables warnings.Turning on warnings will make Perl yelp and complain at a huge variety of things that are almost always sources of bugs in your programs.

-t:Perl offers a mechanism called taint that marks any variable that the user can possibly control as being insecure. This includes user input, file input and environment variables.

Strict: It makes you declare all your variables (``strict vars''), and it makes it harder for Perl to mistake your intentions when you are using subs (``strict subs'').


  • Difference between for & foreach ?
For and foreach both are for looping the code but if you want to use array in place of scalar for loop, you have to use foreach keyword

  • What is a subroutine?
subroutine is a reusable piece of code.


  • Why we use Perl?
1.Perl is a powerful free interpreter.
2.Perl is portable, flexible and easy to learn.
-For shell scripting
-For CGI 
-Tons of scripts are available.
-Easy development
-Enormous big support script archive like CPAN
-No one starts to write a Perl scripts from scratch, you choose one from an archive and modify that.
-It is a "mature" scripting language.
-You may find Perl interpreter on every mission critical environment
-Easy to learn


  • what's hash?
Hash in basically used to comment the script line.
A hash is and unordered set of key/value pairs that you access using strings (keys) as subscripts, to look up the scalar value corresponding to a given key.


  • Name all the prefix dereferencer in perl?
The symbol that starts all scalar variables is called a prefix dereferencer. The different types of dereferencer are.
(i) $-Scalar variables
(ii) %-Hash variables
(iii) @-arrays
(iv) &-subroutines
(v) Type globs-*myvar stands for @myvar, %myvar.




  • What's the difference between grep and map in Perl?

grep returns those elements of the original list that match the expression, while map returns the result of the expression applied to each element of the original list.
http://perlknowledge.blogspot.com/2010/12/perl-basic-interview-question-and.html




how to perl on linux



@variables



A variable is defined by the ($) symbol (scalar)
the (@) symbol (arrays)
the (%) symbol (hashes)


Scalar variables are simple variables containing only one element--a string, a number, or a reference

Strings may contain any symbol, letter, or number.
Numbers may contain exponents, integers, or decimal values.
The bottom line here with scalar variables is that they contain only one single piece of data


Arrays contain a list of scalar data (single elements).

Hashes are complex lists with both a key and a value part for each element of the list.

Reference:
http://www.tizag.com/perlT/perlvariables.php



$a=1;
($a,$b)=(7,8);

$nummer1 =3;
$string1="estamboel";

print "$string1 $nummer1 \n";

print "$string1 + $nummer1 \n";

Reference:

http://www.youtube.com/watch?v=y25VxNiGc2M&feature=autoplay&list=PLE7511681ABEA8635&playnext=2





@syntax

File names, variables, and arrays are all case sensitive

'#' sign. Any words, spaces, or marks after a pound symbol will be ignored

use the backslash (\) character to escape any type of character that might interfere with our code



@strings

There is no limit to the size of the string, any amount of characters
string can be used with single or double quotations

@numbers

Numbers exist as real numbers, float, integers, exponents, octal, and hexidecimal numbers

@arrays

sequential number arrays
Rather than typing out each element when counting to 100 for example
@100 = (1 .. 100);

finding the length of an array
set the array to a scalar variable, then just print the new variable
@nums = (1 .. 20);
$nums = @nums;


adding and removing elements

push() - adds an element to the end of an array.
unshift() - adds an element to the beginning of an array.
pop() - removes the last element of an array.
shift() - removes the first element of an array.

Function Definition
push(@array, Element) Adds to the end of an array
pop(@array) Removes the last element of the array
unshift(@array, Element) Adds to the beginning of an array
shift(@array) Removes the first element of an array
delete $array[index] Removes an element by index number






how to run simple perl code on linux

Platform
Red Hat Enterprise Linux 5 (RHEL 5)

@Locate where the perl is installed.you can try where and which commands


[yeniceri@localhost ~]$ whereis perl
perl: /usr/bin/perl     /usr/share/man/man1/perl.1.gz


[yeniceri@localhost ~]$ which perl
/usr/bin/perl


@create a new file and type the following code

[yeniceri@localhost ~]$ vi test.pl 

#!/usr/bin/perl
print "hello world \n";

@execute test.pl

[yeniceri@localhost ~]$ perl test.pl 
hello world 

there's another way but you should grant access first


[yeniceri@localhost ~]$ ls -l test.pl
-rw-rw-r-- 1 yeniceri yeniceri 71 May 29 04:31 test.pl
[yeniceri@localhost ~]$ chmod u+x test.pl
[yeniceri@localhost ~]$ ls -l test.pl
-rwxrw-r-- 1 yeniceri yeniceri 71 May 29 04:31 test.pl
[yeniceri@localhost ~]$ ./test.pl
hello world


Reference;
http://www.tizag.com/perlT/perlvariables.php




Spring AOP



aspects get executed just before related objects run
aspects look like the way triggers work in the database
according to spring configuration files before a method is executed spring configuration file is checked.

aspect oriented programming is different because if there are three objects and these three objects share a common class to use a method you have to extend or make
references as what happens normally in object oriented programming.however in aspect programming you don't need to do these.you create special
classes called aspects and a configuration file.whenever few objects invoke a method before objects are executed aspect configuration file checks on them and then run the aspect class which is also referenced in aspect configuration file

Reference:
http://www.youtube.com/watch?v=QdyLsX0nG30&list=PLE37064DE302862F8&index=1&feature=plpp_video

Wednesday, May 9, 2012

why JPA?




Why JPA?

A fundamental question for many Java developers is "Why JPA?
 Why do I need to know how to use this API when object-relational mapping tools like Hibernate and Toplink are already available?"

The answer is that JPA is not a new technology; rather, it has collected the best ideas from existing persistence technologies like Hibernate, TopLink, and JDO.

The result is a standardized specification that helps you build a persistence layer that is independent of any particular persistence provider.

http://www.javaworld.com/javaworld/jw-01-2008/jw-01-jpa1.html





The Java Persistence API - A Simpler Programming Model for Entity Persistence

A major enhancement in EJB technology is the addition of the new Java Persistence API, which simplifies the entity persistence model and adds capabilities that were not in EJB 2.1 technology.

The Java Persistence API deals with the way relational data is mapped to Java objects ("persistent entities"), the way that these objects are stored in a relational database so that they can be accessed at a later time, and the continued existence of an entity's state even after the application that uses it ends.

In addition to simplifying the entity persistence model, the Java Persistence API standardizes object-relational mapping


The Java Persistence API draws on ideas from leading persistence frameworks and APIs such as Hibernate, Oracle TopLink, and Java Data Objects (JDO), and well as on the  earlier EJB container-managed persistence


The Java Persistence API simplifies the programming model for entity persistence and adds capabilities that were not in EJB 2.1.

Here's a quick list of its simplifications and additions:

Provides cleaner, easier, standardized object-relational mapping
Eliminates the need for lookup code
Adds support for inheritance, polymorphism, and polymorphic queries.
Provides a Java Persistence query language -- an enhanced EJB QL


http://www.oracle.com/technetwork/articles/javaee/jpa-137156.html

Tuesday, May 8, 2012

What is software architecture of EJB?



Session and Entity EJBs consist of 4 and 5 parts respetively:

1. A remote interface (a client interacts with it),

2. A home interface (used for creating objects and for declaring business methods),

3. A bean object (an object, which actually performs business logic and EJB-specific operations).

4. A deployment descriptor (an XML file containing all information required for maintaining the EJB) or a set of deployment descriptors (if you are using some container-specific features).

5.A Primary Key class - is only Entity bean specific.

What makes J2EE suitable for distributed multitiered applications?


What makes J2EE suitable for distributed multitiered applications?

The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application

components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs


Client-tier components run on the client machine.
Web-tier components run on the J2EE server.
Business-tier components run on the J2EE server.
Enterprise information system (EIS)-tier software runs on the EIS server.

What are the components of J2EE application?


What are the components of J2EE application?

Application clients and applets are client components.
Java Servlet and JavaServer Pages technology components are web components.
Enterprise JavaBeans components (enterprise beans) are business components.

Are JavaBeans J2EE components?


Are JavaBeans J2EE components?
No.JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables.

Differences between EJB 3.0 and EJB 2.1


Differences between EJB 3.0 and EJB 2.1

EJB2.0 has Deployment descriptors but in EJB3.0 has no Deployment Descriptors.
EJB2.0 we have to write Home and Remote Interfaces But in EJB3.0 No need to write Home and remote interfaces

Compared to EJB 2.1, EJB 3.0 simplifies the process of creating Enterprise JavaBean applications.

The underlying concept of the EJB 3.0 specification centers on a plain old Java™ object (POJO) programming model that uses Java annotations to capture information that deployment descriptors used to contain

Deployment descriptors are now optional in most cases.

session beans also no longer require EJB-specific component interfaces either.

EJB 3.0 has introduced a lightweight entity bean persistence mechanism through the Java Persistence API. These entities are POJO based and can then be run outside of an EJB container and do not require any interfaces or EJB code in them

What is the EAR file?

An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.

Monday, May 7, 2012

auto-boxing, boxing, unboxing



  • Lesson3 Boxing & Unboxing

http://www.youtube.com/watch?v=ujbeM5MD84M&feature=autoplay&list=ULr_jhKrpDD5c&playnext=1



  • java 09 - Wrappers and Boxing

http://www.youtube.com/watch?v=KUdvCjLqP_0
wrapper class wraps primitive type into an object





  • Java Tutorial 7.1 Autoboxing Part 1/3

http://www.youtube.com/watch?v=JPIN1vZBM8M&feature=relmfu


  • Java Tutorial 7.2 Autoboxing Part 2/3

http://www.youtube.com/watch?v=uGLoHyjURtc&feature=relmfu


  • java Tutorial 7.3 Autoboxing Part 3/3

http://www.youtube.com/watch?v=jqKn_dCBU20&list=UU77mSrM47r2NgFoxGSl4DXw&index=154&feature=plpp_vide



  • Autoboxing

Autoboxing and unboxing is introduced in Java 1.5 to automatically convert primitive type into boxed primitive( Object or Wrapper class).
before Java 1.5 then you are familiar with the issues like you can not directly put primitives into Collections, instead you first need to convert them into Object only then only you can put them into Collections. Wrapper class like Integer
With the introduction of autoboxing and unboxing in Java this primitive to object conversion happens automatically by Java compiler which makes code more readable


it becomes even more important because they are automatic and can create subtle bugs if you are not sure when autoboxing  in Java code occurs and when unboxing happens.

When Java automatically converts a primitive type like int into corresponding wrapper class object e.g. Integer than its called autoboxing  because primitive is boxed into wrapper class while in opposite case is called unboxing, where an Integer object is converted into primitive int.


All primitive types e.g. byte, short, char, int, long, float, double and boolean has corresponding wrapper class e.g. Byte, Short, Integer, Character etc and participate in autoboxing and unboxing.


During autoboxing boolean is converted to Boolean, byte to Byte, char converted to Character, float changes to Float, int goes to Integer, long goes to Long and short converts to Short, while in unboxing opposite happens like Float to float.

for example In method invocation where an object argument is expected,  if you pass primitive, Java automatically converts primitive into equal value Object.

Autoboxing mainly occur in two places one is during assignment and other is during method invocation


One of the danger of autoboxing is throw away object which gets created if autoboxing occurs in a loop. Here is an example of how unnecessary object can slow down your application


Integer sum = 0;
 for(int i=1000; i<5000 i="i" p="p">   sum+=i;
 }

In this code sum+=i will expand as sum = sum + i and since + operator is not applicable to Integer object it will trigger unboxing of sum Integer object and then autoboxing of result which will be stored in sum which is Integer as shown below :

sum = sum.intValue() + i;
Integer sum = new Integer(result);    
   
here since sum is Integer, it will create around 4000 unnecessary Intger object which are just throw away and if this happens on large scale has It potential to slow down system with frequent GC for arithmetic calculation always prefer primitive over boxed primitive and look for unintentional autoboxing in Java

autoboxing is error prone e.g. equality operator "==". Since equality operator can be applied on both primitive and Objects it leads to confusion and can cause subtle issues

When you compare two object using "==" operator it compares object's identity and not value and also no auto boxing occur.
its not best practice to use  equality operator to compare Objects, use equals method instead

if we compare one primitive with another object than unboxing of object is occur which could throw NullPointerException if object is null e.g.

Since autoboxing creates unnecessary object and if that goes beyond a limit usually outside the range of cached value it can potentially slow your program by frequently causing garbage collection.



http://javarevisited.blogspot.com/2012/07/auto-boxing-and-unboxing-in-java-be.html#ixzz22r1HOohK





what is transaction?



  • Lesson6 Transactions

http://www.youtube.com/watch?v=r_jhKrpDD5c&feature=channel&list=UL



  • transaction

In computer programming, a transaction usually means a sequence of information exchange and related work (such as database updating) that is treated as a unit for the purposes of satisfying a request and for ensuring database integrity.

A typical transaction is a catalog merchandise order phoned in by a customer and entered into a computer by a customer representative. The order transaction involves checking an inventory database, confirming that the item is available, placing the order, and confirming that the order has been placed and the expected time of shipment. If we view this as a single transaction, then all of the steps must be completed before the transaction is successful and the database is actually changed to reflect the new order. If something happens before the transaction is successfully completed, any changes to the database must be kept track of so that they can be undone.
http://searchcio.techtarget.com/definition/transaction



  • What Is a Transaction Processing System?

Transaction processing system is a program or software that processes all transactions that go in and out of a business or a company.
The system goes over the transactions one by one, like in an automated teller machine (ATM) that permits only one user at a time
The term “transaction,” in this case, does not only refer to financial aspects, but to requests for information as a whole, such as booking a flight or just logging into an online bank account.

In direct contrast to a transaction processing system is a batch processing system.
This system processes multiple transactions—or a “batch” of transactions—simultaneously.
The main disadvantage is that the processed transactions do not return immediate results.

A modern analogy is a torrent file connected to a folder of files.
The user cannot immediately access a file until all the files in the folder are completely downloaded.
http://www.wisegeek.com/what-is-a-transaction-processing-system.htm


Wednesday, April 25, 2012

binary heap


  • GRE Computer Science Question 02

http://www.youtube.com/watch?v=Imfaj84IaWY&feature=relmfu


  • Heaps

http://www.youtube.com/watch?v=_9QXNFcrF4c


  • Heaps Part 2

http://www.youtube.com/watch?v=DHhPg01rBGs&feature=relmfu



  • Binary Heaps


A binary heap is a complete binary tree which satisfies the heap ordering property. The ordering can be one of two types:

the min-heap property: the value of each node is greater than or equal to the value of its parent, with the minimum-value element at the root.
the max-heap property: the value of each node is less than or equal to the value of its parent, with the maximum-value element at the root.

Since a heap is a complete binary tree, it has a smallest possible height - a heap with N nodes always has O(log N) height.

http://www.cs.cmu.edu/~adamchik/15-121/lectures/Binary%20Heaps/heaps.html




  • Binary Heaps

A binary heap is a complete binary tree, where each node has a higher priority than its children

Complete binary tree: Each node has two children, except for the last two levels.
(The nodes at the last level do not have children.)
New nodes are inserted at the last level from left to right.

This is called heap-structure property.

http://faculty.simpson.edu/lydia.sinapova/www/cmsc250/LN250_Tremblay/L11-BinHeap.htm
  • Heap is a binary tree with two special properties: it must have all its nodes in specific order and its shape must be complete.

have duplicate values in a heap — there’s no restriction against that
 The ordering of the child nodes isn’t important for a heap
A heap doesn’t follow the rules of a binary search tree; unlike binary search trees, the left node does not have to be smaller than the right node

Heap can be broadly classified in two types :
1. Min heap
2. Max heap

Min Heap
A min heap is a heap where every single parent node, including the root, is less than or equal to the value of its children nodes.

Max Heap
Every parent node, including the root, is greater than or equal to the value of its children nodes.

Heap Majorly has 3 operations –

Insert Operation(Time complexity O(log n))
Delete Operation (Time complexity O(log n))
Extract-Min (OR Extract-Max) (Time complexity O(n))


The heap data structure has many applications:

Heapsort:with no quadratic worst-case scenarios.
Selection algorithms: A heap allows access to the min or max element in constant time, and other selections (such as median or kth-element) can be done in sub-linear time on data that is in a heap.
Graph algorithms: By using heaps as internal traversal data structures, run time will be reduced by polynomial order. Examples of such problems are Prim's minimal-spanning-tree algorithm and Dijkstra's shortest-path algorithm.
Priority Queue: A priority queue is an abstract concept like "a list" or "a map"; just as a list can be implemented with a linked list or an array, a priority queue can be implemented with a heap or a variety of other methods
K-way merge: A heap data structure is useful to merge many already-sorted input streams into a single sorted output stream. 
Order statistics: The Heap data structure can be used to efficiently find the kth smallest (or largest) element in an array.

https://iq.opengenus.org/max-heap-min-heap/

Tuesday, April 24, 2012

Comparable vs. Comparator interface



  • Comparable vs. Comparator interface


Classes should implement the Comparable interface to control their natural ordering
Use Comparator to sort objects in an order other than their natural ordering.
http://grdurand.com/static/presentation_four/comparable.html



  • Use of comparable and comparator interface

A class implementing Comparable interface need to override compareTo(Object obj) method and put the logic for sorting
Comparator interface is used when an extra logic is required to sort the objects. One need to override compare(Object obj1, Object obj2) method
http://java-questions.com/use_of_comparable_comparator.html




  • How to use Comparator and Comparable in Java? With example

If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

How to Compare String in Java
For comparing String in Java we should not be worrying because String implements Comparable interface in Java and provides implementation for CompareTo method which Compare two strings based on  characters inside or you can say in lexical order. You just need to call String.compareTo(AnotherString) and Java will determine whether specified String is greater than , equal to or less than current String. String is also immutable in Java an important property to remember.


How to Compare Dates in Java
Dates are represented by java.util.Date class in Java and like String Dates also implements Comparable in Java so they will be automatically sorted based on there natural ordering if they got stored in any sorted collection like TreeSet or TreeMap.

http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html#ixzz1swgniOFa





  • Lesson12 java lang Comparable

http://www.youtube.com/watch?v=6x_YG-27iwY&feature=related




  • “How you will sort Employee object based on his EmployeeID and his name” and this involves the use of both Comparable as well as Comparator interface in Java. 


often required to sort objects stored in any collection classes like ArrayList, HashSet or in Array and that time we need to use either  compare() or  compareTo() method defined in java.util.Comparator and java.lang.Comparable.


java.util.Comparator
Comparator interface in Java has method public int compare (Object o1, Object o2)
Comparator in Java compare two objects provided

java.lang.Comparable
public int compareTo(Object o)
Comparable interface compares "this" reference with the object specified
In Java API String, Date and wrapper classes implements Comparable interface.Its always good practice to override compareTo() for value objects


if you want to sort objects based on natural order then use Comparable in Java
if you want to sort on some other attribute of object then use Comparator in Java.

For a Person class, sorting based on person_id can be treated as natural order sorting and sorting based on name field can be implemented using Comparator interface. To sort based on person_id we need to implement compareTo() method.

http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html#ixzz2D3Lj5aSb



  • public boolean equals(Object obj)

This method checks if some other object passed to it as an argument is equal to the object on which this method is invoked.
The default implementation of this method in Object class simply checks if two object references x and y refer to the same object. i.e.
It checks if x == y.
This particular comparison is also known as "shallow comparison".


public int hashCode()
This method returns the hash code value for the object on which this method is invoked.
This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet etc. This method must be overridden in every class that overrides the equals method
http://www.javaranch.com/journal/2002/10/equalhash.html




  • A comparator object is capable of comparing two different objects. 

The class is not comparing its instances, but some other class's instances.
This comparator class must implement the java.util.Comparator interface.
http://www.java-connect.com/collection-framework/Comparator-in-java.html




  • Understanding Java's Integer Pool Can Avoid Problems

Integer i1 = 128
Integer i2 = 128

If you then execute the test (i1 == i2), the returned result is false. The reason is that the JVM maintains a pool of Integer values (similar to the one it maintains for Strings). But the pool contains only integers from -128 to 127. Creating any Integer in that range results in Java assigning those Integers from the pool, so the equivalency test works. However, for values greater than 127 and less than -128), the pool does not come into play, so the two assignments create different objects, which then fail the equivalency test and return false.
http://www.devx.com/tips/Tip/42276



Monday, April 23, 2012

The Difference Between Internet, Intranet, and Extranet


The Difference Between Internet, Intranet, and Extranet
http://www.iorg.com/papers/iw/19981019-advisor.html


İntranet, sadece belirli bir kuruluş içindeki bilgisayarları, yerel ağları (LAN) ve geniş alan ağlarını (WAN) birbirine bağlayan, çoğunlukla TCP/IP tabanlı bir ağdır. İntranet'ler Ağ geçitleri (İng: gateways) ile diğer ağlara bağlanabilir. Temel oluşturulma amaçları, kuruluş bünyesinde bilgileri ve bilgi işlem kapasitesini
paylaşmaktır.
http://tr.wikipedia.org/wiki/%C4%B0ntranet


An intranet is a computer network that uses Internet Protocol technology to share information, operational systems, or computing services within an organization.
http://en.wikipedia.org/wiki/Intranet


The Internet is a global system of interconnected computer networks that use the standard Internet protocol suite (often called TCP/IP, although not all protocols use TCP) to serve billions of users worldwide.
http://en.wikipedia.org/wiki/Internet


An extranet is a computer network that allows controlled access from the outside, for specific business or educational purposes
http://en.wikipedia.org/wiki/Extranet

Voice over IP

Voice over IP (VoIP) commonly refers to the communication protocols, technologies, methodologies, and transmission techniques involved in the delivery of voice

communications and multimedia sessions over Internet Protocol (IP) networks, such as the Internet. Other terms commonly associated with VoIP are IP telephony, Internet

telephony, voice over broadband (VoBB), broadband telephony, and broadband phone.
http://en.wikipedia.org/wiki/Voice_over_IP

Differences between threads and processes

  • Threads vs. Processes


 processes are independent execution units that contain their own state information, use their own address spaces, and only interact with each other via interprocess communication mechanisms (generally managed by the operating system)

Applications are typically divided into processes during the design phase, and a master process explicitly spawns sub-processes when it makes sense to logically separate significant application functionality.
Processes, in other words, are an architectural construct.


a thread is a coding construct that doesn't affect the architecture of an application.
A single process might contains multiple threads;
all threads within a process share the same state and same memory space, and can communicate with each other directly, because they share the same variables.

http://www.cafeaulait.org/course/week11/02.html




Threads share the address space of the process that  created it; processes have their own address.

Threads can directly communicate with other threads of its process;
processes must use interprocess communication to communicate with sibling processes.

http://erpbasic.blogspot.in/2012/03/what-is-difference-between-thread-and.html?goback=.gde_118012_member_102219377

course pages

Electrical Engineering and Computer Science
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/

Wednesday, April 18, 2012

course pages

Yazilim Mühendisligi
http://eng.harran.edu.tr/~nbesli/

BIL 582
http://sadik.etu.edu.tr/

Dosyalar / Yazilim Mühendisligi
http://www.ce.yildiz.edu.tr/personal/yunus/file/295/Yaz%C4%B1l%C4%B1m+M%C3%BChendisli%C4%9Fi


BM 314 Yazilim Mühendisligi
http://ceng.gazi.edu.tr/~hkaracan/bm314.html


SE102 Foundations of Software Engineering II
https://www.cs.drexel.edu/~spiros/teaching/SE102/index.html


Software Project Management
http://ii.metu.edu.tr/~is529/index.html#dwn

GRE Computer Science Questions

GRE Computer Science Question 01


40. Consider the following pseudocode program.
int i
main ()
{
i = 3
S ()
R ()
}
void S ()
{
print i // prints the value of i on the current line of output
print " " // prints a blank space on the current line of output
}
void R ()
{
int i
i = 2
S ()
}
What is the output of the program if the pseudocode uses either static (lexical) scoping or dynamic scoping?
Static Scoping Dynamic Scoping
(A) 3 2 3 2
(B) 3 3 2 2
(C) 3 3 2 3
(D) 3 3 3 2
(E) 3 3 3 3

http://www.youtube.com/watch?v=SwyaLVsJCsI

Selection Sort

  • Algorithms Lesson 8: Selection Sort

http://www.youtube.com/watch?v=6nDMgr0-Yyo&feature=relmfu



  • Selection Sort


In computer science, a selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

The algorithm works as follows:
Find the minimum value in the list
Swap it with the value in the first position
Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)


/* a[0] to a[n-1] is the array to sort */
int i,j;
int iMin;

/* advance the position through the entire array */
/*   (could do j < n-1 because single element is also min element) */
for (j = 0; j < n-1; j++) {
    /* find the min element in the unsorted a[j .. n-1] */

    /* assume the min is the first element */
    iMin = j;
    /* test against elements after j to find the smallest */
    for ( i = j+1; i < n; i++) {
        /* if this element is less, then it is the new minimum */
        if (a[i] < a[iMin]) {
            /* found new minimum; remember its index */
            iMin = i;
        }
    }

    /* iMin is the index of the minimum element. Swap it with the current position */
    if ( iMin != j ) {
        swap(a[j], a[iMin]);
    }
}


http://en.wikipedia.org/wiki/Selection_sort




  • Selection Sort

https://www.youtube.com/watch?v=f8hXR_Hvybo


  • Algorithms #3 - Selection Sort

https://www.youtube.com/watch?v=TW3_7cD9L1A

Insertion Sort


  • Algorithms Lesson 2: Insertion Sort


worst case: n^2

http://www.youtube.com/watch?v=c4BRHC7kTaQ&feature=fvwrel




  • Insertion sort


Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time.
It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort
More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such as selection sort or bubble sort; the best case (nearly sorted input) is O(n)

Every repetition of insertion sort removes an element from the input data, inserting it into the correct position in the already-sorted list, until no input elements remain

When humans manually sort something (for example, a deck of playing cards), most use a method that is similar to insertion sort

for i ? 1 to i ? length(A)-1
   {
     // A[ i ] is added in the sorted sequence A[0, .. i-1]
     // save A[i] to make a hole at index iHole
     item ? A[i]
     iHole ? i
     // keep moving the hole to next smaller index until A[iHole - 1] is <= item
     while iHole > 0 and A[iHole - 1] > item
       {
         // move hole to next smaller index
         A[iHole] ? A[iHole - 1]
         iHole ? iHole - 1
       }
     // put item in the hole
     A[iHole] ? item
   }
 
http://en.wikipedia.org/wiki/Insertion_sort






  • The ideas of insertion


The main operation of the algorithm is insertion. The task is to insert a value into the sorted part of the array.

Java implementation

void insertionSort(int[] arr) {
      int i, j, newValue;
      for (i = 1; i < arr.length; i++) {
            newValue = arr[i];
            j = i;
            while (j > 0 && arr[j - 1] > newValue) {
                  arr[j] = arr[j - 1];
                  j--;
            }
            arr[j] = newValue;
      }
}


http://www.algolist.net/Algorithms/Sorting/Insertion_sort

Bubblesort


  • Algorithms Lesson 1: Bubblesort

http://www.youtube.com/watch?v=P00xJgWzz2c&feature=relmfu


  • Bubble sort - algorithm and analysis

http://www.youtube.com/watch?v=PdmyYqO_59s&feature=related




  • Bubble sort


Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order

Bubble sort has worst-case and average complexity both O(n2), where n is the number of items being sorted

procedure bubbleSort( A : list of sortable items )
   repeat    
     swapped = false
     for i = 1 to length(A) - 1 inclusive do:
       /* if this pair is out of order */
       if A[i-1] > A[i] then
         /* swap them and remember something changed */
         swap( A[i-1], A[i] )
         swapped = true
       end if
     end for
   until not swapped
end procedure


http://en.wikipedia.org/wiki/Bubble_sort



  • Bubble Sort

Bubble sort belongs to O(n2) sorting algorithms, which makes it quite inefficient for sorting large data volumes.

Java

public void bubbleSort(int[] arr) {
      boolean swapped = true;
      int j = 0;
      int tmp;
      while (swapped) {
            swapped = false;
            j++;
            for (int i = 0; i < arr.length - j; i++) {                                      
                  if (arr[i] > arr[i + 1]) {                        
                        tmp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = tmp;
                        swapped = true;
                  }
            }              
      }
}

http://www.algolist.net/Algorithms/Sorting/Bubble_sort




Heapsort


  • Algorithms Lesson 9: Heaps

http://www.youtube.com/watch?v=v1YUApMYXO4&feature=fvwrel


  • Algorithms Lesson 10: Heapsort

http://www.youtube.com/watch?v=6NB0GHY11Iw


  • Heapsort


Heapsort is a comparison-based sorting algorithm to create a sorted array (or list), and is part of the selection sort family
has the advantage of a more favorable worst-case O(n log n) runtime


Heapsort is a two step algorithm.
The first step is to build a heap out of the data.
The second step begins with removing the largest element from the heap

http://en.wikipedia.org/wiki/Heapsort



  • Heap Sort Algorithm

The heap sort combines the best of both merge sort and insertion sort. Like merge sort, the worst case time of heap sort is O(n log n) and like insertion sort, heap sort sorts in-place.
http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Sorting/heapSort.htm

Quicksort



  • Algorithms Lesson 4: Quicksort

http://www.youtube.com/watch?v=y_G9BkAm6B8&feature=relmfu
partition step


  • Visualization of Quick Sort

http://www.youtube.com/watch?v=vxENKlcs2Tw


  • Quick Sort

http://www.youtube.com/watch?v=J7FTIe5y3Mw&feature=related


  • QuickSort

http://www.youtube.com/watch?v=Fju_NstEy3M



  • Lec-11 Mergesort And Quicksort

http://www.youtube.com/watch?v=KrjWloKRE2U&feature=related




  • Quicksort

Quicksort is a sorting algorithm
In the worst case, it makes O(n2) comparisons
Quicksort is often faster in practice than other O(n log n) algorithms

Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists.

The steps are:
Pick an element, called a pivot, from the list.

Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.

Recursively sort the sub-list of lesser elements and the sub-list of greater elements.

function quicksort('array')
      if length('array') = 1
          return 'array'  // an array of zero or one elements is already sorted
      select and remove a pivot value 'pivot' from 'array'
      create empty lists 'less' and 'greater'
      for each 'x' in 'array'
          if 'x' = 'pivot' then append 'x' to 'less'
          else append 'x' to 'greater'
      return concatenate(quicksort('less'), 'pivot', quicksort('greater')) // two recursive calls
     
http://en.wikipedia.org/wiki/Quicksort



  • Quicksort


Quicksort is a fast sorting algorithm, which is used not only for educational purposes, but widely applied in practice

Java

int partition(int arr[], int left, int right)
{
      int i = left, j = right;
      int tmp;
      int pivot = arr[(left + right) / 2];
   
      while (i <= j) {
            while (arr[i] < pivot)
                  i++;
            while (arr[j] > pivot)
                  j--;
            if (i <= j) {
                  tmp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = tmp;
                  i++;
                  j--;
            }
      };
   
      return i;
}

void quickSort(int arr[], int left, int right) {
      int index = partition(arr, left, right);
      if (left < index - 1)
            quickSort(arr, left, index - 1);
      if (index < right)
            quickSort(arr, index, right);
}

http://www.algolist.net/Algorithms/Sorting/Quicksort


  • Quick Sort is a sorting algorithm which uses divide and conquer technique.
In quick sort we choose an element as a pivot and we create a partition of array around that pivot. by repeating this technique for each partition we get our array sorted

depending on the position of the pivot we can apply quick sort in different ways

taking first or last element as pivot
taking median element as pivot

Time Complexity Analysis of Quick Sort
The average time complexity of quick sort is O(N log(N)).

Best case Time Complexity of Quick Sort
O(Nlog(N))
the best case of quick sort is when we will select pivot as a mean element.

Worst Case Time Complexity of Quick Sort
O(N^2)
This will happen when we will when our array will be sorted and we select smallest or largest indexed element as pivot

Average Case Time Complexity of Quick Sort
O(Nlog(N))

Space Complexity
O(N)


https://iq.opengenus.org/time-and-space-complexity-of-quick-sort/

Tuesday, April 17, 2012

Primary Key

Primary Key:
A primary key is a field or combination of fields that uniquely identify a record in a table, so that an individual record can be located without confusion.
http://www.databasedev.co.uk/primary_foreign_key_constraints.html


A primary key is one which uniquely identifies a row of a table. this key does not allow null values and also does not allow duplicate values
http://www.allinterview.com/showanswers/15625.html


A primary key in a database, is simply a useful device (key) that makes each record unique.
Read more: http://wiki.answers.com/Q/What_is_the_purpose_of_a_primary_key_in_a_database#ixzz1sIudT06W

foreign key

foreign key - a foreign key is one which will refer to a primary key of another table
http://www.allinterview.com/showanswers/15625.html

A foreign key is a relationship or link between two tables which ensures that the data stored in a database is consistent.
The foreign key link is set up by matching columns in one table (the child) to the primary key columns in another table (the parent)
http://www.visualcase.com/kbase/database_basics_-_foreign_keys.htm


Foreign Key:
A foreign key (sometimes called a referencing key) is a key used to link two tables together.
Typically you take the primary key field from one table and insert it into the other table where it becomes a foreign key
(it remains a primary key in the original table).

A foreign key constraint specifies that the data in a foreign key must match the data in the primary key of the linked table, in the above example we couldn't set the DeptID in the Employee table to 04 as there is no DeptID of 04 in the Department table. This system is called referential integrity, it is to ensure that the data entered is correct and not orphaned (i.e. there are no broken links between data in the tables)
http://www.databasedev.co.uk/primary_foreign_key_constraints.html

EXISTS Condition

EXISTS Condition

The EXISTS condition is considered "to be met" if the subquery returns at least one row.

The syntax for the EXISTS condition is:

SELECT columns
FROM tables
WHERE EXISTS ( subquery );




Example #1:

Let's take a look at a simple example. The following is an SQL statement that uses the EXISTS condition:

SELECT *
FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);

This select statement will return all records from the suppliers table where there is at least one record in the orders table with the same supplier_id.



Example #2 - NOT EXISTS:

The EXISTS condition can also be combined with the NOT operator.

For example,

SELECT *
FROM suppliers
WHERE not exists (select * from orders Where suppliers.supplier_id = orders.supplier_id);

This will return all records from the suppliers table where there are no records in the orders table for the given supplier_id.

http://www.techonthenet.com/sql/exists.php

what is multiprogramming ?


  • what is multiprogramming ?


Multiprogramming is a rudimentary form of parallel processing in which several programs are run at the same time on a uniprocessor.
Since there is only one processor , there can be no true simultaneous execution of different programs.
Instead, the operating system executes part of one program, then part of another, and so on.
To the user it appears that all programs are executing at the same time.




  • What are the advantages of multiprogramming?

Multiprogramming makes effifcient use of the CPU by overlapping the demands for the CPU and its I/O devices from various users. It attempts to increase CPU utilization by always having something for the CPU to execute
http://wiki.answers.com/Q/What_are_the_advantages_of_multiprogramming



  • What is the advantage of Multiprogramming?

Multiprogramming increases CPU utilization by organizing jobs so that the CPU always has one to execute.
Several jobs are placed in the main memory and the processor is switched from job to job as needed to keep several jobs advancing while keeping the
peripheral devices in use.
Multiprogramming is the first instance where the Operating system must make decisions for the users.
Therefore they are fairly sophisticated.

Friday, April 13, 2012

course pages,quizes,tests,exams

CSC 257/457 - Computer Networks (Fall 2008)
http://www.cs.rochester.edu/~bukys/csc257-fall2008/


Computer Networks
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-829-computer-networks-fall-2002/lecture-notes/


CS 268: Computer Networks, Spring 2003: Syllabus
http://inst.eecs.berkeley.edu/~cs268/sp03/



BBS 676 Veri Iletisimi ve Bilgisayar Aglari
http://www.ee.hacettepe.edu.tr/~toker/BBS676/BBS676-Homepage.html


BIL 472 Bilgisayar Aglari 2006-2007 Bahar Dönemi
http://www.gyte.edu.tr/dosya/104/ders/BIL472/


AYÅžE BETÜL OKTAY BTP 213 AÄŸ Sistemleri 
http://www.fatih.edu.tr/~betulg/network.htm

Trees

  • Data Structures - Chapter 3: Tree-part1

http://www.youtube.com/watch?v=7Ac2qNITEYQ&feature=channel&list=UL




  • Tree (data structure)

In computer science, a tree is a widely used data structure that simulates a hierarchical tree structure with a set of linked nodes.
A tree can be defined recursively (locally) as a collection of nodes (starting at a root node), where each node is a data structure consisting of a value, together with a list of nodes (the "children"), with the constraints that no node is duplicated.
A tree can be defined abstractly as a whole (globally) as an ordered tree, with a value assigned to each node

Representations

There are many different ways to represent trees; common representations represent the nodes as dynamically allocated records with pointers to their children, their parents, or both, or as items in an array, with relationships between them determined by their positions in the array (e.g., binary heap).

http://en.wikipedia.org/wiki/Tree_(data_structure)





  • Trees

we shall extend the use of pointers to define a non-linear structure to model hierarchical relationships, such as a family tree.
In such a tree, we have links moving from an ancestor to a parent, and links moving from the parent to children

A tree is a data structure that is made of nodes and pointers, much like a linked list.
The difference between them lies in how they are organized

The height of a tree is defined to be the length of the longest path from the root to a leaf in that tree ( including the path to root)


Tree Examples
Directory Hierarchies:
In computers, files are stored in directories that form a tree.
The top level directory represents the root.
It has many subdirectories and files

Organization charts:

Biological classifications:
Starting from living being at the root, such a tree can branch off to mammals, birds, marine life etc

Game Trees:
All games which require only mental effort would always have number of possible options at any position of the game.
For each position, there would be number of counter moves.
The repetitive pattern results in what is known a game tree

http://www.cs.ucf.edu/courses/cop3502h.02/trees1.pdf





  • Trees have many uses:


representing family genealogies
as the underlying structure in decision-making algorithms
to represent priority queues (a special kind of tree called a heap)
to provide fast access to information in a database (a special kind of tree called a b-tree)
http://pages.cs.wisc.edu/~vernon/cs367/notes/8.TREES.html

linked list



  • Linked Lists in 10 minutes - I

http://www.youtube.com/watch?v=LOHBGyK3Hbs&feature=related

Disadvantages of arrays are
-when element is added all elements need to be shifted
-fixed size

with linked list these problems are overcame




  • linked list in plain english

http://www.youtube.com/watch?v=oiW79L8VYXk




  • advantages

The biggest advantage of linked lists is that they can be expanded in constant time without memory overhead. 

For example when you make an array you must allocate memory for a certain number of elements. 
If you want to add more elements to the array than you allocated for you must create a new array and copy the old array into the new array. 
This can take lots of time. 
You can prevent this by allocating lots of space initially but then you might allocate more than you need wasting memory. 

With a linked list you can start with space for just one element allocated. And add on new elements easily without the need to do any copying and reallocating. 

Read more: http://wiki.answers.com/Q/What_are_the_advantages_of_linked_lists#ixzz1xDOa8ksU





  • Linked lists have several advantages over dynamic arrays. 

Insertion or deletion of an element at a specific point of a list, assuming that we have a pointer to the node (before the one to be removed, or before the insertion point) already, is a constant-time operation, whereas insertion in a dynamic array at random locations will require moving half of the elements on average, and all the elements in the worst case.
While one can "delete" an element from an array in constant time by somehow marking its slot as "vacant", this causes fragmentation that impedes the performance of iteration.

Moreover, arbitrarily many elements may be inserted into a linked list, limited only by the total memory available; while a dynamic array will eventually fill up its underlying array data structure and will have to reallocate — an expensive operation,


http://en.wikipedia.org/wiki/Linked_list#Linked_list_operations





  • Linked lists are preferable over arrays when:


a) you need constant-time insertions/deletions from the list (such as in real-time computing where time predictability is absolutely critical)

b) you don't know how many items will be in the list. With arrays, you may need to re-declare and copy memory if the array grows too big

c) you don't need random access to any elements

d) you want to be able to insert items in the middle of the list (such as a priority queue)


  • Arrays are preferable when:


a) you need indexed/random access to elements

b) you know the number of elements in the array ahead of time so that you can allocate the correct amount of memory for the array

c) you need speed when iterating through all the elements in sequence. You can use pointer math on the array to access each element, whereas you need to lookup the node based on the pointer for each element in linked list, which may result in page faults which may result in performance hits.

d) memory is a concern. Filled arrays take up less memory than linked lists. Each element in the array is just the data. Each linked list node requires the data as well as one (or more) pointers to the other elements in the linked list.

Array Lists (like those in .Net) give you the benefits of arrays, but dynamically allocate resources for you so that you don't need to worry too much about list size and you can delete items at any index without any effort or re-shuffling elements around. Performance-wise, arraylists are slower than raw arrays.

http://stackoverflow.com/questions/393556/when-to-use-a-linked-list-over-an-array-array-list





  • When should I use LinkedList?


When you need efficient removal in between elements or at the start.
When you don't need random access to elements, but can live with iterating over them one by one



  • When should I use ArrayList?

When you need random access to elements ("get the nth. element")
When you don't need to remove elements from between others. It's possible but it's slower since the internal backing-up array needs to be reallocated.
Adding elements is amortized constant time (meaning every once in a while, you pay some performance, but overall adding is instantly done)






  • Making the decision

If your data is best represented using a multidimensional structure, or the number of elements is known in advance and will remain consistent, an array is best.
If your data is easily represented in one dimension, and the number of elements is unknown or is expected to change often throughout the operation of your program, a linked list is more efficient.

If your data will be searched and accessed often but will change infrequently, the array offers the least overhead for your expected operations.
If you expect to be regularly adding or subtracting elements, especially if you need to maintain a sorted order, the versatility of the linked list will be of greater benefi

http://www.techrepublic.com/article/deciding-whether-to-use-arrays-or-linked-lists/1050183



ArrayList is very useful when a well defined set of data is needed in a List interface as opposed to an array. It can be dynamically changed, but try not to do so frequently throughout the life of the application. LinkedList is there for you to do just that: Manipulating it is very easy, and as long as its used for iteration purposes only and not for random accessing, it’s the best solution. Further, if you need random accessing from time to time, I suggest toArray for that specific moment.

http://chaoticjava.com/posts/linkedlist-vs-arraylist/



  • Bagli listeler
Programlama açisindan liste, aralarinda dogrusal iliski olan veriler toplulugu olarak görülebilir. 
Yigit ve kuyruklarin genisletilmesi yani üzerlerindeki sinirlamalarin kaldirilmasi ile liste yapisina ulasilir.


Yigitlarda ve kuyruklarin gerçeklestiriminde sirali bellek kullaniminin (dizi) en büyük dezavantaji, hiç kullanilmasa veya az kullanilsa bile sabit miktardaki
bellegin bu yapilara ayrilmis olarak tutulmasidir.

Ayrica sabit bellek miktari asildiginda da tasma olusmasi ve eleman ekleme isleminin yapilamamasidir. 
Bagli listeler üzerinde gerçeklestirildiklerinde ise bu problemler ortadan kalkmaktadir.

Bir bagli listenin n. elemanina erismek için n tane islem yapmak yani kendinden önceki (n-1) eleman üzerinden geçmek gerekmektedir. 
Elemanlarin bellekteki yerleri dizilerdeki gibi sirali olmadigindan elemanlar ve siralari ile yerlestikleri bellek bölgeleri arasinda bir iliski yoktur.

Circular Linked Lists
Son elemanin bagi NULL degildir; ilk elemani gösterir.

Doubly Linked Lists
Her dügümü iki bag içerdigi bagli listelerdir.
ilk bag kendinden önceki dügümü gösterirken ikincisi de kendinden sonraki dügümü gösterir
Çift bagli listelerde, tek bagli listelerdeki geriye dogru listeleme ve dolasmadaki zorluklar ortadan kalkar.

Circular Doubly Linked Lists
ilk dügümden önceki dügüm son, son dügümden sonraki dügüm de ilk dügümdür.

Stack

Data Structures - Chapter 1: Stack

http://www.youtube.com/watch?v=_EyhFWwnvcs

Stack is a first in last out data structure
you can't do selective removal from a stack
selective removal is possible with data structure like array and linked list
push()
pop()
size()
isempty()
top()
to implement stack we use an array
linked list also can be used to implement stack

  • Polish notation (prefix notation)
It refers to the notation in which the operator is placed before its two operands . Here no parentheses are required, i.e.,

+AB 

Reverse Polish notation(postfix notation) –
It refers to the analogous notation in which the operator is placed after its two operands. Again, no parentheses is required in Reverse Polish notation, i.e.,

AB+ 


Stack organized computers are better suited for post-fix notation then the traditional infix ntation.
Thus the infix notation must be converted to the post-fix notation. The conversion from infix notation to post-fix notation must take into consideration the operational hierarchy. 

Highest: Exponentiation (^)
Next highest: Multiplication (*) and division (/)
Lowest: Addition (+) and Subtraction (-) 

Now we need to calculate the value of these arithmetic operations by using stack.

The procedure for getting the result is:

    Convert the expression in Reverse Polish notation( post-fix notation).
    Push the operands into the stack in the order they are appear.
    When any operator encounter then pop two topmost operands for executing the operation.
    After execution push the result obtained into the stack.
    After the complete execution of expression the final result remains on the top of the stack.

For example –

Infix notation: (2+4) * (4+6)
Post-fix notation: 2 4 + 4 6 + *
Result: 60 


From Postfix to Answer
•The reason to convert infix to postfix expression is that we can compute the answer of postfix expression easier by using a stack.

Postfix Expression

•Infix expression is the form AOB
–A and B are numbers or also infix expression
–O is operator ( +, -, *, / )

•Postfix expression is the form ABO
–A and B are numbers or also postfix expression
–O is operator ( +, -, *, / )

From Postfix to Answer

•Algorithm: maintain a stack and scan the postfix expression from left to right–If the element is a number, push it into the stack
–If the element is a operator O, pop twice and get A and B respectively. Calculate BOAand push it back to the stack
–When the expression is ended, the number in the stack is the final answer

Transform Infix to Postfix

•Observation 1: The order of computation depends on the order of operators 

–The parentheses must be added according to the priority of operations. 
–The priority of operator * and / is higher then those of operation + and –
–If there are more than one equal-priority operators, we assume that the left one’s priority is higher than the right one’s
•This is called left-to-right parsing.

https://faculty.utrgv.edu/john.abraham/6314/assignments/postfix%20tutorial.pdf

Infix to Postfix Conversion
•We use a stack
•When an operand is read, output it
•When an operator is read
–Pop until the top of the stack has an element of lower precedence
–Then push it
•When ) is found, pop until we find the matching (
•( has the lowest precedence when in the stack
•but has the highest precedence when in the input
•When we reach the end of input, pop until the stack is empty

https://cs.nyu.edu/courses/fall10/V22.0102-004/lectures/InfixToPostfixExamples.pdf

  • Infix to postfix conversion algorithm
A summary of the rules follows:

1. Print operands as they arrive.

2. If the stack is empty or contains a left parenthesis on top, push the incoming operator onto the stack.

3. If the incoming symbol is a left parenthesis, push it on the stack.

4. If the incoming symbol is a right parenthesis, pop the stack and print the operators until you see a left parenthesis. Discard the pair of parentheses.

5. If the incoming symbol has higher precedence than the top of the stack, push it on the stack.

6. If the incoming symbol has equal precedence with the top of the stack, use association. If the association is left to right, pop and print the top of the stack and then push the incoming operator. If the association is right to left, push the incoming operator.

7. If the incoming symbol has lower precedence than the symbol on the top of the stack, pop the stack and print the top operator. Then test the incoming operator against the new top of stack.

8. At the end of the expression, pop and print all operators on the stack. (No parentheses should remain.)

http://csis.pace.edu/~wolf/CS122/infix-postfix.htm