Friday, 9 June 2017

Multithreading in C


What is a Thread? 
A thread is a single sequence stream within in a process. Because threads have some of the properties of processes, they are sometimes called lightweight processes.
What are the differences between process and thread?
Threads are not independent of one other like processes as a result threads shares with other threads their code section, data section and OS resources like open files and signals. But, like process, a thread has its own program counter (PC), a register set, and a stack space.
Why Multithreading?
Threads are popular way to improve application through parallelism. For example, in a browser, multiple tabs can be different threads. MS word uses multiple threads, one thread to format the text, other thread to process inputs, etc.
Threads operate faster than processes due to following reasons:
1) Thread creation is much faster.
2) Context switching between threads is much faster.
3) Threads can be terminated easily
4) Communication between threads is faster.
Can we write multithreading programs in C?
Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or Pthreads) is a POSIX standard for threads. Implementation of pthread is available with gcc compiler.
A simple C program to demonstrate use of pthread basic functions
Please not that the below program may compile only with C compilers with pthread library.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
 
// A normal C function that is executed as a thread when its name
// is specified in pthread_create()
void *myThreadFun(void *vargp)
{
    sleep(1);
    printf("Printing GeeksQuiz from Thread \n");
    return NULL;
}
  
int main()
{
    pthread_t tid;
    printf("Before Thread\n");
    pthread_create(&tid, NULL, myThreadFun, NULL);
    pthread_join(tid, NULL);
    printf("After Thread\n");
    exit(0);
}
In main() we declare a variable called thread_id, which is of type pthread_t, which is an integer used to identify the thread in the system. After declaring thread_id, we call pthread_create() function to create a thread.
pthread_create() takes 4 arguments.
The first argument is a pointer to thread_id which is set by this function.
The third argument is name of function to be executed for the thread to be created.
The fourth argument is used to pass arguments to thread.
The pthread_join() function for threads is the equivalent of wait() for processes. A call to pthread_join blocks the calling thread until the thread with identifier equal to the first argument terminates.
How to compile above program?
To compile a multithreaded program using gcc, we need to link it with the pthreads library. Following is the command used to compile the program.
gfg@ubuntu:~/$ gcc multithread.c -lpthread
gfg@ubuntu:~/$ ./a.out
Before Thread
Printing GeeksQuiz from Thread 
After Thread
gfg@ubuntu:~/$ 
A C program to show multiple threads with global and static variables
As mentioned above, all threads share data segment. Global and static variables are stored in data segment. Therefore, they are shared by all threads. The following example program demonstrates the same.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
 
// Let us create a global variable to change it in threads
int g = 0;
 
// The function to be executed by all threads
void *myThreadFun(void *vargp)
{
    // Store the value argument passed to this thread
    int myid = (int)vargp;
 
    // Let us create a static variable to observe its changes
    static int s = 0;
 
    // Change static and global variables
    ++s; ++g;
 
    // Print the argument, static and global variables
    printf("Thread ID: %d, Static: %d, Global: %d\n", myid, ++s, ++g);
}
 
int main()
{
    int i;
    pthread_t tid;
 
    // Let us create three threads
    for (i = 0; i < 3; i++)
        pthread_create(&tid, NULL, myThreadFun, (void *)i);
    
    pthread_exit(NULL);
    return 0;
}
gfg@ubuntu:~/$ gcc multithread.c -lpthread
gfg@ubuntu:~/$ ./a.out
Thread ID: 1, Static: 1, Global: 1
Thread ID: 0, Static: 2, Global: 2
Thread ID: 2, Static: 3, Global: 3
gfg@ubuntu:~/$ 
Please note that above is simple example to show how threads work. Accessing a global variable in a thread is generally a bad idea. What if thread 2 has priority over thread 1 and thread 1 needs to change the variable. In practice, if it is required to access global variable by multiple threads, then they should be accessed using a mutex.

A TCP Tutorial

This mini-tutorial provides a general overview of TCP, and is not specific to the SSF implementation.


TCP SUMMARY

