Pages

Monday, December 19, 2016

Sockets in C

Socket function creates an endpoint for communication and returns a descriptor. It has three arguments.

a. Protocol Family : AF_INET,(IPv4 internet protocols), AF_INET6(IPv6 internet protocols),                                              AF_UNIX, AF_LOCAL(Local Communication)
b. Communication Semantics :  SOCK_STREAM(tcp), SOCK_DGRAM(udp)
c. Protocol Type: ip(0), icmp(1),  ospf(89), isis(124)

Information regarding (a) and (b) can be found in man pages (man socket) in Linux.
Information regarding (c) can be found in protocols file in Linux (cat /etc/protocols).

Definition:

int socket(int domain, int type, int protocol);

This method returns a file descriptor on success and -1 on failure. It does not specify where data will be coming from nor where it will be coming, it just provides the interface.

 #include <sys/types.h>
 #include <sys/socket.h>
 #include <stdio.h>
 #include <errno.h>  // for error macros
 
int main(){

        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock != -1){
            printf("Socket created successfully\n");
            close(sock);
        }else if(sock == ENFILE){
            printf("The system limit on total number of open files has been reached\n");
       }
 
}

Tuesday, December 13, 2016

Generics in C++

C++ provides templates to define short, simple code and avoid code duplication.With templates programmers can define a family of functions or classes that can perform operations on multiple types of data. Through templates, C++ provides generic programming.

Entities such as functions or classes created using generic programming are called generics.

Uses of templates:

1. Templates are widely used to implement the Standard Template Library (STL).
2. Templates are used to create Abstract Data Types (ADTs) and classify algorithms and data                    structures.
3. Class templates are generally used to implement containers.

Function Templates

A function template enables a programmer to write generic code without specifying specific type of data. Template keyword tells the compiler that what follows is a template. Here class is keyword and T is generic argument. You can also use 'typename' instead of 'class'

template<class T> return-type function-name(T a,...){
     //body of template
}

Consider the c++ code below:

#include <iostream>
using namespace std;

//template definition
template<class T> void sum(T x, T y)
{
    cout << "Sum is:" << (x+y) ;
}

int main()
{
int a = 10, b = 20;
sum(a, b);
float p = 1.5, q = 2.4;
sum(p, q);
return 0;
}

Output for the above program is as follows:
Sum is: 30
Sum is: 3.9


Here, in first call to sum, integers are passed and float on the second call to sum.


Class object can also be passed as an argument as follows:

#include <iostream>
using namespace std;

class Student
{
    public:
        int age;
        string name;
 
    Student(int age, string name)
    {
        this->age = age;
        this->name = name;
    }
};

template<class T>void display(T &obj)
{
    cout << "Name is: " << obj.name << endl;
    cout << "Age is: " << obj.age << endl;
}

int main()
{
    Student s(25, "hey");
    display(s);  // object s of class Student passed as an argument.
    return 0;
}

Output for the above program is as follows:
Name is: hey
Age is: 25

Wednesday, November 30, 2016

Test if a given number is power of two in one line in C

In binary representation, a number is power of two if it has only one on bit and others bits as off.
For ex: binary representation of 8 is 1000 (contains only one on bit) whereas, that of 5 is 0101(contains two on bits).

If a number is power of two, for example 8, bitwise and of 8 and 7 is 0

Code:

#include <stdio.h>

int main(){
     int n = 8;
     if((!(n & (n-1)))){  // & is bitwise and whereas ! is logical not
          printf("The number is power of two\n");
     }else{
           printf("Not a power of two\n");
     }
     return 0;
}

However, this does not give correct result for n = 0. For n = 0, the above expression would be 1, thus printing, "the number is power of two". To accommodate, the case for n = 0, use the following code.

 #include <stdio.h>

int main(){
     int n = 8;
     if((n && !(n & (n-1)))){     // && is logical and, ! is logical not and & is bitwise and
          printf("The number is power of two\n");
     }else{
           printf("Not a power of two\n");
     }
     return 0;
}


Wednesday, November 23, 2016

lvalue required as left operand of assignment error when using C

Consider the following array:

int arr[5] = {1,2,3,4,5};

We know that name of the array points to address of first element of array i.e. address of 1 here.

So, the following code:

printf("%u",arr);

will give address of 1 in this case. This address of 1 is constant and cannot be changed. So, in a C program, it is not possible to change the value of arr.

The following code will give an error: lvalue required as left operand

