Uncategorized

Classification of design patterns : Creational Design Patterns

Before reading further , let us first understand what are design patterns read part 1 of this article

Creational Design Pattern

Object creation is a very common pattern we need to use almost for all complex objects. Object creation is not just allocating a memory and use it, we may need to consider lot of aspects while creating an object.

Creational design pattern solves this problem by following a sophisticated approach, typically creational design patterns will be used for initialising hardware configuration, database connections , Logger object.

Creational design patterns are important to use because they follow SOLID Principles closely. It allows long term flexibility, it allows more decoupling and easily testable.

Let us look into some of the important creational design patterns

Singleton Pattern

We have to identify a scenario where we may need to maintain only one object, even if you try to create an object, the program should not allow to create new object instead it has to return only one object.

Singleton pattern is meaningful where multiple objects doesn’t make any sense. Taking few scenarios here for example , DBConnectionHandler, MQManager for managing Queue connections, these are classical examples where having multiple objects has no meaning.

Example of Singleton Pattern in Javascript

<code>class MQManager {
  constructor() {
    this.amqpProducerConn = null;
    this.amqpConsumerConn = null;
    this.producerChannel = null;
    this.consumerChannel = null;
  }
  createProducerConnection(onConnectSuccess, onConnectFail) {
  }

  createConsumerConnection(onConnectSuccess, onConnectFail) {
  }
  createProducerChannel(connection) {}
  createConsumerChannel() {}
  enqueueJob(queueName, jobDetails) {}
  dequeueJob(queueName, consumerCallback) {}
  closeProducerConnectionOnErr(err) {}
  closeConsumerConnectionOnErr(err) {}
};
module.exports = (() => {
  let instance;
  function getInstance() {
    //TO RESTRICT CREATING SINGLE OBJECT 
    if (instance === undefined) {
      instance = new MQManager();
    }
    return instance;
  }
  // Public API definition
  return {
    getInstance
  };
})();</code>

The above class we can import as follows

<code>const MQManager = require('./mqManager').getInstance();</code>

Read More About Creational Design Pattern

Thanks to refactoring.guru for wonderful images - https://refactoring.guru/design-patterns/

Design Patterns – importance and Examples

What are design pattern?

design patterns are typical solutions to common problems a developer face repeatedly

Design Patterns Classification 

Creational Pattern

These patterns provides various objects creation mechanism. Which increase flexibility and reuse of existing code

Structural Pattern

These patterns explain how to assemble objects and classes into larger structure, while keeping these structures flexible and efficient

Behavioral Pattern

These patterns are concerned with algorithms and assignment or responsibilities between objects

Design patterns are the best practices adapted by experienced software developers, with a vast experience, we developers will find a best way to solve a problem which we face almost every day. The outcome of such solution we usually call it as design patterns

Let us look into some of the design patterns: Read Here

Thanks to refactoring.guru for wonderful images - https://refactoring.guru/design-patterns/

Server Side Rendering (SSR) in React 16 with create-react-app using Material Ui, Redux and Express Libraries

What is Server Side Rendering in React (SSR)?

Server side rendering is normally rendering the requested page at server side of client and sending back the whole html page from server.
i.e: Server-side rendering is all about handling the initial render whenever a request hits the server. For more on basics of SSR please read my first article

Let us see how to implement server side rendering in ReactJs

How to Enable Server Side Rendering using React and ExpressJS

Dependencies:

React: 16.7.0
Material Ui Library from Google: v3.9.3
redux: 4.0.1
redux-thunk: 4.0.1
express: 4.17.1
react-jss: 8.6.1
react-router-dom: 4.3.1
react-document-meta: 2.1.2
axios: 0.19.0
@babel/plugin-proposal-class-properties: 7.4.0
@babel/preset-env: 7.4.3
@babel/register: 7.4.4
babel-preset-es2015: 6.24.1

Step1: Create React Application
Create a react app using command create-react-app
Install the create-react-app globally on your machine with below command.

npm install -g create-react-app

Create a project by create-react-app as follows

create-react-app ssr-react-16


Step2: Install necessary npm packages for React server side rendering applicationInstall the following packages by running the following commands, if necessary please use the same version too.

