Builder pattern + inheritance

In general, it is very simple to implement in Java the builder pattern, a few lines of code and the problem is solved but, when we are using inheritance, it is not as intuitive apparently as it should be. I have lately seen poor attempts of doing it and not achieving the desired result.

In this article, we are going to build a very simple example of that.

public class Parent {

    private final String a;

    protected Parent(final Builder<?> builder) {
        this.a = builder.a;
    }

    public String getA() { return a; }

    public static class Builder<T extends Builder<T>> {

        private String a;

        public T a(final String a) {
            this.a = a;
            return (T) this;
        }

        public Parent build() {
            return new Parent(this);
        }
    }
}

In this first class, the parent class, we can see we are using generics to allow child classes to pass their builders.

public class Children extends Parent {

    private final String b;

    protected Children(final Builder builder) {
        super(builder);
        this.b = builder.b;
    }

    public String getB() {
        return b;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder extends Parent.Builder<Builder> {
        private String b;

        public Builder b(final String b) {
            this.b = b;
            return this;
        }

        public Children build() {
            return new Children(this);
        }
    }
}

Here, we can see how we pass the child builder in the diamond operator, this will allow us to add values for the properties to the patent and to the child using the builder.

public class Main {

    public static void main(String[] args) {
        final Children children = Children.builder()
            .a("Hi")
            .b("Bye")
            .build();

        System.out.println(children.toString());
    }
}

Here, we can see how to use the builder. Thanks to the generics, the call to .a(“Hi”) returns a child builder and not a parent builder what it would make impossible to call .b(“Bye”).

I hope it is useful.

Builder pattern + inheritance

Detecting a phishing email

Christmas and New Year are usually happy moments, families, people, lights on the streets, ex-pats flying home, gifts… but, it is a very good season for phishing emails too, in both environments, personal and enterprise.

This article is just a collection of rules, more focus on enterprise environments but applicable to both, to try to educate our employees or ourselves to prevent ransomware infections or any other infection received by email. They are not golden rules, just some basic guidelines to follow by email users.

