How to convert image to black and white using CSS ?

Using CSS filter property we can easily apply the graphical effects like blurring or color shifting to an element. Filters are commonly used to adjust the rendering of images, backgrounds, and borders. Below are some common graphical effects-

  • Blur
  • Brightness
  • Contrast
  • Drop Shadow
  • Grayscale
  • Hue Rotation
  • Invert etc…


img {
-webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */
filter: grayscale(100%);

Programming is Easy…



JavaScript Modules : Quick Overview

As now most of the web application frameworks uses the modules so lets have a quick introduction what exactly is a module.

What is Module?:

Someone said- Good authors divide their books into chapters and sections; good programmers divide their programs into modules.

  • In JavaScript, the word “modules” refers to small units of independent, reusable code.  JavaScript modules export a value, rather than define a type. In practice, most JavaScript modules export an object literal, a function, or a constructor
  • Modules are highly self-contained with distinct functionality, allowing them to be shuffled, removed, or added as necessary, without disrupting the system as a whole
  • It is an object or collection of objects which can contain lots of logic inside it usually defined in its own file or a separate file.

For code implementations please visit to below links-

How to reset and sync local git repository with remote branch?

If you are looking a command to destroy/reset any local changes in your current git repository then below are the steps for you –

Remember to replace origin and master with the remote and branch that you want to synchronize with.

Command –

> git fetch origin && git reset –hard origin/master && git clean -f -d

Or step-by-step-

> git fetch origin
> git reset –hard origin/master
> git clean -f -d

Your local branch is now an exact copy (commits and all) of the remote branch.

We can also add these as an alias in .gitconfig file –

resetorigin = !git fetch origin && git reset –hard origin/master && git clean -f -d

Then we can type –

> git resetorigin

Programming is easy…

Transpile ES6 code to ES5 using Babel

After reading this I hope now we know what actually is ECMAScript or ES-5, ES-6 or ES-2015.

ECMAScript 6, also known as ECMAScript 2015, is the latest version of the ECMAScript standard. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now

As mentioned that all browsers are currently not supported ES6 features so we would need a transpiler like BABEL (Babel is a compiler. At a high level, it has 3 stages that it runs code in: parsing, transforming, and generation) or TRACEUR to convert ES6 code to ES5 so that all browsers can understand and execute ES6 code.

System Setup –

We can use babel built-in CLI or any build systems like grunt, gulp or webpack to load babel transpiler. Lets do system setup with both built ins CLI and gulp to convert ES6 code to ES5. I am assuming you have already installed Node in your machine 🙂

  1. Using Babel CLI :

    Below are the steps to create a sample application (ES6_to_ES5_using_babel) using ES6 code.

    • Create a folder at your preferred location. In my case this is –D:\git_public\es6_to_es5_using_babel/using-babel-cli
    • Create a JavaScript file index.js with some ES6 code like below. I am putting all my ES6 code files into scripts folder.
      let greet = () => {
              alert(‘Hello, Welcome to ES-6 world!’);
    • Open command prompt and type below commands-
      • cd D:\git_public\es6_to_es5_using_babel\using-babel-cli
      • > npm init
        • This will ask you a bunch of questions, and then write a package.json file for you
      • > npm install babel-cli –save-dev
        •  It will install the babel-cli as local package and save it in the package.json file. The local package installs the commands to the node_modules/.bin folder and these commands can be accessed using the scripts section of the package.json file.
      • Add the below code in the package.json file to run babel command to convert index.js file into ES5 code. We can also configure babel to compile all files at once or with many more options as mentioned here
        “scripts”: {
             “transpile”: “babel scripts/index.js –out-file scripts/index-transpiled.js”
      • All set, now run the below command to transpile code-
        > npm run transpile
      • YAY… index-transpiled.js file is created under scripts folder. Now see what is in this file. Is this same as ES6 code ? Yes, babel did not transpile our code to ES5. Why? because Babel doesn’t do anything. It basically acts like const babel = code => code; by parsing the code and then generating the same code back out again. We will need to add some plugins for Babel to do anything (they affect the 2nd stage i.e transformation).
      • As currently we are using ES6 only arrow function in our code so to understand lets install the only plugin to convert arrow function to ES5 compatible code.
      • > npm install babel-plugin-transform-es2015-arrow-functions -D
        • We can make it available to babel through its configuration file i.e .babelrc (recommended) or directly in the package.json file
      • So create .babelrc file in the root directory and add required plugins
            “plugins”: [“transform-es2015-arrow-functions”]
      • Now again run the command-
        >  npm run transpile
      • Now see in the transpiled file. YAY…  code is converted to ES5 code-
        let greet = function () {
             alert(‘Hello, Welcome to ES-6 world!’);
      • Now, as there are many features in the ES6 and it would be bit difficult to install plugin for each as we did for arrow function. How to solve this problem so we can use all ES6 features instead of installing plugin/package for each feature? To solve such kind of problems presets comes in the picture. Presets are sharable configurations or simply an array of plugins. If we will install a preset then it will automatically install all dependent plugins/packages. 
      • To compile code from ES6 to ES5 we haveES2015 preset which have all required plugins. So lets uninstall the plugin for arrow function which we installed earlier and install ES2015 preset.
      • > npm uninstall babel-plugin-transform-es2015-arrow-functions -D
      • > npm install babel-preset-es2015 -D
      • Now make all the ES6 plugins available to babel via .babelrc config file in the form on presets.

             “presets”: [“es2015”]
      • Now you are all set to use any ES6 feature using babel cli…. Source code can be found here….
  2. Using Gulp –

    Gulp and Grunt are widely used as task runners in front-end applications. They make it easy to configure and run tasks to perform many of the tasks that we otherwise had to perform manually. Babel has packages for both Grunt and Gulp that can be used to achieve everything that is achievable through the commands that we saw in using babel-cli.
    First things first, let’s install the required npm packages to perform Babel’s tasks with Gulp and to use require.js with Gulp. Following are the packages we need-

    • > npm init
    • > npm install gulp -g

      • Installing gulp globally so we can run gulp command directly from command prompt instead of writing script in package.json.
    • > npm install gulp-babel -D
    • > npm install babel-core -D
    • > npm install babel-preset-es2015 -D
    • Create gulpfile.js file
      var gulp = require(“gulp”);
      var babel = require(“gulp-babel”);
      gulp.task(“transpile“, function() {
    • Create .babelrc file
           “presets”: [“es2015”]
    • > gulp transpile
    • YAY…. ES6 code transpiled and put into the dist folder.

Programming is Easy…

Bower VS NPM

If you are confused between Bower and NPM then this is definitely for you. In short Npm and Bower are both Project dependency management tools. Below are some basic differences between these two-

  • Used for-
    • NPM is most commonly used for managing Node.JS modules, but it works for the front-end too when combined with Browserify etc..
    • Bower is front-end Package Manager and used for managing front end components jQuery, Bootstrap and so on.
  • Dependency-
    • NPM does nested dependency tree means packages we added in our project can also be dependent on other dependencies and those can further have more dependencies and so on. So, NPM installs dependencies for each package separately, and as a result makes a big package dependency tree(node_modules\babel-core\node_modules\…) where there could be several version of the same package.  For client-side JavaScript this is unacceptable: you can’t add two different version for jQuery or any other library to a page.The reason many projects use both is that they use Bower for front-end packages and npm for developer tools like Yeoman, Grunt, Gulp, JSHint, CoffeeScript, etc.
    • Bower requires a flat dependency tree No nested versioning of packages. With Bower each package is installed once (jQuery will always be in the bower_components/jquery folder, regardless of how many packages depend on it) and in the case of a dependency conflict, Bower simply won’t install the package incompatible with one that’s already installed.

Programming is Easy…

MongoDB Basics – Part 2 (CRUD Operaions)

Friends, After MongoDB basic overview and system setup now let’s discuss some basic CRUD operations on MongoDB.

First start MongoDB service which we installed in previous article using below command. You can change the db and log path as per your convenience –

Step-1 : Install service

>mongod –dbpath D:\MongoDbFiles\data –logpath “D:\MongoDbFiles\logs\mongo.logs” –logappend –install –serviceName mdb27017 –serviceDisplayName “MongoDB Server Instance 27017” -serviceDescription “MongoDB Server Instance running on 27017”

Step-2 : Start Service

>net start mdb27017

Step-3 : Start mongo client/shell

>mongo OR mongo.exe

As we have three things in MongoDB which are Database, Collection and Document. So lets do some CRUD operation on these.

CRUD Operations on Database (In MongoDB, databases hold collections of documents) – 

  1. Create => use DATABASE_NAME command will create a new database if it doesn’t exist, otherwise it will switch to the existing database.
    • > use TestDB 
    • switched to db TestDB
  2. Read => db command is use to display current database name and show dbs use to display all database names. If a database database does not have any record then it will not display in the list.
    • > db
    • TestDB
    • > show dbs
    • admin 0.00 GB
      local    0.00 GB
  3. Update => We have two options to rename a database. First, copy database with the new name using db.copyDatabase() method and second is create a backup of database using mongodump utility program and restore with a new name using mongorestore utility and then delete the old database. Make sure that new database is created before deleting old database.
    • Rename with Database Copy
      • > db.copyDatabase(‘old_database_name’, ‘new_database_name’)
      • { “ok” : 1 }
    • Rename with Backup/Restore
      • Backup => mongodump is a utility for creating a binary export of the contents of a database. Since its a program not command so we have to run it from the system command prompt, not the mongo shell. 
      • > mongodump –db TestDB
      • Restore => mongorestore program writes data from a binary database dump created by mongodump to a MongoDB instance. Since its also a program not command so we have to run it from the system command prompt, not the mongo shell. 
      • mongorestore –db NewTestDatabase ./dump/TestDB
  4. Delete => db.dropDatabase() is used to drop the current database.
    • > db.dropDatabase()
    • { “dropped” : “TestDB”, “ok” : 1 }

CRUD Operations on MongoDB Collections (Collections are analogous to tables in relational databases and stores documents)- 

  1. Create – There are two ways to create collections-
    • Implicit Creation – MongoDB also creates the collection when you first store data for that collection i.e If the collection does not exist, insert operations will create the collection automaticaly.
    • Explicit Creation – 
      • MongoDB provides the db.createCollection() method to explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.
      • db.createCollection(“myExplicitCollection2”, { capped : true, size : 6142800, max : 10000 } )
      • { “ok” : 1 }
  2. Read – show command is used to display all available collections 
    • > show collections
    • impCollection
  3. Update – db.COLLECTION_NAME.renameCollection(target, dropTarget) is use to update the collection name
    • > db.myNewCollection.renameCollection(“myNewRenamedCollection”, true)
    • { “ok” : 1 }
  4. Delete – db.COLLECTION_NAME.drop() is use to delete a collection
    • > db.myNewCollection.drop()
    • true

CRUD Operations on MongoDB Documents (MongoDB documents is a set of key-value pairs and basic unit of data LIKE row in the RDBMS)  –

  1. Create – Below are some methods to create documents
    • db.COLLECTION_NAME.insert(<document or array of documents>) – It allows you to insert One or more documents in the collection and Returns a WriteResult object
      • > db.testCollection.insert({a:10})
        WriteResult({ “nInserted” : 1 })
      • In the inserted document, if we don’t specify the _id parameter, then MongoDB assigns a unique ObjectId for this document
      • deprecated in major driver
    • db.COLLECTION_NAME.insertOne(document) – It allows you to insert exactly 1 document in the collection and returns the document.
      • > db.testCollection.insertOne({ _id: 10, name: “jogendra”})
        { “acknowledged” : true, “insertedId” : 10 }
    • db.COLLECTION_NAME.insertMany() –  It allows you to insert an array of documents in the collection
      • > db.testCollection.insertMany([{ _id: 1, name: “jogendra”},{name: “anmol”}])
      • {
        “acknowledged” : true,
        “insertedIds” : [
      • >{ name :”sahib”, age : 4.5})
  2. Read – 
    1. Select All Documents in a Collection. 
      • >db.COLLECTION_NAME.find(query, projection)

        • query – Optional. Specifies selection filter
        • projection – Optional. Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter
      • >db.testCollection.find({}) OR db.testCollection.find()
        { “_id” : 1, “name” : “jogendra”, “age” : 30 }
        { “_id” : 2, “name” : “anmol”, “age” : 5 }
        { “_id” : 3, “name” : “bani”, “age” : 5 }
      • To display the results in a formatted way, you can use pretty() method
    2.  Return only Selected Fields- We need to pass in the second parameter i.e projection for required fields only. _id fields always returns if not explicitly excluded.
      • db.testCollection.find({ age : 5}, {_id:false, name : true})
      • { “name” : “anmol” }
        { “name” : “bani” }
    3. Select one document in a Collection
      • db.COLLECTION_NAME.findOne(query, projection)
        • Without query returns the first document from the collection
          • db.testCollection.findOne()
          • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
        • With a Query Specification returns the first matching document from the bios collection.
          • db.testCollection.findOne({age:5})
          • { “_id” : 2, “name” : “anmol”, “age” : 5 }
    4. RDBMS Where Clause Equivalents in MongoDB – All operations are on below documents-
      { “_id” : 1, “name” : “jogendra”, “age” : 30 }
      { “_id” : 2, “name” : “anmol”, “age” : 5 }
      { “_id” : 3, “name” : “bani”, “age” : 5 } 

      • Equality (=)
        • Syntax- {:}
        • Ex- Select all documents where age=5
        • > db.testCollection.find({age:5})
        • { “_id” : 2, “name” : “anmol”, “age” : 5 }
          { “_id” : 3, “name” : “bani”, “age” : 5 }
      • Less Than (<)
        • Syntax- {:{$lt:}}
        • Ex- Select all documents where age < 5
        • > db.testCollection.find({age:{$lt:50}})
        • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
          { “_id” : 2, “name” : “anmol”, “age” : 5 }
          { “_id” : 3, “name” : “bani”, “age” : 5 }
      • Less Than Equals (<=)
        • Syntax- {:{$lte:}}
        • > db.testCollection.find({age:{$lte:5}})
        • { “_id” : 2, “name” : “anmol”, “age” : 5 }
          { “_id” : 3, “name” : “bani”, “age” : 5 }
      • Greater Than ( > )
        • Syntax – {:{$gt:}}
        • > db.testCollection.find({age:{$gt:5}})
        • “_id” : 1, “name” : “jogendra”, “age” : 30 }
      • Greater Than Equals ( >= )
        • Syntax – {:{$gte:}}
        • > db.testCollection.find({age:{$gte:30}})
        • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
      • Not Equals ( != )
        • Syntax – {:{$ne:}}
        • db.testCollection.find({age:{$ne:30}})
        • { “_id” : 2, “name” : “anmol”, “age” : 5 }
          { “_id” : 3, “name” : “bani”, “age” : 5 }
      • Like (%text%)
        • name like ‘%o%’ => contains [ / o  /]
          • > db.testCollection.find({name : /o/})
        • name like ‘j%’ => start with [ / ^ J / ]
          • > db.testCollection.find({name : / ^j /})
        • name like ‘%j’ => end with [ / i $/ ]
          • > db.testCollection.find({name : /i$/})
    5. AND in MongoDB ($and )- In the find() method, if you pass multiple keys in a array then MongoDB treats it as AND condition
      • Syntax – >
        db.testCollection.find( { $and: [ {key1: value1}, {key2:value2}] })
      • > db.testCollection.find({$and : [{age:5}, {name:”anmol”}]})
      • { “_id” : 2, “name” : “anmol”, “age” : 5 }
    6. OR in MongoDB ( $or )
      • db.testCollection.find( { $or: [ {key1: value1}, {key2:value2}] })
      • > db.testCollection.find({ $or : [{age:30}, {name : “anmol” }]})
      • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
        { “_id” : 2, “name” : “anmol”, “age” : 5 }
    7. Using AND and OR Together
      • Ex- where age <= 50 AND (name = “Jogendra” OR name = “bani”)
      • > db.testCollection.find({ age:{$lte:50}, $or:[{name :”jogendra”} , {name : “bani” }]})
      • { “_id” : 1, “name” : “jogendra”, “age” : 30 }
        { “_id” : 3, “name” : “bani”, “age” : 5 }
  3.  Update – 
    • Update a Single Document-
      • db.collection.updateOne(filter, update, options)
        • Updates a single document within the collection based on the filter.
        • > db.testCollection.updateOne({_id:1}, {$set: {name:”Jogendra Singh”, age : 31}})
        • { “acknowledged” : true, “matchedCount” : 1, “modifiedCount” : 1 }
        • > db.testCollection.updateOne({_id:1}, {$set: {name:”Jogendra Singh”, age : 31}, $currentDate: { lastModified: true }})
        • { “_id” : 1, “name” : “Jogendra Singh”, “age” : 31, “lastModified” : ISODate(“2017-09-14T19:16:31.167Z”) }
        •  $set – to update the value of the field
        • $currentDate – to update the value of the lastModified field to the current date
      • db.collection.update(query, update, options)
        • Either updates or replaces a single document that match a specified filter or updates all documents that match a specified filter.
    • Update Multiple Documents
      • db.collection.updateMany(filter, update, options)
        • Updates multiple documents within the collection based on the filter.
        • db.testCollection.updateMany({ $or: [{name:”bani”},{name : “anmol”}]}, { $set : {class: “LKG”}})
        • { “_id” : 2, “name” : “anmol”, “age” : 5, “class” : “LKG” }
          { “_id” : 3, “name” : “bani”, “age” : 5, “class” : “LKG” }
        • db.testCollection.updateMany({ age : {$lt: 30} }, { $set : {city : “Delhi”} })
        • { “_id” : 2, “name” : “anmol”, “age” : 5, “class” : “LKG”, “city” : “Delhi” }
          { “_id” : 3, “name” : “bani”, “age” : 5, “class” : “LKG”, “city” : “Delhi” }
    • Replace a Document
      • db.collection.replaceOne(filter, replacement, options)
        • Replaces a single document within the collection based on the filter.
        • To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to db.collection.replaceOne()
        • db.testCollection.replaceOne({“_id” : 3}, { firstname : “Gurbani”, lastname : “kaur”, age : 2.5})
        • { “_id” : 3, “firstname” : “Gurbani”, “lastname” : “kaur”, “age” : 2.5 }
    • Rename field name
      • $rename
        • The $rename operator updates the name of a field
        • db.testCollection.update({“_id”: 3}, {$rename : {firstname : “First-Name”}})
        • { “_id” : 3, “lastname” : “kaur”, “age” : 2.5, “First-Name” : “Gurbani” }
  4. Delete – 
    • db.collection.remove()
      • Removes documents from a collection.
      • he db.collection.remove() method can have one of two syntaxes. The remove() method can take a query document and an optional justOne boolean.
      • >db.testCollection.remove({“_id” : ObjectId(“59b992326edbc77428869952”)})
    • db.collection.deleteOne(filter, { writeConcern: , collation: })
      • > db.testCollection.deleteOne({$and : [{name:”sahib”},{age:4.5}]})
      • { “acknowledged” : true, “deletedCount” : 1 }
    • db.collection.deleteMany(, { writeConcern: , collation: })
      • Delete all documents that match a specified filter.
      • > db.testCollection.deleteMany({age : {$gte : 50}})

Programming is Easy…

MongoDB Basics – Part 1

 MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling.

MongoDB stores data in flexible BSON documents meaning fields can vary from document to document and data structure can be changed over time. BSON is a binary representation of JSON documents, though it contains more data types than JSON.

Let’s understand the terms used in MongoDB-

  1. Database – 
    • A database is an organized collection of data.
    • A physical container for collections. Each database gets its own set of files on the file system.
    • MongoDB databases hold collections of documents.
  2. Collection –
    • Collection is a group of MongoDB documents.
    • It is the equivalent of an RDBMS table. A collection exists within a single database.
    • Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.
    • MongoDB collections hold data records i.e BSON documents.
  3. Documents –
    • A record in a MongoDB collection.
    • Documents are analogous to JSON objects(but exist in the database in a more type-rich format known as BSON).
    • MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON
    • Documents have dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.
    • MongoDB documents is a set of key-value pairs and basic unit of data.



Components ?

Mongo.exe =>  The mongo shell is an interactive JavaScript interface to MongoDB and is a component of the MongoDB package. You can use the mongo shell to query and update data as well as perform administrative operations. we can start the mongo shell by using the mongo command in the command prompt.


Features ?

  1. High PerformanceMongoDB provides high performance data persistence. In particular-
    • Support for embedded data models reduces I/O activity on database system.
    • Indexes support faster queries and can include keys from embedded documents and arrays. Rich Query Language
  2. Rich Query LanguageMongoDB supports a rich query language to support read and write operations (CRUD) as well as:
  3. High Availability – MongoDB’s replication facility, called replica set(A replica set is a group of MongoDB servers that maintain the same data set, providing redundancy and increasing data availability.), provides:
    • automatic failover and
    • data redundancy.
  4. Horizontal Scalability – MongoDB provides horizontal scalability as part of its core functionality:
    • Sharding distributes data across a cluster of machines.
    • MongoDB 3.4 supports creating zones of data based on the shard key. In a balanced cluster, MongoDB directs reads and writes covered by a zone only to those shards inside the zone. See the Zones manual page for more information.
  5. Support for Multiple Storage Engines – MongoDB supports multiple storage engines, such as:
    • WiredTiger Storage Engine
    • MMAPv1 Storage Engine.



Environment Setup- 

  1. Download and Install latest version from –
    • Let’s assume default installation directory is – C:\Program Files\MongoDB\Server\3.4\bin
  2. Set Env Path variable to – C:\Program Files\MongoDB\Server\3.4\bin
    • Now check the version using below command to ensure that path is setup correctly- C:\Users\jogen>mongo -version
  3. MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is “C:\data\db”
  4. If you want to store the data files at different location so we can set the preferred location path using –dbpath as below then it will show waiting for connections message on the console output, which indicates that the mongod.exe process is running successfully. If this path contains spaces then put all its path in double qoutes.
    • C:\Users\jogen>mongod –dbpath “D:\MongoDbFiles\data”
  5. Set log path – used by mongo daemon process,for flush out logs instead of in standard console as-
    • C:\Users\jogen>mongod –logpath “D:\MongoDbFiles\logs\mongo.logs” –logappend
  6. Set port using –port, default is- 27017

We can also specify above configuration option using a config file. Config file is just text file, containing the parameters in the key=value form and each one is specified on the every line of file. We basically provide file path (which contains the configurations) as command line option as “-f” or “–config” as below-


  • C:\Users\jogen>mongod –f D:\Servers\mongodb\config\mongodb.conf
  • C:\Users\jogen>mongod –config D:\Servers\mongodb\config\mongodb.conf

Start/Stop MongoDB using the Windows services –

MongoDB also comes with excellent support to turn your MongoDB server into a windows service that gets launched automatically at startup.

  • –install : command line switch to install the service
  • –remove : command line switch to remove the service
  • –serviceName :  the name for mongod windows service and must adhere to naming services in windows like only accepting the alphanumeric chars with no spaces
  • –serviceDisplayName : Display name for service that is shown in services console, put this in double quotes if contains the spaces
  • –serviceDescription   : Small description about service, put this in double quotes if contains the spaces

To do this open command prompt with admin rights and fire below on the shell-

mongod –dbpath “D:\MongoDbFiles\data” –logpath “D:\MongoDbFiles\logs\mongo.logs” –logappend –install –serviceName mdb27017 –serviceDisplayName “MongoDB Server Instance 27017” –serviceDescription “MongoDB Server Instance running on 27017”

In log path specified, you can check for the whether windows services started or not or look into services.msc for –




GUI tool for MongoDB –

Robo 3T (formerly Robomongo) is the free lightweight GUI for MongoDB enthusiasts.


Programming is Easy…