C# Binary Search

Binary Search is highly adoptable to many problems. It s faster than sequential search. Running time complexity of Binary Search is O(logn). The data structure should be sorted in order to use Binary Search.

Using C#, binary search can be used on arrays without any extra effort. Using Lists with generics, the object should implement IComparable interface so that binary search will work.

Given an input binary search returns the index of the found element in the list.

If the input is not found in the List,  binary search returns a negative number which is actually the bitwise complement of the index where it would be inserted if the element existed in the list.

Java Email Extractor, Extract Email Address from String, Text, File

This program extracts email addresses from a folder full of text files that has email addresses in it, including SQL dumps. Then it writes all the email addresses to a database or there is functionality for writing the emails to a text file

package com.atagunsoftware.emailExtractor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailExtractor {

	public static ArrayList emailList = new ArrayList();
	public static Connection connection = null;

	public static void main(String[] args) {
		scanDirectory();
		writeToDB();
	}

	public static void scanDirectory(){
		File actual = new File("c:\\emails\\");
        for( File f : actual.listFiles()){
           System.out.println("Processing :"+f.getAbsolutePath());
           readFile(f.getAbsolutePath());
        }
	}

	public static void writeToFile(){

		try {
	        BufferedWriter out = new BufferedWriter(new FileWriter("c:\\emails\\emails"));

	        for(String s : emailList){
	        	out.write(s.toLowerCase()+"\n");
			}
	        out.close();
	    } catch (IOException e) {
	    }
	}

	public static void writeToDB(){

		getConnection();

		for(String email : emailList){
	        String todo = ("INSERT into emails (email) values ('"+email.toLowerCase()+"')") ;

	        try {
	                java.sql.Statement s = connection.createStatement();
	                s.executeUpdate(todo);
	        }catch (Exception e) {
	        	e.printStackTrace();
	        }

		}

	}

	public static void getEmail(String line){
		final String RE_MAIL = "([\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Za-z]{2,4})";
	    Pattern p = Pattern.compile(RE_MAIL);
	    Matcher m = p.matcher(line);

	    while(m.find()) {
	    	if(!emailList.contains(m.group(1))){
		        emailList.add(m.group(1));
	    	}
	    }

	}

	public static void readFile(String filename){
		String filetoRead = (filename.isEmpty()|| filename == null ? "c:\\emails\\list" : filename);

		try{
		    FileInputStream fstream = new FileInputStream(filetoRead);

		    DataInputStream in = new DataInputStream(fstream);
		    BufferedReader br = new BufferedReader(new InputStreamReader(in));

		    String strLine ="";

		    while ((strLine = br.readLine()) != null)   {
		    	//fileContent += strLine+"\n";
		    	getEmail(strLine);
		    }

		    in.close();
		    }catch (Exception e){//Catch exception if any
		      System.err.println("Error: " + e.getMessage());
		    }
	}

	public static void getConnection(){

	    try {

	        String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
	        Class.forName(driverName);

	        String serverName = "localhost";
	        String mydatabase = "emails";
	        String url = "jdbc:mysql://" + serverName +  "/" + mydatabase; // a JDBC url
	        String username = "root";
	        String password = "password";
	        connection = DriverManager.getConnection(url, username, password);
	    } catch (ClassNotFoundException e) {
	    	e.printStackTrace();
	    } catch (SQLException e) {
	    	e.printStackTrace();
	    }
	}

}

Exception in thread “main” java.lang.OutOfMemoryError: Java heap space

If Java runs out of memory, the following error occurs:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

This can have two reasons:

  • Your Java application has a memory leak. There are tools like YourKit Java Profiler that help you to identify such leaks.
  • Your Java application really needs a lot of memory (more than 128 MB by default!). In this case the Java heap size can be increased using the following runtime parameters:
java -Xms<initial heap size> -Xmx<maximum heap size>

Defaults are:

java -Xms32m -Xmx128m

You can set this either in the Java Control Panel or on the command line, depending on the environment you run your application.

Java DNS Client

package com.atagunsoftware.dnsclient;
import java.io.*;
import java.net.*;

