Category Archives: Technology

Combine two Images in C# by Overlaying [Open/Combine/Save]


Ok so here is the deal, Yesterday I came across a problem in which I had to overlay an image onto

basecardimg28Final

Template / Picture / Final Image

another and save it. For instance lets just say that you want to watermark images that a user uploads on a website and you have the source file and the watermark file. I searched for an image processing toolkit but  could not find many. So I dug the procedure by which Bitmaps are written in C#. and that did the trick.

First of all you have to load all your files in a string, you can either hardcode that or just call in a directory function and that will do the trick.

 1:  string[] files = Directory.GetFiles("PATH");

where PATH = C:\Documents and Settings \….. TO the folder where your images are.

Make sure there are only two files in the folder the source and target. Next up you have to load the image using a bitmap object. Don’t worry about the format, C# handles that automatically.

 1: Bitmap template = new Bitmap(files[0]);
2: Bitmap Picture = new Bitmap(files[1]);
Now that you have created the bitmap objects one final step remains, take one of the picture and map it on to other, I calculated the sizes of my pictures and set the margins so that it comes in center. You can always get the sizes using “.Width and .Height” properties.
for (int w=0; w<template.Width; w++){
                for (int H = 0; H < template.Height; H++ )
                { 
                    if(w>=60 && w<240){
                        if(H>=60 && H<390){
                            template.SetPixel(w,H,Picture.GetPixel(w-60,H-60));
                        }
                    }
                    template.SetPixel(w, H, template.GetPixel(w, H));

                }
            }
 and finally you can save this bitmap object in any format, the last property defines the target format.
 1: template.Save("PATH\Filename",System.Drawing.Imaging.ImageFormat.Png); 
Simple Eh?
Complete Code:
using System; 
using System.Collections.Generic; 
using System.Linq; using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.IO; using System.Drawing; 

namespace ExperimentWithImages {     
 public partial class _Default : System.Web.UI.Page     {         
 protected void Page_Load(object sender, EventArgs e)         {
              string[] files = Directory.GetFiles("PATH");  
            Bitmap Card = CombineAndSave(files);
              Card.Save("PATH/FileName",System.Drawing.Imaging.ImageFormat.Png);         }
 
          Bitmap CombineAndSave(string[] img) { 
            Bitmap template = new Bitmap(img[0]);
             Bitmap Picture = new Bitmap(img[1]);
             for (int w=0; w<template.Width; w++){  
               for (int H = 0; H < template.Height; H++ )
                 {                   
   if(w>=60 && w<240){
                         if(H>=60 && H<390){
                             template.SetPixel(w,H,Picture.GetPixel(w-60,H-60));
                         }
                     }
                     template.SetPixel(w, H, template.GetPixel(w, H));
                 }
             }
             return template;
                  }
     }
 } 

			
Tagged , , , , , , , , , ,

The Brain Microprocessor


“Classes will dull your mind; destroy the potential for authentic creativity” –

Nash [A Beautiful Mind]

It is not possible for a man to stick tight for more than 20 minutes and concentrate on something. Initially you try to get the grasp of it but the time you lag behind your brain packs its bag and goes to sleep. Same goes for lectures at university. The other day while the lecture was under commencement, I was hovering somewhere else in world, a strange idea instantiated in my mind. Why can’t a human brain replace a microprocessor? With this question I started comparing the actual computer architecture with our brain. I made the following comparisons in my mind:

Brain

Microprocessor Computer

Memory

· Develops over time

· Volatile/Non Volatile

· Decays

· Nurtures with experience

· Dependent on number of neurons

· Static

· Non Volatile

· Non Intelligent

· Available Always

Processing

· Slow in mathematical calculations

· Fast in image/sound processing

· Builds up on requirement

· Improves by use

· Very Fast processing of Mathematical/logical problems

· Dumb

· Can’t relate previous events

· Parallel

Interfaces

· Biological based, very fast

· Operate on nervous system

· I/O devices with speeds of the order of 10s of megahertz

Backbone connection

· Nervous system

· FSBs, UARTs, USBs, IDEs

