Matrix Introduction

A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets.
A matrix with 9 elements is shown below.


This Matrix [M] has 3 rows and 3 columns. Each element of matrix [M] can be referred to by its row and column number. For example, a23=6

Order of a Matrix :
The order of a matrix is defined in terms of its number of rows and columns.
Order of a matrix = No. of rows ×No. of columns
Therefore Matrix [M] is a matrix of order 3 × 3.

Transpose of a Matrix :
The transpose [M]T of an m x n matrix [M] is the n x m matrix obtained by interchanging the rows and columns of [M].
if A= [aij] mxn , then AT = [bij] nxm where bij = aji

Properties of transpose of a matrix:

  • (AT)TT = A
  • (A+B)TT = ATT + BTT

Singular and Nonsingular Matrix:

  1. Singular Matrix: A square matrix is said to be singular matrix if its determinant is zero i.e. |A|=0
  2. Nonsingular Matrix: A square matrix is said to be non-singular matrix if its determinant is non-zero.

Properties of Matrix addition and multiplication:

  1. A+B = B+A (Commutative)
  2. (A+B)+C = A+ (B+C) (Associative)
  3. AB ≠ BA (Not Commutative)
  4. (AB) C = A (BC) (Associative)
  5. A (B+C) = AB+AC (Distributive)

Square Matrix: A square Matrix has as many rows as it has columns. i.e. no of rows = no of columns.
Symmetric matrix: A square matrix is said to be symmetric if the transpose of original matrix is equal to its original matrix. i.e. (AT) = A.

Diagonal Matrix: A Symmetric matrix is said to be diagonal matrix where all the off diagonal elements are 0.
Identity Matrix: A diagonal matrix with 1s and only 1s on the diagonal. Identity matrix is denoted as I.
Orthogonal Matrix: A matrix is said to be orthogonal if AAT = ATA = I
Idemponent Matrix: A matrix is said to be idemponent if A2 = A
Involutary Matrix: A matrix is said to be Involutary if A2 = I.

Note: Every Square Matrix can uniquely be expressed as the sum of a symmetrix matrix and skew symmetric matrix. A = 1/2 (AT + A) + 1/2 (A – AT).

Adjoint of a square matrix:


Properties of Adjoint:

  1. A(Adj A) = (Adj A) A = |A| In
  2. Adj(AB) = (Adj B).(Adj A)

Inverse of a square matrix:

A-1 = Adj A / |A| ; |A|#0

Properties of inverse:

1. (A-1)-1 = A
2. (AB)-1 = B-1A-1
3. only a non singular square matrix can have an inverse.

Where should we use inverse matrix?

If you have a set of simultaneous equations:

7x + 2y + z = 21
3y – z = 5
-3x + 4y – 2x = -1

As we know when AX = B, then X = A-1B so we calculate inverse of A and by multiplying it B, we can get the values of x, y and z.

Trace of a matrix: trace of a matrix is denoted as tr(A) which is used only for square matrix and equals the sum of the diagonal elements of the matrix. For example:

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Disclaimer: This content belongs to geeksforgeeks, source:

Conditional Probability

Conditional probability P(A | B) indicates the probability of even ‘A’ happening given that the even B happened.

    P(A|B) = \frac{P(A \cap B)}{P(B)}

We can easily understand above formula using below diagram. Since B has already happened, the sample space reduces to B. So the probability of A happening becomes P(A ∩ B) divided by P(B)


In a batch, there are 80% C programmers, and 40% are Java and C programmers. What is the probability that a C programmer is also Java programmer?

Let A --> Event that a student is Java programmer
    B --> Event that a student is C programmer
    P(A|B) = P(A ∩ B) / P(B)
           = (0.4) / (0.8)
           = 0.5
So there are 50% chances that student that knows C also
knows Java

Product Rule:
Derived from above definition of conditional probability by multiplying both sides with P(B)

P(A ∩ B) = P(B) * P(A|B)

1) What is the value of P(A|A)?