  • Do not trust the displayed name of who the email is from: Just because it says it is coming from someone you know or trust does not mean that it truly is. Check the email address to confirm the real sender. Different email clients have different ways to do this but, basically, it is something that it can be done with just one click.
  • Check the email signature: Usually, legitimate enterprise users include a full signature block at the bottom of their emails. If it is there, check if it is correct. If it is from someone that you have exchange previous emails and suddenly the signature is not there, be suspicious.
  • Consider the salutation: People tend to address the person is sending the email to. If the salutation is vague, or generic i.e. “valued customers” or just addressing the recipient by title i.e. “Dear Accountant”, be suspicious.
  • Check for spelling errors: All of us make mistakes when writing, some people write in a language that it is not theirs but, in general, we have autocorrection (not always for good) and people concern about spelling and be grammatically correct. Attackers usually are careless about this kind of details.
  • Double-check the links: Hover or mouse over the different links on the email before you click. If the text showed looks strange or does not match what the link description says, do not click on it.
  • Is the email asking for personal information?: Legitimate companies are unlikely to ask for personal information by email. In some cases, they actively remind you about this. As an example, I am sure everyone here has received these emails from the bank reminding you they will never ask you anything by email.
  • Be careful with attachments: If you have any doubts about the email do not click on the attachments, it does not matter how legit they look or the nice name they have. Contact the sender of the email, if possible, to confirm the legitimacy.
  • Beware of urgency: Emails like this, sometimes, try to push some sense of urgency to push recipients to be unwise and focus on what the email says and ignore the warning signals. Do not do that, take your time (it is going to take a minute) to check the email or do a few basic checkings about the legitimacy. As an example, the typical email from the CEO to the accountant “Hi, I am John Doe (CEO), I need you to transfer 1 million to xxxxxx or we are going to lose the deal…”
  • Better safe than sorry: If you see some signals that make you doubt of the legitimacy of an email, contact your SOC if you have one, the sender or use your common sense.

As I have said, just a few basic and common-sense advice that we, sometimes, forget.

Detecting a phishing email

Remote Tail

This article is just a quick code snipped for bash shell to allow us to tail log files from a remote endpoint.

Nowadays, we are building plenty of microservices and the common pattern is to aggregate them using tools like Kibana to store and search them with the help of some correlation ids. Despite, this is a very good solution, sometimes we do not need anything that fancy.

In Spring Actuator, we can find the endpoint “/logfile” that it has proven a lot of times to be pretty useful. This endpoint allows us to recover the log file from the server. We can download it or just check it on the browser. The problem is when this logfile reach a size that our browser can not manage properly. We can use tools like “wget” to download the log file and analyse it locally but it seems absurd to download the whole file every time we want an update.

I have a different proposal. With a few lines of shell scripting, we can write a snipped to tail the log file into a local file, and we can use “less” to monitor it or perform searches on the file.

#!/bin/bash

#
# Check if the given server support HTTP range header
# param 1: url
#
function check_ranges_support() {
  ret=`curl -s -I -X HEAD $1 | grep "Accept-Ranges: bytes"`

  if [ -z "$ret" ]; then
    echo "Ranges are nor supported by the server"
    exit 1
  fi
}

#
# Recovers the total length of the given file
# param 1: url
#
function get_length() {
  ret=`curl -s -I -X HEAD $1 | awk '/Content-Length:/ {print $2}'`
  echo $ret | sed 's/[^0-9]*//g'
}

#
# Print the requested part of the remote file
# param 1: url
# param 2: off
# param 3: len
# param 4: output file
#
function print_to_logfile() {
  curl --header "Range: bytes=$2-$3" -s $1 >> $4
}

#
# Clean the previous log file
#
function clean_logfile() {
  rm -f $1
}

# call validation
if [ $# -lt 1 ]; then
  echo "Syntax: remote-tail.sh <URL> [<logfile name>]"
  exit 1
fi

url=$1
offset=0
logfile=tmplog

if [ $# -eq 2 ]; then
  logfile=$2
fi

check_ranges_support $url
clean_logfile $logfile

len=`get_length $url`
off=$((len - offset))

until [ "$off" -gt "$len" ]; do
  len=`get_length $url`

  if [ "$off" -eq "$len" ]; then
    sleep 5 # we refresh every 5 seconds if no changes
  else
    sleep 1 # we refresh every second to not hammer too much the server
    print_to_logfile $url $off $len $logfile
  fi

  off=$len
done

We can use it with:

./remote-tail.sh https://server/logfile

I hope it helps.

Remote Tail

ML – Python (VII) – Overfitting & Underfitting

On the previous article, we named overfitting and underfitting but we did not go deep into details about them. Let’s just take a deeper dive on them.

When we work with a set of data to predict or classify a problem we try to achieve our goals implementing a model using the training data and testing it with the testing data. We can make adjustments based on the characteristics we are using or the model itself.

Modifying the model we can end up with a too simple model or a too complex model. Here is when we need to consider the overfitting and underfitting concepts.

Underfitting

As we can see on the image, the underfitting concept refers to a model that can neither model the training data nor generalize to new data. An underfit machine learning model is not a suitable model and will be obvious as it will have poor performance on the training data.

It happens when we do not have enough data to build a precise model or when we try to build a linear model with non-linear data.

There are a few techniques we can try to prevent underfitting:

  • Sometimes the model is underfitting because the feature items are insufficient. In this case, we can add other feature items to unfold it well.
  • Add polynomial features, which are usually utilized as a part of the machine learning algorithm. For example, the linear model is more generalized by adding quadratic or cubic terms.
  • Reduce the regularization parameters. The motivation behind regularization is to prevent overfitting, yet now the model has an underfitting, we have to diminish the regularization parameters.

Overfitting

On the opposite side, the overfitting concept refers to a model that models the training data too well. Overfitting happens when a model learns the detail and noise in the training data to the extent that it negatively impacts the performance of the model on new data.

Overfitting is more probable in non-parametric and non-linear models.

There are a few techniques we can try to prevent overfitting:

  • Cross-validation: It uses our initial training data to generate multiple mini train-test splits, and it uses these splits to tune our model. Cross-validation allows us to tune hyperparameters with only our original training set. This allows us to keep our test set as a truly unseen dataset for selecting our final model.
  • Train with more data: Training with more data can help algorithms detect the signal better but, if we just add more noisy data, this technique won’t help. That’s why we should always ensure our data is clean and relevant.
  • Remove features: We can manually improve algorithms generalizability by removing irrelevant input features. The criteria to remove them, if anything does not make sense, or if it is hard to justify, this is a good candidate to be removed.
  • Early stopping: When training an algorithm, we can measure how well each iteration of the model performs. Up until a certain number of iterations, new iterations improve the model. After that point, the model’s ability to generalize can weaken as it begins to overfit the training data. Early stopping refers to stopping the training process before the learner passes that point.
  • Regularization: Regularization refers to a broad range of techniques for artificially forcing our model to be simpler.
  • Ensembling: Ensembles are machine learning methods for combining predictions from multiple separate models.

The good one

Finally, looking at the middle graph it shows a pretty good predicted line. It covers the majority of the points in graph and also maintains the balance between bias and variance.

That is all for today.

ML – Python (VII) – Overfitting & Underfitting

ML – Python (VI) – Bias & Variance

Now, it is time to start digging in the theory of Machine Learning.

In the machine learning world, precision is everything. When we try to develop a model, we try to make it as much accurate as possible playing with the different parameters. But, the hard truth is that we can not build a one-hundred per cent accurate model due to we can not build a free of errors model. What we can do, it is trying to understand the possible sources of errors and this will help us to obtain a more precise model.

Types of errors

When we are talking about errors, we can find reducible and irreducible errors.

Irreducible errors are errors that cannot be reduced no matter what algorithm you apply. They are usually known as noise and, the can appear in our models due to multiple factors like an unknown variable, incomplete characteristics or a wrongly defined problem. It is important to mention that, no matter how good is our model, our data will always have some noise component or irreducible errors we can never remove.

Reducible errors have two components – bias and variance. This kind of errors derivate from the algorithm selection and the presence of bias or variance causes overfitting or underfitting of data.

Bias

Bias error is the difference between the expected prediction of our model and the real values or, saying it in a different way, how far are the predicted values from the actual values. High bias, predicted values are far off from the actual values, causes the algorithm to miss the relevant relationship between the input and output variable. When a model has a high bias then it implies that the model is too simple and does not capture the complexity of data thus underfitting the data. For example, if we try to adjust a linear regression to a set of data that has a non-linear pattern.

High bias implies that the model is too simple and does not capture the complexity of data thus underfitting the data. As examples, we have linear regression algorithms, logistic regression or linear discriminant analysis.

Low bias implies the opposite and it offers more flexibility. As examples, we have decision trees, k-nearest neighbour (KNN) and vector support machines.

Variance

It refers to the differences in the estimation of the function using different training data or, saying it in a different way, it tells us how scattered is the predicted value from the actual value. Variance occurs when the model performs well on the trained dataset but does not do well on a dataset that it is not trained on. Ideally, the result should not change too much from one set of data to another.

High variance causes overfitting that implies that the algorithm models random noise present in the training data, or that the algorithm is strongly dependent on the input data. It suggests big changes in the estimation of the function when the data changes. As an example, we have decision trees, k-nearest neighbour (KNN) and vector support machines.

Low variance suggests small changes in the estimation of the function when the data changes. As examples, we have linear regression, analysis of discrete linear systems and logic regression.

Bias–variance tradeoff

The objective of any machine learning algorithm is to achieve low bias and low variance, achieving at the same time a good performance predicting results. The bias-variance dilemma or bias-variance problem is the conflict in trying to simultaneously minimize these two sources of error that prevent supervised learning algorithms from generalizing beyond their training set. The bias opposite to the variance refers to the precision opposite to consistency of the trained models. Considering the combinations we can have:

  • High Bias Low Variance: Models are consistent but inaccurate on average. Tend to be less complex with a simple or rigid structure like linear regression or Bayesian linear regression.
  • Low Bias High variance: Models are somewhat accurate but inconsistent on averages. Tend to be more complex with a flexible structure like decision trees or k-nearest neighbour (KNN).
  • High Bias High Variance – Models are inaccurate and also inconsistent on average.
  • Low Bias Low Variance: This is the unicorn.

To build a good model we need to find a good balance between bias and variance that help us to minimise the total error. This is why to understand the bias and variance are fundamental to understand the model’s behaviour.

Detecting high bias or high variance

High Bias can be identified when we have:

  • High training error.
  • Validation error or test error is the same as training error.

High Variance can be identified when:

  • Low training error.
  • High validation error or high test error.

Fixing it

High bias is due to a simple model and we also see a high training error. To fix that we can do the following things:

  • Add more input features.
  • Add more complexity by introducing polynomial features.
  • Decrease Regularization term.

High variance is due to a model that tries to fit most of the training dataset points and hence gets more complex. To resolve the high variance issue we need to work on:

  • Getting more training data.
  • Reduce input features.
  • Increase Regularization term.

That is all for today. I hope the first theory article was not to hard to read. I will try to make them not too long and as concise as possible.

ML – Python (VI) – Bias & Variance

ML – Python (V) – scikit-learn

Finally, the last library we are going to see for now that will help us with our machine learning programs is going to be scikit-learn. This is probably one of the most useful libraries for Machine Learning in Python. It is an open-source library and it brings us a range of supervised and unsupervised learning algorithms.

This library includes the next libraries or packages:

  • NumPy: N-dimensional matrix library.
  • pandas: Data structures and analysis.
  • SciPy: Essential library for computer science.
  • Matplotlib: 2D data representation.
  • IP[y]: Improved interactive console.
  • SymPy: Symbolic mathematics.

Considering the extension and the fact that includes some of the libraries we have already explored, this article is going to be very short and without code examples. Basically, we are going to see a shortlist of basic functions or benefits the library offers us like:

  • Supervised learning algorithms: It brings us a variety of supervised algorithms.
  • Cross-validation: The library brings us instructions to implement some of the model’s precision verification methods.
  • Unsupervised learning algorithms: It brings us a variety of unsupervised algorithms.
  • Data sets: A miscellaneous collection of data sets.
  • Characteristic extraction and selection: It is very useful to extract characteristics from images and texts. In addition, it can help us to identify significant attributes.
  • Community: It has some community behind improving the library.

That’s all. Quick and simple. Let’s save some energy for the next article where we are going to start digging a little bit on Machine Learning theory.

ML – Python (V) – scikit-learn