Saturday, 18 December 2021

Monads in Scala

Monads belongs to Advance Scala concepts. It is not a class or a trait; it is a concept. It is an object which covers other object.

A Monad represents an object that wraps another object in Scala. Each step in Monads has an output that serves as input for subsequent steps. Although, Scala's maximum collections are Monads, but not all Monads are collections. Some Monads, for example, can be used as containers like Options.

In a brief, the data types that implement map() and flatMap() (such as Options, list) in Scala are called Monads.

There are 2 operations provided by Monads -

1. unit(): It doesn't return any value

2. flatMap(): It returns a series in place of returning a single component.


Example: Seq is a Monad as we can apply map() and flatMap() on it.

val temp = Seq("Krishna", "Kumar", "Chourasiya")

    val temp1 = temp.map(_.toUpperCase)

    //output => List(KRISHNA, KUMAR, CHOURASIYA) 

    val temp2 = temp.flatMap(_.toUppercase)

    //output => List(K, R, I, S, H, N, A, K, U, M, A, R, C, H, O, U, R, A, S, I, Y, A)




Thursday, 28 December 2017

Observable in scala

Assuming you are quite familiar with scala basic knowledge. There are three interfaces ObservableSubscription and Observer.
These interfaces are similar to Publisher, Subscription and Subscriber interfaces from the reactive streams JVM implementation. 

Observable  =========> Publisher
Observer      =========> Subscriber
Subscription =========> Subscription


Observable  

It emits its result to the observer based on the demand requested by the subscription.

Subscription

It's an one to one life cycle of an "Observer" subscribing to an "Observable".

Observer

An observer provides the mechanism for receiving push based notification from the observables.

On subscription to an Observable[TResult] the Observer will be passed the Subscription via theonSubscribe(subscription: Subscription)

Demand for results is signaled via the Subscription and any results are passed to the onNext(result: TResult) method. If there is an error for any reason the onError(e: Throwable) will be called and no more events passed to the Observer

Alternatively, when the Observer has consumed all the results from the Observable the onComplete() method will be called.

Examples:
object ObservablesLifetime extends App
{
import rx.lang.scala._
val classics = List("Dangal", "Back to the future", "Die Hard")
val o = Observable.from(classics)
o.subscribe(new Observer[String] {
override def onNext(m: String) = log(s"Movies Watchlist - $m")
override def onError(e: Throwable) = log(s"Ooops - $e!")
override def onCompleted() = log(s"No more movies.") })
}

The ScalaObservable implicit class also provides the following Monadic operators to make chaining and working with Observable instances simpler:

GenerateHtmlObservable().andThen({ case Success(html: String) => renderHtml(html) case Failure(t) => renderHttp500 })


The full list of Monadic operators available are:

  • andThen: Allows the chaining of Observables.
  • collect : Collects all the results into a sequence.
  • fallbackTo : Allows falling back to an alternative Observable if there is a failure
  • filter : Filters results of the Observable.
  • flatMap : Create a new Observable by applying a function to each result of the Observable.
  • foldLeft : Creates a new Observable that contains the single result of the applied accumulator function.
  • foreach : Applies a function applied to each emitted result.
  • head : Returns the head of the Observable in a Future.
  • map : Creates a new Observable by applying a function to each emitted result of the Observable.
  • recover : Creates a new Observable that will handle any matching throwable that this Observable might contain by assigning it a value of another Observable.
  • recoverWith : Creates a new Observable that will handle any matching throwable that this Observable might contain.
  • toFuture : Collects the Observable results and converts to a Future.
  • transform : Creates a new Observable by applying the resultFunction function to each emitted result.
  • withFilter : Provides for-comprehensions support to Observables.
  • zip : Zips the values of this and that Observable, and creates a new Observable holding the tuple of their results.

Wednesday, 29 March 2017

DeadLock in Java Thread


class WorkerThread implements Runnable {
public void run(){
method1();
method2();
}

/*
     * This method request two locks, first String and then Integer
     */
    public void method1() {
        synchronized (String.class) {
            System.out.println(Thread.currentThread().getName() + ":Aquired lock on String.class");

            synchronized (Integer.class) {
                System.out.println(Thread.currentThread().getName()+":Aquired lock on Integer.class");
            }
        }
    }