2) Let P(E) denote the probability of the event E. Given P(A) = 1, P(B) = 1/2, the values of P(A | B) and P(B | A) respectively are (GATE CS 2003)
(A) 1/4, 1/2
(B) 1/2, 1/14
(C) 1/2, 1
(D) 1, 1/2

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Disclaimer: This content belongs to geeksforgeeks, source:

Mathematics | Sum of squares of even and odd natural numbers?

We know sum squares of first n natural numbers is n(n+1)(2n+1)/6.

How to compute sum of squares of first n even natural numbers?
We need to compute 22 + 42 + 62 + …. + (2n)2

EvenSum = 22 + 42 + 62 + .... + (2n)2
        = 4 x (12 + 22 + 32 + .... + (n)2)
        = 4n(n+1)(2n+1)/6
        = 2n(n+1)(2n+1)/3


Sum of squares of first 3 even numbers = 2n(n+1)(2n+1)/3
                                       = 2*3(3+1)(2*3+1)/3
                                       = 56
22 + 42 + 62 = 4 + 16 + 36 = 56

How to compute sum of squares of first n odd natural numbers?
We need to compute 12 + 32 + 52 + …. + (2n-1)2

OddSum  = (Sum of Squares of all 2n numbers) - (Sum of squares of first n even numbers)
        = 2n*(2n+1)*(2*2n + 1)/6 - 2n(n+1)(2n+1)/3
        = 2n(2n+1)/6 [4n+1 - 2(n+1)]
        = n(2n+1)/3 * (2n-1)
        = n(2n+1)(2n-1)/3


Sum of squares of first 3 odd numbers = n(2n+1)(2n-1)/3
                                      = 3(2*3+1)(2*3-1)/3
                                      = 35
12 + 32 + 52 = 1 + 9 + 25 = 35

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Disclaimer: This content belongs to geeksforgeeks, source:

The prisoner’s dilemma in Game theory

Two members of a criminal gang are arrested and imprisoned. Each prisoner is in solitary confinement with no means of communicating with the other. The prosecutors lack sufficient evidence to convict the pair on the principal charge. They hope to get both sentenced to a year in prison on a lesser charge. Simultaneously, the prosecutors offer each prisoner a bargain. Each prisoner is given the opportunity either to: betray the other by testifying that the other committed the crime, or to cooperate with the other by remaining silent. The offer is:

  • If A and B each betray the other, each of them serves 2 years in prison
  • If A betrays B but B remains silent, A will be set free and B will serve 3 years in prison (and vice versa)
  • If A and B both remain silent, both of them will only serve 1 year in prison (on the lesser charge)

Image Source :

Let’s analyze the nature of the dilemma assuming that both understand the nature of the game, and that despite being members of the same gang, they have no loyalty to each other and will have no opportunity for retribution or reward outside the game.

PRISONER A STAYS SILENT Each serves 1 year Prisoner A: 3 years
Prisoner B: goes free
PRISONER A BETRAYS Prisoner A: goes free
Prisoner B: 3 years
Each serves 2 years

Please try to think over the solution for a while and analyze each case yourself.
By analyzing the table we can see that:
You are always punished less for choosing to betray the other person. However, as a group, both of you fare better by cooperating(remaining silent).
Think over the above statement for a while.
If you have problem in analyzing this then you can watch this video: Khan Academy’s explaination

This is the dilemma both the prisoner’s face. Should one cooperate or betray?
Even if the best solution would be both the prisoners cooperating with each other but due to uncertainty on each other both of them betray each other getting a lesser optimum solution.
This can be observed in may real-life cases like:

  • A pair working on a project. You do best if your competitor does all the work, since you get the same grade. But if neither of you do the work, you both fail.
  • Advertising. If both companies spend money on advertising, their market share won’t change from if neither does. But if one company outspends the other, they will receive a benefit.

The prisoner’s dilemma demonstrates that two rational people might not cooperate even if it is in their best interest to do so. Just keep looking around in this beautiful world. Who knows you can find yourself in a prisoner’s dilemma one day!

This article is contributed by Aditya Nihal Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Disclaimer: This content belongs to geeksforgeeks, source:

