Friday, August 24, 2018

Image Classifier Using Machine Learning


ImageClassifier


⚙️ A Convolutional Neural Network (CNN) based Image Classifier Using Machine Learning.


Checkout my GitHub repository for this.

Problem Statement


The problem statement was a part of TECHGIG's hackathon held from 18th July to 2nd Sepember 2018. The hackathon Springer Nature Pune Hack Day: Decoding Scientific Content – Hosted by Springer Nature Pune on decoding scientific content, is a challenge designed to inspire creative and dynamic technology professionals to put their skills to the test. Spread over four weeks, Springer Nature Pune Hack Day: DSC is a platform that allows aspiring tech experts to display their technical prowess in new technologies including ML, NLP, AI.

Every publisher aspires to automate the identification, classification, enhancing, etc. of images using computer vision, which has a large variety of practical applications. Since this task of recognizing a visual concept is relatively trivial for a human to perform and is worth considering the challenges involved are from the perspective of a computer vision model. This problem statement talks about the need to automate the identification of the images as color or grey, which would help the publisher in decision making.

Background Information

The manuscripts submitted by authors have many images inside it. These images can be either colour or grey or both. As part of the business services, the author submitted images will be processed by the publisher before publication. The processing of images differs for color and grey scale images. The identification of this helps to further automate their processing.

Use Case Description - What we have tried to build


  1. The Image Colourfulness Identification system
  2. The system to identify whether the image is grey or colour (with good sensitivity)
  3. Use Cases:
    • Use Case #1: Verify whether the image is grey or colour along with the percentage of confidence
    • Use Case #2: Must identify an image is colour even if the respective image has a small, clear and distinct colour information on it
    • Use Case #3: Must identify an image is grey even if the respective image has a very extremely small degree of colour artefacts in it (not noticeable visually but will/may be computationally)
  4. It automates the identification of the images as colour or grey, which would help the publisher in decision making

Problem Being Solved


  1. Avoid the manual verification of the images as colour or grey
  2. Fully automate the current partial automated process to identify images as colour or grey
  3. Reduce the probability of image misclassification
  4. Reduce the additional cost that an author has to bear due to faulty processing of images
  5. Avoid an additional manual visual checking of each image which would also save the time
  6. Help the publisher in decision making
  7. Help to further automate publishers processing
  8. Classify images with good percentage of confidence

Technology/Tool/Cloud Stack


  • Machine Learning, Deep Learning
  • Convolutional Neural Network (CNN)
  • TensorFlow
  • Python
  • OpenCV
  • Softmax
  • Shape function

Hardware Specifications


  • CPUs
  • GPUs

Solution Approach and Architecture

Demonstration Video/Prototype Demo



Why This Solution Should be Considered


  • Platform Independent - Runs on verity of platforms - from desktops to clusters of servers to mobile and edge devices
  • Easy deployment - can run on multiple CPUs, GPUs and TPUs (Tensor processing unit)
  • System identifies an image is colour or grey along with confidence factor
  • System identifies grey images with extremely small colour artefacts also as grey with good percentage of confidence
  • System identifies even images with small, distinct/clear colour information on it as colour with good percentage of confidence
  • Solution is based on Training Data, Validation Data and Test Data

Challenges Faced


  • Selecting the solution approach
  • Deciding the solution model which fits the requirements

Possible Improvements


  • Select better network design to get more accurate output\predictions
  • Improve Predictions
  • Improve Optimizations

References

Micro-Lending Platform using Blockchain Technology


Micro-Lending Platform using Blockchain Technology

⚙️ Decentralized, Democratized, Transparent Micro-Lending platform based on Blockchain

Checkout my GitHub repository for this.

Problem Statement

The problem statement was a part of TECHGIG's coding contest - Code Gladiators 2018 held from 20th March to 15th May. The problem statement as below was for Blockchain technology.

Develop a truly Decentralized, Democratized, Transparent Micro-Lending platform based on Block chain. This platform would have to do the following:

  1. Free market decision of interest rates which increases competition amongst lenders. 
  2. All Transactions should be visible transparently to everyone. 
  3. No middleman should be required just the borrower and lender. 
  4. Anyone having access to this platform should be able to borrow from remotest of village. 
  5. Platform should not provide limits on finance and duration of finance. 
  6. Based on past transactions it should build the reputations of borrowers and visible to lenders. 

Abstract

Let us think about financial inclusion and digital inclusion and to provide financial lending services to people from low income groups who may be dire need of financial support for their livelihood. A typical example is that of a short-term repeat borrower in a city such as a trader who borrows money from a lender, buys vegetables from one or more farmers in the morning, sells the vegetables for a higher margin profit, and then returns the money to the lender at the end of the day. Borrowers could also borrow for longer durations such as a farmer that needs money to buy seeds and fertilizers to grow crops in a village.

Platform Description


  1. The solution built upon Ethereum Smart Contracts 
  2. This Peer-To-Peer model – no need of any middleman to operate the system 
  3. Provides the financial lending services to the small group of borrowers 
  4. Provides ability to use existing networks to help build and verify borrower identities 
  5. Loans are facilitated through two models - one can be used at a time: 
  6. Model #1: Open Auction Model 
  7. Model #2: Random Number Model – With flat interest rate (not more than 2%) 
  8. Flexibility of choosing suitable model makes this platform unique 

