How can a single core processor run multiple tasks at once?

If you are reading this article then may be you are looking for some answers of questions like below-

  • How can a single core processor run multiple tasks at once?
  • How does multi-threading work in a single-core computer?
  • How does a single thread run on multiple cores?
  • Can a single core of a CPU process more than one process?
  • Multiple CPUs, Cores, and Hyper-Threading, Multitasking, Multiprocessing etc…

Or, If a computer having single core processor can run only one task at a time then how we are able to do multiple things like editing documents, hearing music, scanning computer etc… simultaneously without any interruption?

On a single-processor multitasking system, multiple processes don’t actually run at the same time since there’s only one processor. Instead, the processor switches among the processes that are active at any given time. Because computers are so fast compared with people, it appears to the user as though the computer is executing all of the tasks at once.


Multitasking on a multiple-processor system still involves the processors switching between tasks because there are almost always more tasks to run than there are processors. Note, however, that there can be as many tasks running simultaneously as there are processors in the system. Multitasking OSs can truly execute multiple tasks concurrently. The multiple computing engines work independently on different tasks.


So to make a single core able to run multiple threads, a form of time-division multiplexing was used. To simplify things a bit: the OS sets up a timer which interrupts the system at a fixed interval. A single interval is known as a time slice. Everytime this interrupt occurs, the OS runs the scheduling routine, which picks the next thread that is due to be executed. The context of the core is then switched from the currently running thread to the new thread, and execution continues.

Since these timeslices are usually very short, as a user you generally don’t even notice the switches. For example, if you play an mp3 file, the CPU has to decode the audio in small blocks, and send them to the sound card. The sound card will signal when it is done playing, and this will trigger the mp3 player to load new blocks from the mp3 file, decode them, and send them to the sound card. However, even a single-core CPU has no problem playing an mp3 in the background while you continue work in other applications. Your music will not skip, and your applications will run about as well as when no music is playing. On a modern system that is no surprise, as playing an mp3 takes < 1% CPU time, so its impact is negligible.

Multitasking :  A task generally refers to a single application/process. So multitasking means you are using multiple applications at the same time. Multitasking contrasts with single-tasking, where one process must entirely finish before another can begin. MS-DOS is primarily a single-tasking environment, while Windows XP or later OS are multi-tasking environments.

So, Multitasking refers to the ability of the OS to quickly switch between each computing task to give the impression the different applications are executing multiple actions simultaneously.

Multithreading: Multithreading extends the idea of multitasking into applications, so you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Multithreading provides a way to have more than one thread executing in the same process while allowing every thread access to the same memory address space. This allows very fast communication among threads.

Hyper-Threading: A single physical CPU core with hyper-threading appears as two logical CPUs to an operating system. The CPU is still a single CPU, so it’s a little bit of a cheat. While the operating system sees two CPUs for each core, the actual CPU hardware only has a single set of execution resources for each core. In other words, the operating system is tricked into seeing two CPUs for each actual CPU core. Hyper-threading allows the two logical CPU cores to share physical execution resources. This can speed things up somewhat—if one virtual CPU is stalled and waiting, the other virtual CPU can borrow its execution resources. Hyper-threading can help speed your system up, but it’s nowhere near as good as having actual additional cores.

Multiple Cores: Originally, CPUs had a single core. That meant the physical CPU had a single central processing unit on it. To increase performance, manufacturers add additional “cores,” or central processing units. A dual-core CPU has two central processing units, so it appears to the operating system as two CPUs. A CPU with two cores, for example, could run two different processes at the same time. This speeds up your system, because your computer can do multiple things at once.


Unlike hyper-threading, there are no tricks here — a dual-core CPU literally has two central processing units on the CPU chip. A quad-core CPU has four central processing units, an octa-core CPU has eight central processing units, and so on.

Multiple CPUs: Systems with multiple CPUs aren’t very common among home-user PCs today. Even a high-powered gaming desktop with multiple graphics cards will generally only have a single CPU. You’ll find multiple CPU systems among supercomputers, servers, and similar high-end systems that need as much number-crunching power as they can get.





Node.js Console (R.E.P.L)

Node.js comes with virtual environment called REPL (aka Node shell). The repl module provides a Read-Eval-Print-Loop implementation that is available both as a standalone program or includible in other applications. It can be accessed using: const repl = require(‘repl’);  It is a quick and easy way to test simple Node.js/JavaScript code.

  • R(Read) : Reads user’s input, parses the input into JavaScript data-structure, and stores in memory
  • E(Eval) : Takes and evaluates the data structure.
  • P(Print) : Prints the result.
  • L(Loop) : Loops the above command until the user presses ctrl-c twice

To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC-


You can execute an external JavaScript file by writing node fileName command.


Please visit to for more and deep info 🙂

Programming is Easy…

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…