Print all interleavings of given two strings

Given two strings str1 and str2, write a function that prints all interleavings of the given two strings. You may assume that all characters in both strings are different


Input: str1 = "AB",  str2 = "CD"

Input: str1 = "AB",  str2 = "C"

An interleaved string of given two strings preserves the order of characters in individual strings. For example, in all the interleavings of above first example, ‘A’ comes before ‘B’ and ‘C’ comes before ‘D’.

Let the length of str1 be m and the length of str2 be n. Let us assume that all characters in str1 and str2 are different. Let count(m, n) be the count of all interleaved strings in such strings. The value of count(m, n) can be written as following.

     count(m, n) = count(m-1, n) + count(m, n-1)
     count(1, 0) = 1 and count(0, 1) = 1

To print all interleavings, we can first fix the first character of str1[0..m-1] in output string, and recursively call for str1[1..m-1] and str2[0..n-1]. And then we can fix the first character of str2[0..n-1] and recursively call for str1[0..m-1] and str2[1..n-1]. Thanks to akash01 for providing following C implementation.

// C/C++ program to <a href="#">print all interleavings of given two strings</a>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// The main function that recursively prints all interleavings.
// The variable iStr is used to store all interleavings (or
// output strings) one by one. 
// i is used to pass next available place in iStr
void printIlsRecur (char *str1, char *str2, char *iStr, int m,
                    int n, int i)
    // Base case: If all characters of str1 and str2 have been
    // included in output string, then print the output string
    if (m==0 && n==0)
        printf("%s\n", iStr) ;
    // If some characters of str1 are left to be included, then
    // include the  first character from the remaining characters
    // and recur for rest
    if (m != 0)
        iStr[i] = str1[0];
        printIlsRecur (str1 + 1, str2, iStr, m-1, n, i+1);
    // If some characters of str2 are left to be included, then
    // include the  first character from the remaining characters
    // and recur for rest
    if (n != 0)
        iStr[i] = str2[0];
        printIlsRecur(str1, str2+1, iStr, m, n-1, i+1);
// Allocates memory for output string and uses printIlsRecur()
// for printing all interleavings
void printIls (char *str1, char *str2, int m, int n)
   // allocate memory for the output string
   char *iStr= (char*)malloc((m+n+1)*sizeof(char));
   // Set the terminator for the output string
   iStr[m+n] = '\0';
   // print all interleavings using printIlsRecur()
   printIlsRecur (str1, str2, iStr, m, n, 0);
   // free memory to avoid memory leak
// Driver program to test above functions
int main()
    char str1[] = "AB";
    char str2[] = "CD";
    printIls (str1, str2, strlen(str1), strlen(str2));
    return 0;



Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Disclaimer: This content belongs to geeksforgeeks, source:

Heap Sort

Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.

What is Binary Heap?
Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible (Source Wikipedia)

A Binary Heap is a Complete Binary Tree where items are stored in a special order such that value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called as max heap and the latter is called min heap. The heap can be represented by binary tree or array.

Why array based representation for Binary Heap?
Since a Binary Heap is a Complete Binary Tree, it can be easily represented as array and array based representation is space efficient. If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing starts at 0).

Heap Sort Algorithm for sorting in increasing order:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.
3. Repeat above steps while size of heap is greater than 1.

How to build the heap?
Heapify procedure can be applied to a node only if its children nodes are heapified. So the heapification must be performed in the bottom up order.

Lets understand with the help of an example:

Input data: 4, 10, 3, 5, 1
		/   \
	     10(1)   3(2)
            /   \
	 5(3)    1(4)

The numbers in bracket represent the indices in the array
representation of data.

Applying heapify procedure to index 1:
		/   \
            10(1)    3(2)
           /   \
	5(3)    1(4)

Applying heapify procedure to index 0:
		/  \
	     5(1)  3(2)
            /   \
         4(3)    1(4)
The heapify procedure calls itself recursively to build heap
 in top down manner.