#include

int main(){
     int arr[5] = {1,2,3,4,5};  
     arr++;
     return 0;
}

Even if you give a lvalue by modifying the code as below, it will still throw a compilation error.
error: incompatible types when assigning to type 'int[5]' from type 'int *'  

int main(){
     int arr[5] = {1,2,3,4,5};  
     arr = arr +1;
     return 0;
}

Thus, important thing to understand here is, we are missing out on a key concept.
Here, arr is a constant just like a const variable which cannot be changed and any attempt to change that value will result in a compilation error.

It will be more comprehensible if the error "lvalue required as left operand" would have read "arr is a constant and cannot be changed".

Having said that, the following operation is valid.

int main(){
     int arr[5] = {1,2,3,4,5};  
     printf("%d\n", *(arr + 1));
     return 0;
}

This is because, we are fetching the value at index 1 of array arr and not increasing the value of arr.

This is similar to int y = x +5;
We are not increasing the value of x here. We are just adding 5 to value of 5 and assigning it to y.



Tuesday, November 22, 2016

Advantages of Pointers

Pointers are used frequently in C, as they offer a number of benefits to the programmers. They include the following:

1. Pointers are more efficient in handling arrays and data tables.
2. Pointers can be used to return multiple values from a function via function arguments.
3. Pointers allow passing a function as argument to other functions.
4. The use of pointer arrays to character strings results in saving of data storage space in memory.
5. Pointers allow C to support dynamic memory management.
6. Pointers provide an efficient way for manipulating dynamic data structures such as structures,             linked lists, queues, stacks and trees.
7. Pointers increase the execution speed and thus reduce the program execution time.

Source : https://codingsec.net/2016/11/advantages-using-pointers-c-programming/

Fetching elements in multi-dimensional array in C using pointers

As opposed to traditional method of using integer indexes, elements in a multi-dimensional array in C can be fetched using pointers.

Consider the following code using multi-dimensional array.

#include <stdio.h>

int main()
{
 
    int matrix[10][20] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    int i,j;
    for(i = 0; i < 3;i++){
        for(j = 0 ; j< 4 ;j++){
            printf("%d\n",(*(*(matrix +i)) + j));  
        }
    }
 
return 0;
}

Different methods are available to print individual elements from the above array. Three different approaches are described below.

1.  *(a[i] + j) :
    a[i] refers to first element in i th array of matrix. Adding j gives the address of j th element in i th array.
    De-referencing this address gives value at ith row and j th column of matrix array

2. (*(matrix + i))[j]
      *(matrix + i) gives address of first element of i th row of matrix. [j] gives j th column of row i.

3. *(*(matrix + i) + j)
     As above, *(matrix + i) gives address of first element of i th row of matrix. Adding j gives address of j th column of matrix. De-referencing this element gives the value of  i th row and j th column.

Friday, September 23, 2016

Primitive and Abstract Data Types in Java

Primitive data types are the most basic data types available within the Java language. There are 8 types of primitive data types : boolean, byte, char, short, int, long. float and double.

These primitive types have predefined operations in Java type system and no new operations can be defined on them.

Details of primitive data types are as follows:


CategoryTypesSize (bits)Minimum ValueMaximum ValuePrecisionExample
Integerbyte8-128127From +127 to -128byte b = 65;
char160216-1All Unicode characterschar c = 'A';
char c = 65;
short16-215215-1From +32,767 to -32,768short s = 65;
int32-231231-1From +2,147,483,647 to -2,147,483,648int i = 65;
long64-263263-1From +9,223,372,036,854,775,807 to -9,223,372,036,854,775,808long l = 65L;
Floating-pointfloat322-149(2-2-23)·2127From 3.402,823,5 E+38 to 1.4 E-45float f = 65f;
double642-1074(2-2-52)·21023From 1.797,693,134,862,315,7 E+308 to 4.9 E-324double d = 65.55;
Otherboolean1----false, trueboolean b = true;
void----------

< and > can be used to compare primitive data types. Comparison using these operators cannot be done for abstract data type like string , list, map.

Abstract data types:

The other type of data type is abstract data type. They are called abstract because their implementation is hidden. The combination of data along with its method is called abstract data type.
In general, there are many possible operations that could be defined for each ADT; however, they often fall into these categories:
  1. initialize
  2. add data
  3. access data
  4. remove data
Examples are: List, Stack, Queue, Set, Map, etc.

Monday, September 12, 2016

Object Creation in Javascript

In Javascript, we don't have classes. Instead we use functions. There are two ways to create custom objects.

1. Constructor function
2. Literal Notation

1. Creating an object using constructor function;
        In this method, we first create a function and then create an object using that function.

function Employee(firstName, lastName){
      this.firstName = firstName;
      this.lastName = lastName;

      this.getFullName = function(){
            return this.firstName + " " + this.lastName;
      }
}

var employee = new Employee("Hello","World");

Here, employee is the object and Employee is the constructor function.


2. Literal Notation:

 var employee = {
        firstName : "Hello",
        lastName : "World",
        getFullName : function () {
                      return this.firstName + " " + this.lastName;
        }
}

        document.write("FirstName = " + employee.firstName + "[br/]");
        document.write("LastName = " + employee.lastName + "[br/]");
        document.write("FullName = " + employee.getFullName() ;

In this method, we already have the object. Here, employee is the object name. So, we can access the properties using that object name. Objects created using this method are singletons i.e. any changes to one instance affects the entire script.

Friday, September 9, 2016

Remove duplicate values from array using Javascript

Filter method in JavaScript can be used to easily remove duplicate values from an array in JavaScript.

Syntax:
array1.filter(callbackfn[, thisArg])

Filter method takes two parameters described as below:
Parameter
Definition
array1
Required. An array object.
callbackfn
Required. A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
thisArg
Optional. An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

Return Value

A new array that contains all the values for which the callback function returns true. If the callback function returns false for all elements of array1, the length of the new array is 0.
This property of filter method can be used to remove duplicates from an array.
Code:
var myArray = ["a","b","c","a"];
var newArray = myArray.filter(function(vale,index,array){
  return array.indexOf(value)==index;
});
alert(newArray);

indexOf(value) returns the first index of value. If it is not equal to the current value, filter returns false, so the value is not included in newArray. Thus, newArray will have unique values only.

Sunday, June 5, 2016

Read List Containers in C++

List in c++ are implemented as doubly-linked list as opposed to vectors which are implemented as dynamic arrays. As a property of doubly-linked list, list cannot be accessed with index location as we can with arrays and vectors.


To iterate through a list we need to define iterators as follows:

#include     // std::cout
#include       // std::list
using namespace std;

int main () {

list<int> mylist = {1,45,32,12,67};
list<int>::iterator it =  mylist.begin();

  for(;it != mylist.end();it++){
 cout << "\n" << *it;
  }
 return 0;
}

Sorting in C++

sort method defined under algorithm header file can be used to sort arrays and vectors.
#include

1. Sorting char and int array:

The input parameters to sort char and integer array are pointers to beginning and end of array.


char mychar[] = {'z','q','-','e','a'};
int length = sizeof(mychar)/sizeof(char);
sort(mychar, mychar+length);

int myint[] = {'100','34','45','23','12'};
int length = sizeof(mychar)/sizeof(int);
sort(mychar, mychar+length);

It can also be used to sort strings defined as character arrays.

char mychar[] = "back";
int length = sizeof(mychar)/sizeof(char);
sort(mychar, mychar+length);

The output will be "abck"

2. Sorting vectors:

Similar to arrays, vectors can be sorted using sort method by passing pointers to begin and end of vector.

vector<int> myvector = {'z','q','-','e','a'};
sort(myvector.begin(),myvector.end());

Return value of the method is void as it alerts the containers or arrays directly through pointers.

Tuesday, May 17, 2016

Ref and Type in XML Schema

Ref is used to refer to another XML element.


<xsd:element name="Product">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="ProductName" type="xsd:string" />
            <xsd:element ref="Customer" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>
<xsd:element name="Customer">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="FullName" type="xsd:string" />
            <xsd:element name="Age" type="xsd:string" />
            <xsd:element name="Age" type="xsd:occupation" />
       </xsd:sequence>
    </xsd:complexType>
</xsd:element>


Type is used to refer to a complexType, simpleType or a built-in type.


<xsd:element name="Product">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="ProductName" type="xsd:string" />
            <xsd:element name="Customer" type="Cust" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

    <xsd:complexType name="Cust" >
        <xsd:sequence>
            <xsd:element name="FullName" type="xsd:string" />
            <xsd:element name="Age" type="xsd:string" />
            <xsd:element name="Age" type="xsd:occupation" />
       </xsd:sequence>
    </xsd:complexType>

Sunday, May 8, 2016

Compile C++ program using C++11

C++11 is the standard of the programming language C++ approved by ISO in 12th August, 2011 replacing C++03. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.

To compile a C++ program using this version and make use of all the libraries added in this version we need to use the argument c++0x in the command line.

For Eg.:  g++ -std=c++0x hello.cpp -o hello  //Note:its c++ and numeral 0 and x.

Sunday, March 27, 2016

Reflection in Java

   Reflection is the ability of a computer program to examine and modify the structure and behavior of program at run time.

In layman's language it is a powerful and scary feature that should be used with caution. It is used to subvert the norm of information hiding in OOP. It has the ability to modify private members at runtime and thus the term class manipulator fits much better for Reflection.

Core abilities of Reflection:

1. Inspecting constructors, methods and their parameters
2. Inspecting class and method modifiers (private, public, final, abstract)
3. Getting/setting private data
4. Invoking public/private methods

1. Inspecting constructors, methods and their parameters

package com.reflection;
import java.lang.reflect.Method;

public class Test {
 public static void main(String[] args){
  Class c = "foo".getClass();
  System.out.println(c.getName());

  Method[] strMethods = c.getDeclaredMethods();
  for(Method m : strMethods){
   	System.out.println(m.getName());
   	Class parameterType[] = m.getParameterTypes();

   for(int i=0;i < parameterType.length;i++){
    System.out.println("\t" + parameterType[i].getName());
   }
  }
Output:

java.lang.String
equals
 java.lang.Object
toString
hashCode
compareTo
 java.lang.String
compareTo
 java.lang.Object
indexOf
 java.lang.String
 int
indexOf
 java.lang.String
indexOf
 int
 int
indexOf
 int
2. Inspecting class and method modifiers (private, public, final, abstract)

Lets define a class first named TestClass:

package com.reflection;

public class TestClass {
 private int foobar = 42;
 private String zap = "Not accessibe";
 
 public int foo(){
  return 1;
 }
 
 private String bar(String a){
  return a;
 }
}

Lets define a second class with main method:
package com.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Test {
 public static void main(String[] args){
  TestClass t = new TestClass();
  Class c1 = t.getClass();
  Field[] fields = c1.getDeclaredFields();
  for(Field f : fields){
   System.out.println(f.getName() + " is a " +
      Modifier.toString(f.getModifiers()) + "  field");
  }
  Method[] methods = c1.getDeclaredMethods();
  for(Method m : methods){
   System.out.println(m.getName() + " is a " +
      Modifier.toString(m.getModifiers()) + "  field");
  }
 }  
}
Output:
foobar is a private  field
zap is a private  field
bar is a private  field
foo is a public  field

3.  Getting/setting private data


Using the same TestClass here, we can get the values of fields using the following code.

package com.singleton;

import java.lang.reflect.*;

public class Test {
	   public static void main(String[] args) {
	     try {          
	    	 TestClass t = new TestClass();
	    	 Class c1 = t.getClass();
	    	 Field[] fields = c1.getDeclaredFields();
	    	 for(Field f : fields){
	    		 f.setAccessible(true);
	    		 System.out.println("The value of field " + 
f.getName() + " is: " + f.get(t)); //Here, note that parameter
//for get is instance of a class i.e. t and not c1.      }         }     catch(Exception e) {        System.out.println(e.toString());     }   } }
Output:

The value of field foobar is: 42
The value of field zap is: Not accessible

Saturday, February 27, 2016

Difference between Abstraction and Encapsulation

One of the most confusing concept for developers to understand is the difference between abstraction and encapsulation. This is because the definition seem to say the same thing using different words.

Abstraction is defined as the process of  generalization thus showing only what is necessary.
Encapsulation on the other hand is defined as process of hiding the unnecessary details.

A real world example of abstraction and encapsulation is TV and a remote.

TV hides the complex circuitry inside it. This is similar to encapsulation. Remote provides us an interface to operate the TV without knowing the internal details. This is similar to abstraction.

In programming, encapsulation is achieved by using getters , setters and access modifiers. Also, every method is encapsulation as it hides the internal details.

Abstraction is achieved by using abstract classes and interfaces. They provide a common implementation which is used by derived classes thus providing generalization.


Thursday, February 25, 2016

Implement SQL EXISTS and IN operator using LINQ

LINQ (Language Integrated Query) is a set of features that extends query capabilities to language syntax of C# and Visual Basic.

In this post, we will see LINQ implementation of EXISTS condition and IN operator used in SQL.

Implement IN using LINQ:

    IN operator is used in SQL to check whether a value is contained in the sequence defined using IN operator. The syntax is as follows:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

Two important aspects of this operator is that it needs a column name(column_name in this case) and a set of values(value1, value2,... in this case) with which the column value is compared.

In LINQ, a similar implementation looks like below. It uses the Contains extension method

IEnumerable str = from c in db.table_name
        where new List(){value1,value2,...}.Contains(c.column_name) 
        select c;


Here db is the datacontext this is defined using the LINQ to SQL classes.

Implement EXISTS using LINQ:

    EXISTS operator checks whether at least one value satisfies the condition.

SELECT *
FROM customers
WHERE EXISTS (SELECT *
              FROM orders
              WHERE customers.customer_id = orders.customer_id);

The above query will select all results from customers if the sub query returns at least one result.

In LINQ, a similar implementation looks like below. It uses the Any element operator
if(db.Test1s.Any(s => s.name == "abc"))
{
   var str = from c in db.Test1s
             select c;
}
Here, the condition inside Any is equivalent to subquery and the statement inside if is equivalent to the main query in sql.

Saturday, February 20, 2016

Async and Await Keyword in C#

Async and Await keywords are used together to run a method asynchronously(not multi-threaded).  An async method will be run synchronously if it does not contain an await keyword. An async method either returns void or a task.

With these keywords, we run methods in an asynchronous way. Threads are optional. This style of code is more responsive. A network access can occur with no program freeze.

Eg: In the following example, the task run asynchronously. Thus, the two console.writeline statements are executed before the task completes.

using System;
using System.Threading.Tasks;
using System.Threading;
internal class Program
{
    private static void Main(string[] args)
    {
        var task = DoWork();
        Console.WriteLine("Task status: " + task.Status);
        Console.WriteLine("Waiting for ENTER");
        Console.ReadLine();
    }

    private static async Task DoWork()
    {
        Console.WriteLine("Entered DoWork(). Sleeping 3");
        // imitating time consuming code
        // in a real-world app this should be inside task, 
        // so method returns fast
        Thread.Sleep(3000);

        await Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("async task iteration " + i);
                    // imitating time consuming code
                    Thread.Sleep(1000);
                }
            });

        Console.WriteLine("Exiting DoWork()");
    }
}
Output:
Entered DoWork(). Sleeping 3
async task iteration 0
Task status: WaitingForActivation
Waiting for ENTER
async task iteration 1
async task iteration 2
async task iteration 3
async task iteration 4
async task iteration 5
async task iteration 6
async task iteration 7
async task iteration 8
async task iteration 9
Exiting DoWork()

Friday, February 19, 2016

Setting Up Multithreading in PHP

Multi-threading in PHP is a very useful feature to take advantage of multi-core processors that is common today. However, multi-threading is not enabled by default.

To set up multi-threading in PHP, follow the following steps.

1. Check the PHP Extension Build for the php version you are using:

 After you have set up your website, go to the link:

localhost:8080/?phpinfo=1

The port number depends on the port you have used, it may be default 80 or any other port number
Look for PHP Extension Build in that page. Check the VC number. For me, its VC11. VC stands for Visual C++, the compiler version that was used to build the version of PHP that you are using. It is interesting to note that PHP which is itself a programming language is built using C and C++. Thus, a compiler need to be used to compile C code.

2. Go to http://windows.php.net/downloads/pecl/releases/pthreads/:

Click on the link above and select and download the latest version of zip file that has the same VC number as that of php version that you are using. For VC11, its 2.0.9. I downloaded php_pthreads-2.0.9-5.6-ts-vc11-x64.zip as I am using a 64 bit computer.

3. Extract the zip.

Move php_pthreads.dll to the php\ext\ directory.
Move pthreadVC2.dll to the php\ directory.

4. Change php.ini file

Open php\php.ini and add

extension=php_pthreads.dll

5. Restart your web server



Thursday, January 14, 2016

SQL Server 2012 Capacity Constraints

When designing SQL Server 2012 deployment , one should keep in mind the capacity constraints of SQL Server Database Engine.

1. Maximum size of database : 524,272 TB
2. Maximum size of single file : 16 TB
3. Maximum number of databases that can be hosted : 32,767
4. Maximum number of columns involved in a primary key : 16
5. Maximum number of foreign key references : 253
6. Maximum number of user connections : 32,767