Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Wednesday 7 August 2013

Compile 32 Bit Binaries On 64 Bit Machine

Well I had this special need if you recall my previous blog post since my friend had 64 bit machine. Sometimes, there might be this necessity to compile 32 bit binaries on your 64 bit machine. This post describes how to do so.

First make sure the necessary x86 libraries are installed. We require 32-bit shared libraries for AMD64 to compile binaries in 32 bit format. The command below installs the i386 version of libc6-dev:

$ sudo apt-get install libc6-dev-i386


Now you can compile your code in 32 bit binary format using the -m32 flag where 32 represents the x86 processor (-m64 would mean x64 processor).

$ gcc -m32 -o test test.c


I hope this helps :)


Read more...

Pointers Without Pointer Variables

Since a pointer variable is nothing but a variable holding 4 bytes memory address (at least on 32-bit addressing), I had a thought that non-pointer variables which can hold 4-bytes of data can be used in place of pointer variables. This post shows how this can be achieved.
The code example below uses an unsigned integer variable in order to store memory addresses to point the integer array.

#include 

int main(int argc, char **argv)
{
        int num[] = {1, 2, 3, 4, 5};
        unsigned int ptr;
        int i;
        ptr = (unsigned int) num;
        for (i = 0; i < 5; i++)
        {
                printf("%p - %d\n\n", (void *) ptr, *(int *)(ptr));
                ptr = ptr + 4;
        }
        return 0;
}



The same concept can be used to use non-pointer variable for pointing other datatypes. After all, its about correct type-casting and since 4 bytes datatype can hold memory addresses, pointer is not always necessary. It must be noted that the increment would be different for different datatypes. Since integer requires 4 bytes, ptr is incremented in this example. If we had character array, then ptr would have to be increased by 1 since char type requires 1 byte.

However, pointers are there to make our life easy. It was just for fun :)


Read more...

Wednesday 12 June 2013

Simple Pie Chart Implementation In Turbo C

This is a very simple implementation of pie chart in Turbo C. The source code is quite easy to read through so must not be the big problem understanding the code.

This implementation makes use of pieslice() function which draws and fills the pie slice with centre x, y and radius r. The function also requires the start angle and end angle.

#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>

#define MAX 20
#define X_CENTRE getmaxx()/2
#define Y_CENTRE getmaxy()/2
#define RADIUS 100

struct pie_data
{
 char desc[100];
 int freq;
 int color;
 int style;
 float angle;
};

int main()
{
 struct pie_data data[MAX];
 int gd = DETECT, gm;
 int i, j, k, n, total_freq = 0, start_angle = 0, end_angle = 0, xmax, ystart = 80, yend;
 printf("Enter the number of items: ");
 scanf("%d", &n);
 
 for (i = 0, j = 1, k = 1; i < n; i++)
 {
  printf("Enter the item title: ");
  scanf("%s", data[i].desc);
  printf("Enter the item frequency: ");
  scanf("%d", &data[i].freq);
  total_freq += data[i].freq;
  data[i].color = j;
  data[i].style = k;
  if (j++ >= 13) j = 1;
  if (k++ >= 11) k = 1;
 }
 
 for (i = 0; i < n; i++)
 {
  float angle;
  data[i].angle = 360 * (data[i].freq /(float) total_freq);
 }
 
 initgraph(&gd, &gm, "C:\\TurboC3\\BGI");
 xmax = getmaxx() - 150;
 setaspectratio(10000, 10000);
 for (i = 0; i < n; i++)
 {
  end_angle = start_angle + data[i].angle;
  setcolor(data[i].color);
  setfillstyle(data[i].style, data[i].color);
  pieslice(X_CENTRE, Y_CENTRE, (int)start_angle, (int)end_angle, RADIUS);
  start_angle = end_angle;
  yend = ystart + 40;
  bar(xmax, ystart, xmax + 70, yend);
  ystart = yend + 15;
  outtextxy(xmax + 80, ystart - 20, data[i].desc);
 }
 getch();
 closegraph();
 return 0;
}


Below is the screenshot for sample run:




Read more...

Sunday 31 March 2013

Simple Line Drawing In Turbo C Graphics

