Delegates in C#

Delegates in C#


So what are Delegates? And why do we need them. Delegates are basically pointers to functions (C, C++ parlance). Delegates are reference type variables holding reference to a method. 

First off lets write some code to demonstrate how Delegates are declared and used.

This is a basic example of Delegate. At line 7 we are declaring a delegate

public delegate int ADelegate(int num); 
 On line 10 we assign a method to this delegate

ADelegate md=SquareNum;
And then we call upon the method using the delegate reference.

Note: The delegate must have the same signature as the method that it is referencing.

We can reference another method by the same delegate without any problem. (The signature should be the same)

On line 12 we reference another method
md=CubeNum;

Use of Delegates in Events

Delegates are best exemplified by their use in events. For e.g on a Button Event we can call a method using the below code.

button1.Click+=BTN_CLICK_HANDLER; 
For eg:

button1.Click+=button1_click;

We can then define button1_click as

private void button1_click(object sender, EventArgs e)
{

}
 

Recovering Linux installation after Windows install

Most people make the mistake of installing Windows after Linux. Offcourse one of the main reason is that due to myriad issues in windows, users often have to re-install windows. Not so the case with Linux. However after windows is installed it overrides the boot-loader and your Linux is hidden. Many people resort to re-install Linux in such a situation.

Worry not, the following steps will show you how to recover your boot-loader and be able to access Linux once again.

First up, download the Linux Live CD, burn it on the CD or follow the instructions at http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-windows to create a bootable USB.

Boot your computer from the USB. Once in the Live version, open a terminal

Issue the Following Command

sudo fdisk -l 

Check the partition where Linux is installed. It would be the one where the Type "Linux" is written. Then issue the command

sudo mount /dev/sdaXX /mnt
where XX in the sda is the number where you found the word Linux in the fdisk command.

In the above example it would be 7

At this point your Linux installation is mounted at the location /mnt.

Now we need to install the Grub bootloader.


sudo grub-install --root-directory=/mnt /dev/sda to install grub.  


This will install grub.

Reboot your system. Remove the USB/CD. The system will boot directly into Linux.

After your linux is booted, open the terminal and issue the command

sudo update-grub 

Restart your system. You will now see the Grub Menu on system startup.

Linq Query Operators Cheat Sheet



Linq Query Operators

Category Query Operator
Filter from a collection Where, OfType
Sorting a collection OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
Grouping Data GroupBy, ToLookup
Join Data GroupJoin, Join
Selecting Data  Select, SelectMany
Aggregate functions Aggregate, Average, Count, LongCount, Max, Min, Sum
Conditions All, Any, Contains
Finding Record ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault
Set Distinct, Except, Intersect, Union
Partitioning Skip, SkipWhile, Take, TakeWhile
Concatenation Concat
Equality SequenceEqual
Generation DefaultEmpty, Empty, Range, Repeat
Conversion AsEnumerable, AsQueryable, Cast, ToArray, ToDictionary, ToList

Example

Scala for Programmers The No Shit Reference



Requirements to Run Scala

Ide: There are a couple of IDE to run scala. Depends on your own preference.



How do you define Variables in Scala

  • Scala doesn't need you to declare type of variables if the compiler can detect the type.
  • However if the type can't be inferred automatically you have to provide the type.
var num=10

var x: Int = 5 
var lng: Long = 100000000L 
var sht: Short = 1 
var dbl: Double = 2.50
 
var flt: Float = 2.50f 
var str: String = "Hello Scala" 
var bte: Byte = 0xa 
var chr: Char = 'D'

These variables are also known as mutable types. Mutable types means its values can be changed. Scala prefers you to use as little mutable types as possible.

Constants

 Constants are immutable types. It essentially means that these values can't be changed. Constants are declared in Scala using the val keyword


val x=10x=20  //Wrong.. Will generate an error

Variables with No Initialization 

var test:String=_

When the variable is not initialized it's type must be declared


If else construct in Scala

If else construct in scala is similar to java. However if else can also be used as an expression in scala. 


val x=10if(x==10)
  println("X is equal to 10")
else  println("X is not equal to 10")

println is used for output 

Generally it is a good idea to enclose your statements in { } braces. 


if(x<10){
  println("Value of x ")
  println("X is less than 10")
}
else if (x >10)
{
  println("X is greater than 10")
}
else {
  println("X is equal to 10")
}

Note: You don't need a semicolon to terminate your expression in scala.

 

Loops 

In Scala, loops are not used as often as in other languages. Instead most often the values are processed by applying a function to all values. Its known as functional programming. 
 

Simple Loop

println("Step 1: A simple for loop from 1 to 10 ")
for(i <- 1 to 10){
  println(s"Loop Number = $i")
}
 
 
Use "until" instead of "to" to exclude the last iteration. 

