Design for Server Side Pagination

In previous article, we have discussed about various type of pagination and that how these work. We have seen that in most of the scenarios, server side pagination is better than client side pagination. Client side pagination can be used only if data, i.e. the number of records, are limited. In that case, we can consider to load all data on client side and may divide the data in pages while showing on screen. However, if data is large, we would prefer the server side pagination.

In this article, we shall discuss how we can design the server side pagination component. At first, let us summarize the requirements for server side pagination.

Requirements
  • Data is large enough to support the needs of server side pagination implementation, as discussed in previous article.
  • Only current page of data (or may be 1-2 more pages) should be loaded from data repository (DB), so we want to reduce the need to load large amount of data from data repository. The same or lesser amount of data should be loaded on client side.
  • User can navigate  through the pages using next, previous, first or last page kind of actions. 
  • User can also perform 'sort' and 'search' kind of operation on the data.  
With above requirements, let us design the Pagination Component now. 

Analysis and HLD

After analysis of above requirements, following are the main design requirements:
  1. Client - Any software program which needs to retrieve the large amount of data, but want to present this to end user (or application) in pages. Client can be a UI which is showing listing of data to end user, or may be a command line tool to show the data. 
  2. We need a component which 
    1. Can maintain the state for each client. Various states needs to be maintained are: 
      1. Current Page for which data is returned last time to client
      2. Number of records to be returned for one page
      3. Various data retrieval attributes required for fetching the page data from Data Repository, using data access component. These can be 
        1. Criteria to select the desired data 
        2. Sort criteria
        3. Search criteria
        4. etc
    1. Can work as a channel to retrieve the data from repository using data access components
    2. Can provide utility methods to client for accessing the data pages based on user requests like, next | previous | first | last | specific page number
    3. Can provide methods to client using which client can change various data retrieval attributes. This is to support the scenario, when end user change the search or sort criteria at UI.
  1. We need an abstract data access layer (can call it pagination data provider), which can understand the  language of pages and can return the filtered, and sorted data for specified page. 
  2. This component can be named as 'Pagination Manager' 

Vedic Math - Square Root-2

Note: Vedic Math Blog has been moved to http://vedicmath.vedantatree.com/. Please bookmark the new address for new and existing blogs.

In this article, we shall continue discussing the remaining part of discussion 'how to find the Square Root using Vedic Math'. In last article , we discussed the technique for 4-digit numbers, In this article, we shall discuss the another technique which is useful for bigger numbers. In this method, we shall use "Duplex" (mentioned in General Squaring).

So, First observation:
  • if number is 69563217 then n=8, Digits in the square root is 8/2=4, pairing is 69'56'32'17 and the first digit will be 8(82=64)
  • if number is 764613731 then n=9, Digits in the square root is (9+1)/2=5, pairing is 7'64'61'37'31 and the first digit will be 2 (22=4)

Recall "Duplex"
• for a single digit 'a', D = a2. e.g. D(4) = 16
• for a 2-digit number of the form 'ab', D = 2( a x b ). e.g. D(23) = 2(2x3) = 12
• for a 3-digit number like 'abc', D = 2( a x c ) + b2. e.g. D(231) = 2(2x1) + 32 = 13
• for a 4-digit number 'abcd', D = 2( a x d ) + 2( b x c ) e.g. D(2314) = 2(2x4) + 2(3x1) = 22
• for a 5-digit number 'abcde', D = 2( a x e ) + 2( b x d ) + c2 e.g. D(14235) = 2(1x5) + 2(4x3) + 22 = 38  and so on.

As we know how to calculate the duplex of a number, now we learn how to use it in calculating the square root of a number?
We will explain using an example.

Example:  734449

Step1: n=6, Digits in the square root is 6/2=3, pairing is 73'44'49. Rearrange the numbers of two-digit groups from right to left as follows:
         | 73 :  4  4  4  9