    /*
     * This method also requests same two lock but in exactly
     * Opposite order i.e. first Integer and then String.
     * This creates potential deadlock, if one thread holds String lock
     * and other holds Integer lock and they wait for each other, forever.
     */
    public void method2() {
        synchronized (Integer.class) {
            System.out.println(Thread.currentThread().getName() + ":Aquired lock on Integer.class");

            synchronized (String.class) {
                System.out.println(Thread.currentThread().getName()+":Aquired lock on String.class");
            }
        }
    }
}

public class DeadLockPrac {
public static void main(String[] args) {
WorkerThread wt = new WorkerThread();
Thread t1 = new Thread(wt);
Thread t2 = new Thread(wt);
t1.start();
t2.start();
}
}

Wednesday, 22 March 2017

Angular’s $apply() and $digest()


$apply() and $digest() are two core, and sometimes confusing, aspects of AngularJS. To understand how AngularJS works one needs to fully understand how $apply() and $digest() work. This article aims to explain what $apply() and $digest() really are, and how they can be useful in your day-to-day AngularJS programming.

$apply and $digest In deep

AngularJS offers an incredibly awesome feature known as two way data binding which greatly simplifies our lives. Data binding means that when you change something in the view, the scope model automagically updates. Similarly, whenever the scope model changes, the view updates itself with the new value. How does does AngularJS do that? When you write an expression ({{aModel}}), behind the scenes Angular sets up a watcher on the scope model, which in turn updates the view whenever the model changes. This watcher is just like any watcher you set up in AngularJS:
$scope.$watch('testModel', function(newValue, oldValue) {
  //update the DOM with newValue
});
The second argument passed to $watch() is known as a listener function, and is called whenever the value of testModel changes. It is easy for us to grasp that when the value of testModel changes this listener is called, updating the expression in HTML. But, there is still one big question! How does Angular figure out when to call this listener function? In other words, how does AngularJS know when testModel changes so it can call the corresponding listener? Does it run a function periodically to check whether the value of the scope model has changed? Well, this is where the $digest cycle steps in. 
It’s the $digest cycle where the watchers are fired. When a watcher is fired, AngularJS evaluates the scope model, and if it has changed then the corresponding listener function is called. So, our next question is when and how this $digest cycle starts.
The $digest cycle starts as a result of a call to $scope.$digest(). Assume that you change a scope model in a handler function through the ng-click directive. In that case AngularJS automatically triggers a $digest cycle by calling $digest(). When the $digest cycle starts, it fires each of the watchers. These watchers check if the current value of the scope model is different from last calculated value. If yes, then the corresponding listener function executes. As a result if you have any expressions in the view they will be updated. In addition to ng-click, there are several other built-in directives/services that let you change models (e.g. ng-model, $timeout, etc) and automatically trigger a $digest cycle.
So far, so good! But, there is a small gotcha. In the above cases, Angular doesn’t directly call $digest(). Instead, it calls $scope.$apply(), which in turn calls $rootScope.$digest(). As a result of this, a digest cycle starts at the $rootScope, and subsequently visits all the child scopes calling the watchers along the way.
Now, let’s assume you attach an ng-click directive to a button and pass a function name to it. When the button is clicked, AngularJS wraps the function call within $scope.$apply(). So, your function executes as usual, change models (if any), and a $digest cycle starts to ensure your changes are reflected in the view.
Note: $scope.$apply() automatically calls $rootScope.$digest(). The $apply() function comes in two flavors. The first one takes a function as an argument, evaluates it, and triggers a $digest cycle. The second version does not take any arguments and just starts a $digest cycle when called. We will see why the former one is the preferred approach shortly.

When Do You Call $apply() Manually?

If AngularJS usually wraps our code in $apply() and starts a $digest cycle, then when do you need to do call $apply() manually? Actually, AngularJS makes one thing pretty clear. It will account for only those model changes which are done inside AngularJS’ context (i.e. the code that changes models is wrapped inside $apply()). Angular’s built-in directives already do this so that any model changes you make are reflected in the view. However, if you change any model outside of the Angular context, then you need to inform Angular of the changes by calling $apply() manually. It’s like telling Angular that you are changing some models and it should fire the watchers so that your changes propagate properly.
For example, if you use JavaScript’s setTimeout() function to update a scope model, Angular has no way of knowing what you might change. In this case it’s your responsibility to call $apply() manually, which triggers a $digest cycle. Similarly, if you have a directive that sets up a DOM event listener and changes some models inside the handler function, you need to call $apply() to ensure the changes take effect.