Well this post consists of the source code for very very simple line drawing using the in-built functions.
#include <stdio.h>
#include <conio.h>
#include <graphics.h>

int main()
{
 int gd = DETECT, gm;
 initgraph(&gd, &gm, "C:\\TurboC3\\BGI");
 line(100, 100, 350, 100);
 line(100, 100, 70, 140);
 line(70, 140, 130, 140);
 line(350, 100, 380, 140);
 rectangle(70, 140, 130, 200);
 rectangle(130, 140, 380, 200);
 getch();
 closegraph();
 return 0;
}


I hope it proves useful for learning purpose.


Read more...

Implementation Of BLA Line Drawing Algorithm

Here is the source code that makes use of the traditional DOS mode graphics to implement the Bresenham line drawing algorithm for the lines with slope |m| < 1.

Bresenham Line Drawing Algorithm for |m| < 1


Algorithm


1) Input two points (x1, y1) & (x2, y2).
2) Determine the differences dx = x2 - x1 and dy = y2 - y1.
3) Calculate the initial decision parameter P0 = 2dy - dx.
4) For each xk along the line starting at k = 0,
   if Pk < 0,
      a) put a pixel at (xk + 1, yk)
      b) Pk+1 = Pk + 2dy
   else
      a) put a pixel at (xk + 1, yk + 1)
      b) Pk+1 = Pk + 2dy - 2dx.
5) Repeat step 4 for dx time.
6) End

Source Code


#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>

int main()
{
 int gd = DETECT, gm;
 int x1, y1, x2, y2, dx, dy;
 int x, y, i, p0, pk;
 printf("Enter x1, y1: ");
 scanf("%d %d", &x1, &y1);
 printf("Enter x2, y2: ");
 scanf("%d %d", &x2, &y2);

 dx = x2 - x1;
 dy = y2 - y1;

 x = x1;
 y = y1;
 p0 = ( 2 * dy - dx);
 initgraph(&gd, &gm, "C:\\TurboC3\\BGI");
 pk = p0;
 for (i = 0; i < abs(dx); i++)
 {
  if (pk < 0)
  {
   putpixel(x, y, WHITE);   
   pk += (2 * dy);
  }
  else
  {
   putpixel(x, y, WHITE);
   pk += (2 * dy - 2 * dx);
  }

  (x1 < x2)?x++:x--;
  (y1 < y2)?y++:y--;
  
  delay(50);
 }
  
 getch();
 closegraph();
 return 0;
}


Make sure to provide an appropriate path for graphics library.


Read more...

Tuesday 26 March 2013

Implementation of DDA Line Drawing Algorithm

Here is a source code in traditional Turbo C that makes use of old DOS mode graphics to implement the digital differential analyzer.

Digital Differential Analyzer


Algorithm

1) Input two points (x1, y1) & (x2, y2).
2) Determine the differences dx = x2 - x1 and dy = y2 - y1.
3) Choose step size as the bigger value between the absolute values of dx and dy.
4) Determine x-increment = dx/step_size and y-increment = dy/step_size.
5) Start from (x0, y0) = (x1, y1).
6) For i -> 0 to stepsize:
    a) draw pixel at (xi, yi)
    b) set xk = xk + x-increment
    b) set yk = yk + y-increment

Source Code


#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>

int main()
{
 int gd = DETECT, gm;
 int x1, y1, x2, y2, dx, dy, stepsize;
 float xinc, yinc, x, y;
 int i;
 printf("Enter x1, y1: ");
 scanf("%d %d", &x1, &y1);
 printf("Enter x2, y2: ");
 scanf("%d %d", &x2, &y2);
 dx = x2 - x1;
 dy = y2 - y1;
 stepsize = (abs(dx) > abs(dy))?abs(dx):abs(dy);
 xinc = dx/(float)stepsize;
 yinc = dy/(float)stepsize;
 x = x1;
 y = y1;
 initgraph(&gd, &gm, "C:\\TC\\BGI");
 putpixel(x, y, WHITE);
 delay(10);
 for (i = 0; i < stepsize; i++)
 {
  x += xinc;
  y += yinc;
  putpixel(x, y, WHITE);
  delay(50);
 } 
 getch();
 closegraph();
 return 0;
}


Make sure to provide an appropriate path for graphics library.


Read more...

