Friday, May 18, 2018

What you absolutely need to know about JavaScript

When it comes to making websites HTML, CSS and JS are the three core technologies you need to know.
Both JS and CSS rely on the tree structure of the web page. The tree structure is represented with the Document Object Model (DOM).

Browser compatibility

Websites are rendered by the web browsers thus JS is also interpreted by the browsers, and this is why there are differences between their capabilities in interpreting JS.
You have two options here:
  • check for browser compatibility yourself e.g. in the MDN JS Reference
  • use a compiler/polyfill e.g. Babel to take care of compatibility for you

The standardized version of JavaScript is called ECMAScript. It has several editions since 1997. The 6th edition called ES6 and ES2015 added a significant new syntax and new libraries that generally make development easier, however it is not supported by all browsers.

The main browser compatibility issue is with Internet Explorer. Currently (2018/05) the only supported Internet Explorer version is IE11 and it only gets technical support and security updates from Microsoft - instead of being developed further it is replaced by Microsoft Edge.
If you want to support IE11 you have two options here:

Why you want to use the enhanced Javascript syntax

Probably the most important new feature of ES2015 is the use of promises instead of callbacks. This was then further simplified by the introduction of the async/await keywords in ES2017. Here is a demonstration of the above, and here is a guide to picking the right asynchronous way out of the three. 
If this is not enough see what else is in ES2015.

Frameworks and Libraries

There are many frameworks and libraries to help developers implement frontend applications. If you read How it feels to learn JavaScript in 2016 you'll get a general idea of how fast the frontend technology is changing.
Here are some recent trends:

Running Javascript outside of the browser

It is possible to use JS outside of the context of a web browser, for example it can be used to write server code or desktop applications. The most well known JS runtime environment is NodeJS. It has a package manager called npm.
If you want to run tests, compile code, do style checks it is a convenient way to run these commands and maintain these dependencies through npm.

Further readings

Documentation

Thursday, May 17, 2018

Some random notes about Jenkins pipelines

First of all, there are two type of syntax:
  • Declarative
    • has a single pipeline{} block on the top level
    • it is possible to use Scripted pipeline syntax within a script{} step
  • Scripted
    • has stage('name'){} or node{} blocks on the top level
There are subtle differences:
  • Changing directories
    • in Scripted you can use the dir(){} block
    • in Declarative you cannot. One way to change directories is to change directory on every line of your commands.

Declarative pipeline

Workspace

Apparently the workspace is something that is shared within the pipeline. It doesn't matter how many different docker images you run your steps in, they will all work in the exact same directory and whatever they change will be inherited by the next stage too.

Example: Same and different agents across multiple stages modifying the same workspace

pipeline {
    agent none
    stages {
        stage ('Node build') {
            agent {
                docker {
                    image 'node:8.7.0'
                }
            }
            steps {
                sh 'npm install'
                sh 'npm run build'
            }
        }
        stage ('Node test') {
            agent {
                docker {
                    image 'node:8.7.0'
                }
            }
            steps {
                sh 'npm run test'
            }
        }
        stage ('Maven build') {
            agent {
                docker {
                    image 'maven:3.3.9'
                }
            }
            steps {
                sh 'mvn clean install'
            }
        }
    }
}

Sunday, May 6, 2018

Some common HSQLDB stored procedures

HSQLDB is the default database of LibreOffice Base.
Here are some of the stored procedures that might come in handy:

Numerical built-in Functions / Stored Procedures
ABS(d) returns the absolute value of a double value
CEILING(d) returns the smallest integer that is not less than d
FLOOR(d) returns the largest integer that is not greater than d
MOD(a,b) returns a modulo b
POWER(a,b) returns a raised to the power of b
RAND() returns a random number x bigger or equal to 0.0 and smaller than 1.0
ROUND(a,b) rounds a to b digits after the decimal point
SQRT(d) returns the square root
String built-in Functions / Stored Procedures
CONCAT(str1,str2) returns str1 + str2
LENGTH(s) returns the number of characters in s
LOWER(s) converts s to lower case
REPEAT(s,count) returns s repeated count times
REPLACE(s,replace,s2) replaces all occurrences of replace in s with s2
SUBSTRING(s,start[,len]) returns the substring starting at start (1=left) with length len
TRIM( LEADING ... FROM ...) TRIM([{LEADING | TRAILING | BOTH}] FROM <string expression>)
UPPER(s) converts s to upper case
Date/Time built-in Functions / Stored Procedures
CURRENT_DATE returns the current date
CURRENT_TIME returns the current time
CURRENT_TIMESTAMP returns the current timestamp
DATEDIFF(string, datetime1, datetime2) returns the count of units of time elapsed from datetime1 to datetime2.
The string indicates the unit of time and can have the following values (both the long and short form of the strings can be used):
  • 'ms'='millisecond', 
  • 'ss'='second',
  • 'mi'='minute',
  • 'hh'='hour', 
  • 'dd'='day', 
  • 'mm'='month', 
  • 'yy' = 'year'
DAYOFMONTH(date) returns the day of the month (1-31)
DAYOFWEEK(date) returns the day of the week (1 means Sunday)
HOUR(time) return the hour (0-23)
MINUTE(time) returns the minute (0-59)
MONTH(date) returns the month (1-12)
SECOND(time) returns the second (0-59)
YEAR(date) returns the year
System built-in Functions / Stored Procedures
CAST(term AS type)
CONVERT(term,type)
converts exp to another data type
COALESCE(expr1,expr2,expr3,...) if expr1 is not null then it is returned else, expr2 is evaluated and if not null it is returned and so on
CASE v1 WHEN... CASE v1 WHEN v2 THEN v3 [ELSE v4] END
when v1 equals v2 return v3 [otherwise v4 or null if there is no ELSE]
CASE WHEN... CASE WHEN expr1 THEN v1[WHEN expr2 THEN v2] [ELSE v4] END
when expr1 is true return v1 [optionally repeated for more cases] [otherwise v4 or null if there is no ELSE]


Notational Conventions used above
  • [A] means A is optional.
  • { B | C } means either B or C must be used.
  • [{ B | C }] means either B or C may optionally be used, or nothing at all.
  • ( and ) are the actual characters '(' and ')' used in statements.
  • UPPERCASE words are keywords

Java basics - random numbers

Math.random()

This is as simple as it gets:
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Usage:
double d = Math.random();

Random class methods

An instance of this class is used to generate a stream of pseudorandom numbers.
Here are some of the methods:
Method Return type Return value
Get the next value in the stream:
nextBoolean() boolean true or false
nextDouble() double between 0.0d (inclusive) and 1.0d (exclusive)
nextFloat() float between 0.0f (inclusive) and 1.0f (exclusive)
nextInt() int any int within int range
nextLong() long any long within long range
Generate a random integer in a given range:
nextInt(int n) int between 0 (inclusive) and the specified value (exclusive) 
Usage:
Random r = new Random();
double d = r.nextDouble();

ThreadLocalRandom class methods

A random number generator isolated to the current thread.
It's a subclass of java.util.Random, so all methods that are in Random can be used here too.
Get the instance with ThreadLocalRandom.current()
Method Return type Return value
nextDouble(double n) double between 0 (inclusive) and the specified value (exclusive)
nextDouble(double least, double bound) double between the given least value (inclusive) and bound (exclusive)
nextInt(int least, int bound) int between the given least value (inclusive) and bound (exclusive)
nextLong(long n) long between 0 (inclusive) and the specified value (exclusive)
nextLong(long least, long bound) long between the given least value (inclusive) and bound (exclusive)
Usage:
double d = ThreadLocalRandom.current().nextDouble(0.0, 1.0);

Wednesday, May 2, 2018

Java basics - Enum

An enum type is a special data type that enables for a variable to be a set of predefined constants.
An enum is static by default. There is an Enum class too, read about the differences here.

The simplest use case

public enum Status {
 TODO, DOING, DONE
}

Properties and more

The enum values can have properties assigned. The type may contain other methods that calculate using the values. It may also contain a main method.
Note: If the values have properties, these conditions must be fulfilled:
  • Semicolon after the last value declaration
  • A field for each property
  • Required arguments constructor
public enum Status {
 TODO(0, "A"), 
 DOING(1, "B"), 
 DONE(2, "C");
 
 private final int code;
 private final String variant;
 