I came up with a formula that the brain only lacks storage space but can perform extremely well in terms of processing as the number of processing units in our grey matter is of the order of billions. Also it has been established [Einstein had more connected brain than ours] that the more connected your brain is from the inside the smarter it functions. However this was just my speculation during the class along with other scribbling and doodling information on a piece of paper.

The idea appealed to me so much that I searched for it online. My research online revolved around brain, computers, the function of brain, brain as a microprocessor and new developments in areas of computing.

The function of the brain isn’t that simple as I thought initially. But being a going-to-be-engineer it is easy to model things as subsystems. Therefore I found out that brain is one central controlling authority that deals with individual subsystems to make things work for us. The brain is linked with our body through a stream of fibers bundled together to form a network of devices dependent on brain. The entity which lays the foundation of our brain is called a neuron. On average a human brain possesses around a 100 billion of them. Our brain is generally divided into four parts depending on the function and the portions of the cranium [The stuff that makes your head hard]. These parts are:

· Cerebrum – Voluntarily movement

· Limbic System – Survival instinct and emotions

· Brain Stem – Vital supporting mechanisms e.g. heart rate blood pressure etc.

· Cerebellum – Motoric movements

These parts are further divided into many different portions depending upon their function but that is an entire subject and cannot be discussed over here. These parts are interconnected to each other via connections of the order of 1000’s of trillions. However these connections vary from requirement and gender basis.

Ok now we know how our brain looks like let’s have a look at the numbers now. The technique which makes brain function faster than a computer in some applications is adaptive parallelism. The neurons in our brain join forces to complete the task earlier and faster than a normal computer. A brain fires approximately 10^3 neurons per second, which is quite less than the clock cycles of a CPU – normally 2 GHz – , but the fact that the number of neurons performing the task multiplies this number by many folds. For example if a neuron fires an 10^3 neurons per second, multiply this by 100 billion, also the neighboring neurons also fire at the same rate so we multiply another 1000,  the result comes out to be of the order of 100’s of millions of billions neurons. That’s what makes the brain so fast. However this number is only calculated by raw hypothesis so it may vary by magnitudes. The brain carries a lot of memory with it as contrast to my initial belief that we are short of memory; actually it does have a memory equal to 1000’s of normal hard drives of a normal computer.  The memory is also dependent on number of neurons therefore ours is only a rough estimate. All in all a brain uses its resources much more efficiently than a computer does.

Now we come to computer and see how similar is the architecture. A typical computer system consists of the following:

· CPU – Central Processing Memory

· RAM – Random Access Memory

· HDD – Hard Disk

· FSB – Front side Bus

Now the CPU is the brain of computer, the RAM is a faster memory while the Hard Disk is permanent. Front Side Bus is the backbone of computer. In computers the Memory is static, i.e. it can’t be expanded without physical modifications. CPU operates at GHz speeds while there are at most four CPU’s operating in parallel In home PC’s. Notice the architecture is very similar to our brain. The brain acts like a microprocessor, It has got everything embedded into it e.g. memory, ALU and CU. Therefore it is established that we can replace the Processor of a PC with a human brain. The story doesn’t end here, like every other idea conceived, there is work going on it some other part of the world. So I searched for the current trends in the field, here is what I found;

MonoLayer

Researchers from Japan and Michigan Technological University have come up with the circuit that mimics the behavior of neurons. This circuit consists of parallel layes of switches known as monolayers.  These switches can evolve like neurons and solve complex problems. It has been published in the paper “Massively parallel computing on an organic molecular layer”.  The circuit also has the ability of self-healing like the neurons. An MRI of the human brain in comparison with this circuit is shown which clearly shows how similar the patterns are.

clip_image001[4]

Memristors

The concept of memristor had been around In late 80’s but nobody actually produced it till 2008. A memristor is a circuit element in which resistance is strictly dependent in current and voltage feedback. The memristor also is capable of creating complex structures to speed up processing power of a processor. This CE is also capable of maintaining states without consumption of power. It’s also seen in memristors that they seem to have more than two states therefore this can entirely revolutionize the process of computing, therefore a future computer may not require programming but paradoxically it programs itself. Recently HP which is one of the prominent organizations working in this area has reported that their Titanium based memristor is capable of handling logic, therefore it’s a microprocessor in itself – Remember how neurons also are microprocessors – .