npm install @material-ui/core
npm install  react-redux
npm install redux
npm install redux-thunk 
npm install express
npm install react-router-dom
npm install react-document-meta
npm install react-jss
npm install axios
npm install @babel/plugin-proposal-class-properties
npm install @babel/preset-env
npm install @babel/register
npm install babel-preset-es2015

Thats it now your app is ready with library setup

Step3: babel configs for react server side app
Create a file called .babelrc in root directory of the app and paste the below code.
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. For more you can read the babel doc.

{
  "presets": ["@babel/env", "@babel/preset-react"],
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}

Step4:
Create a file called www under bin folder which is in root directory
In this file we will be creating a server for client and allocate a port (I am using 5000 here)
Copy the code below to file just created

const app = require('../src/client/src/ssr/clientServer');
const http = require('http');

const port = normalizePort(process.env.PORT || 5000);
app.set('port', port);

const server = http.createServer(app);
server.listen(port);

function normalizePort(val) {
  const port = parseInt(val, 10);
  if (isNaN(port)) {
    // named pipe
    return val;
  }
  if (port &gt;= 0) {
    // port number
    return port;
  }
  return false;
}

In the above code snippet, we are importing a file called clientServer.js that’s covered in the next step.

Step5: ReactJS server side script to initialise server part of client app.
Create a file clientServer.js
For better folder structure, I have organised as shown in the below screenshot where bin and src will falls under root directory. Paste the below code in clientServer file. clientServer is kind of server side script for our client application, it will initiate expressjs and configurations for server side script of client.

require("@babel/register")({
  presets: ["@babel/preset-env"]
});

const express = require('express');
const path = require('path');

const requestHandler = require('./requestHandler');
const app = express();

//static files nd build file reference
app.use(express.static(path.join(__dirname, '../../../../build')));
app.use(express.static(path.join(__dirname, 'public')));

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'public'));

//for server side rendering
app.use(requestHandler);

// catch 404 and forward to error handler
app.use((req, res, next) =&gt; {
  const err = new Error('Notdff Found');
  err.status = 404;
  next(err);
});

module.exports = app;<b><i></i></b>


In the above code you can see a requestHandler file, which is very important file and will see there.

Step6: A request handler for ReactJS for server side rendering and invoking (calling) apis at server side
This step is very important for serving the requested page from server side.  All magic of serving the requested page is done in this script.  When client request for a page, it matches the path and determines whether is there any API call for this page and invokes api then updates HTML body for the respective response. Basically here its creating the react component at server side. Hence React component is fully ready with all the data for the first render itself. 
If there is no api call for a particular page, it just serves a just a static page 


Create a file requestHandler.js Copy the below code.

'use strict';
import React from 'react';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { applyMiddleware, createStore } from 'redux';
import { renderToString } from 'react-dom/server';
import { SheetsRegistry } from 'jss';
import JssProvider from 'react-jss/lib/JssProvider';
import path from 'path'
import fs from 'fs'
import {
  MuiThemeProvider,
  createMuiTheme,
  createGenerateClassName,
} from '@material-ui/core/styles';
import green from '@material-ui/core/colors/green';
import red from '@material-ui/core/colors/red';
import { StaticRouter, matchPath } from 'react-router-dom';
import DocumentMeta from 'react-document-meta';
import reducers from '../reducers/index';
import routes from '../routes';
import routesConfigs from './routesConfig';

const middleware = applyMiddleware(thunk);