println("Step 1: A simple for loop from 1 to 10 ")
for(i <- 1 until 10){
  println(s"Loop Number = $i")
}
 
While Loop

While loop in scala is the same as Java/C++

while (x > 0) {
  r = r * n
  x -= 1}

Scala doesn't have ++ and -- increment. Instead use += or -=

Scala Lists 

Scala lists are similar to arrays in a sense that they consist the same type of data. 


val colors:List[String]=List("red","blue","green")

val nums:List[Int]=List(1,2,3,4)

Two Dimensional Lists

val twoDimensional: List[List[Int]] =
  List(
    List(1, 0, 0),
    List(0, 1, 0),
    List(0, 0, 1)
  )

Lists are Immutable
 Lists have the following methods. 

println( "Head of colors : " + colors.head )
println( "Tail of fruit : " + colors.tail )
println( "Check if fruit is empty : " + colors.isEmpty )
println( "Check if nums is empty : " + colors.isEmpty )
 
  • Lists can also be concatenated by List.concat(list1,list2,listn)
  • List.fill() method creates a list consisting of zero or more copies of the same element
  •  List.reverse method reverses all elements of the list 
 For further info on lists visit https://www.scala-lang.org/api/2.12.3/scala/collection/immutable/List.html
 

 

 

Next: Functions, Objects, Classes,Inheritance


Running ONE Simulator in Eclipse Part 2

In the first part of this series we discussed how to download, configure and Run ONE Simulator. In this part we are going to see how we can work in this simulator in Eclipse. This has been tested on Linux and Windows.

Eclipse Installation

Linux Users (For the Serious folks)

For Linux user, best way is to open Software Center (if you are using Ubuntu) and search for Eclipse, and install it.

Windows Users (Part time Users)

For Windows users, download Eclipse from eclipse.org website. Once Downloaded extract the compressed archive in any root drive, e.g C D. Once uncompressed, double click eclipse.exe to launch Eclipse.

If eclipse doesn't launch or it throws and error, check your Java installation. If you have installed Java 32 bit version then download the 32 bit eclipse, if you have installed 64 bit java, then download 64 bit eclipse.


Creating a Project in Eclipse

Click on File -> New -> Java Project. 

A Window will open. 

Give it any Name, i gave it the name ONESimulator. Click on Next and then click on Finish. 

The Project will open, on the left hand side you will see a window with the project ONESimulator. 

Click on the Project and you will find an src folder inside it. 

Right Click on the src and select 'Import' Option. You will be see a box like this 

 Select File System Option and click Next, you will be presented with another window. 



Click on Browse, And Find the ONE Simulator Folder that you downloaded in the First Part of the Series. 

Or you can download it from https://www.netlab.tkk.fi/tutkimus/dtn/theone/  . Download the latest version, unzip it.

Select the ONE Simulator Folder


Click on the Check box on the Left Hand Side and then Click Finish. This Imports all the resources (Class Files/Jars) from the one_14.1 folder into your current project. 


Now you will see all the folders of the ONE simulator project in your Eclipse. 

But Hang on, you will also see a cross sign on the src folder icon. This means Eclipse cannot resolve all the libraries being referenced by ONE simulator. These libraries have to be included manually. 

Follow the below steps to add the libraries. 

1) Within Eclipse, Right Click on the Project Folder i.e the Folder over the src folder. Go to Build Path -> Add External Archives. Go to the ONE Simulator Folder, (that you extracted) and open the lib folder, and select both the jar files present in the folder. 

2) Right Click on the test folder within the src folder and delete it.


Running the ONE simulator

Important: Copy default_settings.txt and data folder to the Root Folder of your Eclipse Project. Without this it will not work 
 
For me there was no other need, Just Right Click on the Project folder Select Run As -> Java Application, and a window will open 

Select DTNSim - core and main window will appear.. 



Compiling and Running ONE Simulator under Linux

ONE simulator stands for Opportunistic Network Environment. It is a network simulator developed in Java. In this blog i will show how to compile and run ONE simulator from source in Linux. For this purpose i am using Ubuntu 14.0.4 trusty. Although the steps should be similar in any distribution of Linux, still it is better to know which version of Linux are you using.

So launch the terminal and issue the following command.

$ lsb_release -a


You should have Java Installed on your Machine. Find if java is installed on your computer by firing the following command on your terminal

$ which javac

It should tell you the location where java is installed like the one in the screen-shot


If it doesn't show the path, it either means that you don't have java installed, or java is not in your path.

You can install Java by issuing the following command.

$ sudo apt-get install openjdk7-jre

This will install java.

Now once again issue the command

$which javac

It should tell you the path of the java.

Step2 Download ONE Simulator by issuing the following command


$ wget https://www.netlab.tkk.fi/tutkimus/dtn/theone/down/one_1.4.1.tar.gz

 Step 3 Extract the archive. 


$ tar -xvf one_1.4.1.tar.gz 

