Javascript Interview Question


Javascript Interview Question
Today I came across an interesting interview question in javascript.

function testOk(abcd){
return abcd && "ok" ||"not ok";
}

Will this work? What will be the output?

testOk(65)
>>"ok"
testOk(0)

>>"not ok"
testOk("a")
>>"ok"
testOk(true)
>>"ok"
testOk(false)

>>"not ok"

So abcd && "ok" || "not ok"; is equivalent to abcd ? "ok" : "not ok";

The trick here is for &&, it should verify both sides and for ||, it is not required all the time. For || operator, if left part is true, it is not required to process right part.

var abcd = 10;  
abcd == 10 && doSomething(); // is the same thing as if (abcd == 10) doSomething(); 

abcd == 5 || doSomething(); // is the same thing as if (abcd != 5) doSomething();

Sencha ExtJs: How to make a Panel Transparent

Sencha ExtJs: How to make a Panel Transparent

Just add bodyStyle: 'background:transparent" as below. :)

Ext.define('MyApp.view.myPanel', {
extend: 'Ext.form.Panel',
bodyStyle: 'background:transparent;",
html : "test"
});

Reference:

https://www.sencha.com/forum/showthread.php?37270-How-to-make-a-panel-transparent

JavaScript Style Guide by Google


JavaScript Style Guide by Google

Sharing an article having useful information on  JavaScript Style Guides used by Google.

http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

Sencha cmd change port

Sencha cmd Change Port Number

sencha web -port 8000 start

When we generate and run app using sencha cmd, by default it will map to http://localhost:1841/. The port number can be changed by specifying the port number as above while starting the server.

eg:

D:\senchaSamples\sample_app>sencha web start
Sencha Cmd v5.1.1.39
[INF] Mapping http://localhost:1841/ to ....
[INF] ------------------------------------------------------------------
[INF] Starting web server at : http://localhost:1841
[INF] ------------------------------------------------------------------
^C
D:\senchaSamples\sample_app>sencha web -port 8000 start
Sencha Cmd v5.1.1.39
[INF] Mapping http://localhost:8000/ to ....
[INF] ------------------------------------------------------------------
[INF] Starting web server at : http://localhost:8000
[INF] ------------------------------------------------------------------



Mind Your Email Manners - Tips from the etiquette expert

Mind Your Email Manners - Tips from the etiquette expert

Email is often the first impression that others get of you. Here are some tips from the etiquette expert Jacqueline Whitmore, who has done executive coaching and leadership training programs for various Fortune 500 companies.

  1. Err on the side of being more formal. 
  2. An email deserves a greeting.
  3. Mirror the person you are emailing.
  4. The rule is you should reply to an email within 24 hours. Even if you don’t have an answer for someone, reply anyway and say 'Thank you for your email—I’ll get back to you by such and such a date'.
  5. If you haven’t spoken to the person, it’s best to put some little nicety in the front, like ‘Happy New Year’ or ‘I hope you had a great holiday'.The safest way to sign off is ‘Best regards' 
  6. Always keep the sentences very short 
  7. Remember that emails can be forwarded, they can be duplicated - Keep emotions out of it, and keep it simple.
  8. No one can see your facial expressions or hear your tone of voice, so the only way they’re gauging your emotions is the tone that you use in that email -add words such as 'I’m happy to do it' to convey a little warmth. 
  9. 'Text speak' is a strict don’t . Acronyms such as 'lol' don’t have a place in a business email.
  10. Reserve writing messages in all lowercase letters for personal emails. 
  11. Make sure nothing is misspelled. It can reflect poorly on your company if you send a poorly composed email. 
  12. Also, be sure to put in a clear subject line at the top—something busy professionals prize.  
  13. A signature tag line beneath your signoff is a must 
  14. Don’t put unnecessary things in your signature like quotes or religious sayings 


http://www.wsj.com/articles/mind-your-email-manners-1429117413

New technologies in software testing

 New technologies in software testing

Found a document on New technologies in software testing - www.professionaltester.com/files/pt-issue2.pdf

Create HTML5 App using SenchaCmd - Sencha ExtJs 5

Create HTML5 app using cmd commands
Sencha Ext Js 5 

We can create HTML5 apps using Sencha cmd just typing some commands. See below.

sencha -sdk /path/to/sdk generate app MyApp /path/to/myapp
cd /path/to/myapp
sencha app watch 

eg: Open command prompt and enter as below,


If we go to http://localhost:1841/,



If we check the folder,