public class DnsClient
{
	public static void main(String args[])
	{
		try
		{
			BufferedReader FromUser=new BufferedReader (new InputStreamReader (System.in));

			DatagramSocket clientSocket = new DatagramSocket();

			InetAddress addrs = InetAddress.getByName("208.67.222.222");

			byte[] receiveData = new byte[1024];
			byte sendData[]=
			{
				-50, 23, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3, 119, 119, 119, 2, 105, 116, 4, 105, 105, 116, 98, 2, 97, 99, 2, 105, 110, 0, 0, 1, 0, 1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
			};

			System.out.print("Enter URL: ");
			String url = FromUser.readLine();

			int index=url.indexOf(".");

			String domain="";

			if (index!=-1) {
				domain=url.substring(index+1);
			}

			short pos=0;
			int j=0;
			int i=1;
			byte urlbyte[]= new byte[url.length()+20];

			for (i=1; i<4; k++){
							int jk=receiveData[len+k+1];
							if (jk<0) jk=jk+256;
							if (k!=3) System.out.print(jk+".");
							else System.out.print(jk);
						}

						System.out.println();

						len=len+4;

					} else{
						System.out.println(i+" "+receiveData[len+4]+" "+len);
					}
			}

		}
		catch (Exception e)
		{
			System.out.println(e);
		}
	}
}

Networking Review and Short Summary

Telecommunication system – enable the transmission of data over public or private networks

Network – a communications, data exchange, and resource-sharing system created by linking two or  more computers and establishing standards, or protocols, so that they can work together

Network operating system (NOS) the operating system that runs a network, steering information between computers and managing security and users

Packet-switching occurs when the sending computer divides a message into a number of efficiently sized units called packets, each of which contains the address of the destination computer

LAN Models

There are several ways of organizing (or modeling) a LAN (or just about any other network). One way is to organize it as a Client/Server model, and another way is to organize it as a Peer-to-Peer model.

Client/Server

In client/server models, there are some stations which are called servers, and lots of other stations called clients. Normally, a client connects to a server to perform some service—such as printing, accessing a file, or send email, etc. In a small network, there may only be one server that handles many services (for example, one computer on a LAN may act as a web-server, a print server, and a file server).

Peer-to-Peer

In a Peer-to-Peer model, no stations are specifically dedicated to be a client or a server. Each station can take on whatever role from time to time when needed.

As we’ve seen, we can classify networks by their topology. We can also classify networks by who owns them, how big they are geographically, what type of data they transfer, what kind of medium they use, etc.

Local Area Networks

This is your average LAN. Small organizations generally have their own little computer networks. These can either be stand-alone networks or connected to other networks, etc.

Metro Area Networks

These are your bigger LANs. These can span a city. Many large companies have offices in diverse parts of the city—and often they have their own private network that spans their different locations. Since geographically it’s not ‘local’, it’s a MAN.

Wide Area Networks

Another notch up the scale is the WAN. These can span states, countries, and even the whole world. A good example of a WAN is the Internet (as well as a telephone network).

Private Networks

Ignoring the size, etc., these networks belong to some corporate entity, and are mostly used for businesses purposes of that corporate entity. In real life, this is rather uncommon (now a days), and most private networks lease part of their bandwidth to other businesses to off-set the cost of running their own private network.

Public Networks

These are networks used by the general public. The telephone, and the Internet, etc., where everyone’s packets are along with every body else’s packets travel side by side.

Wireless Networks

These are the networks that have been provided by someone or company such as home wireless networks, hotspots, or the companies wireless networks.

Backbone Networks

These generally comprise very fast and very robust large scale networks, through which smaller networks can communicate. For example, the Internet has a few backbones stretching the country. If you connect to a web-site that’s located in say California, your message will travel in your LAN, etc., and eventually it will hit the backbone that stretches the country.

Voice Networks

Networks that can carry voice are voice networks. Usually we call these telephone voice networks. They’re not on the general Internet, even though they use many of the same/similar technologies that are found on the Internet.

Private Voice Networks

These are usually company wide telephone networks. This is how you can dial an extension to get to someone in the same company. These are done via PBX (Private Branch Exchange), which is basically a small part of the public telephone network in your own private control.

Inter-connecting Networks
There are networks that exist for the sole purpose of connecting other networks.

Network topology is the pattern of links connecting pairs of nodes of a network. It’s the shape of a LAN or other communications system. A given node has one or more links to others, and the links can appear in a variety of different shapes. The simplest connection is a one-way link between two devices.