TCP provides a connection oriented, reliable, byte stream service. The term connection-oriented means the two applications using TCP must establish a TCP connection with each other before they can exchange data. It is a full duplex protocol, meaning that each TCP connection supports a pair of byte streams, one flowing in each direction. TCP includes a flow-control mechanism for each of these byte streams that allows the receiver to limit how much data the sender can transmit. TCP also implements a congestion-control mechanism.




 


Two processes communicating via TCP sockets. Each side of a TCP connection has a socket which can be identified by the pair < IP_address, port_number >. Two processes communicating over TCP form a logical connection that is uniquely identifiable by the two sockets involved, that is by the combination < local_IP_address, local_port, remote_IP_address, remote_port>.


 

TCP provides the following facilities to:
Stream Data Transfer
From the application's viewpoint, TCP transfers a contiguous stream of bytes. TCP does this by grouping the bytes in TCP segments, which are passed to IP for transmission to the destination. TCP itself decides how to segment the data and it may forward the data at its own convenience.
 
Reliability
TCP assigns a sequence number to each byte transmitted, and expects a positive acknowledgment (ACK) from the receiving TCP. If the ACK is not received within a timeout interval, the data is retransmitted. The receiving TCP uses the sequence numbers to rearrange the segments when they arrive out of order, and to eliminate duplicate segments. 
 
Flow Control
The receiving TCP, when sending an ACK back to the sender, also indicates to the sender the number of bytes it can receive beyond the last received TCP segment, without causing overrun and overflow in its internal buffers. This is sent in the ACK in the form of the highest sequence number it can receive without problems. 
 
Multiplexing
To allow for many processes within a single host to use TCP communication facilities simultaneously, the TCP provides a set of addresses or ports within each host. Concatenated with the network and host addresses from the internet communication layer, this forms a socket. A pair of sockets uniquely identifies each connection.
 
Logical Connections
The reliability and flow control mechanisms described above require that TCP initializes and maintains certain status information for each data stream. The combination of this status, including sockets, sequence numbers and window sizes, is called a logical connection. Each connection is uniquely identified by the pair of sockets used by the sending and receiving processes.

Full Duplex
TCP provides for concurrent data streams in both directions. 



TCP HEADER

TCP data is encapsulated in an IP datagram. The figure shows the format of the TCP header. Its normal size is 20 bytes unless options are present. Each of the fields is discussed below:



 

The SrcPort and DstPort fields identify the source and destination ports,respectively. These two fields plus the source and destination IP addresses, combine to uniquely identify each TCP connection.
 
The sequence number identifies the byte in the stream of data from the sending TCP to the receiving TCP that the first byte of data in this segment represents.
 
The Acknowledgement number field contains the next sequence number that the sender of the acknowledgement expects to receive. This is therefore the sequence number plus 1 of the last successfully received byte of data. This field is valid only if the ACK flag is on. Once a connection is established the Ack flag is always on.
 
The Acknowledgement, SequenceNum, and AdvertisedWindow fields are all involved in TCP's sliding window algorithm.The Acknowledgement and AdvertisedW indow fields carry information about the flow of dat going in the other direction. In TCP's sliding window algorithm the reciever advertises a window size to the sender. This is done using the AdvertisedWindow field. The sender is then limited to having no more than a value of AdvertisedWindow bytes of un acknowledged data at any given time. The receiver sets a suitable value for the AdvertisedWindow based on the amount of memory allocated to the connection for the purpose of buffering data.
 
The header length gives the length of the header in 32-bit words. This is required because the length of the options field is variable.
 
The 6-bit Flags field is used to relay control information between TCP peers. The possible flags include SYN, FIN, RESET, PUSH, URG, and ACK.
  • The SYN and Fin flags are used when establishing and terminating a TCP connection, respectively.
  • The ACK flag is set any time the Acknowledgement field is valid, implying that the receiver should pay attention to it.
  • The URG flag signifies that this segment contains urgent data. When this flag is set, the UrgPtr field indicates where the non-urgent data contained in this segment begins.
  • The PUSH flag signifies that the sender invoked the push operation, whic h indicates to the receiving side of TCP that it should notify the receiving process of this fact.
  • Finally, the RESET flag signifies that the receiver has become confused and so wants to abort the connection.
 
The Checksum covers the TCP segment: the TCP header and the TCP data. This is a mandatory field that must be calculated by the sender, and then verified by the receiver.
 