Memristors are essentially the next big thing in the semiconductor hardware market. Their ability to self-program makes them a hot topic of research.

clip_image003[4]image Source: Wikipedia

NOMFETs

Nanoparticle Organic Memory Field Effect Transistors are organic devices and are essentially composed of molecules. These are based on organic semiconductor known as pentacene and gold Nano particles. The NOMFET mimics a human synapse. Synapse is the gateway through which a neuron communicates to its surroundings by sending electrical signals. NOMFETSs operate on the principle of firing an amplified spike if the time distance between two incoming pulses becomes shorter and vice versa, this is called plasticity. NOMFETs use plasticity, which in turn will be basis for faster image processing applications.

Brain Computer Interface

The first thing that comes in mind when you think of brain as a device which is based on charges, is can we externally interpret the charges using some device? In fact yes, Brain computer Interface deals with this subject. Scientists initially tried it on animals like rats and monkeys, and later they devised devices which could be implanted in humans. In experimentation on a monkey a test was conducted by reading the brain signals of the animal. At the back they had a robotic Arm which moved with the movement of monkey’s arm. The Monkey was given a computer mouse; it had to drag it to a target on a computer screen. When the animal did it successfully it was rewarded with a sweet. The animal quickly got the hang of it and started doing it again and again. This gave the scientist enough time to monitor the brain signals of the animal responsible for the action of his arm. Sometime later the scientist disconnected the mouse secretly and kept the exercise going. This time the cursor moved because of the brain signals only. Amazingly the monkey got the hang of it as well, after sometime the monkey was just sitting and moving the cursor with its brain, WITHOUT any arm movement.

clip_image005[4] BCI is also used in people with blindness, electrodes are inserted in their brains and they are connected to a camera and a device which converts the image into neural signals, result is that the patient can get a very vague idea of the surroundings around him.

Conclusion

It is evident from the above discussion that science is progressing along the lines of analogue computing. We still are waiting for a breakthrough from this industry but the revelations that have already been made, makes the idea look promising. A computer with human brain would require very sensitive instruments to monitor the most delicate and intricate part of our body. Or in search for it we might be able to replicate the human brain altogether, who knows.

So keeping all the above discussion in a nutshell don’t you see intelligent computers come into existence in next twenty years? It’s alright if you don’t; probably you are taking too many classes.

References:

· Researchers develop new brain-like molecular processor – http://www.zdnet.com/blog/emergingtech/researchers-develop-new-brain-like-molecular-processor/2213

· Massively parallel computing on an organic molecular layer

· Anirban Bandyopadhyay1, Ranjit Pati2, Satyajit Sahu1, Ferdinand Peper3 & Daisuke Fujita

· The amazing memristor – beyond Moore’s law and beyond digital computing http://www.zdnet.com/blog/foremski/tha-amazing-memristor-beyond-moores-law-and-beyond-digital-computing/1309

· An organic transistor that mimics a brain synapse http://www.zdnet.com/blog/emergingtech/an-organic-transistor-that-mimics-a-brain-synapse/2095

· Energy Limits to the Computational Power of the Human Brain

http://www.merkle.com/brainLimits.html

· The Brain As An Information Processor http://www.racai.ro/~dragam/The_brain_as_an_information_processor.htm

· BBC Science and Nature http://www.bbc.co.uk/science/humanbody/body/interactives/organs/brainmap/index.shtml

· Brain Structures & their functions http://serendip.brynmawr.edu/bb/kinser/Structure1.html

· Wikipedia http://www.wikipedia.org

Tagged , , , , , ,

Going v6–For Newbies, Doctors, Architects and Average Joe’s


In this article I have tried my best to remain non technical. For technology savvy public, a pdf is link is present at the end of the post.

Prologue

The year 2011 dawned on the internet as 2012 of human race. A lot has been said about the end of internet and human race as we know it. But fact remains that this over exaggeration of something that is really not “that” much importance to the end user will increase the market of IPv6 based boxes.