A bus network is a network architecture in which a set of clients are connected via a shared communications line, called a bus. There are several common instances of the bus architecture, including one in the motherboard of most computers, and those in some versions of Ethernet networks. Bus networks are the simplest way to connect multiple clients, but often have problems when two clients want to transmit at the same time on the same bus. Thus systems which use bus network architectures normally have some scheme of collision handling or collision avoidance for communication on the bus.

Advantages and Disadvantages of a Bus Network

Advantages

  • Easy to implement and extend
  • Well suited for temporary networks (quick setup)
  • Typically the cheapest topology to implement
  • Faster than a ring network.
  • If any node on the bus network fails, the bus itself is not affected.
  • Requires less cable than a Star network.
  • Cheap
  • Difficult to administer/troubleshoot
  • Limited cable length and number of stations
  • A cable break can disable the entire network
  • Maintenance costs may be higher in the long run
  • Performance degrades as additional computers are added or on heavy traffic
  • Low security (all computers on the bus can see all data transmissions)
  • One virus in the network will affect all of them
  • Proper termination is required.(loop must be in closed path)

Disadvantages

Star networks are one of the most common computer network topologies. In its simplest form, a star network consists of one central switch, hub or computer which acts as a router to transmit messages. If the central node is passive, the originating node must be able to tolerate the reception of an echo of its own transmission, delayed by the two-way transmission time (i.e. to and from the central node) plus any delay generated in the central node. An active star network has an active central node that usually has the means to prevent echo-related problems.

Advantages

  • Easy to implement and extend, even in large networks
  • Well suited for temporary networks (quick setup)
  • The failure of a non-central node will not have major effects on the functionality of the network.
  • Reliable market proven system
  • No problems with collisions of Data since each station have its own cable to the server/hub.
  • Security can be implemented in the hub/switch.
  • The centre of a star i.e. the hub or switch is best place to find network faults.
  • It is easy to adjust and add new computers to a star network without disturbing the rest of the network.
  • Failure of the central node can disable the entire network
  • Limited cable length and number of stations
  • Maintenance costs may be higher in the long run

Disadvantages

A ring network is a topology of computer networks where each node is connected to two other nodes, so as to create a ring. Ring networks tend to be inefficient when compared to Star Networks because data must travel through more points before reaching its destination. For example, if a given ring network has eight computers on it, to get from computer one to computer four, data must travel from computer one, through computers two and three, and to its destination at computer four. It could also go from computer one through eight, seven, six, and five until reaching four, but this method is slower because it travels through more computers. Ring networks also carry the disadvantage that if one of the nodes in the network breaks down then the entire network will break down with it as it requires a full circle in order to function.

Advantages

  • Data is quickly transferred without a ‘bottle neck’.
  • The transmission of data is relatively simple as packets travel in one direction only.
  • Adding additional nodes has very little impact on bandwidth
  • Data packets must pass through every computer between the sender and recipient Therefore this makes it slower.
  • If any of the nodes fail then the ring is broken and data cannot be transmitted successfully.
  • It is difficult to troubleshoot the ring.

Disadvantages

Mesh networking is a way to route data, voice and instructions between nodes. It allows for continuous connections and reconfiguration around broken or blocked paths by “hopping” from node to node until the destination is reached. A mesh network whose nodes are all connected to each other is a fully connected network

Mesh networks are self-healing: the network can still operate even when a node breaks down or a connection goes bad. As a result, a very reliable network is formed. This concept is applicable to wireless networks, wired networks, and software interaction.

A mesh network is a networking technique which allows inexpensive peer network nodes to supply back haul services to other nodes in the same network. It effectively extends a network by sharing access to higher cost network infrastructure.A fully connected network, complete topology or full mesh topology is a network topology in which there is a direct link between all pairs of nodes. In a fully connected network with n nodes, there are n(n-1)/2 direct links. Networks designed with this topology are usually very expensive to set up, but have a high amount of reliability due to multiple paths data can travel on.

Hybrid networks use a combination of any two or more topologies in such a way that the resulting network does not have one of the standard forms. For example, a tree network connected to a tree network is still a tree network, but two star networks connected together (known as extended star) exhibit hybrid network topologies. A hybrid topology is always produced when two different basic network topologies are connected. Two common examples for Hybrid network are: star ring network and star bus network