function renderView(req, res, state) {

  // Create a theme instance.
  const theme = createMuiTheme({
    palette: {
      primary: green,
      accent: red,
      type: 'light',
    },
  });

  // STEP-1 CREATE A REDUX STORE ON THE SERVER
  const store = createStore(reducers, state, middleware);
  const sheetsRegistry = new SheetsRegistry();
  // Create a sheetsManager instance.
  const sheetsManager = new Map();
  const generateClassName = createGenerateClassName();
  // STEP-2 GET INITIAL STATE FROM THE STORE
  const initialState = JSON.stringify(store.getState()).replace(/&lt;\/script/g, '&lt;\\/script').replace(/&lt;!--/g, '&lt;\\!--');
  // STEP-3 IMPLEMENT REACT-ROUTER ON THE SERVER TO INTERCEPT CLIENT REQUESTs AND DEFINE WHAT TO DO WITH THEM
  const context = {};
  const reactComponent = renderToString(
    &lt;JssProvider registry={sheetsRegistry} generateClassName={generateClassName}&gt;
      &lt;MuiThemeProvider theme={theme} sheetsManager={sheetsManager}&gt;
        &lt;Provider store={store}&gt;
          &lt;StaticRouter
            location={req.url}
            context={context}&gt;
            {routes}
          &lt;/StaticRouter&gt;
        &lt;/Provider&gt;
      &lt;/MuiThemeProvider&gt;
    &lt;/JssProvider&gt;
  );
  const css = sheetsRegistry.toString()
  const reactMetaComponent = DocumentMeta.renderToStaticMarkup();
  if (context.url) {
    // can use the `context.status` that
    // we added in RedirectWithStatus
    redirect(context.status, context.url);
  } else {
    //https://crypt.codemancers.com/posts/2016-09-16-react-server-side-rendering/
    //res.status(200).render('index', { reactComponent, reactMetaComponent, initialState });
    fs.readFile(path.resolve('build/index.html'), 'utf8', (err, data) =&gt; {
      if (err) {
        return res.status(500).send('An error occurred')
      }
      const replacedData = data.replace(
        '&lt;div id="root"&gt;&lt;/div&gt;',
        `&lt;div id="root"&gt;${reactComponent}&lt;/div&gt;
        &lt;style id="jss-server-side"&gt;${css}&lt;/style&gt;
        &lt;script&gt;
          window.INITIAL_STATE = ${initialState}
        &lt;/script&gt;`
      );
      const replacedMetaTagData = replacedData
        .replace(`&lt;meta id="reactMetaTags"/&gt;`,
          `${reactMetaComponent}`);
      res.send(replacedMetaTagData);
    })
  }
}

function handleRender(req, res) {
  const components = routesConfigs
    .filter(route =&gt; matchPath(req.path, route)) // filter matching paths
    .map(route =&gt; route.component); // check if components have data requirement
  let promiseObj = null;
  if (components.length &gt; 0 &amp;&amp; (components[0].fetchData instanceof Function)) {
    /* fetchData is the function defined in each component and make it like class 
       function and it will be called at server side
    */
    components[0]
      .fetchData(req.query)
      .then((response) =&gt; {
        renderView(req, res, response);
      })
      .catch((error) =&gt; {
        console.log('***--- handleRender error ', error);
        renderView(req, res, {});
      });
  } else {
    renderView(req, res, {});
  }
}

