MacOS

Fix xcrun: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

Posted on

After recently updating my MacOS I encountered an error message

xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

To resolve that we will need to reinstall xcode necessary components

xcode-select --install
Linux

How to set default group on new files or directory in Linux

Posted on

I am managing a linux server where I want developers to run a springboot application which will generate files and folders. Those newly application created files and folders must inherit the parent group ID to let other developers manipulate the generated information.

chmod g+s is for setting and inheriting the setgid.
setfacl -m g::rwx is for setting the group access permission

Example:

In this example we assume that we already have a group named “devops”

sudo mkdir /company
sudo chgrp -R devops /company
sudo chmod -R g+s /company
sudo setfacl -m g::rwx /company

Any new folder or files created inside /company will have a default group devops
which has the permission to read, write and execute.

Java

Search a word in a two dimensional array using Java

Posted on
Overview

I was playing this word search game with my children when I realized that I can create a simple Java application that search for words in a grid.
You can checkout the source code at https://github.com/johnpili/search-a-word-in-a-two-dimensional-array-using-java

Algorithm Concept
Grid Algorithm Concept
My approach starts by creating a two dimensional character array and use a loop within a loop to iterate through the rows and columns. Since we know the length of the keyword we can extract the sequence of characters from the matrix from a specified direction.
Project Structure

MainApp.java

In this example, I created a 15×15 character array and populate it with strings per row. This program uses the program argument to set the keyword.

public class MainApp {
    public static void main(String[] args) {
        char[][] m = new char[15][15];
        m[0] = "LRHCODRUMAJTMLE".toCharArray();
        m[1] = "IYDTANDARPMAKLJ".toCharArray();
        m[2] = "SNOTKKASHINGLHD".toCharArray();
        m[3] = "IARESWALTONIKAJ".toCharArray();
        m[4] = "NMTFAQLHBTSOKLM".toCharArray();
        m[5] = "TDEFPMCPYOWHGUA".toCharArray();
        m[6] = "TIGUIEIANKMUYAB".toCharArray();
        m[7] = "ARABRAGTDELWLDR".toCharArray();
        m[8] = "RFJBEMPXTENTKDA".toCharArray();
        m[9] = "NRLPDBDOHALXNAM".toCharArray();
        m[10] = "AAQRZAVUTHLSWWO".toCharArray();
        m[11] = "UFRZQNRMAAGDOBV".toCharArray();
        m[12] = "LKJKNIRBDSNNJNI".toCharArray();
        m[13] = "TCEGATESCMLIIMC".toCharArray();
        m[14] = "FEMORDASHOVANSH".toCharArray();
        MatrixReader matrixReader = new MatrixReader(m);
        ConsoleDisplay consoleDisplay = new ConsoleDisplay(m);
        try {
            if(args.length > 0)
            {
                SearchResult searchResult = matrixReader.searchWord(args[0]);
                if(searchResult != null)
                {
                    consoleDisplay.displayResult(searchResult);
                }
            }
        }
        catch(Exception exception)
        {
            System.out.println(exception.getMessage());
        }
    }
}
SearchResult.java

This class will contain the details of the found keyword. pointer1 will hold the first character position while pointer2 will hold the position the last character.

To help with console highlight, I added a pointer chains which will hold the sequence of position to highlight.

public class SearchResult {
    private Pointer pointer1;
    private Pointer pointer2;
    private String keyword;
    private Pointer[] chains;

    public SearchResult(Pointer pointer1, Pointer pointer2, String keyword, Pointer[] chains)
    {
        this.pointer1 = pointer1;
        this.pointer2 = pointer2;
        this.keyword = keyword;
        this.chains = chains;
    }

    public Pointer getPointer1()
    {
        return this.pointer1;
    }

    public Pointer getPointer2()
    {
        return this.pointer2;
    }

    public String getKeyword()
    {
        return this.keyword;
    }

    public Pointer[] getChains()
    {
        return this.chains;
    }
}
MatrixReader.java

The search algorithm starts by iterating through the cells and check if the cell contains the starting character of the keyword.
It then performs a directional string extraction base on the keyword size and execute a string comparison. If the keyword is
found it returns the result.

The method extractByDirection has a logic to not execute the extraction if the starting position and angle of extraction will intersect with the array boundary.

public class MatrixReader implements IMatrixReader {
    protected char[][] matrix;
    protected int xmin = 0;
    protected int ymin = 0;
    protected int xmax = 0;
    protected int ymax = 0;

    public MatrixReader(char[][] matrix) {
        this.matrix = matrix;
        this.xmax = this.matrix[0].length;
        this.ymax = this.matrix.length;
    }
    
