Bootstrap 4 Tutorial

One of a kind tutorial, packed with all that is needed to start Bootstrap 4. When we are debugging an issue for some server side issue, we will need to know a lot of nit-picky details of Bootstrap. But this was a quite a walk thro’ of all the items that are needed to know and read the bootstrap code.

Freecode camp checkCashRegister problem.

I did not like the solution to this problem. But here it is., the question was about giving exact change back to user. The probiem with a $100 spent for a $3.26 purchase.


    var changeGiven = [];
    var total = 0;
    var quarters = 0;
    var pennies = 0;
    var nickels = 0;
    var dimes = 0;
    for (var totalCount = 0; totalCount < cid.length; totalCount++) {
        total = total + cid[totalCount][1];
        if (cid[totalCount][0] === "QUARTER") {
            quarters = Math.round((cid[totalCount][1] * 100 / 25), 2);
        } else if (cid[totalCount][0] === "PENNY") {
            pennies = Math.round((cid[totalCount][1] * 100 / 1), 2);
        } else if (cid[totalCount][0] === "NICKEL") {
            nickels = Math.round((cid[totalCount][1] * 100 / 5), 2);
        } else if (cid[totalCount][0] === "DIME") {
            dimes = Math.round((cid[totalCount][1] * 100 / 10), 2);
        }
    }
        return changeGiven
 