Tuesday 22 January 2013

Simple Sorting Algorithm Using DMA

This post provides the source code for simple and naive integer sorting algorithm by exploiting the dynamic memory allocation feature of C programming.

#include <stdio.h>
#include <stdlib.h>

int main()
{
 int *arr, i, j, n;
 
 printf("Enter the number of items: ");
 scanf("%d", &n);
 
 arr = malloc(n * sizeof(int));
 
 for (i = 0; i < n; i++)
 {
  printf("Enter the %dth item: ", i + 1);
  scanf("%d", &arr[i]);
 }
 
 for (i = 0; i < n - 1; i++)
 {
  for (j = 0; j < n - 1; j++)
  {
   int temp;
   
   if (arr[j] > arr[j + 1])
   {
    temp = arr[j];
    arr[j] = arr[j + 1];
    arr[j + 1] = temp; 
   }
   
  }
 }
 
 printf("The sorted array is:\n");
 
 for (i = 0; i < n; i++)
 {
  printf("%d\n", arr[i]);
 }
 return 0;
}
samar@samar-Techgaun:~$ gcc -Wall -o sort sort.c 
samar@samar-Techgaun:~$ ./sort 
Enter the number of items: 5
Enter the 1th item: 2
Enter the 2th item: 4
Enter the 3th item: 1
Enter the 4th item: 92
Enter the 5th item: 45
The sorted array is:
1
2
4
45
92




Read more...

Matrix Multiplication Using DMA [C Source Code]

This post provides a source code for matrix multiplication by dynamically allocating memory for matrices to be multiplied and multiplication of those matrices.

#include <stdio.h>
#include <stdlib.h>

int main()
{
 int **A, **B, **C, m, n, p, q, i, j, k;
 printf("Enter the size of matrix A: ");
 scanf("%d %d", &m, &n);
 
 printf("Enter the size of matrix B: ");
 scanf("%d %d", &p, &q);
 
 if (n == p)
 {
  A = malloc(m * sizeof(int));
  B = malloc(p * sizeof(int));
  C = malloc(m * sizeof(int));
  
  for (i = 0; i < m; i++)
  {
   A[i] = malloc(n * sizeof(int));
   C[i] = malloc(q * sizeof(int));
  }
  
  for (i = 0; i < p; i++)
  {
   B[i] = malloc(q * sizeof(int));
  }
   
  printf("Enter the matrix A:\n\n");
  for (i = 0; i < m; i++)
  {
   for (j = 0; j < n; j++)
   {
    scanf("%d", &A[i][j]);
   }
  }
  
  printf("Enter the matrix B:\n\n");
  for (i = 0; i < p; i++)
  {
   for (j = 0; j < q; j++)
   {
    scanf("%d", &B[i][j]);
   }
  }
  
  for (i = 0; i < m; i++)
  {
   for (j = 0; j < q; j++)
   {
    C[i][j] = 0;
    for (k = 0; k < n; k++)
    {
     C[i][j] = C[i][j] + (A[i][k] * B[k][j]);
    }
   }
  }
  
  printf("Multiplication of given matrices is: \n\n");
  
  for (i = 0; i < m; i++)
  {
   for (j = 0; j < q; j++)
   {
    printf("%d ", C[i][j]);
   }
   printf("\n");
  }
 
  for (i = 0; i < m; i++)
  {
   free(A[i]);
   free(C[i]);
  }
  for (i = 0; i < p; i++)
  {
   free(B[i]);
  }
  free(A);
  free(B);
  free(C);
 }
 else
 {
  printf("Matrix multiplication is not possible for given size\n\n");
 }
 return 0;
}
samar@samar-Techgaun:~$ gcc -Wall -o matrix_mul matrix_mul.c
samar@samar-Techgaun:~$ ./matrix_mul 
Enter the size of matrix A: 3 2
Enter the size of matrix B: 2 3
Enter the matrix A:

1 2
3 4
5 6
Enter the matrix B:

1 2 3
4 5 6
Multiplication of given matrices is: 

9 12 15 
19 26 33 
29 40 51 



Read more...

Thursday 17 January 2013

Addition Of Two Matrices Using DMA [C Source Code]

