Thursday, December 14, 2017

Hello world in Microsoft Quantum Computing #qsharp #quantum

This week Microsoft Quantum Computing research team released their first quantum development kit (free preview release).

Steps to play around Quantum!

a) You need Windows 64 bit
b) Visual Studio
c) Download quantum development kit, and install it (download link at the end)
d) Download the quantum library's & samples from git hub(download link at the end)
e) Compile and run any one of the samples.

I have compiled and ran the TeleportationSample project:



Link to github MS quantum libs and code: https://github.com/Microsoft/Quantum.git


Tuesday, November 28, 2017

Fundamentals of Wireless Communication 5G

 

What is wireless communication?

Data or information transferred from point A to B without any wire or dedicated cables is called wireless communication.

Mother Nature is doing wireless communication for millions of years*.  Let me give few real examples of how nature does wireless communication:
   a)   When you make an eye contact with other person, the light bouncing off from your body will enter into other person’s eyes, then inside their eyes millions of light sensitive rods and cones or photoreceptor neuron receives and transfers it to brain, where your actual picture is drawn.
   
   b)   When you are talking to other person, vocal cord\folds in your body, generates pressure in the air, that converted into sound waves and enters into the ears, then ear drum vibrates and converts into electrical signal then passed it to brain and different part of brain processes it.

In both the scenario, main point is humans are doing wireless communication unconsciously.

If you are one of the smart people, you might have asked this question, ‘how come I can hear and understand multiple sounds at a time, like car honking, hearing voices people passing by, etc. at the same time’ trick is all these sounds have different hertz or frequency of sound waves. So ear drum vibrates differently for different sounds waves’ frequency.

That’s it, wireless communication in simple sentences:

A gentleman says hello to a lady, his vocal cord generates a sound wave and her ear drum receives sound waves and processes it.

A transmitter antenna, encodes information and  generates radio waves by vibrating electrons, then radio waves travels at the speed of light , when it its receiver antenna, information will be decoded”.

Compare above both the sentences lot of similarities, isn’t it?  When you are stuck in traffic jam, you turn on the radio station. It follows same principle transmitter antenna broadcast and a receiver antenna in your car receives and plays it.
The very key point here is at what hertz the radio waves are broad casted. Don’t worry hertz is simple words for a second how many time it rotates or vibrates. Basically sender and receiver should know the language which they are talking about.

Let’s get little bit technical:

Electricity, Automation, Wireless communication … all these things boils down to “Electromagnetic Spectrum” after understanding this spectrum led to revolution in wireless communication.

There are two types of wireless communication, analog and digital. Analog, all nature communication is analog which is continuous in time and value, ex: sun light. Digital is discrete in both time and value.

After the dawn of transistors and integrated circuits, it revolutionized the wireless communication, after this point of time, wireless means mostly digital wireless.

Below flow path explains steps inside modern wireless communication system:
Analog Signal -> ADC -> Signal Processing -> DAC -> Analog Signal

What is this 1G, 2G, 3G, 4G and now 5G?

In simple words, A telecom company called X, which has setup of lot of cell sites or antennas, and users who want to pay for wireless service like talk or text, subscribes to X’s wireless services. With this setup is in place, here is all what that Gs does as follow:
1G (first generation): user can send and receive couple kb bytes – approx.
4G, user can send and receive few Megabytes – approx.
5G, user can send and receive few Giga bytes – approx.

So basically in 1G user can send and receive just text msg’s but in 5G user can send and receive HD videos, high res pics etc.


PS: I am trying to simplify the technology into simple English words and approximating the measurement or units. This is not for any references, just to create the abstraction of complex ideas into simple real life examples and intention is to reach technology to wider audiences.

Monday, November 6, 2017

Basic statistics/probability formulas using c#

Data science / Machine learning is all about statistics/probability, graphs and linear algebra.

Here are few basics stats functions in c# :

static decimal GetMean(decimal[] inputs)

{

    int count = inputs.Length;

    decimal avg = 0;

    for (int n = 0; n < count; n++)

    {

        avg += inputs[n];

    }

    return Math.Round(avg / count, 1);

}


static decimal GetMedian(int[] inputs)

{

    Array.Sort(inputs);

    int count = 0;


    if ((inputs.Length % 2) == 1)

    {

        count = (inputs.Length - 1) / 2;

        return inputs[count];

    }

    else

    {

        count = inputs.Length / 2;

        decimal a = inputs[count - 1];

        decimal b = inputs[count];

        return Math.Round((a + b) / 2, 1);

    }

}

static decimal GetMode(decimal[] inputs)

{

    //you can substitute below C# lambda express to hasttable technique

    return inputs.GroupBy(n => n).

        OrderByDescending(g => g.Count()).

        Select(g => g.Key).FirstOrDefault();

}