Any Error? Check following are installed on your machine. (Windows)

1. Java Runtime Environment version 1.7
How to check? Enter java -version in cmd
Installed, still not coming? check java is included in path environment variable
eg: C:\Program Files (x86)\Java\jre7\bin;

2. Ruby
How to check? Enter ruby -v in cmd
Installed, still not coming? check ruby is included in path environment variable
eg: C:\Ruby21\bin;

3. Sencha Cmd
How to check? Enter sencha in cmd
Installed, still not coming? check sencha cmd is included in path environment variable
eg: C:\Users\username\bin\Sencha\Cmd\5.1.1.39


Apple Watch Apps and Resources

Create your free Apple Watch App prototype in just 10 minutes.
No coding required.

GIT Setup



Steps to setup GIT:

1. Install GIT

2. Go to your code base location

3. Create a .gitigonore file to the root directory of project

4. Add the below content to the .gitignore file
.svn
.gitignore
.DS_Store

5. Run the following command from the root directory. This is to be done only once

git init

6. Run the following commands everytime when you want to commit the changes to GIT

git add --all
git commit  -m "checkin message"

7. Go to backup location where you want to keep the backup files. Execute following command for first time

git clone "$CURRENT_PATH"

eg: git clone C:\wamp\www\app1

8. For updating backup location run the following command

git pull 

e-Verification of income tax returns using onlinesbi

 e-Verification of income tax returns using onlinesbi

Today I have e-verified my income tax return filed(2015-16) using net banking option provided by SBI. So that no need to send the hard copy of the efiling documents. Steps are as follows.

1. Login to the incometax efiling portal. if you uploaded your efile, it will be listed in e-Filed Returns/Forms.

2. Click on e-Verify. There will be 4 options,
Option 1 – I already have an EVC to e-Verify my return.
Option 2 – I do not have an EVC and I would like to generate EVC to e-Verify my return.
Option 3 – I would like to generate Aadhaar OTP to e-Verify my return.
Option 4 – I would like to send ITR-V/ I would like to e-Verify later.

3. Click on option 2, I do not have an EVC and I would like to generate EVC to e-Verify my return.

4. Select EVC - Through Netbanking in the next window. (My income was less than 5L and have refund.)



5. Click on continue from the next window. (Steps to be followed in netbanking site is described here.)
6. Select your bank. In my case it is State Bank of India(SBI).
7. Onlinesbi will be opened in a  new tab. Log in to the netbanking.



8. Click on Login to e-Filing from left menu. A high security password may be sent to your mobile number. Enter high security password sent to your mobile phone.

9. Click on confirm which confirms the details like PANCARD, Account number, etc. You will be redirected to income tax efiling site. Click on e-Verify from e-Verify return list.
10. Click on continue to confirm the verification. Done, a "Return successfully e-Verified" message will be displayed.

References:
https://incometaxindiaefiling.gov.in/eFiling/Portal/StaticPDF/e-Verification_User_Manual.pdf

Web Development Guidelines Document

Found a good documentation on Web Development Guidelines :

https://iqmskm.ultimatix.net/km/index.php/File:Org_it_Web_Application_Development_Standards_and_Guidelines.pdf

Next Version Javascript - ES6 - Harmony

Next Version Javascript - ES6 - Harmony

Interesting article on next version javascript - ECMAScript6, the upcoming version of the ECMAScript standard.
Reference: http://babeljs.io/docs/learn-es2015/#introduction
Code samples : http://www.es6fiddle.net/
ECMAScript 6 compatibility table : http://kangax.github.io/compat-table/es6/
ECMAScript6 is also called as “ES6″, “Harmony” and “ES.next”, which supports Classes, Promises, Octal/Binary numbers and Templates etc.

New features of ES-6 below :

  • Arrows
  • Classes
  • Enhanced Object Literals
  • Template Strings
  • Destructuring
  • Default + Rest + Spread
  • Let + Const
  • Iterators + For..Of
  • Generators
  • Comprehensions
  • Unicode
  • Modules
  • Module Loaders
  • Map + Set + WeakMap + WeakSet
  • Proxies
  • Symbols
  • Subclassable Built-ins
  • Math + Number + String + Object APIs
  • Binary and Octal Literals
  • Promises
  • Reflect API
  • Tail Calls

Machine Learning Video Library - California Institute of Technology

Machine Learning Video Library - California Institute of Technology

Some useful free tutorials from California institute of technology on Machine Learning.

http://work.caltech.edu/library/