.|    :
-----------------
.|    :
     As you see, in above representation, we provide spaces in front of the numbers to perform straight division, if required.

Step2: Now, find the perfect square less than the first group 73 i.e 64 and its square root is 8. Write down this 8 and the reminder 9 (73-64=9) as shown below:
         | 73 :   4   4   4   9
     16| 64 :9
     ------------------
         | 8  :

     We also calculate twice of number '8' (i.e. 8 x 2 = 16), and put that number to the left of the "|" on the second line as shown above. Here, number '16' is the divisor and which is always double of the quotient (here, quotient is 8).

Step3: Next is the gross dividend, the number which we have written after the colon on the second line appended in front of the next digit of the square. Thus, our gross dividend is 94.
 
     Since there are no digits to the right of the " " on the answer line, we will not subtract anything here. If there are any digits on the answer line to the right of the " ", then we calculate duplexes for that digit and subtract it from dividend. But here, without subtracting anything from the gross dividend, we divide 94 by the divisor 16 and put down the second Quotient digit 5 and the second reminder 14 in their proper place.
  

Vedic Math - Square roots

Note: Vedic Math Blog has been moved to http://vedicmath.vedantatree.com/. Please bookmark the new address for new and existing blogs.

Earlier we discussed "Squaring numbers near base" and "General Squaring through Duplex Process" and now we will find out how to calculate the square root of numbers. To understand this, let us first learn basic rules for finding the square root.

(1). The given number is first arranged in two-digit groups from right to left. If on left hand side, a single digit is left, that will also be counted as a group.
(2). The number of digits in the square root will be the same as the number of groups derived from the number. Examples are:
  • 25 will be having one group as '25', hence square root should be of one digit.
  • 144 will be having two groups as '44' and '1', hence the square root should be of two digits.
  • 1024 will be having two groups as '24' and '10', hence the square root should be of two digits.
(3). If the given number has 'n' digits then the square root will have n/2 or (n+1)/2 digits
(4). The squares of the first nine natural numbers are 1,4,9,16,25,36,49,64, and 81. All of these squares end with 1, 4, 5, 6, 9, 0. This means
  • An exact square never ends in 2, 3, 7 or 8
  • If a number ends in 2, 3, 7 or 8, its square root will always be an irrational number
  • If an exact square ends in 1, its square root ends in 1 or 9
  • If an exact square ends in 4, its square root ends in 2 or 8
  • If an exact square ends in 5, its square root ends in 5
  • If an exact square ends in 6, its square root ends in 4 or 6
  • If an exact square ends in 9, its square root ends in 3 or 7
(5). If a perfect square is an odd number, the square root is also an odd number
(6). If a perfect square is an even number, the square root is also an even number
(7). A whole number, which ends with an odd numbers of 0's, can never be the square of a whole number
(8). An exact square never ends in a 6 if the penultimate digit(digit that is next to the last digit) is even (eg. exact squares can not end in 26, 46, 86, etc.)
(9).An exact square never has an odd penultimate digit unless the final digit is a 6 (thus, exact squares can not end in 39,71, etc.)
(10).An exact square never ends with an even number when the last two digits taken together are not divisible by 4 (thus, no exact square can end in 22, 34 and other non-multiples of 4 if the last digit is even)

Firstly, we use "The First by the First and the Last by the Last" technique to solve the square root.

(1). 6889
     There are two groups of figures, '68' and '89'. So we expect 2-digit answer.
     Now see since 68 is greater than 64(82) and less than 81(92), the first figure must be 8.

     So, 6889 is between 6400 and 8100, that means, between 802 and 902.
     Now look at the last figure of 6889, which is 9.
     Squaring of numbers 3 and 7 ends with 9.
     So, either the answer is 83 or 87.
     There are two easy ways of deciding. One is to use the digit sums.
     If 872 = 6889
     Then converting to digit sums
     (L.H.S. is 8+7 = 15 -> 1+5 -> 6 and R.H.S. is 6+8+8+9 -> 31 -> 3+1 -> 4)
     We get 62 -> 4, which is not correct.
     But 832 = 6889 becomes 22 -> 4, so the answer must be 83.
     The other method is to recall that since 852 = 7225 and 6889 is below this. 6889 must be below 85. So it must be 83.