The above block solves most of the items that is needed to solve the problem. But when we are working on the $100 problem, where cashRegister had to return some definite values., here is the code snippet for that.


    var changeToGive = cash - price;
    runningChange = changeToGive;
    var runningChange;
    var twenties;
    if (total - changeToGive == 0) {
        return "Closed";
    } else if (total - changeToGive < 1) {
        return "Insufficient Funds";
    }

    if ((changeToGive  1 && changeToGive > 20) {
        twenties = cid.find(function (element) {
            return element[0] == "TWENTY";
        });
        if (changeToGive > twenties[1]) {
            runningChange = parseFloat(
                Math.round((runningChange - twenties[1]) * 100) / 100).toFixed(
                2);
        }
        changeToGive = runningChange;
        if (runningChange > 0) {
            changeGiven.push([twenties[0], parseFloat(twenties[1].toFixed(2))]);
        }

    }
    var tens;
    if (changeToGive > 1 && changeToGive > 10) {
        tens = cid.find(function (element) {
            return element[0] == "TEN";
        });
        if (changeToGive > tens[1]) {
            runningChange = parseFloat(
                Math.round((runningChange - tens[1]) * 100) / 100).toFixed(2);
        }
        changeToGive = runningChange;
        if (runningChange > 0) {
            changeGiven.push([tens[0], parseFloat(tens[1].toFixed(2))]);
        }

    }
    var fives;
    if (runningChange > 1 && changeToGive > 5) {
        fives = cid.find(function (element) {
            return element[0] == "FIVE";
        });
        if (changeToGive > fives[1]) {
            console.log("Fives more" + fives[1]);
        }
        runningChange = parseFloat(
            Math.round((runningChange - fives[1]) * 100) / 100).toFixed(2);
        if (runningChange > 1) {
            changeGiven.push([fives[0], parseFloat(fives[1].toFixed(2))]);
        } else {
            runningChange = parseFloat(
                runningChange - Math.floor(runningChange / 5) * 5).toFixed(2);
            var temp = ((Math.floor(changeToGive / 5) * 5) / 5);
            changeToGive = runningChange;
            changeGiven.push(["FIVE", parseFloat((temp * 5).toFixed(2))]);
            console.log(changeGiven);
        }
    }
    var ones;
    if (runningChange > 1 && changeToGive > 1) {
        ones = cid.find(function (element) {
            return element[0] == "ONE";
        });
        changeGiven.push(
            ["ONE", parseFloat(Math.floor(runningChange).toFixed(2))]);
        runningChange = runningChange - Math.floor(runningChange);
        changeToGive = runningChange;
        console.log(changeGiven);
    }
    if (runningChange * 100 > 24 || ((runningChange * 100)) % 25 == 0) {
        changeGiven.push(["QUARTER",
            parseFloat(Math.floor(runningChange / 0.25) * .25.toFixed(2))]);
        runningChange = runningChange - Math.floor(runningChange / 0.25) * .25;
        changeToGive = runningChange;
        console.log(changeGiven);
    }
    if (runningChange * 100 > 10) {
        changeGiven.push(["DIME",
            parseFloat((Math.floor(runningChange / 0.10) * .10).toFixed(2))]);
        runningChange = runningChange - Math.floor(runningChange / 0.10) * .10;
        changeGiven.push(["PENNY", parseFloat(runningChange.toFixed(2))]);
        console.log(changeGiven);
    }
    
    

So first we calculated how much money we have to return from a cash register. Then we have three code blocks for the dollar denominations. Each block we check if the amount returned is greater than the money inside cashRegister.
The tricky part was the calculation of the last .76 cents. We first found out how many quarters we have in that denomination. Then went to the nickel and then to dimes.
Finally, the solution needed everything in common float blocks. So before adding to the final array, we made a sanity check to ensure all amounts are on a float.

Stackoverflow survey results.

The stackoverflow survey is out for anyone who might be interested in some numbers. I was interested in the technology and the pay information.
Obviously it is good to see JAVA is still a bankable language to know. I really like the JAVA 8 world. Streams are obviously awesome, I also like the less verbosity the language gives now. JigSaw is picking up steam, but the 6 month release cycle of Oracle for new Java language seems to be a welcome change.
My biggest surprise is the spot JAVASCRIPT is holding up. It is the most dreaded as well, most popular language.
Salary of software developers seem to be holding steady. With new anti immigration policies, it going to be interesting to see how year 2019 is turning out to be.

Design discussion.

This is a great write-up. I liked the fact that, engineers were first trying to be designers. The reason is, they invented the internet and whole technical stack. But designers never fought for their place. This is so true, the design of a designer licensed professional has always turned out better for me. The other point discussed, the ROI of engaging a designer.

SpEL introduction – part 1

SpEL is a powerful utility framework provided by spring for looking up object graph. We will take a look at how to use spEL in this post. We will divide this article into two parts.

We will first create a simple object and see how SpEL is used for reading and manipulating the object graph and then in the second part of the article, we will define a properites file. Read the properties and assign it to a object variable.

SpEL expression evaluation interface

We will take take a simple object here and see how to use the expression api’s to manipulate the object.


public class SampleProgrammer{
        public String name;
        public String occupation
        @Autowired
        SampleProgrammer(String name, String occupation) {
            this.name = name;
            this.occupation = occupation;
        }
}

Now we will create the object and see how to parse the object using SpEL.


       ...
        SampleProgrammer programmer = new SampleProgrammer("Sathish Jayapal", "Programmer");
        ExpressionParser expressionParser = new SpelExpressionParser();
        Expression nameExpression = programmer.parseExpression("name");
        Expression occupExpression = programmer.parseExpression("occupation");
     // EvaluationContext context = new StandardEvaluationContext(programmer);
        String name = (String) nameExpression.getValue(programmer);
        String occupation = (String) occupExpression.getValue(programmer);
        if (logger.isDebugEnabled()) {
            logger.debug("Context Name is " + name);
            logger.debug("Context Occupation is " + occupation);
        }

Looking at the code snippet above, there are few items that we can discuss. We create an Object of the Programmer and manipulate the object tree dynmaically. We are using the expression and its sublass SpelExpressionParser parser. There are two items in the SamplePrgorammer’s programmer object. They are name and occupation. We will define an expression for each class variable. After this we use the expression class to get the value parsed. Here is the code snippet for this :


        ...
        Expression nameExpression = expressionParser.parseExpression("name"); // Define name for expression
        ...
       String name = (String) nameExpression.getValue(programmer);
       ...
       if (logger.isDebugEnabled()) {
            logger.debug("Context Name is " + name);
        ...
        }

We will discuss the reason why this following line of code is commented out.

// EvaluationContext context = new StandardEvaluationContext(programmer);

StandardEvaluationContext uses reflection API’s to identify the constructors and methods. But this is a costly object, in our example we can quickly use the getValue method to get the value.

SpEL by default is interpreter based, all expression are interpreted for evaluation. The reason for this is to give flexibility during evaluation. But if the expression evaluation is not changing often, we can switch the expression to be compiled to JAVA Class. This switch can be done using the [SpringCompilerMode][1] enum parameter. There are few available modes to operate, it is OFF, IMMEDIATE and MIXED. By default SpEL has this in the OFF mode. Immediate mode ensures that expressions are compiled right away. MIXED mode as name suggests expressions are switched between the compile and interepreter mode.

We saw a quick introduction of SpEL and some basic operation in this post. In the next part we will use SpEL to read a properties file and evaluate values.

The sample code for this is in GitHub.

Using Spring AnnotationConfigApplicationContext

Overview

Using the AnnotationConfigApplicationContext

  • We will learn how to use the AnnotationApplicationContext. We are going to create a standalone spring application, using the AnnotationApplicationContext.
  • In this example, we have two classes:

Music Class:



@Component
public class Music {
    @Autowired private String genre;
    public void setGenre(String genre) {
        this.genre = genre;
    }
    @Override
    public String toString() {
    return "Music{" + "Genre='" + genre + ''' + '}';
    }
} 

Piano class:


@Component
public class Piano {
    @Autowired
    private Music rawMusic;
    private String numberOfKeys;
    @ConstructorProperties({"rawMusic", "pianoKeys"})
    public Piano(Music music, String numberOfKeys) {
        this.rawMusic = music;
        this.numberOfKeys = numberOfKeys;
    }
    @Override
    public String toString() {
        return "Piano{" +
                "pianoMusic=" + rawMusic +
                ", numberOfKeys='" + numberOfKeys + ''' +
                '}';
    }
}

Spring Configuration

  • Now we have the POJO’s, now we are going to use the Configuration class to create these two bean objects:


@Configuration
@ComponentScan("springinjection")
public class MusicConfig {
    @Autowired Music rawMusic;
    @Autowired Music carnaticMusic;
    @Autowired Piano babyPianoMusic;
    @Autowired Piano pianoMusic;
    @Bean
    public String identifier(@Value("${genre:Generic}") String genre) {
        return genre;
    }
    @Bean(name = "rawMusic")
    @Value("#{genre}")
    public Music createMusic() {
        Music music = new Music();
        return music;
    }
    @Bean(name = "carnaticMusic")
    public Music createCarnaticMusic() {
        Music music = new Music();
        music.setGenre("Carnatic");
        return music;
    }
    @Bean(name = "pianoMusic")
    public Piano createPiano() {
        Piano piano = new Piano(rawMusic, "108");
        return piano;
    }
    @Bean(name = "babyPianoMusic")
    public Piano createBabyPiano() {
        Piano piano = new Piano(carnaticMusic, "88");
        return piano;
    }
}

String object in the Music class

The auto-wired genre property in the Music class is a bit tricky one to Initialize, spring by default treats auto-wired property as required. So when Music class is initialized the container will try to inject a value for the Genre property. But since there is no easy way to inject the String object, We are using the spEL. We will do more about the Spring EL in another post. Now that is all with our configuration file. we will use the following method expression:


@Bean
public String identifier(@Value("${genre:Generic}") String genre) {
        return genre;
}

AppRunner class

  • We will use AnnotationConfigApplicationContext API to inject and run the classes that we created. We will now look at the AppRunner class:

public class MusicRunner {
    public static void main(String args[]) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext("springinjection");
        Piano piano = applicationContext.getBean("pianoMusic", Piano.class);
        Piano babyPiano = applicationContext.getBean("babyPianoMusic", Piano.class);
        Music rawMusic = applicationContext.getBean("rawMusic", Music.class);
        System.out.println("Sathish Music :" + rawMusic);
        System.out.println("Grand Piano :" + piano);
        System.out.println("Baby Piano :" + babyPiano);
    }
}

We inform the container we are using the AnnotationConfigApplicationContext and specifying the package we are using. The other way to initialize the AnnotationConfig is using the class., for example:


ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MusicConfig.class);
        Piano piano = applicationContext.getBean("pianoMusic", Piano.class);
        
        

We have to make sure the MusicConfig class is annotated with @Configuration and the classes that it is annotating is preceding with @Component annotation. One other way to use the AnnotationConfig is to just call the default constructor and register the context at some later point. Let us take look at this sample:


AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(MusicConfig.class);
        ctx.refresh();
        Piano piano = applicationContext.getBean("pianoMusic", Piano.class);
        System.out.println("Sathish Music :" + rawMusic);
        
        

We will have to make sure we refresh the context after registering. The same came be done by passing a package as well. If we have an web application we can use the AnnotationConfigWebApplicationContext to configure.

Conclusion

We looked at how to use the AnnotationConfigApplicationContext to configure and run a spring application. With no XML code, spring now allows us to use annotations and configurations to build applications.
Code for this sample can be found in github here