Very useful one.

http://work.caltech.edu/telecourse.html

iscroll - Javascript Scroller Plugin

iscroll - Javascript Scroller plugin

Recently I have started using iscroll, a javascript scroller. It has got tons of features, a few of which are:
1. Custom events such as onBeforeScrollStart, onScrollStart, onScroll, onScrollEnd, flick, etc.
2. Animation with user defined easing functions, bounce, elastic, etc.
3. Enable/disable scroll bar, fade or style the scroll bar.
4. Programmatic scrolling - scrollTo(x, y, time, easing), scrollBy(x, y, time, easing), scrollToElement(el, time, offsetX, offsetY, easing).

For the full list of configurable options and demo, check out : https://github.com/cubiq/iscroll

Example:

HTML:

<div class="wrapper">
<div class="content"></div>
</div

JS:

// On load
var scrollBar = new IScroll(".wrapper", {
                    scrollX: true,
                    scrollY: true,
                    mouseWheel: true,
                    bounce: true
                });

Google's "material design lite" toolkit

Google's  "material design lite" toolkit

Google wants to incoporate material design to all websites , releases toolkit.

http://www.getmdl.io

CORS (Cross Origin Resource Sharing) and Disabling Web Security

CORS (Cross Origin Request Policy) and Disabling Web Security



You might have come to this error XMLHttpRequest cannot load xxx.com/xxx/... No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin abc.com is therefore not allowed to access. Here abc.com want to access resources of xxx.com, but browser is telling it is not allowed to access the resource since 'Access-Control-Allow-Origin' header is not present. This is due to cross origin resource sharing(CORS) policy.

According to w3c specification, cross domain communication is possible. That is abc.com can access the resources of xxx.com provided xxx.com should allow others to access its resources. Xxx.com can allow others to access its resources by setting 'Access-Control-Allow-Origin' to its response header. If it is not set, then the resources can not be accessed from other domains. Usually 'Access-Control-Allow-Origin' is set for public data.

If you are a web developer, you might have faced this above issue. For Google chrome, you will get some relax by disabling web security. That is you can still access the data from other domain even if  'Access-Control-Allow-Origin' is not set by disabling web security in chrome browser.

To disable web security, make a shortcut for chrome on desktop, and in the shortcut properties add the parameter --disable-web-security at the end of chrome executable path.

"C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security

Close all chrome windows/tabs and start Chrome using this shortcut icon. If web security is disabled, you will  see the yellow bar below the address bar with the warning message.

Object Oriented Javascript using Mozart

Object Oriented Javascript using Mozart

"Do java like programming in javascript." We can develop web applications following OOPs concepts with mozart js. It also helps to develop mvc architecture. Mozart is inheritance library.
It has got following features

  • Simple subclassing.
  • Private and protected methods and properties.
  • Intuitive super method calling.
  • Dynamic getter and setter generation.


Reference: https://github.com/philipwalton/mozart

Chrome Developer Tools: Break point on Exceptions or Error

Chrome Developer Tools: Break point on Exceptions or Error

Today I found a good feature in chrome developer tools which pause the execution of Javascript code on exceptions or errors. This will definitely help in debugging js code.


splice() - Push or pop to array at position


splice() - Add or remove elements to array at position

I have been trying to push an element to array at position. I found splice() method in javascript as a solution.

splice() can be used for adding/removing elements in array at given position.

Array.splice(position, numberOfElementsToRemoveFromPosition, ElementsToPushAtPosition)

Eg:
var array1=[1,2,3,4,5]

Adding at "0" added to 0th position
array1.splice(0,0,0)

array1 -> [0, 1, 2, 3, 4, 5]

Adding "6" at 6th position
array1.splice(6,0,6)

array1 -> [0, 1, 2, 3, 4, 5, 6]

Removing 2 elements from 2nd index , ie removing 2 and 3
array1.splice(2,2)
[2, 3]
array1 -> [0, 1, 4, 5, 6]

adding 2 elements at 2nd index , ie adding 2 and 3
array1.splice(2,0,2,3)
[]
array1 -> [0, 1, 2, 3, 4, 5, 6]

Removing "6" at 6th position and adding "7" and "8"
array1.splice(6,1,7,8)
[6]
array1 -> [0, 1, 2, 3, 4, 5, 7, 8]

References:
http://www.w3schools.com/jsref/jsref_splice.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

_.pluck - Pluck attribute values from array of objects

_.pluck() - Pluck attribute values from array of objects

