Java, NoSQL, SQL, REST API and other scary words

Best Practice to display image on a page

Let’s start with something simple – there are three universally supported image formats: GIF, PNG, and JPEG. In addition to these formats, some browsers also support newer formats such as WebP and JPEG XR, which offer better overall compression and more features. So, which format should you use?

1

At first – we should do a good work with images itself (this part is so boring, so, I’ll just provide a short list of recommendations):

  • Sizing. Developers / designers – make sure the images you deliver perfectly fit their required website dimensions. Even if the same image should be made into different sized thumbnails to fit different pages, it’s well worth creating all these different thumbnails rather than deliver a large image and rely on the browser to resize it.
  • Quality. don’t be afraid to experiment with lower JPEG quality levels. For certain websites we found that using a 50% JPEG quality yielded a very reasonable result.
  • Correct Format.Once again, PNG should be used for computer generated images (charts, logos, etc.), JPEG when you are showing a captured photograph.Notice that despite the common belief, PNG will outperform GIF in almost every other aspect.
  • Use compression tools
  • Useless data. Make sure you strip the meta-data off your images and user uploaded photos
  • Using images when CSS3 can be used. This one point is more interesting, but still, we are far away from algorithms. Just make sure you use CSS3 whenever possible. If your graphics designer is responsible for the markup, make sure you ask for CSS3 based elements where it makes sense. This thing should go as a non-functional requirement.
  • Incorrect image cache settings. we highly recommend using aggressive caching for all your website images by setting your images HTTP ‘Expires’ header to as far in the future as possible.
  • Using a single image size across all delivery mediums. The solution is pretty simple – identify your visitors mobile devices and resolution using their user agent and optionally additional client-side Javascript code. With the correct resolution in hand, retrieve the best fitting image from your servers.

Delivering static icons one by one

Other than photos and thumbnails, your website most likely includes many icons (arrows, stars, signs, marks) and auxiliary images. Google’s search results page is comprised of over 80 (!) tiny icons.

A simple solution for this problem is to utilize a CSS Sprite, a single image that contains all your smaller icons. Your web page is modified to download this single image from your server and the page’s HTML uses alternative CSS class names to point to the smaller images within the larger one.

Now, instead of 80 images, Google’s visitors download just a single image. Their browser will quickly download and cache this single image from Google’s servers and all images will be immediately visible.

To be honest, would also highly recommend Font Awesome to be implemented at your page.

Continue reading

Advertisements
Standard
Java, NoSQL, SQL, REST API and other scary words

Most popular and simple Search and Sort algorithms

Binary Search

Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].

  1. Compare x with the middle element.
  2. If x matches with middle element, we return the mid index.
  3. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.
  4. Else (x is smaller) recur for the left half.

Search an element in a sorted and rotated array

Input  : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}; key = 3

Output : Found at index 8

1) Find middle point mid = (first_element + length)/2

2) If key is present at middle point, return mid. if (arr[mid] == key) return mid;

3) Else If arr[l..mid] is sorted

  1.    a) If key to be searched lies in range from arr[l]

      to arr[mid], recur for arr[l..mid].

  1.    b) Else recur for arr[mid+1..r]

4) Else (arr[mid+1..r] must be sorted)

  1.    a) If key to be searched lies in range from arr[mid+1]

      to arr[r], recur for arr[mid+1..r].

  1.    b) Else recur for arr[l..mid]

Continue reading

Standard
Java, NoSQL, SQL, REST API and other scary words

Array Algorithms

Reverse an array or string

Input: 123

Output: 321

1) Initialize start and end indexes (start = 0, end = n-1).

2) In a loop, swap arr[start] with arr[end] and change start and end as follows (start = start +1; end = end – 1)

Given an array A[] and a number x, check for pair in A[] with sum as x

1) Sort the array in non-decreasing order. sort(A, 0, arr_size-1);

2) Initialize two index variables to find the candidate elements in the sorted array.

   (a) Initialize first to the leftmost index: l = 0

  (b) Initialize second  the rightmost index:  r = ar_size-1