Here is the source code in C that makes use of DMA function malloc() to dynamically allocate the memory for matrices and find their sum.
#include <stdio.h>
#include <stdlib.h>

int main()
{
 int **A, **B, **C, m, n, p, q, i, j;
 printf("Enter the size of matrix A: ");
 scanf("%d %d", &m, &n);
 
 printf("Enter the size of matrix B: ");
 scanf("%d %d", &p, &q);
 
 if (m == p && n == q)
 {
  A = malloc(m * sizeof(int));
  B = malloc(m * sizeof(int));
  C = malloc(m * sizeof(int));
  
  for (i = 0; i < m; i++)
  {
   A[i] = malloc(n * sizeof(int));
   B[i] = malloc(n * sizeof(int));
   C[i] = malloc(n * sizeof(int));
  }
   
  printf("Enter the matrix A:\n\n");
  for (i = 0; i < m; i++)
  {
   for (j = 0; j < n; j++)
   {
    scanf("%d", &A[i][j]);
   }
  }
  
  printf("Enter the matrix B:\n\n");
  for (i = 0; i < m; i++)
  {
   for (j = 0; j < n; j++)
   {
    scanf("%d", &B[i][j]);
   }
  }
  
  for (i = 0; i < m; i++)
  {
   for (j = 0; j < n; j++)
   {
    C[i][j] = A[i][j] + B[i][j];
   }
  }
  
  printf("The addition of two matrices is: \n\n");
  
  for (i = 0; i < n; i++)
  {
   for (j = 0; j < m; j++)
   {
    printf("%d ", C[i][j]);
   }
   printf("\n");
  }
 
  for (i = 0; i < m; i++)
  {
   free(A[i]);
   free(B[i]);
   free(C[i]);
  }
  free(A);
  free(B);
  free(C);
 }
 else
 {
  printf("Matrix addition is not possible for given size\n\n");
 }

 return 0;
}


Below is a sample run along with the compilation step.

samar@samar-Techgaun:~$ gcc -Wall -o matrix_addn matrix_addn.c
samar@samar-Techgaun:~$ ./matrix_addn 
Enter the size of matrix A: 2 2
Enter the size of matrix B: 2 2
Enter the matrix A:

1 2
3 4
Enter the matrix B:

4 3
2 1
The addition of two matrices is: 

5 5 
5 5 



Read more...

Tuesday 15 January 2013

Transpose Of Matrix Using DMA [C Source Code]

This snippet utilizes the dynamic memory allocation function, malloc() and finds the transpose of the user provided matrix.

Below is the source code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
 int **matrix, **transpose, m, n, i, j;
 printf("Enter the size of matrix: ");
 scanf("%d %d", &m, &n);
  
 matrix = malloc(m * sizeof(int));
 transpose = malloc(n * sizeof(int));
 
 for (i = 0; i < m; i++)
 {
  matrix[i] = malloc(n * sizeof(int));
 }
 
 for (i = 0; i < n; i++)
 {
  transpose[i] = malloc(m * sizeof(int));
 }
  
 printf("Enter the matrix:nn");
 for (i = 0; i < m; i++)
 {
  for (j = 0; j < n; j++)
  {
   scanf("%d", &matrix[i][j]);
  }
 }
 
 for (i = 0; i < m; i++)
 {
  for (j = 0; j < n; j++)
  {
   transpose[j][i] = matrix[i][j];
  }
 }
 
 printf("The transpose of given matrix is: nn");
 
 for (i = 0; i < n; i++)
 {
  for (j = 0; j < m; j++)
  {
   printf("%d ", transpose[i][j]);
  }
  printf("n");
 }

 for (i = 0; i < m; i++)
 {
  free(matrix[i]);
 }
for (i = 0; i < n; i++)
 {
  free(transpose[i]);
 }
 free(matrix);
 free(transpose);
 return 0;
}


Below is the sample run:

samar@Techgaun:~$ gcc -Wall -o transpose transpose.c 
samar@Techgaun:~$ ./transpose 
Enter the size of matrix: 2 3
Enter the matrix:

1 2 3
4 5 6
The transpose of given matrix is: 

1 4 
2 5 
3 6



Read more...

Wednesday 12 December 2012

GitHub Snippet Sharing Gist Gets Revamped