 private Status(int code, String variant) {
  this.code = code;
  this.variant = variant;
 }

 public int getCode() {
  return code;
 }

 public String getVariant() {
  return variant;
 }
}

EnumMap

It is recommended to use EnumMap if the key is enum. The syntax to create one is:
Map<Status, Integer> map = new EnumMap<Status, Integer>(Status.class);
Then it can be used like any map with put and get.

Monday, April 30, 2018

Comparing objects in Java

This is our example class:
public class Person {
 private final int age;
 private final String name;
 public Person(int age, String name) {
  this.age = age;
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public String getName() {
  return name;
 }
}
When implementing this.compareTo(that) or compare(this, that) follow these rules:
  • return -1 if this is less than that
  • return 0 if this equals to that, also should give the same result as Object.equals()
  • return 1 if this is greater than that
The two basic ways to achieve comparison are the followings:

Implementing the Comparable interface

public class Person implements Comparable<Person> {
 // ...
 @Override
 public int compareTo(Person that) {
  if (this.getName().compareTo(that.getName()) == 0) {
   if (this.getAge() < that.getAge()) return -1;
   else if (this.getAge() > that.getAge()) return 1;
   else return 0;
  }
  else return this.getName().compareTo(that.getName());
 }
 // ...
}

Using a Comparator

The Comparator interface can be implemented by an anonymous class in the class or at the place of usage like when giving it to Collections.sort() as an argument.
If only the compare() method is implemented that's enough.
public class Person {
 // ...
 public static Comparator<Person> byAge() {
  return new Comparator<Person>() {
   @Override
   public int compare(Person p1, Person p2) {
    if (p1.getAge() < p2.getAge()) return -1;
    else if (p1.getAge() > p2.getAge()) return 1;
    else return p1.getName().compareTo(p2.getName());
   }
  };
 }

 public static Comparator<Person> byName() {
  return new Comparator<Person>() {
   @Override
   public int compare(Person p1, Person p2) {
    if (p1.getName().equals(p2.getName())) {
     if (p1.getAge() < p2.getAge()) return -1;
     else if (p1.getAge() > p2.getAge()) return 1;
     else return 0;
    }
    else return p1.getName().compareTo(p2.getName());
   }
  };
 }
 // ...
}

Sorting Objects

Now that we have ways to compare the object, we can use that for sorting:
private Person a = new Person(20, "Amanda");
private Person b = new Person(20, "Anna");
private Person c = new Person(21, "Anna");
private Person d = new Person(19, "Beata");
private List<Person> list = Arrays.asList(b, a, d, c);

// using the Comparable implementation
Collections.sort(list);
assertEquals(Arrays.asList(a, b, c, d), list);
Collections.reverse(list);
assertEquals(Arrays.asList(d, c, b, a), list);
Collections.sort(list, Collections.reverseOrder());
assertEquals(Arrays.asList(d, c, b, a), list);

// using the Comparator implementation
Collections.sort(list, Person.byAge());
assertEquals(Arrays.asList(d, a, b, c), list);
Collections.sort(list, Collections.reverseOrder(Person.byAge()));
assertEquals(Arrays.asList(c, b, a, d), list);
Further readings:

Sunday, April 22, 2018

Eclipse: frequently used keyboard shortcuts

File
Save Ctrl+S
Save All Shift+Ctrl+S
Refactor - Java
Extract Local Variable Shift+Alt+L
Extract Method Shift+Alt+M
Inline Shift+Alt+I
Rename - Refactoring Shift+Alt+R
Source
Format Shift+Ctrl+F
Organize Imports Shift+Ctrl+O
Toggle Comment Shift+Ctrl+C
Ctrl+/
Ctrl+7
Toggle Mark Occurrences Shift+Alt+O
Text Editing
Copy Lines Ctrl+Alt+Down
Delete Line Ctrl+D
Duplicate Lines Ctrl+Alt+Up
Insert Line Above Current Line Shift+Ctrl+Enter
Insert Line Below Current Line Shift+Enter
Join Lines Ctrl+Alt+J
Line End End
Line Start Home
Move Lines Down Alt+Down
Move Lines Up Alt+Up
Toggle Block Selection Shift+Alt+A