Monday, April 17, 2017

Calculate number of weaks between two dates in javascript

How could I get the difference for two Date() objects in JavaScript, while only return the number of weaks in the difference?.

I struggle a lot to find the difference between two dates and finally a lots of googling i find the below solution :


var date = new Date("2017/04/04"); var year = date.getFullYear(); var month = (date.getMonth()+1 <10) ? "0"+(parseInt(date.getMonth())+1) : parseInt(date.getMonth())+1; var day = (date.getDate()<10) ? "0"+date.getDate() : date.getDate(); var newdate = year+"/"+month+"/"+day; var date1 = new Date(newdate).getTime(); var date2 = new Date().getTime(); var dif = Math.floor(date2-date1); dif = Math.floor(dif/1000/60/60/24/7);
alert("Total number of weaks between date1 and date2 ="+dif);


You can check the above code. You will return the difference between the "2017/04/04" and Current date in weaks.



Output :



If you like this post don't forgot to leave a comment..

Chears :)

Happy Coding..


Calulate number of months between two dates in javascript

How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?.

I struggle alot to find the difference between two dates and finally alots of googling i find the below solution :


var firstdate = new Date("2017/02/15"); var seconddate = new Date(); //current date // Find no of months between years. var months = (seconddate.getFullYear() - firstdate.getFullYear()) * 12; // Find no of months between firstdate & seconddate Months. months += seconddate.getMonth() - firstdate.getMonth(); // Subtract one month if seconddate date is less that firstdate. months = (seconddate.getDate() < firstdate.getDate()) ? months-- : months;
alert("Total number of months between firstdate and seconddate ="+months);

You can check the above code. You will return the difference between the "2017/02/15" and Current date in months.

Output :



If you like this post don't forgot to leave a comment.

Chears :)
Happy coding..

Wednesday, April 12, 2017

What is the difference between a HAVING CLAUSE and a WHERECLAUSE?

There are several questions in my mind until i am not giving the answer of this question like -


  • Why do you need to place columns you create yourself (for example select 1 as "number") after HAVING and not WHERE in MySQL?
  • And are there any downsides instead of doing WHERE 1 (writing the whole definition instead of a column name)?

But now i have giving all my answers. Assume we have a table like below :



CREATE TABLE `table` (
         `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `value` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `value` (`value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

And have 10 rows with both id and value from 1 to 10 like below :


INSERT INTO `table`(`id`, `value`) VALUES (1, 1),(2, 2),(3, 3),(4, 4),(5, 5),(6, 6),(7, 7),(8, 8),(9, 9),(10, 10);

Try the following 2 queries :

SELECT `value` v FROM `table` WHERE `value`>5; -- Get 5 rows
SELECT `value` v FROM `table` HAVING `value`>5; -- Get 5 rows

You will get exactly the same results, you can see the HAVING clause can work without GROUP BY clause.


Here's the difference:

SELECT `value` v FROM `table` WHERE `v`>5;

Above Query will return an Error #1054 - Unknown column 'v' in 'where clause'


SELECT `value` v FROM `table` HAVING `v`>5; -- Get 5 rows

Main Difference :  


  • WHERE clause requires a condition to be a column in a table, but HAVING clause can use either column or alias.
  • This is because WHERE clause filters data before select, but HAVING clause filters data after select.
Try EXPLAIN to see the key difference:



EXPLAIN SELECT `value` v FROM `table` WHERE `value`>5;
+----+-------------+-------+-------+---------------+-------+---------+------+------+--------------------------+
| id | select_type | table | type  | possible_keys | key | key_len | ref  | rows | Extra |
+----+-------------+-------+-------+---------------+-------+---------+------+------+--------------------------+
1 | SIMPLE | table | range | value | value | 4  | NULL5 | Using where; Using index |
+----+-------------+-------+-------+---------------+-------+---------+------+------+--------------------------+



EXPLAIN SELECT `value` v FROM `table` having `value`>5;
+----+-------------+-------+-------+---------------+-------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key   | key_len | ref  | rows | Extra |
+----+-------------+-------+-------+---------------+-------+---------+------+------+-------------+
1 | SIMPLE | table | index | NULL | value | 4   | NULL |   10 | Using index |
+----+-------------+-------+-------+---------------+-------+---------+------+------+-------------+


You can see either WHERE or HAVING uses index, but the rows are different.


If you like this post don't forgot to leave a comment.

Chears :)

Happy Coding..






What is Indexing


What is an index?