Internet Corporation for Assigned Names and Numbers (ICANN). This organization is responsible for issuing the IP addresses and domain names used on the internet, ie., .com, .net and .org.

DNS: Domain name servers or services. These are authorities to store and manage domain names, map the domain names to IP addresses so that the client who requests the address can find the server.

TCP/IP is a set of protocols that enable communication between computers. TCP/IP stands for Transmission Control Protocol / IP protocol. TCP/IP is platform independent and can be used across any network to communicate between computers or connector. TCP/IP is compatible with all kinds of computer.

TCP/IP is supported by many software vendors, thus TCP/IP is platform independent and can run on any system, TCP/IP is very flexible, and an administrator can work around with TCP/IP. TCP/IP is routable, so there will be a big network of all networks.

UDP (User Datagram Protocol) is a communications protocol that offers a limited amount of service when messages are exchanged between computers in a network that uses the Internet Protocol.

The Open Systems Interconnection Reference Model (OSI Reference Model or OSI Model for short) is a layered, abstract description for communications and computer network protocol design, developed as part of the Open System Interconnection initiative. It is also called the OSI seven layer model. The goal of OSI model is to break down the task of data communication into simple steps. These steps are called layers, and the OSI model is made up of 7 distinct layers. The purpose is abstraction; these layers don’t have to know what s going on in the other layers. All these layers has tasks to do and waiting for their turn to come.

7 Layers of OSI model are:

  • The application layer
  • The presentation layer
  • The session layer
  • The transport layer
  • The Network layer
  • The data link layer
  • The Physical layer

Application layer: The top layer of the OSI model is the application layer. The purpose of the application layer is to manage communications between applications. A standard application layer programs such as ftp, smtp, http interacts with a program that is running at a local workstation. In application layer ports reside. These ports are also known as Daemons such as httpd, ftpd, fingerd, mysqld etc.. These daemons allow communication between network and the client programs. All these daemons work on some ports like  httpd daemon listen to the requests and responses on port 80, ftp daemon listens to 21, mysql daemon listens to 3306 port etc..

The presentation Layer: This layer makes the data presentable to any platform. Platform independency occurs at this level. After data comes from application layer, presentation layer takes this data and converts into a form that any computer system can understand the format, which enables platform independence communication.

The session Layer: The session layer protocols set up sessions, or connections. These protocols cover such topics as how to establish a connection, how to use a connection, how to break down the connection when session is complete.

The transport layer: The transport later can guarantee that packets are received. The transport layer can also establish a connection and send acknowledgments as packets are received. The protocols in this layer provide the means to establish maintain and release connections for the hosts involved in communication. Provides flow control, acknowledgments and retransmission of data when necessary. Protocols are used in this layer such as TCP/IP or UDP. Transport layer makes the transmission connection oriented (TCP/IP) or connectionless (UDP). Provides same order delivery, Transport layer control delivery order, aka flow control

The network layer: The network layer is responsible for routing the packet based on its logical address. This layers adds routing info, destination address etc. This layer is where routing of data occurs. The network layer addresses messages and translates logical addresses and names into physical addresses.

The data link Layer: This is the layer where data is being prepared for delivery. Mac address will be added on to the data packets. The packet is encapsulated into a frame. This layer has two sub layers: Media Access Control (MAC) and Logical Link Control (LLC).

The physical layer: This is the layer where the bits and packets are being transferred over networks. The physical layer is the most basic network layer, providing only the means of transmitting raw bits.

Ajax Rain

Ajax Rain has been one of the sites I was visiting when I was working on web development and it s definitely worth a visit.

Ajax Rain introduces and brings together several JavaScript Frameworks such as JQuery, Prototype etc. and several Ajax, JavaScript Applications.

http://www.ajaxrain.com/

What s a RockNRolla ?

People ask the question… what’s a RocknRolla? And I tell ’em – it’s not about drums, drugs, and hospital drips, oh no. There’s more there than that, my friend. We all like a bit of the good life – some the money, some the drugs, other the sex game, the glamour, or the fame. But a RocknRolla, oh, he’s different. Why? Because a real RocknRolla wants the fucking lot.

I dig this line.