How Many Times Does the $digest Loop Run?

When a $digest cycle runs, the watchers are executed to see if the scope models have changed. If they have, then the corresponding listener functions are called. This leads to an important question. What if a listener function itself changed a scope model? How would AngularJS account for that change?

The answer is that the $digest loop doesn’t run just once. At the end of the current loop, it starts all over again to check if any of the models have changed. This is basically dirty checking, and is done to account for any model changes that might have been done by listener functions. So, the $digest cycle keeps looping until there are no more model changes, or it hits the max loop count of 10. It’s always good to stay idempotent and try to minimize model changes inside the listener functions.


Note: At a minimum, $digest will run twice even if your listener functions don’t change any models. As discussed above, it runs once more to make sure the models are stable and there are no changes.


Conclusion 

I hope this article has clarified what $apply and $digest are all about. The most important thing to keep in mind is whether or not Angular can detect your changes. If it cannot, then you must call $apply() manually.

      

Tuesday, 21 March 2017

All Attributes in Spring's @Transactional Annotation

In case of Spring's declarative transaction management using annotations, there are five main attributes:

1. Propagation: This decides if method should execute within an existing/new or no transaction. Propagation.REQUIRED is the default value.



2. Isolation Level: This map to the isolation attribute of ACID properties. It decides the level of isolation between transactions. DEFAULT is the default value.



3. Read only: If an operation does not modify the data in database, but simply reads it then a read-only transaction can be used. Read only transactions provide the database with an opportunity to apply additional optimizations.As these optimizations need to be made at the start of the transaction the value of true is useful only in case of PROPAGATION_REQUIRED, PROPAGATION_REQUIRES_NEW and PROPAGATION_NESTED. The default value is false.

4.Transaction Timeout: To prevent long running transactions a timeout value can be set, which causes the transaction to rollback if it does not complete in the specified time. As the clock is started at the start of the transaction the value of true is useful only in case of PROPAGATION_REQUIRED, PROPAGATION_REQUIRES_NEW and PROPAGATION_NESTED.This value is in seconds. The default value is -1.

5. Rollback Rules: Spring commits a transaction when the method executes successfully. So accordingly to rollback a transaction, the method must fail. Failure is identified by exceptions. By default when a method throws a run-time exception, Spring will rollback the transaction. The behavior can be modified to include any exception checked or unchecked. Spring also allows us to specify exceptions on which the rollback should not occur.

Saturday, 22 October 2016

Angular Modal Service Example

Creating a Modal Service
To make a custom modal service you first need to reference the Angular UI Bootstrap script And Angular Modal Service in your main page:
<script src="scripts/bootstrap.js"></script>
<script src="scripts/angular-modal-service.min.js"></script>

Add a dependency in your application

var app = angular.module('myApp',['angularModalService'])

Modal in your Controller


Inject ModalService into your controller, directive or service and call the displayModal() function to show a modal:

app.controller('MyController', function($scope, ModalService) {

  ModalService.displayModal({
    templateUrl: "template/modalTemplate.html",
    controller: "MyModalController"
  }).then(function(modal) {
    //it's a bootstrap element, use 'modal' to show it
    modal.element.modal();
    modal.close.then(function(result) {
      console.log(result);
    });
  });
);
You will invoked "displayModal()" on clicking of the button. This function will load HTML from template/modalTemplate.html and adds it to DOM. MyModalController a separate controller specific to the Modal only. Please follow the comment mentioned in the code ass well.
Later on the above code will create the instance of MyModalController.
When this is done, the promise returned by the displayModal() function resolves and you get a modal object. This object contains the element created. If it's a Bootstrap modal just call modal to show it.
The controller that is created always has one extra parameter injected into it - a function called close. Call this function to close the modal, anything you pass to it is passed to the caller as the result object. You can use this result object in promise.
You can pass a number of milliseconds to wait before destroying the DOM element as an optional second parameter to close() function.
app.controller('MyModalController', function($scope, close) {
  close("Hello World!");
});

Example - Click Here 

Tuesday, 27 September 2016

Custom Directive Isolated Scope

Javascript Code:

var app = angular.module("myApp",[]);

app.controller("Ctrl1",function($scope){
    $scope.name = "Krishna";
    $scope.reverseName = function(){
        $scope.name = $scope.name.split('').reverse().join('');
    };
});
app.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: {},
        template: "<div>Your name is : {{name}}</div>"+
        "Change your name : <input type='text' ng-model='name'/>"
    };
});