The Option field is the maximum segment size option, called the MSS. Each end of the connection normally specifies this option on the first segment exchanged. It specifies the maximum sized segment the sender wants to recieve.
 
The data portion of the TCP segment is optional.



TCP STATE TRANSITION DIAGRAM




 

The two transitions leading to the ESTABLISHED state correspond to the opening of a connection, and the two transitions leading from the ESTABLISHED state are for the termination of a connection. The ESTABLISHED state is where data transfer can occur between the two ends in both the directions.
If a connection is in the LISTEN state and a SYN segment arrives, the connection makes a transition to the SYN_RCVD state and takes the action of replying with an ACK+SYN segment. The client does an active open which causes its end of the connection to send a SYN segment to the server and to move to the SYN_SENT state. The arrival of the SYN+ACK segment causes the client to mo ve to the ESTABLISHED state and to send an ack back to the server. When this ACK arrives the server finally moves to the ESTABLISHED state. In other words, we have just traced the THREE-WAY HANDSHAKE.
In the process of terminating a connection, the important thing to kee p in mind is that the application process on both sides of the connection must independently close its half of the connection. Thus, on any one side there are three combinations of transition that get a connection from the ESTABLISHED state to the CLOSED state:
  • This side closes first:
ESTABLISHED -> FIN_WAIT_1-> FIN_WAIT_2 -> TIME_WAIT -> CLOSED.
  • The other side closes first:
ESTABLISHED -> CLOSE_WAIT -> LAST_ACK -> CLOSED.
  • Both sides close at the same time:ESTABLISHED -> FIN_WAIT_1-> CLOSING ->TIME_WAIT -> CLOSED.
The main thing to recognize about connection teardown is that a connection in the TIME_WAIT state cannot move to the CLOSED state until it has waited for two times the maximum amount of time an IP datagram might live in the Inter net. The reason for this is that while the local side of the connection has sent an ACK in response to the other side's FIN segment, it does not know that the ACK was successfully delivered. As a consequence this other side might re transmit its FIN segment, and this second FIN segment might be delayed in the network. If the connection were allowed to move directly to the CLOSED state, then another pair of application processes might come along and open the same connection, and the delayed FIN segment from the earlier incarnation of the connection would immediately initiate the termination of the later incarnation of that connection.



SLIDING WINDOW


 



The sliding window serves several purposes:
(1) it guarantees the reliable delivery of data
(2) it ensures that the data is delivered in order,
(3) it enforces flow control between the sender and the receiver.

Reliable and ordered delivery

The sending and receiving sides of TCP interact in the following manner to implement reliable and ordered delivery:
Each byte has a sequence number.
ACKs are cumulative.
Sending side
  • LastByteAcked <=LastByteSent
  • LastByteSent <= LastByteWritten
  • bytes between LastByteAcked and LastByteWritten must be buffered.
Receiving side
  • LastByteRead < NextByteExpected
  • NextByteExpected <= LastByteRcvd + 1
  • bytes between NextByteRead and LastByteRcvd must be buffered.

Flow Control

Sender buffer size : MaxSendBuffer
Receive buffer size : MaxRcvBuffer
Receiving side
  • LastByteRcvd - NextBytteRead <= MaxRcvBuffer
  • AdvertisedWindow = MaxRcvBuffer - (LastByteRcvd - NextByteRead)
Sending side
  • LastByteSent - LastByteAcked <= AdvertisedWindow
  • EffectiveWindow = AdvertisedWindow - (LastByteSent - LastByteAcked)
  • LastByteWritten - LastByteAcked <= MaxSendBuffer
  • Block sender if (LastByteWritten - LastByteAcked) + y > MaxSendBuffer

Always send ACK in response to an arriving data segment
Persist when AdvertisedWindow = 0



Adaptive Retransmission

TCP guarantees reliable delivery and so it retransmits each segment if an ACK is not received in a certainperiod of time. TCP sets this timeout as a function of the RTT it expects between the two ends of the connection. Unfortunately, given the range of possible RTT's between any pair of hosts in the Internet, as well as the variation in RTT between the same two hosts over time, choosing an appropriate timeout value is not that easy. To address this problem, TCP uses an adaptive retransmission medchanism. We describe this mechanism and how it has evolved over time.

 