static decimal GetWeightedAvg(decimal[] avg, decimal[] weight)

{

    int count = avg.Length;

    decimal w = 0;

    decimal aAndW = 0;


    for (int n = 0; n < count; n++)

    {

      aAndW +=  avg[n] * weight[n];

      w += weight[n];

    }

    return  Math.Round( (aAndW / w), 1); 

}



static  double GetStandardDeviation(int[] inputs)

{
    int count = inputs.Length;
    int avg = 0; int sum = 0;

    for (int n = 0; n < count; n++)

    {

        sum += inputs[n];

    }

    avg = sum / count; //getting avg or mean

    int preSd = 0;

    for (int n = 0; n < count; n++)

    {

        int tmp = Math.Abs( ((inputs[n] - avg) )); //replace abs to sub and sub from higher to lower

        preSd += tmp * tmp ; 

    }

   return Math.Sqrt( preSd / count);


}

Tuesday, October 10, 2017

opencv c++ visual studio 2017 configuration

In this article, download software's, configure visual studio for opencv and build hello world opencv app using c++ in visual studio 2017.

First download required softwares:

a) Download latest from opencv 3.3
b) Install visual studio 2017 with c++ packages

Then, lets setup global environment variables for opencv build:

a) Goto My computer -> Right click -> Properties
b) Click "Advance System Settings" -> click "Environment Variables"
c) Click "New" from System variables grid
d) Enter "Variable name:" = OPENCV_DIR  & "Variable value:" = C:\Program Files\opencv\build\ or opencv build path
e) Select Variable 'Path' from System variables grid
f) Edit append ";%OPENCV_DIR%\x64\vc14\bin" ; is delimiter to earlier paths

Last, we should configure Visual studio 2017 opencv project properties:

a) create a new c++ console project in visual studio 2017
b) click project properties
c) Goto -> Configuration Properties->C/C++->General->Additional Include Directories-> set "C:\Program Files\opencv\build\include"
 d)Goto -> Configuration Properties->Linker->General->Additional Library Directories-> set  "C:\Program Files\opencv\build\x64\vc14\lib"


e)Goto -> Configuration Properties->Linker->Input->Additional Dependencies-> add "opencv_world330.lib" "opencv_world330d.lib"










Woot woot , thats it, you are all set to develop amazing image processing app.

Here is the Test code:

#include "stdafx.h"
#include opencv2/core/core.hpp
#include opencv2/highgui/highgui.hpp
#include iostream

using namespace cv;
using namespace std;

int main()
{
Mat image;
image = imread("c:\\mahesh\\pics 110.jpg", IMREAD_COLOR); // Read the file
namedWindow("Display window", WINDOW_AUTOSIZE); // Create a window for display.
imshow("Display window", image); // Show our image inside it.

waitKey(0); // Wait for a keystroke in the window
    return 0;
}

Monday, August 28, 2017

Digital Image Processing in a minute!

Digital Image Processing

 

What is DIP?

DIP means, processing digital images by means of a digital computer using math’s\signal processing algorithms. Digital image (jpg, png, gif, video’s) is nothing but a two dimensional array of pixels, basically a grid which contains RGB values.  Images can be generated by using Electromagnetic spectrum like visible light, X-rays, Gamma rays and also other waves like Acoustic (ultrasound).

 

Why DIP?

Simple answer, Automation & to Sense the information out of it.
a)   You want to search your baby\most cherished moment photos in the middle of hundreds of photos in your laptop instantly.
b)   FBI wants to track a fugitive criminal, they can scan automatically scan his photo against CCTVs across airport, streets …
c)    If Robots want to help humans in automation, it has learn to recognize humans, objects, animals etc.
d)   If you want to board airplane by just showing your face, no more boarding pass. DIP scans your face, processes and authenticates you.
e)   Instagram, Snapchat all making money because of DIP – filters
f)    Robots, can quickly take the inventory count for you.
The list goes on…

Processes inside DIP:


Inside Image processing series of process goes on, you can transform images from grayscale to color, apply filters, enhance the image color, delete a part of the images etc. They are as follow:
  1. Image Grabbing or acquisition
  2. Image Preprocessing
  3. Image Enhancement
  4. Image Compression
  5. Image Segmentation
  6. Image Representation and feature extraction
  7. Image Recognition and interpretation.

Image Compression, is a technique to compress and decompress the images\videos, may be lossy or lossless.
Image segmentation is the process of subdividing the given image into its constituent parts or objects. Basically identifying the edges in the images.
Image Restoration is a process that attempts to reconstruct or recover an image that has been degraded by using a priori knowledge of the degradation phenomenon.


Conclusion:


Image processing is part of parcel of modern human life. It started slowly with image transfer from London to New York in 1920’s, later with the advancement of computers, field of image processing is growing exponentially.
Image processing can solve lot of problems, improve human living standards, automate routine stuffs, etc.