Basically an index on a table works like an index in a book (that's where the name came from):

Let's say you have a book about databases and you want to find some information about, say, storage. Without an index (assuming no other aid, such as a table of contents) you'd have to go through the pages one by one, until you found the topic (that's a full table scan). On the other hand, an index has a list of keywords, so you'd consult the index and see that storage is mentioned on pages 113-120,231 and 354. Then you could flip to those pages directly, without searching (that's a search with an index, somewhat faster).

Of course, how useful the index will be, depends on many things - a few examples, using the simile above:


  • If you had a book on databases and indexed the word "database", you'd see that it's mentioned on pages 1-59,61-290, and 292 to 400. In such case, the index is not much help and it might be faster to go through the pages one by one (in a database, this is "poor selectivity").
  • For a 10-page book, it makes no sense to make an index, as you may end up with a 10-page book prefixed by a 5-page index, which is just silly - just scan the 10 pages and be done with it.
  • The index also needs to be useful - there's generally no point to index e.g. the frequency of the letter "L" per page. 


In  technical term an index is a data structure (most commonly a B- tree) that stores the values for a specific column in a table. An index is created on a column of a table. So, the key points to remember are that an index consists of column values from one table, and that those values are stored in a data structure. The index is a data structure – remember that.


Let’s start out our tutorial and explanation of why you would need a database index by going through a very simple example. Suppose that we have a database table called Employee with three columns – Employee_Name, Employee_Age, and Employee_Address. Assume that the Employee table has thousands of rows.
Now, let’s say that we want to run a query to find all the details of any employees who are named ‘Jesus’? So, we decide to run a simple query like this:


SELECT * FROM Employee WHERE Employee_Name = 'Jesus'


What would happen without an index on the table?

Once we run that query, what exactly goes on behind the scenes to find employees who are named Jesus? Well, the database software would literally have to look at every single row in the Employee table to see if the Employee_Name for that row is ‘Jesus’. And, because we want every row with the name ‘Jesus’ inside it, we can not just stop looking once we find just one row with the name ‘Jesus’, because there could be other rows with the name Jesus. So, every row up until the last row must be searched` – which means thousands of rows in this scenario will have to be examined by the database to find the rows with the name ‘Jesus’. This is what is called a full table scan.

How a database index can help performance?

You might be thinking that doing a full table scan sounds inefficient for something so simple – shouldn’t software be smarter? It’s almost like looking through the entire table with the human eye – very slow and not at all sleek. But, as you probably guessed by the title of this article, this is where indexes can help a great deal. The whole point of having an index is to speed up search queries by essentially cutting down the number of records/rows in a table that need to be examined.

What kind of data structure is an index?

B- trees are the most commonly used data structures for indexes. The reason B- trees are the most popular data structure for indexes is due to the fact that they are time efficient – because look-ups, deletions, and insertions can all be done in logarithmic time. And, another major reason B- trees are more commonly used is because the data that is stored inside the B- tree can be sorted. The RDBMS typically determines which data structure is actually used for an index. But, in some scenarios with certain RDBMS’s, you can actually specify which data structure you want your database to use when you create the index itself.


How does an index improve performance?

Because an index is basically a data structure that is used to store column values, looking up those values becomes much faster. And, if an index is using the most commonly used data structure type – a B- tree – then the data structure is also sorted. Having the column values be sorted can be a major performance enhancement – read on to find out why. Let’s say that we create a B- tree index on the Employee_Name column This means that when we search for employees named “Jesus” using the SQL we showed earlier, then the entire Employee table does not have to be searched to find employees named “Jesus”. Instead, the database will use the index to find employees named Jesus, because the index will presumably be sorted alphabetically by the Employee’s name. And, because it is sorted, it means searching for a name is a lot faster because all names starting with a “J” will be right next to each other in the index! It’s also important to note that the index also stores pointers to the table row so that other column values can be retrieved.

How to create an index in MYSQL/SQL? 

Here’s what the actual SQL would look like to create an index on the Employee_Name column from our example earlier:


CREATE INDEX name_index ON Employee (Employee_Name);

How to create a multi-column index in SQL?


CREATE INDEX name_index ON Employee (Employee_Name, Employee_Age);

If you like this post leave a comment from comment box.


Chears :)

Happy Coding..

Wednesday, April 5, 2017

Twitter Bootstrap alert message are not display after being closed

I have a problem with alert messages. It is displayed normally, and I can close it when the i presses x (close), but when the user tries to display it again (for example, click on the button event) then it is not shown. (Moreover, if I print this alert message to console, it is equal to [].) My code is here:


<div class="alert" style="display: none">
   <a class="close" data-dismiss="alert">×</a>
   <strong>Warning!</strong> Best check yo self, you're not looking too good.
</div>


Solution :

Actually the problem is "data-dismiss" completely removes the element. Use jQuery's .hide() method instead of data-dismiss like below:


<div class="alert" style="display: none"> 
    <a class="close" onclick="$('.alert').hide()">×</a>  
    <strong>Warning!</strong> Best check yo self, you're not looking too good.  
</div>

Please comment if you like this post Inspired By #stackoverflow

Chears :)
Happy Coding..

Tuesday, April 4, 2017

Display 1K as 1000, 1M as million and 1B as billion in angular js

I have a scenario during coding in my angular js project where i need to display the currency in short form like suppose if currency is $12000 so it should be display like $12K , 3200000 => 3M (million), 7000000000 => 7B (billion) etc

To do this i just created a simple filter currencyFormat for your angular js application :

Code :


.filter("currentFormat",function(){
    return function(number, decPlaces){
  decPlaces = decPlaces || 0;
  decPlaces = Math.pow(10,decPlaces);
  var abbrev = [ "K", "M", "B", "T" ];
  for (var i=abbrev.length-1; i>=0; i--) {
   var size = Math.pow(10,(i+1)*3);
   if(size <= number) {
     number = Math.round(number*(decPlaces/size))/decPlaces;
     if((number == 1000) && (i < abbrev.length - 1)) {
      number = 1;
      i++;
     }
     number += abbrev[i];
     break;
   }
  }
  return number;
    }
})



Now you just need to call this filter in you html code like below:


<p style="font-size:25px;font-weight:bold">&pound;{{totallendings | currentFormat}} <span>{{'LENT' | translate}}</span></p>

Output :




Please comment if you like this.

Chears 
Happy Coding:)

Wednesday, January 4, 2017

How to swap two numbers without using third variable in php?

This is a very general question of any interview in any programming language. But most of the developers not aware about the logic of this question. 

Below is the solution of it see -



$first = 10;
$second = 20;

echo "Before swapping the number is First=".$first." second=".$second.'<br>';

$first  = $first + $second;
$second = $first - $second;
$first  = $first - $second;

echo "After swapping the number is First=".$first." second=".$second;



Output :

Before swapping the number is First=10 second=20
After swapping the number is First=20 second=10 


You like this post don't forgot to leave a comment.

Chears :)
Happy coding