Change Directory

$cd one_1.4.1

Compile the source by issuing the following command

$ ./compile.bat

If everything goes right, you will have the compiled source.

Step 4 Run the One Simulator 


$ ./one.sh 

The One simulator window should be displayed.







Force PHP to display Errors

At the top of your page add the following.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
 
?> 
 
 

Configuring Hadoop for a single Cluster Operations


From Apache Hadoop Website,

The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models. It is designed to scale up from single servers to thousands of machines, each offering local computation and storage. Rather than rely on hardware to deliver high-availability, the library itself is designed to detect and handle failures at the application layer, so delivering a highly-available service on top of a cluster of computers, each of which may be prone to failures.

I hope Dr Imran will give me additional marks for this effort.. :)

Ok so now to installing Hadoop. I assume that you have installed Ubuntu or any other version of linux. I will go through the procedure step by step. Remember installing hadoop is easy but you need to follow the step by step procedure.

And you must know how to use the terminal.

 Remember You should be connected to Internet for these commands
So Login to the Ubuntu start a terminal and enter the following command. (Remember Linux is case sensitive so the case of the commands should be exactly the same.

Install JDK

sudo apt-get install openjdk-7-jdk  
It will ask for your password and then install java development kit

Install SSH Server

From Wikipedia
Secure Shell, or SSH, is a cryptographic (encrypted) network protocol to allow remote login and other network services to operate securely over an unsecured network.
After installation proceed to install openssh server

sudo apt-get install openssh-server
 This will install ssh server. SSH Server is required to communicate with the machine from other machine. It is secure shell

Now to some system administration

Create Users and Groups

 The command to add a Group is

addgroup <GROUP-NAME>

We want to add a group named hadoop so fire the following command and also add a user hduser

sudo addgroup hadoop
 After asking for your password this will create a user hadoop

Now we need to Create a New User and add it to group hadoop

sudo adduser --ingroup hadoop hduser

This will ask you a couple of questions, Except for the Password, in most cases the Default is Ok.. So Keep on Pressing Enter

Now we have a hduser added to hadoop

Now Logout, and then login using the hduser and entering the password for that account.

You should not encounter any problems, if you encounter any problems Check the commands and its case..

Setup SSH Access by Creating a Certificate

 Issue the following command
ssh-keygen -t rsa -P ''
This will generate a key for ssh access

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

 Test that your access is working by executing the command

ssh localhost

This will ask you to store the key.. and then ask for your password. If you manage to login using the above command, it means that your ssh server is working. Otherwise restart your computer and try again.


Now things are set.. We need to download Hadoop. I downloaded Hadoop from the following link


http://www.eu.apache.org/dist/hadoop/core/hadoop-2.7.1/hadoop-2.7.1.tar.gz

Download Hadoop

You can either use the browser to download it. If you don't want to leave the console, issue the following command


wget http://www.eu.apache.org/dist/hadoop/core/hadoop-2.7.1/hadoop-2.7.1.tar.gz

Once download is completed, issue the following command


sudo tar vxzf hadoop-2.2.0.tar.gz -C /usr/local
This command will extract the files to /usr/local directory

Change directory to /usr/local

cd /usr/local
rename hadoop-2.7.1 to hadoop

mv hadoop-2.7.1 hadoop
In order for hduser to access the hadoop directory change its ownership

sudo chown -R hduser:hadoop hadoop
That's the easy part and it is done. Congrats. Take a break, drink a cup of coffee or root beer.. :)


Now to configure Environment variables for Hadoop

Setting User Variables 

Switch to your home Directory by issuing the following command
cd ~
 gedit .bashrc

This will open the file .bashrc which keeps user information. You will see a lot of lines of code. Don't change any code. Move to the end of the file  and paste the following

#Hadoop variables
export JAVA_HOME=/usr/lib/jvm/jdk/
export HADOOP_INSTALL=/usr/local/hadoop
export PATH=$PATH:$HADOOP_INSTALL/bin
export PATH=$PATH:$HADOOP_INSTALL/sbin
export HADOOP_MAPRED_HOME=$HADOOP_INSTALL
export HADOOP_COMMON_HOME=$HADOOP_INSTALL
export HADOOP_HDFS_HOME=$HADOOP_INSTALL
export YARN_HOME=$HADOOP_INSTALL

Setting Hadoop Variables 

Switch to hadoop directory by this command
cd /usr/local/hadoop/etc/hadoop
Open hadoop-env.sh by issuing the command
gedit hadoop-env.sh
Add the following code at the end of the file
#modify JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/jdk/
Logout and then login once again using the hduser

Now open a terminal Fire the command to test hadoop version

hadoop version
 If it shows the version. Hadoop is installed.. Happy Coding.






Running Drupal in Docker

I will assume that you have already installed docker. If you haven't installed docker please visit https://www.docker.com/ to download a...