References:


Digital Image Processing (3rd Edition) by Rafael C. Gonzalez, Richard E. Woods



Sunday, July 23, 2017

How to intercept HTTP request? asp.net core, IHTTPModule, middleware

Asp.net core is a brand new, open source and cross platform framework for building modern internet applications. Unlike its predecessor Asp.net core is lightweight, robust, fast (Kestrel Web server), and cloud ready.

Asp.net core is designed to integrate seamlessly with varieties of client side frameworks like AngularJS, ReactJS, KnockoutJS

Modern internet applications communication language is HTTP. So you will came across many scenarios to intercept client’s HTTP request and process it. I will explain a real scenario, “As part of application authentication, you have to make sure user\company employee must be logged into their corporate network/global login before accessing application.”

In Asp.net core Middleware’s replaced IHTTPModule and IHTTPHandler.  Middleware is an application pipeline to handle request and response .

I will quickly walk through you the code snippets:
         First create two class as below
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication5.Middleware
{
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
         
            string companyAuthCookie = ApiHelper.GetConfigValue("companyAuthCookie");
            bool securityEnabled = bool.Parse(ApiHelper.GetConfigValue("SecurityEnabled"));

            if (securityEnabled)
            {
                var header = context.Request.Headers;
                var cookies = context.Request.Cookies;

                if (cookies.ContainsKey(companyAuthCookie))
                {
                    //allow other middle to process http request
                    await _next.Invoke(context);
                }
                else
                {
                    //short circuit or terminate http process request because user haven't logged in
                    context.Response.Redirect(ApiHelper.GetConfigValue("RedirectUrl"));
                }
            }
            else
            {
                await _next.Invoke(context);
            }
        }
    }

    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseCSPMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomMiddleware>();
        }
    }
}

Then goto Startup class (Startup.cs)

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

               //in asp.net core order is important. Make sure you call it in early stage
            app.UseCSPMiddleware();

            app.UseMvc();
        }

That’s it, you have created code to intercept http request and process it inside asp.net core.

Reference: 

Friday, July 7, 2017

Quotes by Mahesh

"Give me Data, I will give you the past or future" mcsj

"Gratitude is very rare, not Diamonds." mcsj

"Human life is a  precious gift,  ask plants, birds and animals" mcsj

"Once you understand a System thoroughly, then you can take control of it" mcsj

"Its very difficult to impress Aries" mcsj

"Where there is Quality, There is Demand" mcsj

"Where there is Healthy Competition, there is Creativity/Invention/Innovation" mcsj

"Best investment for a Nation, Family, Individual is on Education" mcsj

"Where there is no principles, structure, and order, there is no growth." mcsj

"A star gets birth, only to shine bright, remember you are a STAR " mcsj

"Your behavior decides, your education and social background" mcsj

"To understand a system, you have two choice, start all over, spend 100/1000 years on finding patterns or read books" mcsj

"Inside Mathematics, at any point of time you will be either doing JUST addition or subtraction" mcsj

"To solve issues or enhance or improve a system, first you have to understand the System" mcsj

"What is more important is whether you LIKE it or not, you should never worry about the price or anything else, life is short" mcsj

"What matter's is what do you do, not where you are" mcsj

"The only way to pierce into the minds of genius is by reading their book" mcsj

"Benefits of travel, it will make you wise, entrepreneur, humble,  knowledge... " mcsj

"There are two kinds of people in the world, one who writes book, another who reads it" mcsj

"Queen must wait till she finds a guy with character\behavior of  a King" mcsj

"One of the toughest task is, to communicate/exchange ideas/thoughts with people, without hurting their feelings" mcsj

"If you think its there, it is there, if no, it is not there, everything boils down to what you think" mcsj

"Greatest tips/tricks for any startup or work is, 'you just start working on it' " mcsj

"For  certain category/group of kids, teach them basics, they will teach you advanced" mcsj

"The only way to travel fastest in the past is by reading a book" mcsj


"In theory with energy (e=mc2) we can travel, back into past or future, but with data  practically we   can go back into past or future" mcsj

"Excellent communicator or people manager is one who knows that, every individuals activity\personality\character is determined by the data inside their Brain" mcsj

To those who care
for people and mankind


Sunday, June 18, 2017

Wednesday, May 10, 2017

Computer Vision API - Microsoft Cognitive Services

MS Computer Vision API is powerful REST API’s or Web services, which takes image as input, processes it and return back the image analysis in JSON or in structured format. For ex: API identifies for any adult content, does recognizes texts/character (OCR), face recognition etc.

MS Computer Vision API, is based on the hundreds of image processing algorithms which internally uses lots of complex math’s to process and analyze the images.