Original Algorithm

Measure SampleRTT for each segment/ACK pair
Compute weighted average of RTT
EstimatedRTT = a*EstimatedRTT + b*SampleRTT, where a+b = 1
a between 0.8 and 0.9
b between 0.1 and 0.2
Set timeout based on EstimatedRTT
TimeOut = 2 * EstimatedRTT

 

Karn/Partridge Algorithm

Do not sample RTT when retransmitting
Double timeout after each retransmission

Jacobson/Karels Algorithm




New calculation for average RTT
Difference = SampleRTT - EstimatedRTT
EstimatedRTT = EstimatedRTT + ( d * Difference)
Deviation = Deviation + d ( |Difference| - Deviation)), where d is a fraction between 0 and 1
Consider variance when setting timeout value
Timeout = u * EstimatedRTT + q * Deviation, where u = 1 and q = 4



Congestion Control

Slow Start

It operates by observing that the rate at which new packets should be injected into the network is the rate at which the acknowledgments are returned by the other end.
Slow start adds another window to the sender's TCP: the congestion window, called "cwnd". When a new connection is established with a host on another network, the congestion window is initialized to one segment (i.e., the segment size announced by the other end, or the default, typically 536 or 512). Each time an ACK is received, the congestion window is increased by one segment. The sender can transmit up to the minimum of the congestion window and the advertised window. The congestion window is flow control imposed by the sender, while the advertised window is flow control imposed by the receiver. The former is based on the sender's assessment of perceived network congestion; the latter is related to the amount of available buffer space at the receiver for this connection.
The sender starts by transmitting one segment and waiting for its ACK. When that ACK is received, the congestion window is incremented from one to two, and two segments can be sent. When each of those two segments is acknowledged, the congestion window is increased to four. This provides an exponential growth, although it is not exactly exponential because the receiver may delay its ACKs, typically sending one ACK for every two segments that it receives.
At some point the capacity of the internet can be reached, and an intermediate router will start discarding packets. This tells the sender that its congestion window has gotten too large.
Early implementations performed slow start only if the other end was on a different network. Current implementations always perform slow start.

Congestion Avoidance