// C++ program for implementation of Heap Sort
#include <iostream>
using namespace std;
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
    int largest = i;  // Initialize largest as root
    int l = 2*i + 1;  // left = 2*i + 1
    int r = 2*i + 2;  // right = 2*i + 2
    // If left child is larger than root
    if (l < n && arr[l] > arr[largest])
        largest = l;
    // If right child is larger than largest so far
    if (r < n && arr[r] > arr[largest])
        largest = r;
    // If largest is not root
    if (largest != i)
        swap(arr[i], arr[largest]);
        // Recursively heapify the affected sub-tree
        heapify(arr, n, largest);
// main function to do heap sort
void heapSort(int arr[], int n)
    // Build heap (rearrange array)
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);
    // One by one extract an element from heap
    for (int i=n-1; i>=0; i--)
        // Move current root to end
        swap(arr[0], arr[i]);
        // call max heapify on the reduced heap
        heapify(arr, i, 0);
/* A utility function to print array of size n */
void printArray(int arr[], int n)
    for (int i=0; i<n; ++i)
        cout << arr[i] << " ";
    cout << "\n";
// Driver program
int main()
    int arr[] = {12, 11, 13, 5, 6, 7};
    int n = sizeof(arr)/sizeof(arr[0]);
    heapSort(arr, n);
    cout << "Sorted array is \n";
    printArray(arr, n);


Sorted array is
5 6 7 11 12 13

Heap sort is an in-place algorithm.
Its typical implementation is not stable, but can be made stable .

Time Complexity: Time complexity of heapify is O(Logn). Time complexity of createAndBuildHeap() is O(n) and overall time complexity of Heap Sort is O(nLogn).

Applications of HeapSort
1. Sort a nearly sorted (or K sorted) array
2. k largest(or smallest) elements in an array

Disclaimer: This content belongs to geeksforgeeks, source:

Project Idea | Analysis of Emergency 911 calls using Association Rule Mining

Analysing emergency calls dataset and discovering hidden trends and patterns will help in ensuring that the emergency response team is better equipped to deal with emergencies.
Considering road accidents, fire accidents etc, high numbers in specific areas indicate that there is a high demand for ambulance services in those areas. Road accidents in some areas might be due to road conditions which need to be improved. High frequency of emergencies due to respiratory problems might be due to harmful pollutants in the air in that specific area. Association rule mining will thus help in discovering such patterns.

Proposed System
Pre-processing the dataset —> Association Rule Mining —> Extracting interesting patterns from the rules obtained —> Validation of the rules

Dataset Used
The dataset for analysis has been obtained from Kaggle. The dataset contains Emergency 911 calls in Montgomery County located in the Commonwealth of Pennsylvania. The attributes chosen include: type of emergency, time stamp, township where the emergency has occurred.

The rows with missing values are eliminated. Numerical values have to be converted to categorical for Association Rule Mining. Therefore, time stamp is converted to day of the week, month and time of day(Morning, Afternoon, Evening, Night).

Association Rule Mining
Association rule learning is a rule-based machine learning method for discovering interesting relations between variables in large databases. It is intended to identify strong rules discovered in databases using some measures of interestingness(Support, Confidence).

Choosing a suitable threshold for support and confidence:
Set minimum support higher for a very small database and lower for very large databases. If you set minimum support higher for small database, it is to ensure that item sets are significant. If you set minimum support lower for large databases, it is to ensure that enough item sets are found.

Lift : If a rule had a lift of 1, it would imply that the probability of occurrence of the antecedent and that of the consequent are independent of each other. When two events are independent of each other, no rule can be drawn involving those two events. If the lift is > 1, that lets us know the degree to which those two occurrences are dependent on one another, and makes those rules potentially useful for predicting the consequent in future data sets. If a rule has higher confidence and lower lift, intuitively it would seem that it is more valuable because of its higher confidence — it seems more accurate (better supported). But accuracy of the rule can be misleading. The value of lift is that it considers both the confidence of the rule and the overall data set.