Microsoft, bundled image processing API’s into Computer Vision API and hooked up it with her Cloud platform. So basically you have to pay for every single API call. You might be wondering how and what scenario you can consume it.

Here is a typical scenario where you can use Computer Vision API:

You have a camera, it’s an IoT device hooked up with internet. You have set up that in front of your home / apt / office, as soon as someone pops in and knocks the door. Your camera/IoT device takes photo of her/his and sends it to MS Azure\ cloud, it’s their you make call to MS computer vision api to process and get the result, from that result you analyze and decide to open the door or not. Like this you can use it in any scenario where you want to process image.

Following are just few things you can do on images with CV API’s: Tagging, Categorizing, Identifying, OCR, Face recognition, generate thumbnails and lot more. Obviously it can process video (video is an illusion, when you display a set of frames /images like 24 images or more in a second, eye processes it as movie)

Simple Client program to invoke computer vision api:






Monday, April 24, 2017

Uni & Multi Culture

More varieties of flowers, more beautiful  the garden.

Thursday, April 13, 2017

Asp.net Core MVC CORS preflight issue REST api

Browser -> CORS -> IIS -> Kestrel Asp.net Core MVC REST apis

Project:
Silverlight migration project into HTML5/AngularJS/Asp.net Core MVC.

Problem:
CORS preflight (http options) request was throwing 403 forbidden error.

Story & Solution:

I did hosted Asp.net core REST apis on IIS, initially UI\AngularJS developers were consuming basic GET api's everything was going smooth.
Next, when they tried to consume my http POST apis, panic button pressed its not working.

Unlike WFC, xml web services, web apis, Asp.Net Core MVC has brand new web server called 'Kestrel' which is faster and modern compared to IIS. But Kestrel is not matured enough to put behind internet so we have to do reverse proxy using IIS, basically IIS forwards http calls to kestrel and vice versa. Story doesn't end their to make complicated, when angularjs or client makes calls from modern browsers, it will make a preflight call to web server to make sure request service is available and client has access, this is for security purpose according W3C CORS standard. So browser make a preflight http OPTIONS request, but most web server doesn't enable or accept http OPTIONS, PUT, Delete requests, admin disables it by default Then developer have to scratch his head and trace where its going wrong.

Solutions:

So, when you stuck, pls go through the following areas, which might help you to solve the issue.

a) Enable http log at IIS level, go through the logs.

b) Enable logging at asp.net core mvc api.

c) Use Fiddler or REST api client like postman(beware unlike browser postman doesn't make preflight request, it works here but from browser it fails)

d) In web config allow required verbs

e) Verify url scan config.

f) Verify and make sure all the required configs are enabled system32\inetserv\config applicationhost root config file for IIS.


Pls make sure changes you do must be compliance towards company cyber security policies.

PS: above tips works well other web servers; apache, nginx ...

Tuesday, March 28, 2017

What is HTTP2, HTTP/2, SPDY?


History:

HTTP – hypertext transfer protocol. It’s an Application protocol to exchange hypertext or hypermedia over World Wide Web. Hyper text\media means, a HTML page is nothing but a text document contains links to other documents or media. So user can open a web page and traverse to other pages and come back.
The term hypertext was coined by Ted Nelson in 1965 for his xanadu project.
But actual credit goes to Tim Berners Lee and his team at CERN. In 1989, He proposed a system to track tons information\data created by LHC. Basically, Tim wanted to create a system to link documents and access over network.

Evolution of HTTP:

HTTP/0.9

1989. Simplest, it just had a single method GET, no headers. It supported just to fetch text documents, no images.

HTTP/1.0

1995. By this time http proven its potential. RFC 1945 introduced, headers, response codes, errors …

HTTP/1.1

1996 to 2010 (approx.) 1.1 has six RFCs, addressing issues of message, cache, pipeline, semantics …

SPDY

2009, google proposed alternative to HTTP they called it SPDY. It contains features like multiplexing, framing, header compression, etc.

HTTP/2

May 14, 2015. SPDY was the driving force of HTTP/2. RFC 7540 made official of HTTP/2
Data compression of headers, Multiplex, Pipelining of requests, Server push, Priority requests…

Why HTTP2?


To know answer for question why http2, we have to understand evolution of http. It started with simple GET, serving simple html/text pages to present serving a text file to ultra hd video over internet. When a user types and enter a url on a browser, behind the scene a series of action will be performed before user sees what they want. Briefly here is what happens: Resolve Hostname (DNS), Open TCP connection, Handshake, Get Data …
In simple word answer to above question is “Latency”. How much time it takes to get data from server to client. Previous versions of http were struggling to handle modern, high volume traffics. HTTP/2 will address drawbacks of earlier versions. So HTTP/2 enhances existing http features and speed up process to get by implementing clever techniques.

Most of the modern browsers and web servers support http/2 features. Say thanks to google and IETF.