module.exports = handleRender;
  1. By default it will be executing a handleRender function in the above code. In the handleRender function, we read a routesConfig file which is just for keeping track of respective component for each route path.
    import LandingComponent from '../pages/landing/components/LandingComponent';
    import AboutComponent from '../pages/about/components/AboutComponent';
    export default [
      {
        path: "/",
        component: LandingComponent,
        exact: true,
      },
      {
        path: '/about',
        component: AboutComponent,
        exact: true,
      }
    ];
  2. routesConfigs will be used by requestHandler to find dynamically which component needs to be rendered for the request. It also checks for fetchData, if fetchData is defined by the component then requestHandler will invoke it which internally invokes api. Note here is all this is happening at server side not on the browser, component object is created in server and fetchData action will be invoked in server. You can see the brief description of fetchData and how to use this in the component in the next step.
  3. When renderView is called, every times it creates is own redux store and a material ui theme provider, thats why we follow this code(which is also mention in the above code snip). 
    const theme = createMuiTheme({
        palette: {
          primary: green,
          accent: red,
          type: 'light',
        },
      });
    
      // STEP-1 CREATE A REDUX STORE ON THE SERVER
      const store = createStore(reducers, state, middleware);
      const sheetsRegistry = new SheetsRegistry();
      // Create a sheetsManager instance.
      const sheetsManager = new Map();
      const generateClassName = createGenerateClassName();
  4. Next major step is reading a build/index.html file which you will get by running npm run build,
    Here we will be injecting the component created at server side into index.html.

    const replacedData = data.replace(
            '&lt;div id="root"&gt;&lt;/div&gt;',
            `&lt;div id="root"&gt;${reactComponent}&lt;/div&gt;
            &lt;style id="jss-server-side"&gt;${css}&lt;/style&gt;
            &lt;script&gt;
              window.INITIAL_STATE = ${initialState}
            &lt;/script&gt;`
     );

    where in index.html of public folder should compulsory has this tag

    &lt;div id="root"&gt;&lt;/div&gt;
  5. For facebook sharing, when you share the url a image and the title and description of the page has to be displayed, for that all those content has to be in the meta tag inside the head tag, hence we need to replaced meta tag with server generated meta tag code. 
    const replacedMetaTagData = replacedData
      .replace(`&lt;meta id="reactMetaTags"/&gt;`,
      `${reactMetaComponent}`);

    Where in index.html of public folder, meta tag with id is should be unchanged

    &lt;meta id="reactMetaTags"/&gt;
  6. Finally we will serve the requested page with updated meta tags and updated html for the first rendering cycle it self. 
    res.send(replacedMetaTagData);
    
    

    Step 7

  7. Every component should define an action which will be invoked from server side script, however in server side the request handler will be a generic script and we have to dynamically invoke an action at server side, to achieve that, each component has to define an action and assign action function pointer to fetchData, fetchData is a static class variable kept in component. Check the below code snippet , fetchData is defined at AboutComponent class level and a pointer to action is assigned to it.
    AboutComponent.fetchData = fetchAboutData;
    export default connect(mapStateToProps, null)(AboutComponent);
    
  8. You can refer to the fetchAboutData action in the aboutActions.js which will make the API call to some server, for testing iI am using the JSON placeholder get API which will get the list of posts as response, refer the code below 
    import axios from 'axios';
    export const fetchAboutData = (params) =&gt; {
      return new Promise((resolve, reject) =&gt; {
        const url = 'https://jsonplaceholder.typicode.com/posts';
        axios
          .get(url)
          .then(response =&gt; {
            resolve({
              about: {
                posts: response.data
              }
            });
          })
          .catch((error) =&gt; {
            console.log('Error while fetching posts from network', error);
            reject(null);
          });
      });
    }
  9. In the positive view, it goes to then block(success block) of the axios api call, you can observe that it’s not direct resolve, its resolving a reducer named about and that contain the posts as one of the key, this set up has to be same in both client side reducer as well in axios call in order to use it component (About Component), Observe the below codes, I have shown the code snips of axios call, aboutReducer to mapStateToProps in AboutComponent,
    In axios call 

    resolve({
        about: {
           posts: response.data
        }
    });

    In about reducer 

    const INITIAL_STATE = {
    posts: []
    };

    In about component

    const mapStateToProps = (state) =&gt; {
        return {
           posts:state.about.posts
        };
    }
  10. So in the render method, you can access the posts array like this.props.posts, in the return method of render function i have written one more function which will return the list of posts(only title) and it creates a html code
    getAllPosts = () =&gt; {
       const postView = this.props.posts.map(post =&gt;
       &lt;li&gt;{post.title}&lt;/li&gt;
     );
     return postView;
    }
  11. Once the html is ready, then its in the success block of the fetchData function in the handleRender function of requestHandler file , then followed by the code it calls the renderView method along with data(html) returned from the component.