Results and Validation of Rules Obtained
Set 1:
{Afternoon,December} => {Traffic: VEHICLE ACCIDENT}
{December,Evening} => {Traffic: VEHICLE ACCIDENT}
{December,Morning} => {Traffic: VEHICLE ACCIDENT}
{December} => {Traffic: VEHICLE ACCIDENT}

These rules indicate that a lot of accidents are likely to occur in December.
In winter (December–January–February), temperatures are 44 °F (7 °C) and 28 °F (?2 °C). During winters, due to sheets of ice in spots throughout the county, the number of vehicle accidents are high. According to National Highway Traffic Safety Administration (NHTSA), during the Christmas period, many fatalities involving an alcohol-impaired driver occur. All these accidents would certainly be lower if breathalyzer use was more widespread.

Set 2:

These rules indicate that Norristown, Pottstown may not be safe at nights and in the evenings.
According to reports, although overall crime rates have been slowly and steadily declining for more than a decade, mirroring a national trend, Norristown remains stubbornly ahead of neighbouring Montgomery County townships in violent crimes. The reasons for this may be — a more dense and less affluent population; the scourge of drugs; the challenges presented by rapidly changing demographics.

Set 3:
{EMS: OVERDOSE,Sunday} => {Night}
{EMS: OVERDOSE,Saturday} => {Night}
{EMS: OVERDOSE,Friday} => {Night}

These rules indicate that drug overdose may be high during weekends at night probably because people are more likely to party and take drugs at that time. Another reason for drug overdose, when a physician stops prescribing opioids or those drugs become too expensive, a patient may switch to heroin, which is relatively cheap and easy to obtain. Heroin(drug) is an opioid — a substance that reduces the intensity of pain signals in the body.
Rules indicate that Lower Merion, Cheltenham, Norristown, Pottstown(towns in Pennsylvania) get significant number of drug overdose emergency calls.
The 2015 state-wide drug overdose death rate in Pennsylvania was 26 per 100,000 people, an increase from the reported 2014 rate of 21 per 100,000 people. According to the CDC, the national drug overdose death rate in 2014 (most recent available) was 14.7 per 100,000 people. According to reports, overdoses have drastically increased across Montgomery County over the past year. The county undergoes the worst overdose epidemic in its history, according to information provided by the District Attorney’s Office.

Set 4:
{EMS: CVA/STROKE} => {Morning}

Rule indicates that stroke is likely to occur in the morning.
Scientific research says that you are more likely to suffer a stroke in the early morning than any other time, and this increased risk is linked to the body’s natural rhythms.
Circadian rhythms ( The circadian rhythm, present in humans and most other animals, is generated by an internal clock that is synchronized to light-dark cycles and other cues in an organism’s environment.) seem to play a part in blood pressure, body temperature, and other body functions. During the early morning, when blood pressure is higher, the risk for stroke appears to increase.

Set 5:
{EMS: FEVER} => {Night}
{EMS: FEVER} => {Morning}
{EMS: FEVER} => {Evening}

The first rule has higher confidence than other two.
The reason for this pattern in rules may be due to this: Body temperature usually follows a built-in 24-hour cycle. Its lowest point is between 3 and 6 a.m., followed by a peak between 4 and 11 p.m.
Two major factors regulate this cycle:
The hypothalamus has its own 24-hour hormone-secretion pattern.
The things the body does during the day (heartbeat, muscle movements, breathing) involve a release of heat energy, causing your core body temperature to warm up as the day progresses.
This explains why your temperature increases toward the end of the day under normal conditions. However, this cycle still happens when you have a fever. The difference is that now, the temperature elevation is more obvious since you’re already starting from a higher temperature than normal.

Set 6:
{EMS: HEAT EXHAUSTION,Evening,Thursday} => {August}
{Afternoon,EMS: HEAT EXHAUSTION,Monday} => {July}
{EMS: HEAT EXHAUSTION,Evening,Monday} => {June}

Rules indicate that heat exhaustion is high in Abington in the months of August, June during the day.
Temperatures soar high during the day in summer (June, July, August) leading to heat exhaustions. Educating people to practice heat safety measures(Do not spend too much time in the hot sun, do outside work during early morning or late evening hours, wear lightweight, light coloured, loose fitting clothes, take frequent breaks in the shade, keep well hydrated.) will help reduce these emergencies.