3) Loop while l < r.

   (a) If (A[l] + A[r] == sum)  then return 1

   (b) Else if( A[l] + A[r] <  sum )  then l++

   (c) Else r–

4) No candidates in whole array – return 0

/* The main function that implements QuickSort() arr[] –> Array to be sorted, low  –> Starting index, high  –> Ending index */

static void sort(int arr[], int low, int high)

{

    if (low < high)

    {

        /* pi is partitioning index, arr[pi] is now at right place */

        int pi = partition(arr, low, high);

        // Recursively sort elements before partition and after partition

        sort(arr, low, pi-1);  sort(arr, pi+1, high);

    }

} Continue reading

Standard
Java, NoSQL, SQL, REST API and other scary words

Rest Chat – Avatars, News Feed and State Machine

So, as a next step I decided to implement Avatars, News Feed and State Machine.

Avatars

That was pretty simple to add avatars – add module which will handle image upload/cropping for future upload to the DB Avatar field. I found couple modules to add, but they are not 100% working:

  1. https://github.com/andyshora/angular-image-crop Zoom is not working for chrome 57.0 and angularjs 1.4.8
  2. https://github.com/allenRoyston/ngCroppie is not working at all (I made a bug – https://github.com/allenRoyston/ngCroppie/issues/32).
  3. etc

So, finally I found ngImgCrop module for this purpose.

State Machine

I used classic state machine to handle friendship statuses (and errors), so, I draw a pretty simple scheme with transitions and after that – excel file with description of every transition (including errors handling with proper messages). You will never see this error messages unless you would like to modify existing RESR URLs to try to approve friendship of some unknown user and etc.

Cause this is a pretty simple and well known area – here is some theoretical description and implementation of the state machine:

code snapshot:

case "Restore Subscription":
 switch (relationFriend){
 case 0: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 1: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 10: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 11: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 12: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 20: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 21: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 22: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 23: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 30: newRelationFriend=21; break;
 } break;
 case "Unsubscribe":

News Feed

In fact, news feed is a somewhat like a messaging, but with the different security and CQL statement of course. Therefore, new requirements for the New Feed are:

  1. Add News Feed item
  2. Edit News Feed item
  3. Delete News Feed item
  4. Add subscription
  5. Delete subscription
  6. Hide News Feed item from everybody
  7. Show News Feed item for friends only
  8. Show News Feed item for everybody
  9. Select favorite authors

I don’t want to make a full description for each requirement and don’t want to describe User Stories because I’m a Facebook user and requirements on this level are pretty obvious and straight forward. I skipped some of these requirements during implementation and will implement them during some of the next iterations.

Let me describe my current database structure (I used draw.io for that):

Let me introduce DB changes:

1)  Introduce new object to store News Feed items

2) Add fields to store avatars

So, as a result I got this demo video and a bunch of items for the next version at my backlog.

Standard
Java, NoSQL, SQL, REST API and other scary words

Angular JS – implement Emoji

Today I’ll show you how to implement custom emoji (in fact – how to replace any text with any image) with AngularJS. In fact, that will kill you browser, cause this is a pretty heaven operation and for the chat application, which refreshes every 3 seconds, such kind of solution is a real disaster.

So, the first step is to implement custom binding for your text, you could easily do it this way:

2017-03-27_12-02-15

As you can see – I’m using emoji function here, and here is my code listing:

var emoticons = {
 ':)' : getUrlToMessages +'img_smile.png',
 ':(' : getUrlToMessages +'img_sad.png',
 ':D' : getUrlToMessages +'img_haha.png',
 ':o' : getUrlToMessages +'img_omg.png'
 }, patterns = [], metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;