GitHub team has today announced the new Gist, their online snippet sharing tool. Gist is a simple way to share snippets and pastes with others offering syntax support for several languages, configuration file formats and document formats.

The great thing about Gist is that all gists are git repositories, so they are automatically versioned, forkable and usable as a git repository. Whether it's a simple snippet or a full app, Gist is a great way to get your point across.

The new Gist is re-written completely from scratch using better libraries and following appropriate style guide.

Read rest of the story at GitHub


Read more...

Monday 19 November 2012

PHP 5.5 To Include Simple And Secure Password Hashing API

Few days ago, we saw the release of PHP 5.5.0 Alpha 1 to the public. The PHP development team is serious about addressing all the criticism it gets time and again. With the recent leaks of several high profile sites, a simple to use yet secure password hashing API has been introduced now.

Here's the RFC for simple password hashing API proposed by ircmaxell and now it has been implemented as a PHP core in 5.5.0 Alpha 1 release and will continue to be part of the PHP core in future releases.

In case you would like to use the API functions in older releases, there's a compatible PHP library for PHP >= 5.3.7. The reason for this is that PHP prior to 5.3.7 contains a security issue with its BCRYPT implementation.



Basically the idea behind simple password hashing API is that most of the PHP developers either don't understand or don't think worth the effort the whole concept of strong password hashing. By providing a simple API that can be called, which takes care of all of those issues for you, hopefully more projects and developers will be able to use secure password hashing.

Using the API is quite simple. All you have to do to get the hash is:

$hash = password_hash($password, PASSWORD_BCRYPT);


Verifying the password is also quite simple.

if (password_verify($password, $hash)) {
    // pass is correct :)
} else {
    // pass is correct :/
}


The simple password hashing API provides sets of password_* functions for the developers to make use of strong password hashing.

Reading materials



RFC for simple password hashing API

Designing an API

PHP 5.5.0 Alpha 1 released


Read more...

Monday 20 August 2012

Build A Sample Custom Packet [Embedded Systems]

This code snippet was my submission for embedded systems assignment from the embedded system black book by Dr. K.V.K.K. Prasad. It is in no way a real packet and is not meant to represent the IP layer.


Question: Write a C program that takes the filename as input and generates packets of 100 bytes. Develop a simple packet format of your own.

Compilation:

gcc -Wall -lm -o custom_packet custom_packet.c

//custom_packet.c
//      
//eg: ./custom_packet /home/samar/Desktop/cs_rules.txt
//Compilation: gcc -Wall -lm -o custom_packet custom_packet.c
//Custom Packet: Header -> 20 bytes and Data -> 80 bytes
//Find me on http://www.techgaun.com

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

typedef struct
{
        int8_t fragment_offset;
        int8_t ttl;
        int32_t source_ip;
        int32_t dest_ip;
} custom_packet_header;

typedef struct
{
        custom_packet_header header;
        char data[80];
} custom_packet;

long int get_file_size(char fname[])
{
        int fd;
        int count;
        if ((fd = open(fname, O_RDONLY)) == -1)
        {
                perror("Error reading the file\n");
                exit(EXIT_FAILURE);
        }
        
        struct stat buf;
    fstat(fd, &buf);
    count = buf.st_size;
        close(fd);
        return count;
}

int decimalip2numeric(int a, int b, int c, int d)
{
        return (a * 16777216 + b * 65536 + c * 256 + d);
}

/*char * numericip2decimal(int num)
{
        char strs[4];
        strs[0] = (char *) num / 1677;
}*/