Tools Used
R and RStudio
• arules package is required for association rule mining.
• arulesViz package is useful for visualising the results.

This project is useful for the emergency response team of every country.

Disclaimer: This content belongs to geeksforgeeks, source:

Project Idea | Get Me Through

Why this name?
The name of the project is just an exclamation to steer through the monotonous work, in today’s world of spreading automation technologies.

A Free, Offline, Real-Time, Open-source(MIT Licensed) web-app to assist organisers of any event in allowing only authorised/invited people using Face-Recognition Technology or QR Code.

It is made to automate the task of authenticating people and no longer need to check invitation cards, checking required apps installed(like in most College Fests) etc.

The project uses MaterializeCSS framework based on Google Material Design Guidelines.

The project is truly Offline and is built using the pre-trained dlib model which has 99.38% accuracy(adult people) in Label Faces in the Wild Dataset.

The person needs a leading browser(preferably Chrome) to use the web-app and UNIX based system MacOS or Linux to interact/use the project.
The User Interface of the Web App when opened on Google Chrome.


  • Node.js
  • MongoDB
  • Python3
  • C++11

The person has to feed the images of invited people in the app, store information in the database, and train the model before using on those images.
The user would have the option to choose to track the Incoming/Outgoing people. First, the person’s face is recognized using the camera and name displayed if his/her info is saved on the server. The name is shown in the red colour. The information of this person is then compared to the record searched in MongoDB database. If the information matches and the person is allowed the name is shown in green colour.
If the above method is not done successfully because of any reason then there is an additional method or fall-back method to be used i.e. QR Code. The person can show his QR Code in which his unique ID is stored which is then searched in the MongoDB database for authentication.
There are 3 layers of security.

  1. Face Recognition
  2. MongoDB Database information cross-verify
  3. Information cross-check physically

The front-end of the app also shows all the information of the person stored in the database. The person can be asked to confirm the confidential information stored in the database in case of some ambiguity.

Barack Obama has been recognized with the face and his data cross-checked with the information stored in the MongoDB database, thus shown in green.

Shubham Malik(me) has his face verified thus the name is shown but the information couldn’t be cross-checked with the database as no such record was saved thus red colour.

There is a small blue icon showing QR Code which is to be used to read the QR Code in case the person can’t be identified or may be misidentified(in the case of children) name would be shown as Unknown(if not identified). The user has to halt the app so that the information stored doesn’t get updated as per real-time data. Click on the QR Code button to scan the code. The user is notified if the QR Code is legit and if the person is authenticated or not. The user then has to resume the app after QR Code scanning is done, so that data can be updated once again in real-time.

When the person is leaving check the Out button to log his outgoing time. Helpful notifications are shown to the user like while authentication, some error occurs etc.
Authenticating people this way, for free, NO INTERNET, no API limit so it should be a breeze.

In the future data insights feature would be added for the data analysis using the chart, graphs etc.

This is a high-level model of how the app functions. The power of JavaScript and Python is combined in a single app. The command can be train or run.

All of this happens inside the computer so no internet is required.

Currently, only face recognition uses the algorithms detecting faces, finding the encoding, matching the encoding with the known encodings using euclidean distance (face_recogntion python package is used for that which have these functions written). Dlib model used is pre-trained so no external algorithms are applied as of now. As far as the data structure is concerned Numpy arrays are used to store the multi-dimensional encoding information of face.

Currently, it uses Linear search to find the required encoding within allowed error limit in O(N) time. In the future, I would try to use the Binary Search to pull it down to O(logN). But the data is multi-dimensional (around 150) dimensions so it would take time.


  • Visual Studio Code
  • Google Chrome Web Browser
  • MongoDB Database
  • RoboMongo

These are some of the use cases which I can see, though I have not used them in real world conditions myself.