Step8 :
Update the package.json start script to point to server side rendering beginning of the file, thats www under bin directory. Now server side rendering is really ready. 

  "scripts": {
    "start": "node bin.www",

Step9 : Running project:

  1. In the requestHandler file we will be pointing to index.html inside the build folder, hence we need to generate a build from react by running the command 
    npm run build
  2. Run the start command of your script by
    npm run start

        OR

    nodemon

        OR 

    node bin/www
  3. Since we are running this project on 5000 port, run http://localhost:5000 which is just a page without requesting for API, you simply see as like below
  4. I have made one more component with calling API and printing the results on screen,  run http://localhost:5000/about . I am using an open dummy api for printing list of posts,
    Ie: https://jsonplaceholder.typicode.com/posts

The output picture is shown below

For View Tutorial on Server Side Rendering using ReactJS, Material-ui and Redux with explanation of each code snippet click here

An Example Source Code is in Github project Link : https://github.com/pilleanand/ssr-react16/tree/master/ssr-react-16

Common issues faced in React SSR Applications 

Posted by:

Anand S,

Software Engineer, Soczen Technologies Pvt Ltd,

Developer: https://sociallygood.com

React Native Android Exception : App Crashes on Launch

How to check exception ? On crash it just shows Close app dialogue box. To check what is the crash open adb logs and check.

<User_home_directory>/Library/android/sdk/platform-tools/adb logcat

This command shows below exception

Exception : java.lang.RuntimeException: Unable to start activity ComponentInfo{/.MainActivity}: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

Fix For this :

Remove android:screenOrientation from your application manifest xml

ReactNative Firebase Application : Firebase App named ‘[DEFAULT]’ already exists (app/duplicate-app)

If by change you are getting following exception 

Firebase App named ‘[DEFAULT]’ already exists (app/duplicate-app)

Then do the following fix :

Check whether firebase is already initialised or not before calling firebase.initializeApp

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

 

How to Increase Upload Speed for GoogleCloudStorage in nodejs

How to Increase Upload Speed for GoogleCloudStorage in nodejs

Uploading Files to GCP : Google Cloud Storage In Nodejs

const Storage = require('@google-cloud/storage');
const config = require('./gcloudConfig');
const Multer = require('multer');

const CLOUD_BUCKET = config.get('CLOUD_BUCKET');

const storage = Storage({
  projectId: config.get('GCLOUD_PROJECT')
});
const bucket = storage.bucket(CLOUD_BUCKET);

// Returns the public, anonymously accessable URL to a given Cloud Storage
// object.
// The object's ACL has to be set to public read.
// [START public_url]
function getPublicUrl (filename) {
  return `https://storage.googleapis.com/${CLOUD_BUCKET}/${filename}`;
}

// Express middleware that will automatically pass uploads to Cloud Storage.
// req.file is processed and will have two new properties:
// * ``cloudStorageObject`` the object name in cloud storage.
// * ``cloudStoragePublicUrl`` the public url to the object.
// [START process]
function sendUploadToGCS (req, res, next) {
  if (!req.files) {
    return next();
  }
  const data = req.body;
  if (req.files.length === 0) {
    next();
  }
  data.accountNumber = '';
    for (let index = 0; index &lt; req.files.length; index++) {
      const gcsname = `${data.accountNumber}/${Date.now()}${req.files[index].originalname}`;
      const file = bucket.file(gcsname);
      const stream = file.createWriteStream({
        metadata: {
          contentType: req.files[index].mimetype
        },
        resumable: false
      });
      stream.on('error', (err) =&gt; {
        req.files[index].cloudStorageError = err;
        next(err);
      });
    //  console.log(' upload in progress for file ', index);
      stream.on('finish', () =&gt; {
        req.files[index].cloudStorageObject = gcsname;
        file.makePublic().then(() =&gt; {
          req.files[index].cloudStoragePublicUrl = getPublicUrl(gcsname);
          console.log(' upload completed, public url is ', req.files[index].cloudStoragePublicUrl,
                     ' index ', index, ' total count ', req.files.length);
          if (index === (req.files.length - 1)) {
            next();
          }
        });
      });
      stream.end(req.files[index].buffer);
    }
}
// [END process]

// Multer handles parsing multipart/form-data requests.
// This instance is configured to store images in memory.
// This makes it straightforward to upload to Cloud Storage.
// [START multer]

const multer = Multer({
  storage: Multer.MemoryStorage,
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb
  }
});
// [END multer]

module.exports = {
  getPublicUrl,
  sendUploadToGCS,
  multer
};

 

The issue is the upload speed is very slow, finding a way to upload faster to google cloud storage

Glimpse Of Intel AI & HPC Summit : Application’s Of Artificial Intelligence – Part 3

Glimpse Of Intel AI & HPC Summit : Application’s Of Artificial Intelligence – Part 3

Read my previous article Part 2