int main(int argc, char **argv)
{
        FILE *fp;
        //char fname[256];      //255 bytes is the limit of filename in extN filesystems
        custom_packet * packets;
        long int fsize;
        int num_of_packet, i;
        if (argc != 2)
        {
                printf("Usage: %s filename\n", argv[0]);
                exit(1);
        }
        
        fsize = get_file_size(argv[1]);
        num_of_packet = ceil((double)fsize / 80.0);
        printf("%ld => %d",fsize, num_of_packet);
        
        if ((fp = fopen(argv[1], "rb")) == NULL)
        {
                perror("Error opening the file");
                exit(1);
        }
        
        packets = (custom_packet *) malloc(sizeof(custom_packet) * num_of_packet);
        for (i = 0; i < num_of_packet; i++)
        {               
                packets[i].header.source_ip = decimalip2numeric(127, 0, 0, 1); //storing source ip as 127.0.0.1 for now
                packets[i].header.dest_ip = decimalip2numeric(127, 0, 0, 1); //storing dest ip as 127.0.0.1 for now
                packets[i].header.ttl = 127;
                packets[i].header.fragment_offset = i;
        }
        i = 0;
        while (!feof(fp))
        {
                fread((void *)packets[i].data, 80, 1, fp);
                i++;
        }
        
        fclose(fp);
        
        printf("\n\n----- Printing all the crafted packets -----\n\n");
        for (i = 0; i < num_of_packet; i++)
        {
                printf("[---- Packet Fragment no. %d ----", packets[i].header.fragment_offset);
                printf("\nSource IP -> %d\nDestination IP -> %d\nTime to live -> %d\n", packets[i].header.source_ip, packets[i].header.dest_ip, packets[i].header.ttl);
                printf("Packet data -> %s", packets[i].data);
                printf("\n---- End of Packet no. %d ----]\n\n", packets[i].header.fragment_offset);
        }
        
        return 0;
}



Read more...

Sunday 29 April 2012

Answers To Introduction To Algorithms 1.2-2 and 1.2-3

Algorithm is a fun subject and we are starting from the very basics of algorithm. Here is my solution for selected questions from chapter 1 of Introduction To Algorithms by Cormen and others.

1.2-2) Suppose we are comparing implementations of insertion sort and merge sort on the same machine. For inputs of size n, insertion sort runs in 8n2 steps, while merge sort runs in 64nlg n steps. For which values of n does insertion sort beat merge sort?

Here, we need to determine the value of n such that 8n2 = 64nlgn

For the value n = 1, obviously the merge sort beats the insertion sort so we will start from 2 and find the higher limit up to which the insertion sort beats merge sort.

The above equation can be further reduced as n = 8lgn. We can now solve it to determine the value of n. A simple code in C that would do the job for us is as below:

#include <stdio.h>
#include <math.h>

int main()
{
 int i = 2;
 while (1)
 {
  int merge = 8 * log2(i);
  if (i > merge)
  {
   printf("Value of i: %d\n", i);
   break;
  }
  i++;
 }
 return 0;
}

Answer: 2 <= n < 44. 1.2-3) What is the smallest value of n such that an algorithm whose running time is 100n2 runs faster than an algorithm whose running time is 2n on the same machine?

Here, we need to determine the smallest value of n such that 100n2 < 2n. The value of n evaluates to 15. The source code for above problem is as below:

#include <stdio.h>
#include <math.h>

int main()
{
 int i = 2;
 while (1)
 {
  int x = 100 * pow(i, 2);
  int y = pow(2,i);
  if (x < y)
  {
   printf("Value of i: %d\n", i);
   break;
  }
  i++;
 }
 return 0;
}

I hope this helps some of the algo beginners out there trying to solve the questions from "Introduction To Algorithms". Btw, they are basic maths however :P

Read more...

Thursday 29 March 2012

Extracting All Hyperlinks From Webpages - Python

In this example, I am going to show how easily you can extract all the links in a webpage using python. If you are learning to write some small scale crawler, this can be a quick startup on how you can extract the links in any webpage.

Basically, we will send the http request to any webpage and we will read the HTML response except in the case when the connection can not be established. In such case, we will simply inform the user that we could not connect to the website.

For all these stuffs, we will import few modules and most important ones are re and urllib2 for regular expression stuff and HTTP request/response stuffs respectively.