Most of us had seen v6 in the past, somewhere in the internet connectivity options but never bothered about why is it there. It had been in almost all the machines for the last 8 or more years. The hype about the protocol took heat when IANA – International Assigned Numbers Authority issued last pool of v4 addresses. Like everything technologically advanced, rumors flooded the internet that somewhere in 2011 internet is going to choke, or there were speculations that its not going to function any more. Well first of all we had similar situation in 1990’s. There were similar speculations that IPv4 was about to end in 1995 [and it could have ended], that was the time when a technology named NAT took birth [RFC-1918] and the deadline of IP address extinction relaxed by a decade and a half. We are in 2011, and NAT is upto its limit in saving address space for our exploding cloud of internet enabled devices.

Background

The Internet was not designed to be used by home users. Yes its True. Initially called ARPA NET the internet was made for military use. At that time it wasn’t realized that in four decades it will be something like water, gas and electric supply in homes. In other words they had believed internet will only be used by restricted military personnel.

Now like your home, every device on internet has an address, a unique number that identifies it on the planet. When you send a snail mail, the mail mechanism nearly matches the mechanism on which internet works. Now consider that in in near future the addresses of homes become so long, that they are unable to fit on an envelop. So we will need bigger envelops. Fortunately this hasn’t yet come for our homes. But internet has reached the stage where the devices have increased exponentially and require a bigger address. 2255765150_98a049fcc1

Initially when the protocol TCP/IP was made, the size of address was kept, 32 bits. This means we could have 2^32 = 4 Billion Internet addresses. Now that we have internet in PC’s, Mobiles, Tablets, Vehicles, KIOSK’s, Bathrooms, Microwaves, Refrigerators , etc etc You name the device we have internet in it and since the WiFi, WLAN, WiMAX, 3G, EDGE, and other mobile IP technologies, the requirement of addresses has increased a lot.

So when IANA allocated the last pool, it was the last of 4 billion allocable addresses. So what does it tell you? Take the house example. Since the address space is full. We can still build new houses, but we wont be able to send them mails or identify them. Same will happen to the internet. The existing system will remain online, and will not crash or cease to work, but there will be problems for new devices that are currently flooding into the market. There will be lesser addresses and more users.

The IETF – Internet Engineering Task Force, had seen it in 1990. At that time somebody gave NAT – Network Address Translation. NAT is the same thing by which no matter how many jobs and offices you change, the IP address of the computers lies in the range of 192.168.x.x or 10.x.x.x or 172.16.x.x . NAT was a very successful but a temporary solution to IP address choke and now things are way out of NAT’s scope.

The Solution

The problem is finally being addressed. The address size of internet machines – in other words the size of IP – is being increased by 4 folds. So the new IP address, known as IPv6 is 128 bits and inherently using it we can have 2^128 = 3.402824e+38 unique addresses. From the consumer point of view, things will not change much, as the internet will continue to behave like it does today. Yes the 128 bit address will be longer, and not easy to memorize. The format of this addressing scheme is in hexadecimal, so a normal IPV6 address will look something like:
1010:4A40:19C0:0010:78D2:1010:4A40:19C0

There are other new things which will later come into existence in shape of application when v6 will be deployed. Like autoconfiguration, self homing , unreachability detection etc. As the address size will change, it will accompany change in many things that accommodate the address. All the protocols will be reconfigured to be compatible with v6. Like if you increase the size of envelop for snail mail, you will need bigger post boxes and larger delivery trucks. The situation is about same with IPv6. Since the progress of this configuration is still in testing phases that is why some semi-technical people have created panic among the masses.

What Can you do with it?

Where the others are panicking, I see a million job opportunities in the area. Since the IPv6 is relatively young, people can relate to endless literature available online and can either contribute in its development or can also make application out of its new features.

Transition to IPv6 was eminent to technological giants, so they started working on it but were not willing to shift to it as there was no need back then to put an investment in it. Times have changed, there doesn’t appear to be any other solution to the internet choke, but IPv6 and it will have to be adopted by the end of this year or so.

I want to Participate

There is an event taking place place known as the “World IPv6 Day”. On this day Top Internet giants, i.e. Facebook, Google, Yahoo are going to test drive IPv6. Facebook and Google already have their IPv6 sites online and are accessible through an IPv6 enabled machine.