Note: To find the square root of a perfect 4-digit square number we find the first figure by looking at the first figures and we find two possible last figures by looking at the last figure. We then decide which is correct either by considering the digit sums or by considering the square of their mean.

(2). 5776
     The first 2-digit(i.e. 57) at the beginning is between 49 and 64, so the first figure must be 7.
     The last digit (i.e. 6) at the end tells us the square root ends in 4 or 6.
     So the answer is 74 or 76.
     742 = 5776 becomes 22 -> 7 which is not true in terms of digit sums, so 74 is not the answer.
     762 = 5776 becomes 42 > 16 -> 7, which is true, so 76 is the answer.
     Alternatively to choose between 74 and 76 we note that 752 = 5625 and 5776 is greater than this so the square root must be greater than 75. So it must be 76.

Second technique is useful for bigger numbers and in this method, we use "Duplex". In the next article, we shall continue to discuss this second technique. Until then, good luck and happy computing!!


If you like the article, you may contribute by:
  • Posting your comments which will add value to the article contents
  • Posting the article link on Social Media using the Social Media Bookmark bar
  • Connecting with 'VedantaTree' on Facebook (https://www.facebook.com/VedantaTree)

Vedic Math - Fourth Power of 2 Digit Numbers

Note: Vedic Math Blog has been moved to http://vedicmath.vedantatree.com/. Please bookmark the new address for new and existing blogs.

We discussed the cube of 2-digit number in previous article. In this article, we shall describe the fourth power of 2-digit numbers using the same formula.

The Algebraic Expression of (a + b)4

 (a + b)4 = a4 + 4a3b + 6a2b2 + 4ab3 + b4

 We can rewrite the above equation as:
           a4       a3b          a2b2           ab3        b4
                   3a3b        5a2b2          3ab3
So, apply the same rule which we applied in previous article, while finding cubic of the number. Consider the first term as a4 and the remaining terms get multiplied by b/a with the previous term.
The Difference comes in second row, in fourth power, we multiply 2nd and 4th term by 3 and 3rd term by 5.

Example: 114

            1    1    1    1    1
                 3    5    3
          -------------------------
            1    4    6    4    1
          -------------------------

Example: 324
         
            81     54      36     24     16
                   162    180     72
          -------------------------------------
          104      8       5        7       6
          -------------------------------------

The "Binomial Theorem" is thus capable of practical application more comprehensively in Vedic Math. Here it is been utilised for splendid purpose as described above, with Vedic Sutras.

If you like the article, you may contribute by:

  • Posting your comments which will add value to the article contents
  • Posting the article link on Social Media using the Social Media Bookmark bar
  • Connecting with 'VedantaTree' on Facebook (https://www.facebook.com/VedantaTree)



Vedic Math - Cube of 2 Digit Numbers

Note: Vedic Math Blog has been moved to http://vedicmath.vedantatree.com/. Please bookmark the new address for new and existing blogs.

Cube of numbers plays an important role in mathematics calculations, like in finding cube root of the numbers. So it is useful if we can do the cube of numbers quickly. We are trying for the same here using 'Anurupya Sutra' of Vedic Math. Let us learn how we can do it.

Cubes of the single digits i.e. from (1 to 9) are given below:
 13  = 1,              23  = 8,              33  = 27,            43  = 64,            53  = 125,
63  = 216,          73  = 343,          83  = 512,           93  = 729,          103  = 1000

If we observe closely, the last digit of every cubic number is unique i.e. numbers from (1 to 9) does not repeat. This observation will be very helpful while calculating cube roots of any 2-digit numbers.

Let us first see the Algebraic Expression for Cube root:

(a + b)3 = a3 + 3a2b + 3ab2 + b3

Above expression for cube root of (a + b) contain 4 terms in total.
  • 1st term is  a3
  • 2nd term is a2b =  a3  x (b/a)  = 1st term x (b/a)
  • 3rd term is ab2 = a2b x (b/a) = 2nd term x (b/a)
  • 4th term is b3   = ab2 x (b/a) = 3rd term x (b/a)

Here (b/a) is the common ratio

Also, as the whole, 2nd term is 3a2b = a2b + 2a2b          {split as sum of two terms}
                      and, 3rd term is 3ab2 = ab2 + 2ab2           {split as sum of two terms}

So to find the cube, we have to compute a3 and b/a.

In Vedic Math, same formula can be used in a different way to find the cube of 2-digit numbers i.e. ab. Apply formula on 'ab' like (a+b)3 as stated above, and add the results of different rows in vertical columns. You will be able to do the cube of any two digit numbers quickly.

We shall use 'Anurupya Sutra' of Vedic Math for this cube calculation, which states:
"If you start with the cube of first digit and take the next three numbers (in the top row) in a Geometrical Proportion (in the ratio of original digits themselves), you will find that the fourth figure on the right hand will be just the cube of second digit".

Following is the step by step description of finding the cube of 2-digit number:
  • Step 1: In the first row, start with a^3 as 1st term and multiplying 1st term by (b/a) to get 2nd term.
  • Step 2: Repeat the multiplication till 4th term.
  • Step 3: In the second row, double the two middle terms (i.e. 2nd term and 3rd term) and write just below 2nd term and 3rd term.
  • Step 4: Add them vertically in columns. Carry forward the 10th place digit to next column.

The example given below will describe this method well.

Example: 113
Here a = 1 , b = 1 ,  a3 = 1 ,  b/a = 1/1 = 1          (Here common ratio is equal to 1)

Now see the formation of the table:
First Row             1     1     1     1
Second Row               2     2
                    -------------------------
Add                     1     3     3     1
113 = 1331

What is Pair Programming

Pair Programming is an interesting technique of Agile Software Development. It means to program the code in pair, i.e. two programmers work on an assignment together. One writes the code, and other think the code. One who Writes Code is called Driver, who has the steering wheel in hand i.e. the keyboard. Other who Think the Code, is called Navigator or Observer. Navigator means who helps in navigation, who shows the path, who see the good or bad road ahead and also try to find the right path to move on. One who observe the every proceeding and provide a helping hand by discussing the observations for right implementation.

What does it mean to think the code? Isn't coding about typing the programming constructs in some specific language? You should be good with that language and then write the program. Isn't that all? Probably Not.

Writing something is not all about writing. It would involve much more than writing. Suppose you are writing an article in newspaper. Whatever language you use, writing this article means first to think what to write, from where to start, what to put in for right message, and right impact. It may require a lot of research, analysis and understanding of the desired topic. It may requires a lot of brainstorming also before finalizing what to write. It may need consultation with other experienced hand. Then it would need the drafting and editing or the written matter.

Similarly writing the software program is also not only about writing the code. It means much more, many things as we have written above for a new article and probably something more specific. This is what we call "Think the Code". And this is where a Navigator or Observer helps in, by doing all such things in parallel while writing the code.

We might have used pair programming one or other time while following any of the software development techniques. We (two developers) may prefer to sit together to write a piece of software. It happens sometimes when we find any part very complex, or quite vast in concepts, tricky or might be having many integration to control and so on. And we follow the same things as we mentioned above. One write the code, and other keeps thinking what should we write considering the bigger picture of the problem. One focuses on complexities of writing the code using language constructs, and other focuses on complexities of design and integration of code. So pair programming is not started with Agile Software Development only; but it is an important step of being Agile.

In this article, we shall discuss what Extreme Programming states about pair programming. It advocates the development of most of the production code in pairs. Reason is all about its benefits as we described briefly above. In more details, these are:

Vedic Math - General Squaring

Note: Vedic Math Blog has been moved to http://vedicmath.vedantatree.com/. Please bookmark the new address for new and existing blogs.

Today, the topic which we are going to discuss is the 'General Procedure to Square any number'. Earlier we discussed about the squaring of numbers near base, however, general procedure is another nice formula to do the squaring and is applicable universally. The method or sutra is "Vertically and Crosswise", but here it is used in a different sense; based on a procedure known as 'Dwandwa Yoga' or 'Duplex Combination Process' or 'Duplex'; denoted as (D).

'Duplex' term is used in two different sense; for squaring and for multiplication. And for current formula, it will be used in both the senses. If we are having a single or central digit, then 'Duplex' means squaring that digit (a2 ). Secondly it can be used for even digits number or on numbers having equidistant digits, then 'Duplex' means to double of cross multiplication of the equidistant numbers (2ab). This concept is very important to understand the current formula and will be used in future articles also. Let us see few example to understand it more:

For 1 digit  – D(a) = single digit = a2
                     e.g. D(5) = 52  = 25
For 2 digits – D(ab) = even digits number = twice the product of the digits (2ab)
                     e.g. D(26) = 2(2)(6) = 24
For 3 digits – D(abc) = product of equidistant digits from center and square of center digits
     = twice the product of the outer digits (2ac) + the square of the middle digit (b2 )
                     e.g. D(734) = 2(7)(4) + 32
                        = 56 + 9 = 65
For 4 digits – D(abcd) = product of equidistant numbers 
                    = twice the product of the outer digits (2ad) + twice the product of the inner digits (2bc)
                     e.g. D(1034) = 2(1)(4) + 2(0)(3)
                           = 8 + 0 = 8
For 5 digits – e.g. D(10345) = product of equidistant digits and square of center digits
= 2(1)(5) + 2(0)(4) + 32 
                        = 10 + 0 + 9 = 19

and so on. This is called Duplex.

What is SwingWorker

Swing is not thread safe as discussed with previous article. That means that any task which can take long time in execution should not be performed in Event Dispatcher Thread (EDT). Otherwise the EDT will be blocked and so the whole UI. So the solution, to perform the time intensive operations, is:

  • Start a new thread from EDT
  • Perform the heavy, time consuming task in this new thread
  • When task is done, update the Swing UI state or call any operation in EDT
  • EDT will invoke the operation

To perform above steps, we need to create a thread for time consuming task and also need to devise a mechanism to invoke the Swing Operation in EDT once the task is done (inter-thread communication). This involves some of the multi-threading code and may need to repeat it again and again with every such requirement. To abstract this code, and simplify this task; Java provides a SwingWorker class to hide all the complexities and hence the repeated work to perform these operations. It is an abstract class, which should be extended and some of its methods should be overridden to get the work done.

SwingWorker class has following important methods.

execute()
This method is the main method which should be called to start the work of SwingWorker class. As soon as you call this method, SwingWorker will give call to do the time consuming task in a new thread (described below).

doInBackground()
This method should be overridden by developer to do the time consuming task. This method will be called in a new thread, other than EDT, by SwingWorker. So any task performed on this thread won't affect the Swing UI operations. Once this method is done, result will be retained by SwingWorker which can be asked by using get() method. publish() method can also be called from this method to make the intermediate results available for GUI operations.

process()
It should be overridden if we want to process any data in EDT, as and when this data becomes available during doInBackground() operation. Suppose, one program is to load the heavy file from network which is being done in doInBackground method. Depending upon the data downloaded, you want to show the progress bar or some %age downloaded in a label on UI. This can be done by putting the work to update the label or progress bar in 'process' method. From 'doInBackground' method, we need to call the 'publish' method with the values which we want to publish; like %age data downloaded in this case. SwingWorker will call process method with this data in EDT. process method then can update the UI label. One more important point, SwingWorker may coalesced the multiple calls of publish in one call to process method, if previous calls were not executed till now. So if we are calling publish with suppose '%10', '%30', and then with '%50'; it might be possible that process method is called first with '10%' and then with '30%, 50%'. Process method should handle this case.

done()
This method is called by SwingWorker when task defined in 'doInBackground' method is finished. This is a place where final Swing UI updates should be done based on outcome from 'doInBackground' method. This method is called in EDT.

Object get()
This method is used to retrieve the result of task performed by 'doInBackground' method. Point to consider, that this method is a blocking method. So calling thread will be blocked till result is not available. So it must be used carefully, as if it is called from EDT, it will block the UI operations. One of the approach to use it could be to show model dialog box till result is received.

This way, SwingWorker class save us from defining the thread safe, and multi-threaded code again and again and work as a great utility class.

Why Swing is not Thread Safe

Big questions for Swing Developers - Why Swing is not Thread Safe? What makes Sun to design the Swing in a way that it can not handle its operation in multi-threaded environment? What if they made some extra efforts to make it thread safe, many developers would be relaxing now with comparatively simpler code? And so on..

So here is the answer. Swing is not made thread safe intentionally. It was a design decision by Swing team. Why? Because thread safety always comes at a cost. And access of Swing components in multiple threads may not be required that much.

What is thread safety and Why is that costly - Thread safety means that every part of the program should be safe to access from more than one thread concurrently. Program should be able to handle the concurrent access, either by serializing the access or ensuring that it is not disrupting the shared states or operations. Serializing the access means that access should be synchronized for access by thread, which will ensure that only one thread access the code block at a time after taking the necessary lock and hence guarantee the safe access to shared states. Or design has to be done in a way that program block does not affect any shared state or won't disrupt any operations due to concurrent access to states. Both of these changes are costly in term of performance or/and application design/development.

Why Multiple Thread Access may not be required - Because most of the UI operations are done in event fired by UI itself which are sequential in nature. There are few cases when we want to touch UI functions or states in parallel threads, like if we want to perform some time intensive operation to load the data and want to keep the UI active. But these cases are limited.

So if requirement to work in multi-threaded environment is very limited, and cost to make the code ready for multi-threaded environment is high; rationale is not to implement it. However, there should be provision using which developers can manage the UI operations in multiple threads environment also as mentioned above in case of loading heavy data in parallel.

This is what Swing Team analyzed and decided. Result is a high performing GUI development library for most of the scenarios with a capability to work with multiple threads also if required.

AWT vs Swing vs SWT

AWT, Swing and SWT are three main User Interface development technologies in Java. All three can be used to develop the desktop applications. Now the question is, which one to use and when? Each of these has its own pros and cons. In this article, we shall try to understand the pros and cons of each of these.

Let us start with AWT being the first Java GUI toolkit. It comes with standard Java packaging and hence no specific installations are required. This is the simplest form of GUI toolkit, where Java provide basic set of components, layout managers, events etc to design the desktop application.

AWT is dependent on host GUI controls (native peers). For every component in AWT, one equivalent host GUI control is built. This means, AWT directly utilizes the GUI control features set provided by host and is entirely dependent on this for available features. That is why it is called Heavyweight components library. As all the host does not support all the UI control, Sun decided to provide the least common denominator from all the UI controls available on different hosts. This means that AWT is having very limited set of controls and even lacks the generally required components nowadays like Tree, Table etc. If any application needs any of these components, it needs to be develop from scratch. That is a big task to develop the components which are quite commonly required in all kind of applications.

Various positive points of AWT are:
  • It is very stable toolkit
  • It is thread safe, which means it can work well in multi-threaded environment also. 
  • It disposes the controls automatically, so application need not to worry about it.
  • UI in AWT can be created in any sequence using bottom up or top down i..e we can start from parent to children or from children to parent; in any order actually.