I came to know a very useful function from underscorejs, _.pluck()  which will return array of attribute values of objects from Array of objects, ie pluck attribute values from array of objects.
eg: var data = [
                {
                    "name": "India",
                    "population": "120",
                    "currency": "Indian rupee",
                    "id": ""
            },
                {
"name": "China",
                    "population": "125",
                    "currency": "Renminbi",
                    "id": ""
            },
                {
                  "name": "USA",
                    "population": "50",
                    "currency": "US Dollars",
                    "id": ""
    }
   ]

  _.pluck(data,"name")
["India", "China", "USA"]

devdocs - Documentation of all APIs at one place

devdocs - Documentation of all APIs at one place

DevDocs contains collection of API documentations in a fast, organized, and searchable interface.
We can find documentation for different APIs like HTML, CSS, Javascript, JQuery, Angular, Backbone, C, C++..

We can search a library or keyword. It is available offline and can be installed in browsers and mobile devices. Keyboard shortcuts are available.  We can disable or enable a particular library from the list. It is free and opensource.

http://devdocs.io/javascript/


If you like DevDocs, please support  Gratipay.

Number Formatting in JavaScript using toLocaleString - Thousand Separator, Currency Formatter

Number Formatting in JavaScript using toLocaleString() - Thousand Separator, Currency Formatter

Today I came across toLocaleString() in javascript which can be used for formatting numbers. Thousand separator, currency formatting etc. can be achieved using this.

var num1= 2000;
num1.toLocaleString();  // "2,000"

 Thousand separator is different for different countries. This is also possible using toLocaleString().

num1.toLocaleString("en-US");
"2,000"
num1.toLocaleString("de-DE");
"2.000"
num1.toLocaleString("ar-EG");
"Ù¢٬٠٠٠"

Currency formatting can also be done.

num1.toLocaleString('ja-JP', { style: 'currency', currency: 'INR' })

"Rs.2,000"

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

lodash - JavaScript utility library delivering consistency, modularity, performance,...

lodash - JavaScript utility library delivering consistency, modularity, performance,...


Today I found a js library just like underscore which has got many useful functions. Check it out.

https://lodash.com/

https://lodash.com/docs

http://devdocs.io/lodash-string/


How to publish a chart to bl.ocks.org

How to publish a chart to http://bl.ocks.org

You have seen awesome d3 data visualizations along with its code snippets in d3js.org gallery. Want to create and publish one like that?

If u have a beautiful visualisation created by d3js and want to publish it as a block in http://bl.ocks.org. ie You want to access your visualization via url like http://bl.ocks.org/xxxxx/06c2b5a357ad862a9157 
Here is how to do this. You just need to create a gist (ie, just need a github account).

1. Go to https://gist.github.com.
2. Create an index.html file and paste the code for your visualization in index.html. After saving your file, check the url, along with your username an id will be generated for your gist as in the example below.(Visualization for a simple dashed line).
https://gist.github.com/nidheesh872/06c2b5a357ad862a9157 
 3. Now just change the url. Replace https://gist.github.com by http://bl.ocks.org/. done.
eg: http://bl.ocks.org/nidheesh872/06c2b5a357ad862a9157

bl.ocks.org  is a tool which will convert the gist code into the format what you see in bl.ocks.org.

Animate SVG - JavaScript Libraries

Animate SVG - JavaScript Libraries

We can animate svg using javascript and CSS. However I came across some Javascript libraries for animating SVG.

1. snapsvg - http://snapsvg.io/
2. svgjs - http://svgjs.com/
3. Raphael - http://raphaeljs.com/

Difference between setTimeout() and setInterval()

Difference between setTimeout() and setInterval()

1. setTimeout():

setTimeout(
...
function or code
...

, delay);

Function or code will execute after the delay(time interval).

eg: setTimeout(function() { alert('Hi') }, 1000);

2. setInterval():

setInterval(
...
function or code
...

, delay)

Function or code will repeatedly execute for every delay interval(time interval).
eg: setInterval(function() { alert('Hi') }, 1000);

How to make sampar - easy - 10 steps

How to make sampar - easy - 10 steps