Congestion can occur when data arrives on a big pipe (a fast LAN) and gets sent out a smaller pipe (a slower WAN). Congestion can also occur when multiple input streams arrive at a router whose output capacity is less than the sum of the inputs. Congestion avoidance is a way to deal with lost packets.
The assumption of the algorithm is that packet loss caused by damage is very small (much less than 1%), therefore the loss of a packet signals congestion somewhere in the network between the source and destination. There are two indications of packet loss: a timeout occurring and the receipt of duplicate ACKs.
Congestion avoidance and slow start are independent algorithms with different objectives. But when congestion occurs TCP must slow down its transmission rate of packets into the network, and then invoke slow start to get things going again. In practice they are implemented together.
Congestion avoidance and slow start require that two variables be maintained for each connection: a congestion window, cwnd, and a slow start threshold size, ssthresh. The combined algorithm operates as follows:
1. Initialization for a given connection sets cwnd to one segment and ssthresh to 65535 bytes.
2. The TCP output routine never sends more than the minimum of cwnd and the receiver's advertised window.
3. When congestion occurs (indicated by a timeout or the reception of duplicate ACKs), one-half of the current window size (the minimum of cwnd and the receiver's advertised window, but at least two segments) is saved in ssthresh. Additionally, if the congestion is indicated by a timeout, cwnd is set to one segment (i.e., slow start).
4. When new data is acknowledged by the other end, increase cwnd, but the way it increases depends on whether TCP is performing slow start or congestion avoidance.
If cwnd is less than or equal to ssthresh, TCP is in slow start; otherwise TCP is performing congestion avoidance. Slow start continues until TCP is halfway to where it was when congestion occurred (since it recorded half of the window size that caused the problem in step 2), and then congestion avoidance takes over.
Slow start has cwnd begin at one segment, and be incremented by one segment every time an ACK is received. As mentioned earlier, this opens the window exponentially: send one segment, then two, then four, and so on. Congestion avoidance dictates that cwnd be incremented by segsize*segsize/cwnd each time an ACK is received, where segsize is the segment size and cwnd is maintained in bytes. This is a linear growth of cwnd, compared to slow start's exponential growth. The increase in cwnd should be at most one segment each round-trip time (regardless how many ACKs are received in that RTT), whereas slow start increments cwnd by the number of ACKs received in a round-trip time.

Fast Retransmit

TCP may generate an immediate acknowledgment (a duplicate ACK) when an out- of-order segment is received. This duplicate ACK should not be delayed. The purpose of this duplicate ACK is to let the other end know that a segment was received out of order, and to tell it what sequence number is expected.
Since TCP does not know whether a duplicate ACK is caused by a lost segment or just a reordering of segments, it waits for a small number of duplicate ACKs to be received. It is assumed that if there is just a reordering of the segments, there will be only one or two duplicate ACKs before the reordered segment is processed, which will then generate a new ACK. If three or more duplicate ACKs are received in a row, it is a strong indication that a segment has been lost. TCP then performs a retransmission of what appears to be the missing segment, without waiting for a retransmission timer to expire.

Fast Recovery

After fast retransmit sends what appears to be the missing segment, congestion avoidance, but not slow start is performed. This is the fast recovery algorithm. It is an improvement that allows high throughput under moderate congestion, especially for large windows.
The reason for not performing slow start in this case is that the receipt of the duplicate ACKs tells TCP more than just a packet has been lost. Since the receiver can only generate the duplicate ACK when another segment is received, that segment has left the network and is in the receiver's buffer. That is, there is still data flowing between the two ends, and TCP does not want to reduce the flow abruptly by going into slow start.
The fast retransmit and fast recovery algorithms are usually implemented together as follows.
1. When the third duplicate ACK in a row is received, set ssthresh to one-half the current congestion window, cwnd, but no less than two segments. Retransmit the missing segment. Set cwnd to ssthresh plus 3 times the segment size. This inflates the congestion window by the number of segments that have left the network and which the other end has cached .
2. Each time another duplicate ACK arrives, increment cwnd by the segment size. This inflates the congestion window for the additional segment that has left the network. Transmit a packet, if allowed by the new value of cwnd.
3. When the next ACK arrives that acknowledges new data, set cwnd to ssthresh (the value set in step 1). This ACK should be the acknowledgment of the retransmission from step 1, one round-trip time after the retransmission. Additionally, this ACK should acknowledge all the intermediate segments sent between the lost packet and the receipt of the first duplicate ACK. This step is congestion avoidance, since TCP is down to one-half the rate it was at when the packet was lost.

TCP Congestion Control

TCP uses a round-trip delay estimate for its adaptive windowing scheme to transmit data reliably over an unreliable network with time varying bandwidth. An estimate of the round trip time is maintained as a smoothed moving average [6] using the relation - tex2html_wrap_inline120
Similarly a smoothed variance (estimated as mean difference to avoid square root calculations in the kernel) is also maintained (Tahoe TCP). A initial re-transmission timeout is then set as -tex2html_wrap_inline122
If an acknowledgement for a segment is not received within the timeout, it is re-transmitted.
TCP uses a congestion window in the sender side to do congestion avoidance. The congestion window indicates the maximum amount of data that can be sent out on a connection without being acknowledged. TCP detects congestion when it fails to receive an acknowledgement for a packet within the estimated timeout. In such a situation, it decreases the congestion window to one maximum segment size (MSS), and under other cases it increases the congestion window by one MSS. There also exists a congestion window threshold, which is set to half the congestion window size at the time when a re-transmit was required.
The inherent assumption in this mechanism is that lack of an acknowledgement is due to network congestion. If a packet, however, is lost by the network for reasons other than network congestion, then waiting for the timer to run out is wasteful. This is a situation that may happen quite frequently in wireless networks, and so to improve TCP performance, it is needed to pre-empt re-transmissions before waiting for the timer to run out.



To guard against this scenario, Reno TCP [7] uses Fast Re-transmit and Fast Recovery algorithms. Both these algorithms depend on counting duplicate acknowledgements sent by the data receiver in response to each additional segment received following some missing data. Fast Re-transmit detects loss of a segment when three duplicate acknowledgements are received, and re-transnits it. Fast Recovery algorithm attempts to estimate how much data is outstanding in the network by counting duplicate acknowledgements.

Tuesday, 30 May 2017

How to Install Django 1.10 on Ubuntu 16.04


In this tutorial, we will install Django 1.10 on a Ubuntu 16.04 server. Django can be installed on a server in many ways, in this tutorial, I will show you 3 different ways to install Django:
  1. Django installation with pip.
  2. Install Django with virtualenv.
  3. Install Django fron it's github repository.
When the Django installation is done, I will show you the first steps to start a new project with the Django web framework.
Django is a web application framework written in python that follows the MVC (Model-View-Controller) architecture, it is available for free and released under an open source license. It is fast and designed to help developers get their application online as quickly as possible. Django helps developers to avoid many common security mistakes like SQL Injection, XSS, CSRF and clickjacking. Django is maintained by the Django Software Foundation and used by many big technology companies, government, and other organizations. Some large websites like Pinterest, Mozilla, Instagram, Discuss, The Washington Post etc. are developed with Django.

Prerequisites
  • Ubuntu 16.04 - 64bit.
  • Root privileges.

Step 1 - Setup python 3 as Default Python version

We will configure python 3 before we start with the Django installation.
On my Ubuntu machine, there are two versions of python available, python2.7 as default python version and python3. In this step, we will change the default python version to python 3.
Check the python version:
python
Result:
python

Python 2.7.12 (default, Jul  1 2016, 15:12:24)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
So the default python is 2.7 at the moment.
Next, remove default python 2 and change the default to python 3 with the 'update-alternatives' command:
update-alternatives --remove python /usr/bin/python2
update-alternatives --install /usr/bin/python python /usr/bin/python3
Now check again the python version:
python
Result:
python

Python 3.5.2 (default, Jul  5 2016, 12:43:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Configure default python on Ubuntu to python 3

Step 2 - Install Django

In this step, I will show you 3 ways to install Django. Please follow either chpater 2.1, 2.2 or 2.3 to install Django but not all 3 options at the same time :)

2.1. Install Django with Pip

Pip is a package management system for python. Python has a central package repository from which we can download the python package. It's called Python Package Index (PyPI).
In this tutorial, we will use python 3 for django as recommended by the django website. Next, we will install pip for python 3 from the ubuntu repository with this apt command:
apt-get install python3-pip
The installation will add a new binary file called 'pip3'. To make it easier to use pip, I will create a symlink for pip3 to pip:
which pip3
ln -s /usr/bin/pip3 /usr/bin/pip
Now check the version :
pip -V
PIP version
The pip installation is done. Now we can use the pip command to install python packages. Let's install django on our server with pip command below:
pip install django==1.10
Note:
We set django==1.10 to get a specific version. If you want a different version, just change the number e.g. to django==1.9 etc.
If you have an error about the locale settings, run the command below to reconfigure the locale settings:
export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
locale-gen en_US.UTF-8
dpkg-reconfigure locales
When the installation is done, check the django version with the command below:
django-admin --version
Alternatively, we can use command below:
python
import django
print(django.get_version())
Check the Django version
Django 1.10 has been installed on the system with pip. Proceed with chapter 3.

2.2. Install Django with Virtualenv

Virtualenv is a python environment builder, it is used to create isolated python environments. We can choose the version of python that will be install in the virtualenv environment. This is very useful for developers, they can run and develop an application with different python versions and different environments on one OS.
Virtualenv is available on PyPI, we can install it with the pip command:
pip install virtualenv
Now we can use the virtualenv command to create a new environment with python3 as default python version. So let's create a new environment "mynewenv" with python3 as the python version and pip3 for the django installation.
virtualenv --python=python3 mynewenv
Note :
--python=python3 is a binary file for python 3.
mynewenv is the name of the environment.
The command will create a new directory called 'mynewenv' which contains the directories bin, include and lib.
The virtualenv has been created, now let's log into the new environment with the command below:
source mynewenv/bin/activate
If you do not have the source command, you can run this command instead:
. mynewenv/bin/activate
Note: If you want to get out from the virtual environment, use the command 'deactivate'.
Now check the pip version:
pip -V
Pip will be automatically installed inside the virtual environment.
Next, install django in thevirtual environment that we've created:
pip install django==1.10
When the installation finished, check the Django installation:
django-admin --version
Django installed inside virtualenv
Django 1.10 has been successfully installed inside our virtual environment. Proceed with chapter 3.

2.3. Install Django from Git Repository

In this chapter, we will install the Django web frame work inside the system, not in a virtual environment. I will show you how to install it manually from the Django Git repository. Make sure you have git installed on your server. If you don't have git, install it with the command below:
apt-get install git -y
Next, create a new python virtual environment and activate it:
virtualenv --python=python3 django-git
source django-git/bin/activate
Then clone the django git repository with the command below:
cd django-git
git clone git://github.com/django/django django-dev
Install django with this pip command:
pip install -e django-dev/
-e =  Install a package in editable mode or a local package. In this chapter, we install Django from the local code that we've cloned.


When the installation process is done, let's check the Django version on the server:
django-admin --version
1.11.dev20160831163130
We see the django 1.11 dev version.Django installed from source - Dev version
The manual Django installation is finished.

Step 3 - Create you First Project with Django

In this step, we will install django inside a virtual environment and then start our first project with django.
Install virtualenv on the server and create a new environment named 'firstdjango' :
pip install virtualenv
virtualenv --python=python3 firstdjango
Now go to the firstdjango directory and activate the virtual envonment, then install django with the pip command:
cd firstdjango/
source bin/activate
pip install django==1.10
Next, create a new project called 'myblog' with the django-admin command:
django-admin startproject myblog
It will create a new directory myblog that contains the django files:
ll myblog

-rwxr-xr-x 1 root root  249 Sep 06 09:01 manage.py*
drwxr-xr-x 2 root root 4096 Sep 06 09:01 myblog/
Go to the myblog directory and run the 'manage.py' file :
cd myblog/
python manage.py runserver
The runserver option will create a HTTP connection with python on localhost IP and port 8000. If your development environment is on a separate server, as in my example here I'm using an Ubuntu server with I : 192.168.1.9, you can use the server IP so you can access Django from outside of the server.
python manage.py runserver 192.168.1.9:8000
Now check from your browser: 192.168.1.9:8000
Django listens on port 8000
The Django default page is working and inside the server, you can look at the access log:
[31/Aug/2016 17:04:40] "GET / HTTP/1.1" 200 1767
Next, we will configure the Django admin. Django will automatically generate the database for a superuser. Before we create the superuser, run the command below:
python manage.py migrate
migrate: make adds the models (adding fields, deleting etc.) into the database scheme, the default database is sqlite3.
Now create the admin/superuser:
python manage.py createsuperuser

Username (leave blank to use 'root'): admin
Email address: admin@mydjango.co
Password:
Password (again):
Superuser created successfully.
Django configure superuser account
The Django super user has been added, now you can execute the runserver command, then go to the browser and visit the django admin page:
python manage.py runserver 192.168.1.9:8000
Visit Django admin page: 192.168.1.9:8000/admin/. Login with username admin and your password, you will see the admin page:
Django admin login page.
Django admin Login page
The Django admin dashboard.
Django admin dashboard
Django has been successfully installed inside a virtual environment and we've created a sample Django project named 'firstdjango'.

Conclusion

Django is a web framework based on the Python programming language, it is released as free software under an open source license and maintained by the Django Software Foundation. Django is very fast and allows it to build web applications rapidly. Django is a web framework that uses the MVC (Model-View-Controller) paradigm. We can install Django on a server with the pip command, in a virtual environment with virtualenv and directly from the Django git repository.

Tuesday, 23 May 2017

What is iBeacon? A Guide to Beacons

What is iBeacon? What are iBeacons? 

The term iBeacon and Beacon are often used interchangeably. iBeacon is the name for Apple’s technology standard, which allows Mobile Apps (running on both iOS and Android devices) to listen for signals from beacons in the physical world and react accordingly. In essence, iBeacon technology allows Mobile Apps to understand their position on a micro-local scale, and deliver hyper-contextual content to users based on location. The underlying communication technology is Bluetooth Low Energy.
iBeacon Contextual, Hyperlocal Content
iBeacon Contextual, Hyperlocal Content

What is Bluetooth Low Energy (BLE)?

Bluetooth Low Energy is a wireless personal area network technology used for transmitting data over short distances. As the name implies, it’s designed for low energy consumption and cost, while maintaining a communication range similar to that of its predecessor, Classic Bluetooth.

How is BLE different from Regular Bluetooth?

  • Power Consumption: Bluetooth LE, as the name hints, has low energy requirements. It can last up to 3 years on a single coin cell battery.
  • Lower Cost: BLE is 60-80% cheaper than traditional Bluetooth.
  • Application: BLE is ideal for simple applications requiring small periodic transfers of data. Classic Bluetooth is preferred for more complex applications requiring consistent communication and more data throughput.

How does BLE communication work?

BLE communication consists primarily of “Advertisements”, or small packets of data, broadcast at a regular interval by Beacons or other BLE enabled devices via radio waves.
BLE Advertising is a one-way communication method. Beacons that want to be “discovered” can broadcast, or “Advertise” self-contained packets of data in set intervals. These packets are meant to be collected by devices like smartphones, where they can be used for a variety of smartphone applications to trigger things like push messages, app actions, and prompts.
Apple’s iBeacon standard calls for an optimal broadcast interval of 100 ms.  Broadcasting more frequently uses more battery life but allows for quicker discovery by smartphones and other listening devices.
Standard BLE has a broadcast range of up to 100 meters, which make Beacons ideal for indoor location tracking and awareness.
iBeacon Detection Example
Source: Nerdery

How does iBeacon use BLE communication?

With iBeacon, Apple has standardized the format for BLE Advertising. Under this format, an advertising packet consists of four main pieces of information.
UUID: This is a 16 byte string used to differentiate a large group of related beacons. For example, if Coca-Cola maintained a network of beacons in a chain of grocery stores, all Coca-Cola beacons would share the same UUID. This allows Coca-Cola’s dedicated smartphone app to know which beacon advertisements come from Coca-Cola-owned beacons.
Major: This is a 2 byte string used to distinguish a smaller subset of beacons within the larger group. For example, if Coca-Cola had four beacons in a particular grocery store, all four would have the same Major. This allows Coca-Cola to know exactly which store its customer is in.
Minor: This is a 2 byte string meant to identify individual beacons. Keeping with the Coca-Cola example, a beacon at the front of the store would have its own unique Minor. This allows Coca-Cola’s dedicated app to know exactly where the customer is in the store.
Tx Power: This is used to determine proximity (distance) from the beacon. How does this work? TX power is defined as the strength of the signal exactly 1 meter from the device. This has to be calibrated and hardcoded in advance. Devices can then use this as a baseline to give a rough distance estimate. 
Example:
A beacon broadcasts the following packet
UUID: 12345678910245
Major: 22
Minor: 2
A device receiving this packet would understand it’s from the Coca-Cola Beacon (UUID) in the Target on 1st Street (Major) at the front of the store (Minor). 
How iBeacons Work
How iBeacons Work (Source: estimote.com)

Why is iBeacon a Big Deal? 

With an iBeacon network, any brand, retailer, app, or platform will be able to understand exactly where a customer is in the brick and mortar environment. This provides an opportunity to send customers highly contextual, hyper-local, meaningful messages and advertisements on their smartphones.
The typical scenario looks like this. A consumer carrying a smartphone walks into a store. Apps installed on a consumer’s smartphone listen for iBeacons. When an app hears an iBeacon, it communicates the relevant data (UUID, Major, Minor, Tx) to its server, which then triggers an action. This could be something as simple as a push message [“Welcome to Target! Check out Doritos on Aisle 3!”], and could include other things like targeted advertisements, special offers, and helpful reminders [“You’re out of Milk!”]. Other potential applications include mobile payments and shopper analytics and implementation outside of retail, at airports, concert venues, theme parks, and more. The potential is limitless.
This technology should bring about a paradigm shift in the way brands communicate with consumers. iBeacon provides a digital extension into the physical world. We’re excited to see where iBeacon technology goes in the next few years.