HTML:
<div ng-app="myApp">
     <div ng-controller="Ctrl1">
        <h2 ng-click="reverseName()">Hey {{name}}, Click me to reverse your name</h2>
        <div my-directive class='directive'></div>
    </div>
</div>

We just created a directive with an isolated scope. Notice, even the parent scope has a name “Krishna”, the textbox inside directive is blank. This is because of the new Isolated scope doesn’t know anything about its parent scope.

But, can we pass some values from the parent scope to the directives now?

Yes ! Not only that, we might need to handle situations like invoking callbacks in parent scope, two-way binding between parent & directives scope ..etc

To access any parent scope data, we need to pass that to our directive explicitly. This is achieved by setting properties on the scope object in the DDO. Imagine these properties as interfaces of the directive to communicate with outside scope. Another important thing is that, these properties also MUST be set as the attributes of the directive html element.

Lets go in deep .......

Javascript code

 var app = angular.module("myApp", []);
 app.controller("MainCtrl", function( $scope ){
    $scope.name = "Krishna";
    $scope.color = "#333333";
    $scope.reverseName = function(){
     $scope.name = $scope.name.split("").reverse().join("");
    };
    $scope.randomColor = function(){
        $scope.color = '#'+Math.floor(Math.random()*16777215).toString(16);
    };
});
myApp.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: {
            name: "@",
            color: "=",
            reverse: "&"
        },
        template: [
            "<div class='line'>",
            "Name : <strong></strong>;  Change name:<input type='text' ng-model='name' /><br/>",
            "</div><div class='line'>",
            "Color : <strong style='color:'></strong>;  Change color:<input type='text' ng-model='color' /><br/></div>",
            "<br/><input type='button' ng-click='reverse()' value='Reverse Name'/>"
        ].join("")  
    };
});

It’s clear that, the controller MainCtrl creates the parent scope. This parent scope has following properties and methods -

  • name = "Krishna"
  • color =  "#333333"
  • reverseName = function for reversing the name
  • randomColor = function for generating random color code

Similarly, we’ve created our directive in Isolated scope by setting an object literal in the DDO. Now our scope object has some properties:

scope: {
        name: "@",
        color: "=",
        reverse: "&"
    }

We can see the scope properties are used in directive scope. Mostly the directive’s templates and link function are going to consume the scope properties. The behaviour of these properties again depends on their values –– also known as Prefixes –– provided. 

These Prefixes are used to bind the parent scope’s methods and properties to the directive scope. All these prefixes receives data from the attributes of the directive element.

There’re 3 types of prefixes AngularJS provides -

1. "@"   (  Text binding / one-way binding )
2. "="   ( Direct model binding / two-way binding )
3. "&"   ( Behaviour binding / Method binding  )


HTML Code:

<div my-directive 
  class="directive"
  name="{{name}}" 
  reverse="reverseName()" 
  color="color" >
</div>

When the directive encounters a prefix in the scope property, it will look for an attribute ( with same property name ) on directive’s html element. However, we can provide a different mapping between property and attributes. This is done by giving a separate attribute name after the prefix. Look at below code.
scope : {
    name: "@"
}

The above will be mapped to an attribute “name” in the directive. Now let’s see what happens if we change the code like below:

scope : {
    name: "@parentName"
}

At this time, the name property will be looking for an attribute “parent-name” in the html element to get its value. Simply, any string after the Prefixes should match the attribute name.

  • The “@” prefix is a one-way binding between the directive scope and parent scope. It always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}. Since “@” is creating a one-way binding between the parent and directive scope, any changes made in the parent scope will reflect inside the directive scope, but not the other way. “@” prefix is really useful when our directive needs to be initialised with some data from parent scope.                        
  • Secondly we have the “=” prefix. It creates a two-way binding between the parent and directive scope. The most important point about “=” prefix is, it’ll always expect the attribute value to be the model name. That means you cannot provide an expression as the value of attribute mapped to “=” prefix. This is useful, when any of our directive scope property to be same as the parent scope property.                                                                           
  • Finally, we’re going to talk about the last prefix. The “&” prefix is also known as a "Method Binding". This is used to bind any methods from the parent scope to the directive scope. This will be particularly useful when our directive needs to execute any callbacks in the parent scope. Look at the code to see how attribute value for the “&” prefix to be set.                                              
That’s it ! 

Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...