$scope.emoji = function(message){
   if (message != null){
   // build a regex pattern for each defined property
   for (var i in emoticons) {
     if (emoticons.hasOwnProperty(i)){ // escape metacharacters
     patterns.push('('+i.replace(metachars, "\\$&")+')');
     }
   }
   // build the regular expression and replace
   return message.replace(new RegExp(patterns.join('|'), 'g'), function (match) {
     var escape = typeof emoticons[match] != 'undefined' ? '<img src="' + emoticons[match] + '" />' : match;
     return $sce.trustAsHtml(escape);
   });
 }
}

As far as I don’t want to use any custom images,  I’ll just use decimal code emoji. This is not so straightforward cause Angular’s $sanitize service attempts to convert the characters to their HTML-entity equivalent.  To avoid that HTML going through $sanitize – pass your string through $sce.trustAsHtml:

$scope.emoji = function(message){
 return $sce.trustAsHtml(message);
 }

I would highly recommend to use Unicode instead of this!

Standard
Java, NoSQL, SQL, REST API and other scary words

Cassandra Datastax and Java – best way to set up connection

I’ll research the best way to make a connection from my Java to Cassandra here. There are a lot of examples how to do that, but the main thing, but I’m developing some kind of chat application on my localhost (will do single insert/update statements, etc.) when all this Spark examples are perfect for analytical workflows.

The first one example is Spark 1.6:

public static JavaSparkContext getCassandraConnector(){
         SparkConf conf = new SparkConf();
         conf.setAppName("Chat");
         conf.set("spark.driver.allowMultipleContexts", "true");
         conf.set("spark.cassandra.connection.host", "127.0.0.1");
         conf.set("spark.rpc.netty.dispatcher.numThreads","2");
         conf.setMaster("local[2]");

         JavaSparkContext sc = new JavaSparkContext(conf);
         return sc;
    }

So, I also got an example for Spark 2.x where the builder will automatically reuse an existing SparkContext if one exists and create a SparkContext if it does not exist. Configuration options set in the builder are automatically propagated over to Spark and Hadoop during I/O. Continue reading

Standard
QA (eng)

QA terms and questions

What are different types of software testing?

Note: Except the Shakeout testing and Unit testing which are respectively done by the CMT and Coder/Developer, all other testing are done by the QA Engineer (Tester).

1) Unit testing: It is a test to check the code whether it is properly working or not as per the requirement.  It is done by the developers (Not testers).

2) Shakeout testing: This test is basically carried out to check the networking facility, database connectivity and the integration of modules. (It is done by the Configuration Team)

3) Smoke testing: It is an initial set of test to check whether the major functionalities are working or not and also to check the major breakdowns in the application. It is the preliminary test carried out by the SQA tester.

4) Functional testingal It is a test to check whether each and every functionality of that application is working as per the requirement. It is major test where 80% of the tests are done. In this test, the Test Cases are ‘executed’.

5) Integration testing: It is a test to check whether all the modules are combined together or not and working successfully as specified in the requirement

6) Regression testing: When a functionality is added to an application, we need to make sure that the newly added functionality does not break the application.  In order to make it sure, we perform a repeated testing which is called Regression Testing.  We also do regression testing after the developers fix the bugs.  See the video below for more understanding. (Courtesy of guru99.com).

7) System testing: Testing which is based on overall requirements specification and it covers all combined parts of a system. It is also a black box type of testing. System testing is black box testing, performed by the Test Team, and at the start of the system testing the complete system is configured in a controlled environment. System testing simulates real life scenarios that occur in a “simulated real life” test environment and test all functions of the system that are required in real life. Upon completion of integration testing, system testing is started. Before system testing, all unit and integration test results are reviewed by Software QA to ensure all problems have been resolved.

8) Load testing: It is a test to check the user’s response time of number of users using any one scenario (single business process) of the same application at the same time.

9) Stress testing: In this type of testing the application is tested against heavy load such as complex numerical values, large number of inputs, large number of queries etc. which checks for the stress/load the applications can withstand.

10) Performance testing: It is a test to check the user’s response time of number of users using multiple scenarios (multiple business process) of the same application at the same time. Continue reading

Standard