Problem Being Solved


  1. Eliminates the lack of Trust and Transparency 
  2. Eliminates the existence of middleman between borrowers and lenders 
  3. Decision making freedom resides with borrowers and lenders 
  4. No mortgage/collaterals required while giving out loans to borrowers 
  5. Decentralised System 
  6. Security - The system allows borrowers to conduct deals directly which avoids the risk 
  7. Provides flexibility of choosing suitable solution model as per need/convenience 
  8. Enables crowd-sourcing anti-corruption measures 

Technology/Tool/Cloud Stack


  • Ethereum smart contracts – Solidity 
  • Ropsten TestNet 
  • Truffle framework 
  • MetaMask
  • Remix IDE 

Steps to Compile


  • truffle init 
  • truffle.cmd compile 
  • truffle.cmd test 
  • npm install truffle-hdwallet-provider 
  • truffle.cmd migrate --network ropsten
  • Use 'remix-ide' command to test the contracts 

Platform Architecture – Open Auction

The Open Auction Approach - Trust And Transparency



  • This is the process where certain people (e.g. from village) forms a group, we call it as a network. 
  • Everyone decides a certain amount which is to be paid by everyone in the number of installments which is equal to the member count in the network. 
  • The installment amount is fixed which is predetermined by the group. 
  • The group hosts the series of open auction process on each month with a pre-scheduled date. Each group member has to deposit their installments monthly. 
  • This open auction process continues for the number of consecutive months which is equal to the total number of members minus one (n-1) in the group/network. 
  • In the auction process, each member can request for the loan from the network. 
  • If the loan request is from only the single person, then the loan amount is to be disbursed by the system without any interest rate. 
  • But, if the loan request is from more than one member of the group/network, then the one of them can take the loan by bidding the maximum interest rate amount. 
  • The loan amount is fixed which is equal to the sum of all individual installments in one complete cycle of this process. 
  • Once the loan is disbursed, the borrower is not allowed to take the loan again from the network in that cycle. 
  • The system processes the loan to the winner who has put the bid with the maximum interest rate or to the eligible person who only has requested the loan amount. 
  • The amount of interest will be pre-deducted from the loan amount itself and it will get equally distributed to each member of the network in that month itself. 
  • The loan borrowers benefits from plenty of time to make profit from their funded business to arrange any dues and/or the installments to be paid in the complete cycle. 
  • To avoid the people who are seeking this as an investment opportunity, the interest amount from the further installments(n-x) will not get distributed to the last x members of the network who are yet to take the loan from the system. 
  • Instead, the interest amount will only get distributed to the remaining members of the group/network. This way, everyone in the network will get benefited equally during the cycle of installments. 
  • The x factor is pre-determined by network and every member should agree to this decision. 
  • The new member is allowed to join/leave the group only after completion of the current cycle. 

e.g. 12 people come to form their own network. Everyone decides to deposit 10000/- as a monthly installments for 12 months. so, everyone is contributing their own amount equal to 120000/- in one complete cycle. Everybody is eligible to get 120000/- as a loan from the network once in the complete cycle starting from the first open auction. Everyone decides 4 as a x factor in the system. That means, in the last 4 installment cycles, whatever the interest rate that network earns from the auction process, it will only get distributed to the remaining people in the network those have already taken the loan. Suppose there are 3 eligible people who are requesting for the loan. then they have to win the loan amount by bidding it with maximum interest rate that they can afford. Consider a case where one has requested a loan by bidding the maximum interest rate equal to 5%. The system will disburse the loan amount (e.g. 120000 - 5% of interest) to the borrower who has won the loan request. The system will distribute the earned interest amount from this auction process depending upon the x factor and the number of current installments in the cycle completed.

Platform Architecture – Random Number