    public SearchResult searchWord(String keyword) throws Exception {
        if(this.matrix != null && keyword != null) {
            
            int keySize = keyword.length();
            if(keySize == 0)
            {
                throw new Exception("Keyword is empty");
            }

            for(int y = this.ymin; y < this.ymax; ++y){
                for(int x = this.xmin; x < this.xmax; ++x)
                {
                    if(this.matrix[y][x] == keyword.charAt(0))
                    {
                        SearchResult searchResult = extractByDirection(new Pointer(x, y), keySize, Angle.A0);
                        if(searchResult != null && searchResult.getKeyword().equals(keyword)) {
                            return searchResult;
                        }

                        searchResult = extractByDirection(new Pointer(x, y), keySize, Angle.A90);
                        if(searchResult != null && searchResult.getKeyword().equals(keyword)) {
                            return searchResult;
                        }

                        searchResult = extractByDirection(new Pointer(x, y), keySize, Angle.A180);
                        if(searchResult != null && searchResult.getKeyword().equals(keyword)) {
                            return searchResult;
                        }

                        searchResult = extractByDirection(new Pointer(x, y), keySize, Angle.A270);
                        if(searchResult != null && searchResult.getKeyword().equals(keyword)) {
                            return searchResult;
                        }

                        searchResult = extractByDirection(new Pointer(x, y), keySize, Angle.A45);
                        if(searchResult != null && searchResult.getKeyword().equals(keyword)) {
                            return searchResult;
                        }

                        searchResult = extractByDirection(new Pointer(x, y), keySize, Angle.A135);
                        if(searchResult != null && searchResult.getKeyword().equals(keyword)) {
                            return searchResult;
                        }
                        
                        searchResult = extractByDirection(new Pointer(x, y), keySize, Angle.A225);
                        if(searchResult != null && searchResult.getKeyword().equals(keyword)) {
                            return searchResult;
                        }

                        searchResult = extractByDirection(new Pointer(x, y), keySize, Angle.A315);
                        if(searchResult != null && searchResult.getKeyword().equals(keyword)) {
                            return searchResult;
                        }
                    }
                }
            }
            return null;
        }
        throw new NullPointerException("Matrix is null");
    }

    public SearchResult extractByDirection(Pointer pointer, int size, int direction) {
        String sample = "";
        Pointer[] chains = new Pointer[size];
        if(direction == Angle.A0)
        {
            if((pointer.getX()+size) <= this.xmax)
            {
                for(int x = pointer.getX(), i = 0; x < (pointer.getX()+size); ++x, ++i)
                {
                    sample += matrix[pointer.getY()][x];
                    chains[i] = new Pointer(x, pointer.getY());
                }
                return new SearchResult(pointer, new Pointer(pointer.getX()+size, pointer.getY()), sample, chains);
            }
        }
        else if(direction == Angle.A90)
        {
            if((pointer.getY()-size) >= this.ymin)
            {
                for(int y = pointer.getY(), i = 0; y > (pointer.getY()-size); --y, ++i)
                {
                    sample += matrix[y][pointer.getX()];
                    chains[i] = new Pointer(pointer.getX(), y);
                }
                return new SearchResult(pointer, new Pointer(pointer.getX(), (pointer.getY()-size)), sample, chains);
            }
        }
        else if(direction == Angle.A180)
        {
            if((pointer.getX()-size) >= this.xmin)
            {
                for(int x = pointer.getX(), i = 0; x > (pointer.getX()-size); --x, ++i)
                {
                    sample += matrix[pointer.getY()][x];
                    chains[i] = new Pointer(x, pointer.getY());
                }
                return new SearchResult(pointer, new Pointer((pointer.getX()-size), pointer.getY()), sample, chains);
            }
        }
        else if(direction == Angle.A270)
        {
            if((pointer.getY()+size) <= this.ymax)
            {
                for(int y = pointer.getY(), i = 0; y < (pointer.getY()+size); ++y, ++i)
                {
                    sample += matrix[y][pointer.getX()];
                    chains[i] = new Pointer(pointer.getX(), y);
                }
                return new SearchResult(pointer, new Pointer(pointer.getX(),(pointer.getY()+size)), sample, chains);
            }
        }
        else if(direction == Angle.A45)
        {
            if(((pointer.getY()-size) >= this.ymin) && ((pointer.getX()+size <= this.xmax)))
            {
                for(int y = pointer.getY(), x = pointer.getX(), i = 0; (y > (pointer.getY()-size)) && (x < (pointer.getX()+size)); --y, ++x, ++i)
                {
                    sample += matrix[y][x];
                    chains[i] = new Pointer(x, y);
                }
                return new SearchResult(pointer, new Pointer((pointer.getX()+size),(pointer.getY()-size)), sample, chains);
            }
        }
        else if(direction == Angle.A135)
        {
            if(((pointer.getY()-size) >= this.ymin) && ((pointer.getX()-size >= this.xmin)))
            {
                for(int y = pointer.getY(), x = pointer.getX(), i = 0; (y > (pointer.getY()-size)) && (x > (pointer.getX()-size)); --y, --x, ++i)
                {
                    sample += matrix[y][x];
                    chains[i] = new Pointer(x, y);
                }
                return new SearchResult(pointer, new Pointer((pointer.getX()-size),(pointer.getY()-size)), sample, chains);
            }
        }
        else if(direction == Angle.A225)
        {
            if(((pointer.getY()+size) <= this.ymax) && ((pointer.getX()-size >= this.xmin)))
            {
                for(int y = pointer.getY(), x = pointer.getX(), i = 0; (y < (pointer.getY()+size)) && (x > (pointer.getX()-size)); ++y, --x, ++i)
                {
                    sample += matrix[y][x];
                    chains[i] = new Pointer(x, y);
                }
                return new SearchResult(pointer, new Pointer((pointer.getX()+size),(pointer.getY()+size)), sample, chains);
            }
        }
        else if(direction == Angle.A315)
        {
            if(((pointer.getY()+size) <= this.ymax) && ((pointer.getX()+size <= this.xmax)))
            {
                for(int y = pointer.getY(), x = pointer.getX(), i = 0; (y < (pointer.getY()+size)) && (x < (pointer.getX()+size)); ++y, ++x, ++i)
                {
                    sample += matrix[y][x];
                    chains[i] = new Pointer(x, y);
                }
                return new SearchResult(pointer, new Pointer((pointer.getX()+size),(pointer.getY()+size)), sample, chains);
            }
        }
        return null;
    }
}
Demo/Screenshots
Search for GATES
Search for ELLISON
Search for ALBRECHT
Conclusion