We then write the regex for the hyperlinks for which we will make a search in the HTML data we get back after sending the request from the server. Note the <a href=[\'"]?([^\'" >]+). The small brackets are there to let us capture our necessary information i.e. the actual links.

Now you understood what we'll be doing, below is the python script to extract the hyperlinks from any webpage.

#!/usr/bin/python

import re, urllib2
from sys import argv

if (len(argv) != 2):
    print "No URL specified. Taking default URL for link extraction"
    url = "http://www.techgaun.com"
else:
    url = str(argv[1])
    
links_regex = re.compile('<a href=[\'"]?([^\'" >]+)', re.IGNORECASE)
url_request = urllib2.Request(url)
try:
    response = urllib2.urlopen(url_request)
    html = response.read()
    links = links_regex.findall(html)
    print '\n'.join(links)
except urllib2.URLError:
    print "Can't Connect to the website"

Now run the script as python extracter.py http://www.techgaun.com or any URL you wish to.

So isn't it a good start for writing your own simple web crawler? :P


Read more...

Tuesday 28 February 2012

Reloading The Page Using Javascript

If you wish to put a nice little Reload this page link in your page, the javascript provides a reload() method that you can use for reloading the page.

The reload() method in window.location can be used to reload the page and works well in most of the browsers. An example snippet is shown below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
 <title>Reload example</title>
 <meta http-equiv="content-type" content="text/html;charset=utf-8" />
 <meta name="generator" content="Geany 0.20" />
</head>

<body>
 <iframe height="300" width="300" src="http://wwwindow.location.reload(true)w.google.com"></iframe>
 <a href="javascript:window.location.reload(true);">Reload this page</a>.
</body>

</html>

I hope this comes useful sometimes.


Read more...

Wednesday 15 February 2012

Best Programming and Computer Quotes and Sayings

Few weeks ago, I was tweeting a lot of programming quotes and sayings I was reading elsewhere in different websites. I thought why not post all those fantastic cool and funny quotes about computer and programming here so here comes this new blog post. Come and read this quotes once you have finished the overloaded tiresome session of writing technologies :D.

Open source is not communism because it does not force people. --Eric S Raymond in Revolution OS

Wozniak designed Apple II. Ken designed Lisa. Jef Raskin designed Macintosh. Sanders designed Apple III. What did Jobs design? Nothing.

Real programmers don't code in BASIC. Actually, no programmers code in BASIC after reaching puberty.

Saying that Java is nice because it works on all OSs is like saying that anal sex is nice because it works on all genders.

"I won't program in java anymore. I'm not Marxist and don't believe in classes." --phluid

Knowing what not to use is far better than knowing what to use in programming languages.

A professional programmer is an amateur who never quits. --Morendil

“If debugging is the process of removing software bugs, then programming must be the process of putting them in.” – E. Dijkstra

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. -Martin Fowler

One man’s crappy software is another man’s full time job.

The best thing about a boolean is: even if you are wrong, you are only off by a bit.

A documented bug is not a bug; it is a feature.

C++, where friends can access your privates.

"It's hard enough to find an error in your code when you're looking for it; it's even harder when you've assumed your code is error-free." - Steve McConnell

"The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time." - Tom Cargill

"Most software today is very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves." - Alan Kay

Amazon became no.1 shopping site coz in the days b4 search giant Google existed,Yahoo would list the sites in their directory alphabetically

"I’ve finally learned what ‘upward compatible’ means. It means we get to keep all our old mistakes."

There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.

There are only two kinds of programming languages: those people always bitch about and those nobody uses.

Windows NT addresses 2 Gigabytes of RAM, which is more than any application will ever need. --Microsoft Corporation in 1992 :D


Please contribute some you know or you've heard recently :D



Read more...

Thursday 22 December 2011

First Thing To Try When Encountered An Odd Error In Eclipse

Hi everybody, this is always worth trying when you encounter some unknown and odd error while developing applications with Eclipse IDE. You may encounter errors even though every line of your code is syntactically correct and still you can't find what exactly is the error. Sometimes you might spend hours trying to find error but actually there might be no error in your application.

To clean the current project in Eclipse, go to Project -> Clean and it will clean all the compiled stuffs and will give you a fresh start for the compilation. Keep in mind this little trick and you might find useful several times while you are working on Eclipse.


Read more...

Tuesday 22 November 2011

Common Programming Mistakes Beginner Programmers Do

The beginner programmers make some common mistakes which might be due to the lack of practice and deeper understanding of the language syntax and semantics. Here I am listing some of the common programming mistakes every programmer does when s/he is beginner or new to programming.

Mistake #1: Lack of code modularization
Many beginners just write everything within the main function and end up repeating many statements again and again. Rather than having everything within a single main function, you could separate the certain logic in a separate module known as function and then just call that function when needed. If you haven't heard about function, start with google and learn to write some. You'll not regret learning to make functions.

Mistake #2: Another common mistake is not indenting(Read the section Indentation in programming in wikipedia entry) your code and not writing the proper comments in the places wherever necessary. Lack of proper indentation and comments reduce readability. While many compilers and interpreters do not take care about the indentation and comments, human eyes find it easy to understand the properly indented and commented code. Also, some languages such as python rely on indentation where indentation is a must.

Mistake #3: Another common mistake is to use '=' instead of '=='. I've seen this mistake in a lot of codes done by my beginner friends usually in the conditional statements(such as if else) thus resulting in a completely wrong output many times. FYI, '=' is the assignment operator while '==' is the is equal to operator. Note that when '=' is used, the variable on left side of '=' gets set to the value of the expression on the rights. The assignment operator changes the variable on the left to have a new value, while the equal operator '==' tests for equality and returns true or false.

Mistake #4: Integer and float division is also another common mistake every beginner programmer happens to do. In the language like C, the division such as 5/10 will result in 0 since 5 and 10 both are integers and integer division is done. This might lead to mathematical errors in programming. So be sure to typecast the variables to the proper data type before performing division.

Mistake #5: Another common mistake is the use of uninitialized variables. Beginners forget to assign the values to the variables thus giving unexpected outputs such as garbage values in C. Some languages provide default values (such as 0 or null) for uninitialized variables but still using uninitialized variable is a mistake to avoid. Also, many forget to declare the variables thus producing compiler error.

Mistake #6: Another mistake is to compare the strings in C(strings in C are array of characters) using the is equal to '==' operator. Note that string comparison in C requires use of the library functions such as strcmp(), strcmpi() and their safe alternatives such as strncmp() and strncmpi(). Btw, do not use strcmp() and strcmpi() since they do not check length thus might lead to overflow.

Mistake #7: Using wrong range of array indices is also another common mistakes the beginners do. For example, an array of size 10 should be accessed using indices from 0 to 9, not from 1 to 10. Also, some other languages such as Matlab and Fortran, indices will go from 1 to 10. Just make sure you understand the specifications of the language you are learning.

Mistake #8: Using function calls within the looping condition is another mistake. Lets take an example of the following code snippet:

for (i = 0; i < strlen(str); i++) { //do something }


In each iteration, the strlen() function is being called which can slow down your program. So always avoid such calls within the looping conditions.

int len = strlen(str);
for (i = 0; i < len; i++) { //do something }


Mistake #9: Another mistake is the use of insecure and vulnerable functions. If you are going to use certain function, always make a deep study about it to know whether it is secure or not and if it is not secure, search for its secure alternative. Buffer overflows are one of the things you should always try to prevent. Also, if you are doing PHP or other web-based language, always use the safe functions to avoid common security issues such as SQL Injection, Cross Site Scripting, etc. Always research to write secure codes so that you can prevent hackers breaking your code.

Mistake #10: Finally, beginners tend to leave what they are doing if they can not locate errors and mistakes in their code. Just remember studying and practising is the only key to master any stuff which applies to programming as well. You've got such a big resource like internet, so make extensive use of it and never let you go down. Just read and practise and you'll eventually master yourself.

I hope this post helps beginner programmers out there. :)


Read more...

Tuesday 27 September 2011

Qt4 Development Using Monkey Studio

Monkey Studio is a free and open-source crossplatform Qt 4 IDE. It is developed using the Qt library itself, meaning it will run on any platform supported by Qt 4. This allows you to work on the same project on multiple platforms using the same IDE. Monkey Studio uses the Qt Project file (.pro) to manage the project, and there are no extra files created.


With a active forum and wiki, Monkey Studio IDE offers pretty cool features for developing Qt4 Apps. Its noticeable features are:

- Monkey Studio also features * Advanced, customizable code editor, based on QScintilla.
- Syntax highlighting for more than 22 programming languages
- Templates wizard - create files or projects from templates
- Code restyling - quickly fix/update style of your code using AStyle
- Qt Designer integration
- Qt Assistant integration

To install MonkeyStudio in ubuntu, open the terminal and type:

sudo apt-get install monkeystudio

For downloads for other platforms and more information, visit official website.


Read more...