Intel demonstrated some of the great applications of Artificial Intelligence where Intel’s hardwares and softwares out performing to solve complex problems in realtime using AI. Intel is working with many customers to solve their complex problems. 

Application’s Of Artificial Intelligence

1. Tumour detection in large 3-D medical images

Identifying tumour from huge medical images is yet another complex problems, today we have algorithms which does this job better than doctors.

2. Disease Risk Prediction Using Genetic Variation Data

3. Classification and predictions of protein sequences

4. Intelligent Knowledge Management 

This is another interesting application where, the algorithms analyse the huge set of documents and help the management to answer for complex queries.

5. Oil Rig Inspector Assist System

This is a very complex problem, identifying corrosion on nut-bolts under deep sea water is a complex problem solve for oil mining industries. Currently it is a manual process, where video cameras are fixed in oil rig systems and several hundred people will manually go through thousands of frames of videos manually and identify the corrosion on nut-bolts.

Now Intel is working with such industries to automate the process by analysing the video frames. thousands of video frames will be analysed in just few hours. The algorithms are capable of identifying the corrosion with great precision.

6. Self driving Cars and Car automation

BMW CARASSO is the system based on ai, the company is using to collect data from several sensors to debug their hard systems and to achieve the quality in their product. Company is using this system only for their internal quality improvements and to understand the roads and behaviour of the cars.

Intel has lot of open source code base which can be used for many such applications, kindly see the source code of Intel’s Nervana in Github

simple steps towards saving water

simple steps towards saving water

I am not going to tell again Water is precious, We have to save water ! I am not going to tell again Importance of water and why we have to save water ! Because since my childhood and ofcourse you too, listening all these and thats nothing new for us.

I am writing this article just to share about a simple experiment we did at our home and a simple analysis based on the data we collected. Now it is upto the reader whether to follow it or not because you know the importance of water and you all know that what you are doing is wrong and you are leaving nothing to your kids.

Few months back we stopped using washing machine and we started using a small hand held machine to wash our cloths. one fine day I realised something very important, that is when we were using washing machine we were wasting lot of water, because all these modern washing machines will consume too much water and we do not re-use that water. Since we started using small hand held machine these days we realised how much water we are saving using this machine and we started re-using the water after washing the cloths.

after doing it for few days  we thought to collect the data so that we can do some simple calculations and do some analysis on it. The analysis gave us an astonishing result, so thought to share with all of you.

Here is what we did :

1.we stopped using washing machine which consumes too much amount of water

water-consuming-washing-machine

water-consuming-washing-machine

2. we started using small hand held washing machine which consumes very minimum amount of water

hand-held-small-washing-machine

hand-held-small-washing-machine

3. finally re-using the water after washing the cloths

re-using-water

re-using-water

These are the simple steps we followed to save enough water. How much water we can save if we all together join hands ? Let us come to the analysis part.

Some data we collected for the period of 30 days

So the above table shows how much buckets of water we are using for washing the cloths and re-using the same water. total for around 30 days we re-used 264 liters of water.

Now considering certain data which helps us to do some calculations 

  1. Average amount of water consumed by any modern washing machine = 170.3 liters per load
  2. Average amount of water used by flush in toilets = 4 liters
  3. Some important data regarding Bengaluru water supply – 

    Bengaluru Water supply

    Bengaluru Water supply

Keeping above data for reference we did some simple calculations as follows

Converting all the data for a month.

170.3 ltr per load in washing machine -> So per month even if we use 10 times = 1700 liters ( assuming in a family of 3-4 people we use atleast 10 times in a month)

4 liters per flush and if we use 6 times per day then 24 liters per day and 744 liters per month ( assuming we use toilet flush at least 6 times in a day )

So total per month both washing machine and toilet flush together it consumes 2500 liters of water

Now here we are just using 264 liters of water for waching cloths and we are re-using the water after washing cloths which means we are able to manage both washing cloths and toilet with just 264 liters of water.

That means almost 90% of total consumption is optimised, means 2300 liters water is saved or reused per month.

2300 liters of water saved per month 

Let us calculate it for 12 months -> 2300 x 12 = 27600 liters

Now considering another stats 8.5 million people served daily in Banglore 