If you want to participate in the event there is a thing by the name of a “tunnel”. You can create a tunnel between yourself and an IPv6 provider server. The server will essentially pack the IPv6 traffic in IPv4 packets and will send you through normal IPv4 address. On your computer this traffic will be unpacked and translated to get IPv6.

v6

There is a website offering this service for free, and I often use the service to check IPv6 based websites. The website is GogoNet. http://gogonet.gogo6.com . You have to register for free on the website and then download a client name Freenet6 form the same site. It will enable you to connect to their server via a tunnel. Then to check if your Client is working properly goto the following sites:

Facebook – http://v6.facebook.com

Google – http://ipv6.google.com

If you can see these two websites your client is working perfectly and you can boast to your friends that you participated in the world event. Also you will not feel the difference when you connect via v6 with exception of some lag due to unpacking and packing of IPv6 traffic.

You can get the Full PDF which includes the technical details on the subject here:

http://www.scribd.com/doc/48706577/IPV6

Tagged , , , , , , ,

TouchPad Stopped Working in Ubuntu


The Story

The other day while I was busy typing something in terminal my palm accidently touched the touch pad of my laptop. The next thing that happened wasn’t very pleasant. The taskbar froze, mouse pointer froze, keyboard stopped working. So there was basically nothing that I could do. Surprising Alt + Ctrl + Del combination worked and I was able to suspend my laptop.

Upon a restart the mouse and keyboard worked fine till I logged in. Just as the desktop appeared, again the same thing happened, and my mouse pointer + Keyboard + Taskbar [most of it] froze. Annoyed, I was able to launch Terminal using Alt + F1. On another PC I searched on the issue and here is what I found:

The Cause

There is a feature in Ubuntu that disables mouse pointer when you are typing, so if you are running many apps don’t expect your laptop to respond that quickly. Worse thing is that people hit hibernate. So for some reason the disabled mouse control never returns.

Quick fixes

  • Hit  Alt + Ctrl + F4 to go into Command line and then Alt + Ctrl + F7 to return. Doing this has fixed the issue for some users.
  • Plug in an external mouse, it will help you sort out the problem and atleast move a round a bit. [If you don’t know the keyboard shortcuts]

Complete Fix

Launch the terminal using the shortcut Alt + F1 and then navigating to terminal in the taskbar. Type in the following commands:

First check if the device is listed here :

xinput list | grep -i touchpad

XInput is a utility that gives you list of devices which are detected by the OS.

Then type this command if your drivers are loaded or not:

lsmod | grep touchpad

Then type in the following command to enable your touchpad:

gconftool-2 --set --type boolean /desktop/gnome/peripherals/touchpad/touchpad_enabled true

 

If this fixes your issue [or even if it doesn’t] hit the like button.

Stay Open Sourced.

Tagged , , , , , , , , , , ,

Matrix Multiplication using Pthreads


The following code i wrote to multiply two n x n matrices. it also prints the time taken to perform the multiplication. BTW this is a multithreaded code. Also to run it you have to type the following

$blah@blahsPC~ gcc path/threadfile.c -lpthread

$blah@blahsPC~ ./A.out

The Code

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

struct Index{
    int LOOP1;
    int LOOP2;  // thread counter and loop multiplier
    };

 //globals for sharing b/w threads
 int** Matrix1;
 int** Matrix2;
 int** ResultMAT;
 int row;

void* multiply(void* _multiplier);