The Random Number Approach - Trust And Transparency





  • This approach is similar to the Open Auction Approach but with following differences. 
  • Instead of requesting for the loan, it gets distributed to one of the random member in the network. 
  • On every months scheduled date, the system generates the random number out of the number from the number = (total members in the network - # of people got the loan earlier in current cycle). 
  • Additional to installment amount, everyone has to pay a pre-defined flat interest amount (e.g. 2%) to the network. 
  • The collected interest amount will then be redistributed to the people in the network who has not yet got the chance to take the loan in current cycle. 
  • This way, it will benefit to all in the network. 
  • In case, if the person who has got the change to take the loan, but he/she doesn't want the loan to be taken at that time, he/she can offer the loan to the member in the network who has not yet got the chance to take it. 

Advantages


  • Increases competition 
  • Eliminates collusion risks almost completely 
  • More secure 
  • Increases transparency significantly 
  • Enables crowd-sourcing anti-corruption measures 
  • Increases trust among all the stakeholders 

Disadvantages


  • One can't leave the network in-between 
  • There is no provision of restructuring the installment amount/period if one wants to join/leave the network in-between. 

Demonstration Video/Prototype Demo



Challenges Faced


  • Deciding the solution model which fits the requirements 

Possible Improvements


  • Maintain Borrower’s/Lender’s Identity - e.g. linking Aadhar card to their digital identity 
  • A simple User Interface is required 
  • Improve Scalability – Can be scaled by allowing it to reach the greatest number of people around the world 
  • Extra features can be added e.g. allow one to join/leave the network in-between the cycle 
  • Provisioning reconstruction of instalment amount/period if one wants to join/leave the network in-between

Thursday, June 23, 2016

Create Your Own Web Based Music Player


Web Based Music Player



Host your own web based music player for FREE !

Here, just as an example, I walk you through the usage of already developed Last.fm (The popular music content provider) web based client application and its deployment on one of the cloud platform. In case you are developing a web based music player using Last.fm as a content provider, you can deploy it onto your existing website(s) or you may want to place it onto your personal blog site.


Last.fm


Last.fm is a music website which can serve as an online music database provider which might not provide full free access to the music contents. There are other online music content providers that are largely available for free of charge e.g. vTunner, FreeDB, etc. In order to make your player free, you need to opt for any of such free music content provider.

The idea can be anything like to create the web based music player with rich UI contents (requires some impressing UI designing skills) which can allow us to browse and play the music contents in the below categories.

Music tracks categorized by:
Artist
Album
Track
Playlist
Favorites
Queue

Internet Radio's categorized by:
Genre
Country
Language
Favorites


The original client application

Here is the original web based client application for Last.fm. This application is built using HTML/CSS/PHP, MySql, and using AJAX/JavaScript/JQuery.

The application gives us the useful information about the Last.fm's top entities e.g. Artists, Album's or Tracks. It allows us to fetch the details about any particular track. Details could be anything like track name, url, duration, artist, album, album art url for different sizes, etc.


Hosting client application in the Cloud

I don't have the required environment setup to build and run this application on my machine. So, I used some trick to build and run this application anyway. In my earlier blog article, Run any code without any Environment SetupI mentioned about the Cloud9 platform. I used the same platform here to manage the things as required.

First of all, you need to create the work-space to host this application in Cloud9. You can also clone it from the GitHub link that I shared earlier for this application. While you create the work-space, you need to choose the correct reconfigured work-space template mentioned there. Once the work-space is created, Colud9 provides us the required environment setup to proceed further.


Setup and Configure the MySQL Database - The Workflow

In order to proceed further, you need to setup and configure the MySql database.
  • Configure your config.ini file as below:

; if change pls use the following command: git update-index --assume-unchanged config.ini
[mysql]
hostname = "localhost"
database = "test"
username = "root"
password = ""

[lastfm]
api_key = "e85bfd5e26e0e91b53160653d86ba063"

[google]
api_key = "AIzaSyDn-UcwMbrIiX8wgyNAlLyHnmqOvZsaddw"

 
  • Right click the workspace folder and click 'Open Ternminal Here'. This should open the terminal.
  • Execute below commands to run the sql script to import the mysql database (import_db.sql).

> mysql-ctl start

> mysql -u root

 
  • Note: Log in without a password, as, the default root password is blank (i.e. empty string) not root.
  • This should open the mysql command prompt. Now, run the below commands to create the test database (db name is already configured in config.ini)

mysql> CREATE DATABASE test;
mysql> USE test

Database changed

 
  • Run the contents of import_db.sql here e.g. CREATE TABLE IF NOT EXISTS 'logtracks'... e.g. mysql> <contents of import_db.sql>
  • Now the database is created and ready to use.
A PHP class LastfmController handles the call's to the LastFM API. There are some java scripts to help you get the response from the server and parse that JSON response into the tabular form as represented in its GUI. For example, the function getTopTracksTag in lastfm_artists.js file used to get the top tracks from the Last.fm. In response to that call, server gives the result in JSON format. The response is then parsed and filled into the HTML table to show to the user. 

The sample JSON that we get is shown as below with the online JSON parser.



Run the client application

Now, you can run the application. On the created work-space there is an option "Run Project" to start running the application. Once you hit the run button, it internally starts the Apache server to host your application on. Once it is ready, the platform provides you the serving link as below using which you can test your application.


Starting Apache httpd, serving https://lastfmclient-jegaonkarsachin.c9users.io/.
Started apache2

 

When you run the application, it shows its own UI with the options to specify some inputs. Now, put some artist name and then select one of the tag names it has populated depending upon the artist name you put. It shows the top tracks tag result as below.




Playing the audio on web using the HTML5 <audio> Element

HTML5 provides a standard for playing audio files. Before HTML5, there was no standard for playing audio files on a web page.

To play an audio files or radio stations in HTML, use the <audio> element:

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
</audio>
 


Conclusion

From the things that I just have mentioned, I can say that, using Last.fm or using similar music content providers(but FREE!), one can create the rich web based music player for FREE !

You would have got an idea about generally how to consume music contents that the provider provides and how it can be used to create the intended player application.


Popular Music Content Providers


Wednesday, June 22, 2016

Call a C# Method From JavaScript



Imagine from within your Windows Forms applications, you are actually navigating different web pages and treating it as a Web Application. This is made possible by the .NET component called as WebBrowser. This control is available as a tool to be put onto your Windows Form.

The WebBrowser .NET control enables the user to navigate Web pages inside your Windows Form.

The below sample shows how to make a use of WebBrowser control and make a call C# from JavaScript or the other way round.


       
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WebBrowserDemo
{
    public partial class WebBrowserDemo : Form
    {
        private HtmlElement button;

        public WebBrowserDemo()
        {
            InitializeComponent();

            // Set the WebBrowser that can be accessed by scripting code 
            // that is contained within the web page displayed in the WebBrowser control.
            webBrowser.ObjectForScripting = new ScriptHanlder(this);

            // Set the HTML contents of the web page 
            // displayed in the WebBrowser control.
            webBrowser.DocumentText = 
    @"<html>
    <head>
        <style>
        .floating-box { float: left; width: 90px; height: 90px; margin: 20px; background-color:#73AD21;}
        .floating_icon { width:100%; text-align:center; height:90%; padding-top:30%; color:#134880;}
        </style>
    </head>
    <body>
    <div width=""120"" height=""120"" border=""3"" >
        <div id=""btnZero"" class=""floating-box"" onClick=""window.external.OnClick(0);"">
        <div class=""floating_icon""> <h2>0</h2> </div>
        </div>
        <div id=""btnOne"" class=""floating-box"" onClick=""window.external.OnClick(1);"">
        <div class=""floating_icon""> <h2>1</h2> </div>
        </div>
        <div id=""btnTwo"" class=""floating-box"" onClick=""window.external.OnClick(2);"">
        <div class=""floating_icon""> <h2>2</h2> </div>
        </div>
        <div id=""btnThree"" class=""floating-box"" onClick=""window.external.OnClick(3);"">
        <div class=""floating_icon""> <h2>3</h2> </div>
        </div>
        <div id=""btnFour"" class=""floating-box"" onClick=""window.external.OnClick(4);"">
        <div class=""floating_icon""> <h2>4</h2> </div>
        </div>
        <div id=""btnFive"" class=""floating-box"" onClick=""window.external.OnClick(5);"">
        <div class=""floating_icon""> <h2>5</h2> </div>
        </div>
        <div id=""btnSix"" class=""floating-box"" onClick=""window.external.OnClick(6);"">
        <div class=""floating_icon""> <h2>6</h2> </div>
        </div>
        <div id=""btnSeven"" class=""floating-box"" onClick=""window.external.OnClick(7);"">
        <div class=""floating_icon""> <h2>7</h2> </div>
        </div>
        <div id=""btnEight"" class=""floating-box"" onClick=""window.external.OnClick(8);"">
        <div class=""floating_icon""> <h2>8</h2> </div>
        </div>
        <div id=""btnNine"" class=""floating-box"" onClick=""window.external.OnClick(9);"">
        <div class=""floating_icon""> <h2>9</h2> </div>
        </div>
    </div>
    </body>
    </html>";
        }

        public void NumberClicked(int num)
        {
            switch (num)
            {
                case 0:
                    button = webBrowser.Document.GetElementById("btnZero");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "0" ? "<div class=\"floating_icon\"> <h2>Zero</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>0</h2> </div>";
                    break;
                case 1:
                    button = webBrowser.Document.GetElementById("btnOne");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "1" ? "<div class=\"floating_icon\"> <h2>One</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>1</h2> </div>";
                    break;
                case 2:
                    button = webBrowser.Document.GetElementById("btnTwo");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "2" ? "<div class=\"floating_icon\"> <h2>Two</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>2</h2> </div>";
                    break;
                case 3:
                    button = webBrowser.Document.GetElementById("btnThree");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "3" ? "<div class=\"floating_icon\"> <h2>Three</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>3</h2> </div>";
                    break;
                case 4:
                    button = webBrowser.Document.GetElementById("btnFour");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "4" ? "<div class=\"floating_icon\"> <h2>Four</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>4</h2> </div>";
                    break;
                case 5:
                    button = webBrowser.Document.GetElementById("btnFive");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "5" ? "<div class=\"floating_icon\"> <h2>Five</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>5</h2> </div>";
                    break;
                case 6:
                    button = webBrowser.Document.GetElementById("btnSix");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "6" ? "<div class=\"floating_icon\"> <h2>Six</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>6</h2> </div>";
                    break;
                case 7:
                    button = webBrowser.Document.GetElementById("btnSeven");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "7" ? "<div class=\"floating_icon\"> <h2>Seven</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>7</h2> </div>";
                    break;
                case 8:
                    button = webBrowser.Document.GetElementById("btnEight");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "8" ? "<div class=\"floating_icon\"> <h2>Eight</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>8</h2> </div>";
                    break;
                case 9:
                    button = webBrowser.Document.GetElementById("btnNine");
                    if (button != null)
                        button.InnerHtml = button.InnerText == "9" ? "<div class=\"floating_icon\"> <h2>Nine</h2> </div>" : 
                            "<div class=\"floating_icon\"> <h2>9</h2> </div>";
                    break;
            }
        }

        // Set the class as ComVisible to be able to access it from JavaScript.
        [ComVisible(true)]
        public class ScriptHanlder
        {
            private WebBrowserDemo demoForm;

            public ScriptHanlder(WebBrowserDemo form)
            {
                // Store the form to refer it later.
                demoForm = form;
            }

            // Method called from JavaScript.
            public void OnClick(int num)
            {
                demoForm.NumberClicked(num);
            }
        }
    }
}
       
 

More information about WebBrowser can be found here.

Monday, May 9, 2016

Become A Better Programmer



Work on interesting and challenging Problems and become a better programmer. HackerRank offers you such a platform. Experts in design, development and data science are competing here. Where do you rank? HakerRank gathers the world’s experts to work on interesting and challenging problems.

HackerRank focuses on competitive programming challenges and has an online community of over one million computer programmers. HackerRank's programming challenges can be solved in a variety of programming languages (including, Java, C++, PHP, SQL, and many more) and span multiple computer science domains.

When a programmer submits a solution to a programming challenge, their submission is scored on the accuracy of their output and the execution time of their solution. Programmers are then ranked globally on the HackerRank leader-board and earn badges based on their accomplishments to drive competition among users. In addition to individual programming challenges, HackerRank also hosts contests where users compete on the same programming challenges during a set period of time and are then ranked at the conclusion of the event. 

In addition to supporting a variety of popular programming languages, HackerRank categorizes most of their programming challenges into a number of core Computer Science domains, including:

  • Artificial Intelligence: involves developing AI bots and using them against others.
  • Algorithms: Traditional algorithmic challenges.
  • Functional Programming: use functional programming abstractions to solve challenges.
  • Machine Learning: use predictive modeling and analysis to solve challenges.


Similar Platforms




Friday, May 6, 2016

LRU Cache Using C++


This article gives the information to implement the class for LRU-caching to be implemented using C++ standard library. Here is the simplified version of the LRU cache using standard C++ library. This is the LRU cache template code to be used for instant usage.


Introduction


LRU Cache is a key-value container providing caching with a least-recently-used replacement mechanism which is a useful in any programming language as a performance optimization toolkit. LRU cache algorithm discards the least recently used items first. It requires to keep track of what was used when, which is expensive if one wants to make sure the algorithm always discards the least recently used item. General implementations of this technique require keeping track the "Least Recently Used" items.


The Need of Cache


Generally, the need for caching arises to preserve the result of some heavy or expensive operations so that, it can be reused without performing the same operation again and again in future. Expensive task could be anything that requires some complex calculations or the task which performs more time consuming operations e.g. I/O operation. If the total number of such results dealt with over the lifetime of the system does not consume excessive memory, it may suffice to store them in a simple key-value container (e.g. std::map), with the key being the input to the expensive function and the value being the result.

Limiting Cache Size


Applications which uses such a caching mechanism, might result into excessive memory usage problems. It could be because, they have no limit to store items or they have heavy items to store into the cache and it results into such problems over the time of application usage.

To avoid such problems, it it worth defining the size of the cache statically. For example, an online media player requires a collection of image files(album arts) while browsing the online content metadata might include a cache to load images of different sizes so as to avoid re-loading the most recently viewed images if the user revisits them. However, by taking the size-in-bytes of the stored images of different sizes into account, the maximum total memory consumed by cached objects could be controlled and the number of images cached automatically adjusted in response to the aggregate size.


Implementation


Standard Library based LRU-cache:

#ifndef _LRU_CACHE_HPP_
#define _LRU_CACHE_HPP_

#include < list >
#include < unordered_map >
#include < cassert > 
#include < iostream >

// Class representing LRU Cache of any generic items with key-value pair.
template < typename Key, typename Value, size_t CacheSize >
class LRUCache
{
public:
    /**
    * @brief Constructor.
    *
    */
    LRUCache()
    {
    }

    /**
    * @brief Destructor.
    *
    */
    ~LRUCache()
    {
        cache.clear();
        lruList.clear();
    }

    /**
    * @brief Check if the key exists in a cache.
    * @param key Key
    * @return true if key exists otherwise false.
    *
    */
    bool exist(Key key)
    {
        if (cache.find(key) == cache.end())
        {
            return false;
        }
        return true;
    }

    /*!
    * @brief Clears the cache.
    *
    * Removes all cache entries and drops all usage count data and so on.
    *
    */
    void clear()
    {
        cache.clear();
        lruList->clear();
    }

    /**
    * @brief Fetches the cache data if the key exists in the cache.
    * @brief If the given key exists, it makes the key and associated value
    * @brief to be the most recently used one by moving the pair to the end of the list.
    *
    * @param  key Key to be spliced.
    * @return get value for the given key.
    *
    */
    Value fetch(const Key& key)
    {
        assert(cache.find(key) != cache.end());

        // cache-hit
        // Update access record by moving accessed key to back of the list
        touch(key);

        print();

        // return the retrieved value
        return cache[key].first;
    }

    /**
    * @brief Adds the given Key-Value pair into the cache.
    * @param key Key
    * @param value Value
    *
    */
    void add(const Key& key, Value value)
    {
        //method should be called only when cache-miss happens
        assert(cache.find(key) == cache.end());

        if (cache.find(key) != cache.end())
        {
            cache[key].first = value;
        }
        else
        {
            insert(key, value);
        }

        touch(key);
    }

private:

    void print()
    {
        typename LRUList::reverse_iterator it = lruList.rbegin();

        for (; it != lruList.rend(); it++)
        {
            //printf("%d\n", *it);
            std::cout << cache[*it].first.c_str() << std::endl;
        }
        std::cout << "------------------" << std::endl;
    }

    /*!
    * @brief Increase usage count for entry of the given key.
    *
    * @brief Touches an entry in cache, simulating access to it.
    * @brief Usefull to splice item in the cache, reducing(or increasing)
    * @brief risk for expiration for it.
    *
    * @param key key to touch
    *
    */
    void touch(const Key &key)
    {
        if (lruList.size() > 0)
        {
            lruList.splice(lruList.end(), lruList, cache[key].second);
        }
    }

    /*!
    * @brief Creates and adds key-value entry linked to the usage record into the cache.
    * @brief It makes the space if necessary.
    * @brief If key exists, it records the key as most-recently-used key.
    * @brief risk for expiration for it.
    *
    * @param key key to insert.
    * @param key value to insert.
    *
    */
    void insert(const Key& key, Value value)
    {
        // make space if necessary
        if (lruList.size() == CacheSize)
        {
            erase();
        }

        // record key as most-recently-used key
        typename std::list< Key >::iterator it = lruList.insert(lruList.end(), key);

        // create key-value entry, linked to the usage record
        cache.insert(std::make_pair(key, std::make_pair(value, it)));
    }

    /*!
    * @brief It identifies and removes the least-recently used element in the cache.
    * @brief It makes the space if necessary.
    * @brief If key exists, it records the key as most-recently-used key.
    * @brief risk for expiration for it.
    *
    * @param key key to insert.
    * @param key value to insert.
    *
    */
    void erase()
    {
        assert(!lruList.empty());

        // identify least-recently-used key
        const typename UnorderedCache::iterator it = cache.find(lruList.front());

        //erase both elements to completely purge record
        cache.erase(it);
        lruList.pop_front();
    }

private:
    // Key access history, most recent at back
    typedef std::list< Key > LRUList;

    // Key to value and key history iterator
    typedef std::unordered_map< Key, std::pair< Value, typename std::list< Key >::iterator> > UnorderedCache;

    LRUList lruList;
    UnorderedCache cache;
};

#endif


Design


In the above class, the key data type and value data type are passed as parameters to the LRUCache class template.

Users of the C++ Standard Library needing an LRU-replacement cache generally gravitate towards std::map or std::unordered_map, because of their support for efficient keyed value accesses (O(log n) or O(1) access complexity). The problem then is how to implement the eviction strategy.

The most obvious solution is to use the std::list < key >.

In the example above, eviction mechanism is implemented using the std::list which maintains the key of the least recently used item at the head and the most recently used item at the tail. Whenever an item is accessed (used), the item is moved to the tail of the LRU cache list. Items from the list gets erased when the number of items in a cache reached the capacity. Notice that the map for (key, value) pair is actually implemented as (key, (value, list_iterator)) where the list_iterator points to an item in the LRU tracker. With this, we don’t need to search the list to find the key which is relatively expensive operation in O(n). Here, it uses std::unordered_map for (key,value) map to improve the average time complexity for add operation to O(1).


How to use the Class


Below code snippet shows the actual usage of the above LRUCache class. It shows a cache, that keeps data of type std::string and keys are of type int.


    typedef LRUCache < int, string, 10 > Cache;
    Cache myCache;
    

Cache object 'myCache' is allowed to keep only 10 items. Cache size is configured at the construction time and cannot be changed in the future.

You could put objects into the cache object using cache::add insert call:

When the cache size is full, it adds the newly requested item into the cache at most recently used position by deleting cache::erase the item at least recently used position.

    myCache.add(1, "One");
    myCache.add(2, "Two");
    myCache.add(3, "Three");
    myCache.add(4, "Four");
    myCache.add(5, "Five");
    myCache.add(6, "Six");
    myCache.add(7, "Seven");
    myCache.add(8, "Eight");
    myCache.add(9, "Nine");
    myCache.add(10, "Ten");
    myCache.add(11, "Elevan");
       
 

Now, when you have some data in the cache, you may want to retrieve it back:
The cache::fetch call will return a data value, associated with the supplied key.

    for (int i = 10; i > 0; i--)
    {
        if (myCache.exist(i))
        {
            myCache.fetch(i);
        }
    }
       

The cache::exist ensures that the key is present or not into the cache. If the key is present, then only we try to fetch the value of that key.

The cache::fetch call internally makes a call to cache::touch function which touches an entry in cache, simulating access to it. This is useful to splice the item into the cache, reducing(or increasing) risk for expiration for it.

The other usage of LRU cache could be for Image Cache as stated earlier:

    typedef enum
    typedef enum
    {
        CACHE_TYPE_SMALL,
        CACHE_TYPE_MEDIUM,
        CACHE_TYPE_LARGE
    }CACHE_TYPE;

    typedef LRUCache< CACHE_TYPE, std::pair< std::string, std::weak_ptr< uint8_t > >, 100> Large;
    typedef LRUCache< CACHE_TYPE, std::pair< std::string, std::weak_ptr< uint8_t > >, 300> Medium;
    typedef LRUCache< CACHE_TYPE, std::pair< std::string, std::weak_ptr< uint8_t > >, 500> Small;

    Large largeSizeCache;
    Medium mediumSizeCache;
    Small smallSizeCache;

    std::shared_ptr< uint8_t > JPEG = ImageScaler.GetImageRawData(JpegImagePath);
    largeSizeCache.add(CACHE_TYPE_LARGE, std::make_pair("JPEG_HASH", ImageScaler.ScaleLarge(JPEG).get()));
    mediumSizeCache.add(CACHE_TYPE_MEDIUM, std::make_pair("JPEG_HASH", ImageScaler.ScaleMedium(JPEG).get()));
    smallSizeCache.add(CACHE_TYPE_SMALL, std::make_pair("JPEG_HASH", ImageScaler.ScaleSmall(JPEG).get()));

    std::shared_ptr< uint8_t > PNG = ImageScaler.GetImageRawData(PngImagePath);
    largeSizeCache.add(CACHE_TYPE_LARGE, std::make_pair("PNG_HASH", ImageScaler.ScaleLarge(PNG).get()));
    mediumSizeCache.add(CACHE_TYPE_MEDIUM, std::make_pair("PNG_HASH", ImageScaler.ScaleMedium(PNG).get()));
    smallSizeCache.add(CACHE_TYPE_SMALL, std::make_pair("PNG_HASH", ImageScaler.ScaleSmall(PNG).get()));

    std::shared_ptr< uint8_t > GIF = ImageScaler.GetImageRawData(GifImagePath);
    largeSizeCache.add(CACHE_TYPE_LARGE, std::make_pair("GIF_HASH", ImageScaler.ScaleLarge(GIF).get()));
    mediumSizeCache.add(CACHE_TYPE_MEDIUM, std::make_pair("GIF_HASH", ImageScaler.ScaleMedium(GIF).get()));
    smallSizeCache.add(CACHE_TYPE_SMALL, std::make_pair("GIF_HASH", ImageScaler.ScaleSmall(GIF).get()));

    assert(mediumSizeCache.contains(CACHE_TYPE_MEDIUM));
 

The above example can be extended for Cache Mediator Pattern and with mediator it can be turned into Asynchronous Cache, High Throughput, Thread-Safe LRU Cache. We'll see such an implementation in my future article.

Happy Coding. :-)

Run any code without any Environment Setup


Run any Code ! for any Platform ! at Anywhere ! for FREE ! using Cloud9 !!! Write, run, and debug your code with Colud9's powerful and flexible cloud IDE. Collaborate on your workspaces publicly, or keep it private.

Cloud9 combines a powerful online code editor with a full Ubuntu workspace in the cloud. Cloud9 supports more than 40 languages, with class A support for PHP, Ruby, Python, JavaScript, Go, and more.

Cloud9 IDE is an open source, from version 3.0, online integrated development environment. It supports hundreds of programming languages, including PHP, Ruby, Perl, Python, JavaScript with Node.js, and Go. It enables developers to get started with coding immediately with pre-setup workspaces, collaborate with their peers with collaborative coding features, and web development features like live preview and browser compatibility testing.

It is written almost entirely in JavaScript, and uses Node.js on the back-end.

Cloud9 IDE














Cloud9 makes web development so easy, that, you can simply pick your configuration and develop your app. No need to spend valuable development time on system setup and maintenance. No need to install browsers and platforms in virtual machines for compatibility testing. Live Preview enables you to interactively see what your web application looks like in any browser! Just choose one of the 300+ browser/OS platform combinations.

Cloud9 Templates for Creating Workspaces







You can create, build and run any development stack in seconds. You can easily handle hundreds of thousands of files in your workspace and hundreds of thousands of lines of code in the editor.

Cloud9 offers some of the below powerful features

  • Built-in terminal, with npm and basic Unix commands
  • Code completion for snippets and identifiers
  • Real-time language analysis for JavaScript (marking common JavaScript pitfalls)
  • Variable/function name refactoring for JavaScript
  • Parenthesis, bracket, and quote character matching
  • Line numbers, warnings, and errors in the gutter
  • Debugger
  • Tabbed file management
  • Themes
  • Customizable key-bindings, including presets for Vim, Emacs, and Sublime Text
  • Built in Image Editor
  • Code reformatting via JSBeautify and CSSLint
  • Ability to drag-and-drop files into your project
  • Support for the following code repositories:
  • Support for deployment to:
  • Support for public and private projects
  • Plug-in support
  • Syntax highlighting for the following languages: C#, C/C++, Clojure, CoffeeScript, ColdFusion, CSS, Groovy, Java, Javascript, LaTeX, Lua, Markdown, OCaml, PHP, Perl, PowerShell, Python, Ruby, Scala, SCSS, SQL, Textile, X(HTML), XML

Similar Platforms

Wednesday, April 27, 2016

Books I Read in 2015

Books I Read in 2015

In 2015, I read number of books. But, the most exciting titles I feel are as below.


TimeLine - Michael Crichton (Author)


In an Arizona desert a man wanders in a daze, speaking words that make no sense. Within twenty-four hours he is dead, his body swiftly cremated by his only known associates. Halfway around the world archaeologists make a shocking discovery at a medieval site. Suddenly they are swept off to the headquarters of a secretive multinational corporation that has developed an astounding technology. Now this group is about to get a chance not to study the past but to enter it. And with history opened to the present, the dead awakened to the living, these men and women will soon find themselves fighting for their very survival–six hundred years ago. . . .

The Lost World - Michael Crichton (Author)


"Harrowing thrills . . . fast-paced and engaging.”—People
“A very scary read.”—Entertainment Weekly
“Action-packed.”—New York Daily News
“An edge-of-the-seat tale.”—St. Petersburg Times

It is now six years since the secret disaster at Jurassic Park, six years since the extraordinary dream of science and imagination came to a crashing end—the dinosaurs destroyed, the park dismantled, and the island indefinitely closed to the public.

There are rumors that something has survived. . . .

Jurassic Park - Michael Crichton (Author)


“Wonderful . . . powerful.”—The Washington Post Book World

An astonishing technique for recovering and cloning dinosaur DNA has been discovered. Now humankind’s most thrilling fantasies have come true. Creatures extinct for eons roam Jurassic Park with their awesome presence and profound mystery, and all the world can visit them—for a price.

Until something goes wrong. . . .

In Jurassic Park, Michael Crichton taps all his mesmerizing talent and scientific brilliance to create his most electrifying technothriller.

“Frighteningly real . . . compelling . . . It’ll keep you riveted.”—The Detroit News
“Crichton’s dinosaurs are genuinely frightening.”—Chicago Sun-Times
“Full of suspense.”—The New York Times Book Review

Congo - Michael Crichton (Author)


Deep in the African rain forest, near the legendary ruins of the Lost City of Zinj, an expedition of eight American geologists are mysteriously and brutally killed in a matter of minutes.

Ten thousand miles away, Karen Ross, the Congo Project Supervisor, watches a gruesome video transmission of the aftermath: a camp destroyed, tents crushed and torn, equipment scattered in the mud alongside dead bodies—all motionless except for one moving image—a grainy, dark, man-shaped blur.

In San Francisco, primatologist Peter Elliot works with Amy, a gorilla with an extraordinary vocabulary of 620 "signs," the most ever learned by a primate, and she likes to finger paint. But recently her behavior has been erratic and her drawings match, with stunning accuracy, the brittle pages of a Portuguese print dating back to 1642 . . . a drawing of an ancient lost city. A new expedition—along with Amy—is sent into the Congo, where they enter a secret world, and the only way out may be through a horrifying death . . .

आर्य चाणक्यजनार्दन ओक (लेखक)


"सर्वसाधारण मनुष्याला जीवनापासून परावृत्त करणं अतिरिक्त अहिंसेचा अवलंब करणाऱ्या गोष्टीमुळे राष्ट्राचं अपरिमित नुकसान होते हे ध्यानी घेणं आवश्यक आहे. आम्हाला कुणावरही आक्रमण करण्याची कांक्षा नही. परंतु आमच्यावरती झालेलं आक्रमण आम्ही सहन करणार नही. नवनिर्माणाच्या नावाने होणारी असंथ मनाची भावना अव्यवस्था राष्ट्रास हानिकारक ठरते. सांप्रत संपूर्ण आर्यावर्तात हीच अवस्था निर्माण झाली आहे. हे सारं संपुष्टात यावं असा माझा आग्रह आहे. आपला हा उद्योग त्याप्रीत्यर्थ आहे. धर्म, वैभव, सद्भाव, साधर्म्य हे राष्ट्राचे सामर्थ्य आहे. या चार गोष्टी जिथे नांदतात ते राष्ट्र आदर्श मानलं जातं. माझा अट्टाहास अशा राष्ट्रांकारिता आहे. कुठल्याही एका विविक्षीत वर्गानं संपन्न असावं आणि इतरांनी त्यापासून वंचित असावं हा राज्यानिर्मितीचा उद्देश नाही. अधिक अधिक प्रजेनं सुखी असावं हा या निर्मितीचा मुळ उद्देश आहे."
                                                                                                                                                                                                                                                  - आर्य चाणक्य

Under the Hood of .NET Memory Management - Chris Farrell (Author), Nick Harrison (Author)


This book starts with an introduction to the core concepts of .NET memory management and garbage collection, and then quickly layers on additional details and intricacies. Once you're up to speed, you can dive into the guided troubleshooting tour, and tips for engineering your application to maximise performance. And to finish off, take a look at some more sophisticated considerations, and even a peek inside the Windows memory model.

Windows Internals, Part 1 and Part 2 (6th Edition) (Developer Reference)by Mark E. Russinovich (Author), David A. Solomon (Author), Alex Ionescu (Author) 

        Delve inside Windows architecture and internals—and see how core components work behind the scenes. Led by three renowned internals experts, this classic guide is fully updated for Windows 7 and Windows Server 2008 R2—and now presents its coverage in two volumes.

As always, you get critical insider perspectives on how Windows operates. And through hands-on experiments, you’ll experience its internal behavior firsthand—knowledge you can apply to improve application design, debugging, system performance, and support.


In Part 1, you will:




  • Understand how core system and management mechanisms work—including the object manager, synchronization, Wow64, Hyper-V, and the registry
  • Examine the data structures and activities behind processes, threads, and jobs
  • Go inside the Windows security model to see how it manages access, auditing, and authorization
  • Explore the Windows networking stack from top to bottom—including APIs, BranchCache, protocol and NDIS drivers, and layered services
  • Dig into internals hands-on using the kernel debugger, performance monitor, and other tools 

Delve inside Windows architecture and internals—and see how core components work behind the scenes. Led by three renowned internals experts, this classic guide is fully updated for Windows 7 and Windows Server 2008 R2—and now presents its coverage in two volumes.

As always, you get critical insider perspectives on how Windows operates. And through hands-on experiments, you’ll experience its internal behavior firsthand—knowledge you can apply to improve application design, debugging, system performance, and support.


In Part 2, you’ll examine:




  • Core subsystems for I/O, storage, memory management, cache manager, and file systems
  • Startup and shutdown processes
  • Crash-dump analysis, including troubleshooting tools and techniques

 
biz.