This project would find its use at every place where authentication is required and still done manually. It includes College Fests, Events, Meetups, Corporate Functions, Parties etc.

Opportunity for Community

This project leverages the power of both Node.js and Python in a single app. It can be used for other purposes also. Popular libraries like Tensorflow, PyTorch which are for Python can be used in Node.js web-app to harness the power of Machine Learning in an app by creating a model for your use case and using it without sending data to third party companies with API limits. It can be used for Online learning / Offline Learning the model with your data to improve accuracy with time and complete privacy. Language should no longer be a barrier to included ML in your app. You don’t need to know the complete Python development stack to use Python ML libraries in your Node.js web-app. Node is here to live :).

Educational Initiative

It can be used by educational institutions to teach the students to see/experience the power of Machine Learning, Deep Learning with an interactive Graphical User Interface(GUI). It would encourage them to leverage this project to build something to help other people.

Project Link

Experience it by running it on your machine and contact me for hugs or bugs!


  • One of a kind project, maybe only of its kind. No backup codes are there on the internet to consult if something goes wrong. Open-ended project.
  • Stackoverflow community closed/downvoted similar type of questions “face recognition in Node.js”. It is a torch-bearer for all of those.
  • Before this project: this(possible with 3rd party APIs), this(closed by community).
  • After this project: this(relevant solution, my first upvote), this(answer edited to include this project).


I googled a lot. I used StackOverflow maybe around 50+ times, googled around 100+ times. I read this post in initial stages to understand. After that, I was on my own along with Google Search. A lot more is in the pipeline. Hint: Speech support, let your imaginations fly.


  • Got offers from 4 online publications to publish my post (where I shared my experience building this project, talking about how it works, why I did it, how I did it, what it means for me, whom it is for…).
  • Published in Hacker Noon. Link to article
  • 75+ stars, 10+ forks on GitHub
  • Built in a few weeks. Open-Sourced on July 23, 2017. MIT Licensed.
  • A great learning experience which I can’t get with already done projects.

I came to know about ProGeek when it was launched. In summer vacations some incident happened with me that lead to this project. I thought it might be a good idea to have a working prototype of the project along with the idea.

Disclaimer: This content belongs to geeksforgeeks, source:

Project Idea | Attendance System Using Smart Card

1. Project Title:
Smart Attendance System

2. Introduction:

The current attendance system in most of the educational institutions is paper based, wherein the students are expected to sign an attendance sheet. This system has several disadvantages like:
(a) The students can mark attendance of their fellow classmates without being caught.
(b) Punctuality of individuals cannot be recorded
(c) Time consuming
(d) It can be lost easily

3. Conceptual framework:

The smart attendance will help to mark the attendance of the students attending a particular lecture.
The following is the procedure to mark the attendance using the smart cards:
i) Every student of the institution is issued (by the institution) a unique smart card that he/she must always carry.
ii) The students, at the lecture hall entry, are expected to insert the smart card in the Card Acceptance Machine, which will record the student entering the lecture hall.
iii) The communication used is ‘Active-Passive Peer Interaction’ wherein the Active component is installed on the entry gate constantly generates an electromagnetic field, which, in turn, creates a small current in the chip inside the card/token whenever it comes into range – hence the chips do not need power of their own. The moment current flows, the chip and the reading component on the gate can interact with each other.
iv) An encryption key is generated each time an interaction takes place to prevent other Smart Card readers from accessing data. This is done to make sure that student attends the stipulated lecture only. Every Lecture Hall has what we call the ‘Lecture Hall Code’. The key is encrypted with lecture hall code on the card at the entry gate and again decrypted at the exit gate.
v) To avoid proxy attendance, a people counter is also placed at the entry of the lecture hall. The people counter records the footfall to count the number of people entering the lecture hall.
vi) The exit from the lecture hall is also marked by the smart card insertion into the CAD, just to ensure the correctness of the recorded data and decrypt it.
vii) After decryption, the student’s attendance for that lecture is increased by 1 in the institution’s database.

4. Tools Used:

Smart Card: A smart card, chip card, or integrated circuit card (ICC) is any pocket-sized card that has embedded integrated circuits.[1] Smart cards are made of plastic, generally polyvinyl chloride, but sometimes polyethylene terephthalate based polyesters, acrylonitrile butadiene styrene or polycarbonate.
Smart cards can be either contact or contact less smart card. Smart cards can provide personal identification, authentication, data storage, and application processing.

People Counter: A people counter is an electronic device that is used to measure the number of people traversing a certain passage or entrance.

Footfall: Footfall measures the number of people who enter a shop or business in a particular period of time.

Smart Card Reader: Smart Card Readers are also known as card programmers (because they can write to a card), card terminals, card acceptance device (CAD), or an interface device (IFD).
When the smart card and the card reader come in contact, each identifies itself to the other by sending and receiving information. If the messages exchanged do not match, no further processing takes place. So, unlike ordinary bank cards, smart cards can defend themselves against unauthorized users and uses in innovative security measures.
Card Contact Types refers to how the contact between a card reader and a smart card is physically made. There are two primary types of contact: landing contact and friction contact (also known as sliding or wiping). For card readers featuring friction contact, the contact part is fixed. The contact wipes on the card surface and the chip when a card is inserted. For card readers featuring the landing type, the contact part is movable. The contact “lands” on the chip after a card is wholly inserted. In general, card readers of the landing type provide better protection to the card than that of the friction type.

5. Application:

It is used for marking attendance in educational institutions where attendance management is itself a time consuming and cumbersome process. It will make the attendance system smooth and reliable.

Disclaimer: This content belongs to geeksforgeeks, source:

div() function in C++

Given a numerator and denominator, we have to find their quotient and remainder without using the modulo or division operator. div() function allows us to do the same task easily and efficiently.

div() function : Returns the integral quotient and remainder of the division of numer by denom ( numer/denom ) as a structure of type div_t, ldiv_t or lldiv_t, which has two members: quot and rem.

div_t div(int numerator, int denominator);
ldiv_t div(long numerator, long denominator);
lldiv_t div(long long numerator, long long denominator);

When we use div() function, it returns a structure which contains the quotient and remainder of the parameters. The first parameter passed in a div() function is taken as numerator and the 2nd parameter is taken as denominator.
For int values, the structure returned is div_t. This structure looks like this:

typedef struct
    int quot; /* Quotient.  */
    int rem; /* Remainder.  */
} div_t;

Similarly, for long values, structure ldiv_t is returned and for long long values, structure lldiv_t is returned.

struct ldiv_t {
    long quot;
    long rem;
struct lldiv_t {
    long long quot;
    long long rem;

Where is it useful ?

The question is, since we have both % and / operators, why should we use div() function?. Well, in a program where we require both – quotient and remainder, using div() function would be the best choice as it calculates both the values for you at once, moreover, it requires less time as compared to using % and / functions one by one.
While using div() function, the difference for the % operator is that, % operator may return a negative value, but div() always returns a non negative value. So, div() function can be efficiently used according to one’s requirement.

What happens when the denominator is 0?

If any one of the part of this function, i.e. the remainder or the quotient cannot be represented or cannot find a result, then the whole structure shows an undefined behaviour .
NOTE : While using div() function, remember to include cstdlib.h library in your program.

Input : div(40, 5)
Output :quot = 8 rem = 0

Input :div(53, 8)
Output :quot = 6 rem = 5


// CPP program to illustrate
// div() function
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
    div_t result1 = div(100, 6);
    cout << "Quotient of 100/6 = " << result1.quot << endl;
    cout << "Remainder of 100/6 = " << result1.rem << endl;
    ldiv_t result2 = div(19237012L,251L);
    cout << "Quotient of 19237012L/251L = " << result2.quot << endl;
    cout << "Remainder of 19237012L/251L = " << result2.rem << endl;
    return 0;


Quotient of 100/6 = 16
Remainder of 100/6 = 4
Quotient of 19237012L/251L = 76641
Remainder of 19237012L/251L = 121

Disclaimer: This content belongs to geeksforgeeks, source: