Sunday, November 15, 2015

Number of lines of code

I was asked to find out the number of lines of code in our entire module so as to figure out how hard is to maintain it. Here is the source to find out the number of lines in a python project

#!\usr\bin\env python
import os
print 'current working directory : ' + os.getcwd()
total_lines = 0
def number_of_lines_in_file( filename ):
global total_lines
if filename.endswith(".py"):
with open(os.path.realpath(filename), 'r') as file_handle:
lines = sum(1 for _ in file_handle)
print 'no of lines in ' + filename + ' is %d' %lines
total_lines = total_lines + lines
def visit_the_directory( folder ):
for element in os.listdir(folder):
if os.path.isdir(os.path.join(folder,element)):
print element + ' is a directroy'
dir = os.path.join(folder, element)
print '------------------------------'
print 'visiting folder ' + dir
startingTotalLines = total_lines
visit_the_directory(dir)
endingTotalLines = total_lines
LinesInThisModule = endingTotalLines - startingTotalLines
print 'total lines in ths module : %d' %LinesInThisModule
print 'total lines until now: %d' %(total_lines)
print 'exiting folder ' + dir
print '------------------------------'
else:
file = os.path.join(folder, element)
number_of_lines_in_file(file)
visit_the_directory(os.getcwd())
print 'total lines : %d' %(total_lines)

Wednesday, November 4, 2015

Finding out the system is little endian or big endian system

Here first a value 1 is stored in a int variable. Address of that variable is taken and cast as a char address which will work only on the first byte of the word. If a value one is available in the char then its little endian system otherwise its big endian
# include <stdio.h>
# include <conio.h>
void main()
{
int i = 1;
char *c = (char *) &i;
if (*c)
printf("Little endian");
else
printf("Big endian");
getchar();
}
view raw endian.c hosted with ❤ by GitHub

Sunday, August 23, 2015

Decorator implementation in python




The decorator implementation in python is helpful while implementing add on to a particular class functionality. Here in the below example the html bold and italic properties are added to a string using the decorator implementation.




def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print hello() ## returns <b><i>hello world</i></b>
view raw decorator.py hosted with ❤ by GitHub

Tuesday, May 5, 2015

Subtract two numbers using bit manipulation

Subtracting numbers is done similar to add number(refer previous post in this blog) with minor difference. Instead of direct and between x and y . We take negation of x to and.
#include<stdio.h>
int subtract(int x, int y)
{
// Iterate till there is no carry
while (y != 0)
{
// borrow contains common set bits of y and unset
// bits of x
int borrow = (~x) & y;
// Subtraction of bits of x and y where at least
// one of the bits is not set
x = x ^ y;
// Borrow is shifted by one so that subtracting it from
// x gives the required sum
y = borrow << 1;
}
return x;
}
// Driver program
int main()
{
int x = 29, y = 13;
printf("x - y is %d", subtract(x, y));
return 0;
}

Adding two numbers using bit manipulation

Adding of two numbers can be done with bit manipulation. The operation if we examine atomically mirrors the actual operation we do while adding two numbers. Here is sample code:
#include<stdio.h>
int Add(int x, int y)
{
// Iterate till there is no carry
while (y != 0)
{
// carry now contains common set bits of x and y
int carry = x & y;
// Sum of bits of x and y where at least one of the bits is not set
x = x ^ y;
// Carry is shifted by one so that adding it to x gives the required sum
y = carry << 1;
}
return x;
}
int main()
{
printf("%d", Add(30, 32));
return 0;
}
view raw addnumbers.c hosted with ❤ by GitHub

Thursday, March 12, 2015

Swapping bits of an Integer

Swapping individual bits is implemented using a function. This function is repeatedly called with different position data.
typedef unsigned int uint;
uint swapBits(uint x, uint i, uint j) {
uint lo = ((x >> i) & 1);
uint hi = ((x >> j) & 1);
if (lo ^ hi) {
x ^= ((1U << i) | (1U << j));
}
return x;
}
uint reverseXor(uint x) {
uint n = sizeof(x) * 8;
for (uint i = 0; i < n/2; i++) {
x = swapBits(x, i, n-i-1);
}
return x;
}
view raw SwapBits.c hosted with ❤ by GitHub

Wednesday, March 11, 2015

Printing the binary format of a integer

Here printing iss done thru a neat macro trick. We can calculate different way too, which is commonly seen. In that case we divide the number by 2 and not the modulo and append it to a string. Same time we will divide the number by two and make it as the new number. This process continues till the number becomes equivalent to one.
/*
* printbinary.c
*
* Created on: Mar 11, 2015
* Author: prasadnair
*/
/*
* printBinary.cpp
*
* Created on: Mar 11, 2015
* Author: prasadnair
*/
#include <stdio.h>
#define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
#define BYTETOBINARY(byte) \
(byte & 0x80 ? 1 : 0), \
(byte & 0x40 ? 1 : 0), \
(byte & 0x20 ? 1 : 0), \
(byte & 0x10 ? 1 : 0), \
(byte & 0x08 ? 1 : 0), \
(byte & 0x04 ? 1 : 0), \
(byte & 0x02 ? 1 : 0), \
(byte & 0x01 ? 1 : 0)
int main()
{
printf("Leading text "BYTETOBINARYPATTERN, BYTETOBINARY(32));
return 0;
}
view raw printbinary.cpp hosted with ❤ by GitHub

Saturday, January 31, 2015

Printing powerset for given set of characters.

Printing powerset of characters is somewhat easy. Here the key point is to understand that for a given number of n characters we will have (2^N)-1 combinations. We will then count thru integers starting from 1 to (2^N)-1 and then check the bit set on the integer and accordingly the same element will be printed from the character array. Below is the C implementation of this interesting program :
/*
* Combinatorial.cpp
*
* Created on: Dec 6, 2014
* Author: prasadnair
*/
#include <stdio.h>
#include <math.h>
void printPowerSet(char *, int );
/*Driver program to test printPowerSet*/
int main()
{
char set[] = {'a','b','c', 'd'};
printPowerSet(set, 4);
getchar();
return 0;
}
void printPowerSet(char *set, int set_size)
{
/*set_size of power set of a set with set_size
n is (2**n -1)*/
unsigned int pow_set_size = pow((float)2, set_size);
int counter, j;
/*Run from counter 000..0 to 111..1*/
for(counter = 0; counter < pow_set_size; counter++)
{
for(j = 0; j < set_size; j++)
{
/* Check if jth bit in the counter is set
If set then print jth element from set */
if(counter & (1<<j))
printf("%c", set[j]);
}
printf("\n");
}
}
view raw PowerSet.c hosted with ❤ by GitHub

Sunday, January 25, 2015

Stack implementation in C language.

Given below is a simple stack implementation in C language. Three main functions of a stack are implemented here, namely push, pop and top.
#include <stdio.h>
#include <stdlib.h>
int top;
int push( int temp , int *arr)
{
if(top >10 )
{
printf("stack is full\n");
return -1;
}
if(arr == NULL)
{
printf("stack is empty\n");
top = 1;
arr[0] = temp;
return 1;
}
else
{
top = top + 1;
arr[top] = temp;
return 1;
}
}
int pop(int *arr)
{
int temp = 0;
if(arr == NULL)
{
printf("stack doesnt exist\n");
return -1;
}
if(top == 0)
{
printf("stack is empty\n");
return -1;
}
else if (top > 0)
{
temp = arr[top];
top = top - 1;
return temp;
}
else
{
printf("Invalid top value\n");
return -1;
}
}
int topstack(int *arr)
{
if(arr == NULL)
{
printf("stack doesnt exist\n");
return -1;
}
if(top >= 0)
{
return arr[top];
}
else
{
printf("Invalid top value\n");
return -1;
}
}
int main()
{
int *arr;
int popvalue;
top = 0;
arr = (int *) malloc (sizeof(10));
push(1,arr);
push(2,arr);
push(3,arr);
push(4,arr);
push(5,arr);
push(6,arr);
push(7,arr);
push(8,arr);
push(9,arr);
push(10,arr);
push(11,arr);
push(12,arr);
printf("Popped value %d \n",pop(arr) );
printf("Popped value %d \n",pop(arr) );
printf("Popped value %d \n",pop(arr) );
printf("Top value %d \n",topstack(arr));
getchar();
return 0;
}
view raw stack.c hosted with ❤ by GitHub

Tuesday, January 6, 2015

String compression

Given a string with repeated characters find out a way to compress the string with a count of number of times the character got appended. For example a string like "aabbbccdeeefff" would become like "a2b3c2de3f3" after compression !
#! /usr/env/path python
sampleStr = "aabbbccdeeefff"
#compress the string a2b3c2de3f3
def compressString(sampleStr):
count = 0
temp = sampleStr[0]
compressedString = ""
for i in range(len(sampleStr)):
if (sampleStr[i] == temp):
count += 1
temp = sampleStr[i]
else:
if (count > 1):
compressedString = compressedString + temp + str(count)
else:
compressedString = compressedString + temp
temp = sampleStr[i]
count = 1
if (count > 1):
compressedString = compressedString + temp + str(count)
else:
compressedString = compressedString + temp
return compressedString
print(compressString(sampleStr))
view raw compress.py hosted with ❤ by GitHub