1. Take dal(parippu) with water in cooker. Wait for 3 whistles.
2. Add vegetables - drum stick (muringa kol), ladies finger(vendakka), carrot(carrot), chilly (pacha mulak) , onion (savala), tomato (thakkali),...
3. Add garlic (veluthulli), ginger (inchi).
4. Add turmeric powder (manhal podi), chilly powder (mulaku podi), Coriander powder (malli powder), sampar powder (sampar podi).
5. Add tamarind (mixed with water).
6. Add salt.
7. Add coconut. (optional, I didn't add. :))
8. Add asafoetidia (Kayam).  (optional)
9. Add curry leaf
10. Add mustard(kaduk) with oil. (kaduk potikkuka or varathikduka).

done.

Javascript MemoryLeak Issues

Javascript Memory Leak Issues

We have been facing memory leak issues while developing html5 apps. It is observed that app is broken after browsing through the pages in the app. The memory usage is increased by time. The memory is not released after use. So we searched for some solution and found some technic which will improve memory usage.

1. Nullify the references after use and delete them
Eg: var name1 = someObject;
after scope,
name1 = null;
delete name1;

2. Remove domElements after use(jquery)
var name2 = $("something");
after scope,
name2.remove();

Javascript Format Date, Number and Currency - Moment.js, Numeral.js and Accounting.js

Format Date, Number and Currency - Moment.js, Numeral.js and Accounting.js

I came to know libraries which help us in formatting numbers, dates and currency.

1. Moment.js - To parse, validate, and format dates.

Examples:
moment().format('MMMM Do YYYY, h:mm:ss a'); // April 4th 2015, 3:11:47 pm
moment().format('dddd');                    // Saturday
moment().format("MMM Do YY");               // Apr 4th 15

// selecting time zone
moment.tz("2015-04-04 11:55", "Indian/Mauritius").format(); // "2015-04-04T11:55:00+04:00"
moment.tz("March 12th 2015 8PM", "MMM Do YYYY hA", "Indian/Mauritius").format();
 // "2015-03-12T20:00:00+04:00"


Url: http://momentjs.com/


2. Numeral.js - To format numbers

Examples:
numeral(10000).format('0,0'); // "10,000"
numeral(10000).format('$0,0');  // "$10,000"
numeral(10000).format('0b'); // "10KB"
numeral(0.10).format('0%'); // "10%"

Url: http://numeraljs.com/

3. Accounting.js - To format numbers, money and currency

Examples:
accounting.formatMoney(1000); // "$1,000.00"

// Indian rupee currency formatting
accounting.formatMoney(1000.99, "₹", 2, ".", ","); // "₹1.000,99"

Url: http://openexchangerates.github.io/accounting.js/

Nice Tutorial on D3.js - Interactive data visualization: D3 - by Mahbubul Majumder

Nice Tutorial on D3.js - Interactive data visualization: D3 - by Mahbubul Majumder

http://www.unomaha.edu/mahbubulmajumder/data-science/fall-2014/lectures/18-interactive-d3/18-interactive-d3.html#/

Draw Class Diagram in Eclipse - ObjectAid


The ObjectAid plug-in in Eclipse can be used to draw class-diagrams.

http://www.objectaid.com/download

The Responsive jQuery Content Slider

The Responsive jQuery Content Slider

Came to know about a slider.The Responsive jQuery Content Slider. It is responsive. The content can be images, videos or HTML content.

License : The MIT License (MIT)

more info : http://bxslider.com/

Height and Span

Can we set height to span?

Can we set height to span? The answer is no. Span is an inline element. If you provide height to span, there will not be any effect. If you really want to set height then you will have to add  display : inline-block or display : block.

Finding Dimension of Text in Pixels - HTML5 Javascript JQuery

Finding Width & Height of Text in Pixels
HTML5 - Javascript - JQuery

For Div, Span
I came across a problem that i want to find width of the text in my page in order to properly align it. I found the solution using JQuery.
Steps
1. Wrap the text in a span and append to some element say to a div.

$(div).append("<span id='find-length'>"+text+"</span>").

2. Find width and height using JQuery.
var textWidth = $("#find-length").width();
var textHeight = $("#find-length").height();

For SVG
For finding dimension of svg text element we will make use of  getBBox() method.

Eg: var dimension = element.getBBox();
var textWidth = dimension .width;

var textHeight = dimension .height;

Passportjs-Authentication Middleware for Node.js


Passportjs-Authentication Middleware for Node.js.


Came to know about authentication middleware for Node.js - Passport.  It has got strategies support authentication using a username and password, Facebook, Twitter, and more.

Features:
  • Support of 140+ authentication strategies
  • Single sign-on with OpenID and OAuth
  • Easily handle success and failure
  • Supports persistent sessions
  • Dynamic scope and permissions
  • Lightweight code base

http://passportjs.org/