void main(){
    ////////////////////////////////////////
    ////A Little Housekeeping///////////////
    int col,i,j,rc,LoopVAR,L2;
    long TimeVAR,t;
    struct Index *L_StructVAR;
    printf("Enter rows: ");
    scanf("%d",&row);
    printf("Enter Columns: ");
    scanf("%d",&col);
    Matrix1= malloc(row * sizeof(*Matrix1));
    Matrix2= malloc(row * sizeof(*Matrix2));
    ResultMAT= malloc(row * sizeof(*ResultMAT));
    L_StructVAR= malloc(row * sizeof(*L_StructVAR));
    void* status;

    ////////////////////////////////////////
    //// Thread initialization////////////
    pthread_t* threads;
    pthread_attr_t _attrib;
    threads = malloc((row*col) * sizeof(threads));  ///// Square Matrix Rows = Columns
    pthread_attr_init(&_attrib);
   // pthread_attr_setdetachstate(&_attrib, PTHREAD_CREATE_JOINABLE);

    ///////////////////////////////////////////////
    // Populating array matrices
    if(Matrix1 != NULL)
        {
            for(i = 0; i < row; i++)
            {
                Matrix2[i]=malloc (col * sizeof **Matrix2);
                Matrix1[i] = malloc(col * sizeof **Matrix1);
                 ResultMAT[i] = malloc(col * sizeof **ResultMAT);
                if(Matrix1[i] == NULL)
                {
                    printf("Memory allocation failed. Exiting....");

                }
            }

        }
    else printf("Failed");
    for(i=0;i<row;i++)
        {
           for(j=0;j<col;j++)
           {
               Matrix2[i][j]=rand() % 10 +1;
               Matrix1[i][j]=rand() % 15 +1;

           }

        }
//////////////////////////////////////////////////
///////////Printing Facility /////////////////////
/////////////////////////////////////////////////
/*
printf("Matrix 1: \n");
        for(i=0;i<row;i++)
        {
           for(j=0;j<col;j++)
           {
               printf("%d", Matrix1[i][j]);
               printf(" ");
           }
           printf("\n");
        }   */
///////////////////////////////

//////////////////////////////////////////////
///////////// Threading :D ///////////////////
TimeVAR = clock();
printf("%ld",TimeVAR);
printf("\n");
long threadVAR=0;

for(LoopVAR = 0; LoopVAR < row;LoopVAR++){

      for(L2 = 0;L2 < col;L2++){
          L_StructVAR[threadVAR]. LOOP1 = LoopVAR;
          L_StructVAR[threadVAR].LOOP2=L2;
            //  printf("%ld\n",threadVAR);
           pthread_create(&threads[threadVAR], &_attrib, (void*)multiply,(void*) &L_StructVAR[threadVAR]);
           threadVAR++;
        }

}
printf("%ld\n",clock());
printf("%ld",CLOCKS_PER_SEC);
 TimeVAR = clock() - TimeVAR;
//TimeVAR *= 1000;
TimeVAR /= CLOCKS_PER_SEC;
printf("Total time taken in seconds: \n");
printf("%ld",TimeVAR);

////////////////////////////////////
///// Printing Facility ///////////
/*
printf("Matrix 2:"); printf("\n");
for(i=0;i<row;i++)
        {
           for(j=0;j<col;j++)
           {
               printf("%d", Matrix2[i][j]);
               printf(" ");
           }
           printf("\n");
        }

printf("check 0");    */
/////////////////////////////////////////////////
/////////////// Thread join //////////////////////
/*
pthread_attr_destroy(&_attrib);
for(t=0; t<(row*col); t++) {
    printf("%ld\n",t);
      //rc = pthread_join(threads[t], &status);
      if (rc) {
        // printf("ERROR %d\n", rc);
         //exit(-1);
         }
     // printf("Main: completed join with thread %ld having a status"
      //      "of %ld\n",t,(long)status);
      }
      //printf("%ld",clock());

printf("check 12");

*/

////////////////////////////////
// Printing facility
/*
printf("Matrix final"); printf("\n");
for(i=0;i<row;i++)
        {
           for(j=0;j<col;j++)
           {
               printf("%d", ResultMAT[i][j]);
               printf(" ");
           }
           printf("\n");
        }       */
/////////////////////////////

  }

void* multiply(void * _multiplier){
    struct Index * _LVAR;
    _LVAR = (struct Index*) _multiplier;
    int  _LOOP_3, _TEMP=0;
    for(_LOOP_3 = 0; _LOOP_3 <  row; _LOOP_3++){
        _TEMP += Matrix1[_LVAR->LOOP1][_LOOP_3] * Matrix2[_LOOP_3][_LVAR->LOOP2];
       // printf(" %d * %d  +",Matrix1[_LVAR->LOOP1][_LOOP_3], Matrix2[_LOOP_3][_LVAR->LOOP2] );
       }
          //printf("%d\n", _TEMP);
    ResultMAT[_LVAR->LOOP1][_LVAR->LOOP2] = _TEMP;
    pthread_exit((void*) _multiplier);
    }
Tagged , , , , , ,