There are other algorithms and ways out there to solve this type of problem but in my situation and time constraint this is good enough.

General

Generating Subresource Integrity (SRI)

Posted on

Since launching my online recruitment platform and job vacancy portal. I became interested in rolling out my own content delivery network (CDN) to host my portal’s images, javascript and CSS. Thanks to NGINX, implementing a CDN is easy. Of course we need to ensure that our digital assets are not compromised during transport so we need to add Subresource Integrity (SRI) to our files.

openssl dgst -sha384 -binary site.css | openssl base64 -A

Using openssl is fine but I want to try writing a golang base program to generate the SRI hash for me. You can find the snippet below and code at my github https://github.com/johnpili/srigen

package main

import (
	"crypto/sha512"
	b64 "encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	args := os.Args[1:] // Fetch the program arguments excluding the program name
	if len(args) == 0 {
		fmt.Println("Usage: srigen \"filename\"")
	} else {
		b, err := ioutil.ReadFile(args[0])
		if err != nil {
			panic(err)
		}
		hash := sha512.New384()

		hash.Write(b)
		hashResult := hash.Sum(nil)

		result := b64.StdEncoding.EncodeToString(hashResult)
		fmt.Printf("sha384-%s\n", result)
	}
}
Subresource Integrity used in CDN
Subresource Integrity used in CDN
MySQL

Using MySQL TIMESTAMPDIFF to delete unverified user records

Posted on

Building a public website with user registration and email verification is typical. It will require users to validate their email by clicking a unique generated URL link.
Sometimes, user registration with pending verification will grow exponentially and needs an automated cleanup of records.

In this example I created a simple MySQL stored procedure to delete users with “pending-email-verification” status for more than five days.

TIMESTAMPDIFF(unit, datetime1, datetime2)

CREATE DEFINER=`dbuser`@`localhost` PROCEDURE `delete_unverified_users`()
BEGIN
	DELETE FROM user WHERE user.status='pending-email-verification' AND TIMESTAMPDIFF(DAY,user.modifiedDateTime,NOW()) > 5;
	SELECT ROW_COUNT() AS 'count';
END
Tutorials

How to stop Mailtrack from tracking you

Posted on

Mailtrack is an online service that provides email tracking capability and analytics. Using its services the sender can track when the receiver read the email, when it was viewed and where is the reader’s location. It is a great tool for marketing but I feel that this is invading privacy and I would like to share to you how to stop getting tracked by mailtrack or other similar services. Internet surveillance and tracking are now more prevalent than ever which is why we have to ensure that our privacy is upheld.

How mail tracking service like Mailtrack works?

Mailtrack uses a transparent, 1×1 pixel size external reference image inserted into the email. When the unsuspecting person opens the email, the image will be loaded from and external server which then can identify that the email has been opened and read.

Steps on how to stop Mailtrack from tracking you

Procedures for

Gmail

1. Go to Gmail settings
1. Go to Gmail settings

2. From the menu, select Settings
2. From the menu, select Settings

3. Inside Gmail settings, Go to Images section and select Ask before displaying external images
3. Ask before loading external images