If all 8.5 million people save water as suggested above, we can save 8.5 * 2300 = 19550 ML 

Another stats given is 1350MLD water served in Bengaluru daily

so now

total_water_saved_by_8.5M_people / water_served_per_day_in_Bengaluru

19550ML/1350ML = 14.48

which means if all 8.5M people together save 19550ML of water then we can serve these 8.5M people for extra 14.48 days.

 

Android Gradle : multiDexEnabled property

Android Gradle : multiDexEnabled property

Android Build Error

Error:Execution failed for task ‘:app:transformClassesWithDexForDebug’.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

Solution: Add the following multiDex property in your build.gradle.
multiDexEnabled true
so your build.gradle looks like follows

 

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "dhi_ti.com.repositoryapp"
        minSdkVersion 11
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
    compile project(path: ':dhilib')
}

What is  multiDexEnabled true ? Why it is required ?

As per the documentation from Google, As the Android platform has continued to grow, so has the size of Android apps. When your app and the libraries it references reach a certain size, you encounter build errors that indicate your app has reached a limit of the Android app build architecture.

About the 64K reference limit

(APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. 

The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536—including Android framework methods, library methods, and methods in your own code. In the context of computer science, the term Kilo, K, denotes 1024 (or 2^10). Because 65,536 is equal to 64 X 1024, this limit is referred to as the ’64K reference limit’.

Reference : https://developer.android.com/studio/build/multidex.html#about

 

Sanskrita Vyakarana : separation, distinction,analysis, explanation

Sanskrita Vyakarana : separation, distinction,analysis, explanation

Sanskrit is called as a perfect language, an unambiguous language and hence NASA preferred it for Artificial Intelligence. But why so ? How it is different from any other language in the world? Why it is called as a most scientific language? What is so unique in sanskrit language ?

To answer all the above questions, we have to really look into the vyakarana in sanskrit. Though I don’t have enough knowledge in sanskrit, I am writing these articles after exploring a little bit about sanskrit with the help of few online courses of sanskrit ( Vyoma Linguistic Labs : Learn Sanskrit From home )

Vyakarana in Sanskrit:

In english if I say Read it is a just a word and you can not give any more explanation for that, is there any logic behind formation of this word ? Is there any explanation for the word Read‘ or ‘Reading ? Definitely we don’t have any answer for this question.

In sanskrit there is nothing which has no explanation, there is a logic behind formation of each and every word. Let me take simple example

  1. There is a word पठति in sanskrit, which means Read but as I said above for every word there is an explanation, let us see how this word formed

पठति  = पठ्‌ + + ति 

पठ्‌ – धातुः [अर्थं निर्दिशति]

अ – विकरणप्रत्ययः [गणं निर्दिशति]

ति – तिङ्‌प्रत्ययः [लकारं निर्दिशति] |

2. भ्वादिः (प्रथमः गणः = भू इत्यादयः धातवः; “भवतिइत्यादीनि क्रियापदानि) | यस्य गणस्य आदौ भू-धातुः अस्ति, सः भ्वादिगणः |

विकरण प्रत्ययः शप्‌ → अ

उदाखाद्‌ (खादति), पठ्‌ (पठति), क्रीड्‌ (क्रीडति), वद्‌ (वदति); शुच्‌ (शोचति), वृत्‌ (वर्तते); जि (जयति), स्रु (स्रवति), हृ (हरति)

Hope these simple examples help us to understand how rich the sanskrit language is. All I am trying to tell here is learn sanskrit, we have plenty of online courses, videos, mobile applications but I prefer the following pointers because these mobile apps for sanskrit are really very nice.

Online tutorials For Learning Sanskrit

Learning Sanskrit From Home

Sanskrit Learning Online Courses : http://www.sanskritfromhome.in/

Sanskrit Learning YouTube Videos : https://www.youtube.com/channel/UCp5mvCwXR-drTRyzNUUjdZg

Sanskrit Learning Android Mobile Applications : https://play.google.com/store/apps/developer?id=Vyoma_labs&hl=en

For CBSC Students : www.cbsesanskrit.com

Read More about Sanskrit : Interesting Facts About Sanskrit