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

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...