Ron and Ella Wiki Page

Extremely Serious

Page 12 of 33

Generating Random Number

Listing the Available Random Algorithms

System.out.printf("%-13s| %s\n-------------|---------------------\n", "Group", "Name");
java.util.random.RandomGeneratorFactory.all()
        .sorted(java.util.Comparator.comparing(java.util.random.RandomGeneratorFactory::name))
        .forEach(factory -> System.out.printf("%-13s| %s\n", factory.group(), factory.name()));

The output is similar to the following:

Group        | Name
-------------|---------------------
LXM          | L128X1024MixRandom
LXM          | L128X128MixRandom
LXM          | L128X256MixRandom
LXM          | L32X64MixRandom
LXM          | L64X1024MixRandom
LXM          | L64X128MixRandom
LXM          | L64X128StarStarRandom
LXM          | L64X256MixRandom
Legacy       | Random
Legacy       | SecureRandom
Legacy       | SplittableRandom
Xoroshiro    | Xoroshiro128PlusPlus
Xoshiro      | Xoshiro256PlusPlus

Check from the following address on how to choose which algorithm to choose:

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html#algorithms

Creating an instance of RandomGenerator

The default algorithm (i.e. L32X64MixRandom)

var generator = java.util.random.RandomGenerator.getDefault();

The specific algorithm (e.g. L64X128MixRandom)

var generator = java.util.random.RandomGenerator.of("L64X128MixRandom");

Use the static method RandomGenerator.of and pass the name of the algorithm.

Generating Random Number

Use one of the following instance methods of the RandomGenerator class:

  • nextDouble()
  • nextDouble(double bound)
  • nextDouble(double origin, double bound)
  • nextFloat()
  • nextFloat(float bound)
  • nextFloat(float origin, float bound)
  • nextInt()
  • nextInt(int bound)
  • nextInt(int origin, int bound)
  • nextLong()
  • nextLong(long bound)
  • nextLong(long origin, long bound)

The origin parameter is inclusive and bound parameter is exclusive.

Example using a classic random algorithm

 var generator = java.util.random.RandomGenerator.of("Random");
 System.out.println(generator.nextInt());

The output is a random integer number.

Generating Random Number Using Streams

Use one of the following instance methods of RandomGenerators class to create streams:

  • doubles()
  • doubles(double origin, double bound)
  • doubles(long streamSize)
  • doubles(long streamSize, double origin, double bound)
  • ints()
  • ints(int origin, int bound)
  • ints(long streamSize)
  • ints(long streamSize, int origin, int bound)
  • longs()
  • longs(long origin, long bound)
  • longs(long streamSize)
  • longs(long streamSize, long origin, long bound)

The origin parameter is inclusive and bound parameter is exclusive.

Example using a classic random algorithm

var generator = java.util.random.RandomGenerator.of("Random");
var randomInt = generator.ints(100, 1, 100)
        .filter(number -> number % 2 == 0 )
        .findFirst();
randomInt.ifPresent(System.out::println);

The output is a random integer number.

Downloading Dependencies with Gradle Script

  1. Create settings.gradle file with the following content:

    rootProject.name = 'download-dependecies'
  2. Create build.gradle file with the following content:

    plugins {
        id 'application'
    }
    
    group 'xyz.ronella.gradle'
    version '1.0.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        //Add all the target dependencies here
        implementation 'org.apache.poi:poi:3.5-FINAL'
    }
    
    task download(group: 'resolver') {
        doFirst {
            ant.delete(dir: 'libs')
            ant.mkdir(dir: 'libs')
        }
        doLast {
            copy {
                from sourceSets.main.runtimeClasspath
                into 'libs/'
            }
            def outputFile = "${project.buildDir}\\${project.name}-${version}.zip"
            ant.zip(basedir: "${file('libs')}", destfile: "${outputFile}", excludes: '*.class')
            println "Output: ${outputFile}"
            ant.delete(dir: 'libs')
        }
    }
  3. Run the following gradle command:

    gradle download

    If you are using the gradle wrapper, use the following command:

    gradlew download

Sealed Classes and Interfaces

Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.

public sealed interface IAnimal 
    permits AquaticAnimal, LandAnimal {
    String lifespan();
}

Notice the use of the sealed modifier and permits keyword. The sealed modifier indicates that the class or interface is restricted. The permit keyword indicates which classes (or interfaces) can implement (or extends) it. Thus, the sealed modifier and the permit keyword must be used together.

public sealed abstract class AquaticAnimal implements IAnimal permits SeaTurtle {
}

The class (or interface) that can implement (or extend) a sealed interface (or class) must have one of the following modifiers:

  • sealed
  • non-sealed
  • final
public non-sealed abstract class LandAnimal implements IAnimal {
}

Using the non-sealed modifier indicates that this class can be extended without restriction.

public sealed class Dog extends LandAnimal permits Boxer {
    @Override
    public String lifespan() {
        return "10 - 13 years";
    }
}

Limiting the hierarchy of Dog class to just Boxer class.

public final class Boxer extends Dog {
    @Override
    public String lifespan() {
        return "10 - 12 years";
    }
}

The final implementation of the Dog class.

public class Cat extends LandAnimal {
    @Override
    public String lifespan() {
        return "12 - 18 years";
    }
}

Since LandAnimal is non-sealed abstract class, it can be inherited without restriction.

public final class SeaTurtle extends AquaticAnimal {
    @Override
    public String lifespan() {
        return "Up to 50 years or more";
    }
}

SeaTurtle is the only class that can implement AquaticAnimal. Because this the only class permitted in the AquaticAnimal definition.

Unlinking Uphold Wallet with Brave

Identifying your Custodian member and Wallet Payment IDs [^1]

On the brave browser where you've successfully verified an uphold wallet.

  1. Type in on your brave browser address bar the following:

    brave://rewards-internals
  2. Select the General info tab.

  3. Note the Wallet payment ID from the the Wallet info section.

    Include this information in the description of the request form.

  4. Note the Custodian member ID from the External wallet info section.

  5. Create a request to Wallet Unlinking Request form

[^1]: How can i verify my browser on a new device have reached the lifetime limit

Ubuntu Stops Resolving Address

Issue

Pinging any known working internet address is returning the following message:

Temporary failure in name resolution

Example

Pinging www.google.com as follows:

ping: www.google.com: Temporary failure in name resolution

Resolution

Check where you /etc/resolve.conf is pointing using the following command:

 ls -al /etc | grep resolv.conf

If it is not pointing to /run/systemd/resolve/resolv.conf. Do the following:

sudo rm /etc/resolv.conf
sudo ln -s /run/systemd/resolve/resolv.conf  /etc/resolv.conf
sudo systemctl restart systemd-resolved.service

Regex Capture Groups with Java

The following java code extracts the group, artifact and version using regex capture groups:

import java.util.regex.Pattern;

public class Main {

    public static void main(String ... args) {
        //Text to extract the group, artifact and version
        var text = "org.junit.jupiter:junit-jupiter-api:5.7.0";

        //Regex capture groups for Group:Artifact:Version
        var pattern = "(.*):(.*):(.*)"; 

        var compiledPattern = Pattern.compile(pattern);
        var matcher = compiledPattern.matcher(text);
        if (matcher.find( )) {
            System.out.println("Whole text: " + matcher.group(0) );
            System.out.println("Group: " + matcher.group(1) );
            System.out.println("Artifact: " + matcher.group(2) );
            System.out.println("Version: " + matcher.group(3) );
        } else {
            System.out.println("NO MATCH");
        }
    }
}

Output

Whole text: org.junit.jupiter:junit-jupiter-api:5.7.0
Group: org.junit.jupiter
Artifact: junit-jupiter-api
Version: 5.7.0

Vagrant Basic Commands

Command Description
destroy Stops and deletes all traces of the vagrant machine
halt Stops the vagrant machine
init Initializes a new Vagrant environment by creating a Vagrantfile.
Vagrant boxes can be found from the following link:
Discover Vagrant Boxes - Vagrant Cloud (vagrantup.com)
provision Provisions the vagrant machine
reload Restarts vagrant machine, loads new Vagrantfile configuration
resume Resume a suspended vagrant machine
ssh Connects to machine via SSH
ssh-config Outputs OpenSSH valid configuration to connect to the machine
status Outputs status of the vagrant machine
suspend Suspends the machine
up Starts and provisions the vagrant environment
validate Validates the Vagrantfile
version Prints current and latest Vagrant version

Retrieving the Versions from maven-metadata.xml

Groovy Snippet

List<String> getMavenVersions(String metadataXmlURL) {
    def strVersions = new ArrayList<String>()
    def mvnData = new URL(metadataXmlURL)
    def mvnCN = mvnData.openConnection()
    mvnCN.requestMethod = 'GET'

    if (mvnCN.responseCode==200) {
        def rawResponse = mvnCN.inputStream.text
        def versionMatcher = rawResponse =~ '<version>(.*)</version>'
        while(versionMatcher.find()) {
            for (nVersion in versionMatcher) {
                strVersions.add(nVersion[1]);
            }
        }
    }

    strVersions.sort {v1, v2 ->
        v2.compareTo(v1)
    }

    return strVersions
}

Example Usage

def metatdataAddress = 'https://repo.maven.apache.org/maven2/xyz/ronella/casual/trivial-chunk/maven-metadata.xml'
def versions = getMavenVersions(metatdataAddress)
println versions

Removing the Timestamp from the downloaded SNAPSHOT

Use case

The downloaded snapshot has timestamp associated with it like the following:

artifact-1.0.0-20211012.041152-1.jar

But the tooling is expecting an absolute name like the the following:

artifact-1.0.0-SNAPSHOT.jar

Powershell Script

#The target artifact
$ArtifactId = "artifact"

#The target SNAPSHOT version
$Version = "1.0.0-SNAPSHOT"

if ($Version -match "^(.*)-SNAPSHOT$") 
{
    $Prefix = "{0}-{1}" -f $ArtifactId,$Matches.1
    $Pattern = "^(${Prefix}).*(\.jar)$"

    Get-ChildItem ('.') | ForEach-Object {
        If ($_.Name -match $Pattern) {
            $NewName = "{0}-SNAPSHOT{1}" -f $Matches.1, $Matches.2
            Rename-Item $_ -NewName $NewName
            $Message = "Renaming from {0} to {1}" -f $_.Name, $NewName
            echo $Message
        }
    }
}

Type Pattern Matching for instanceof

The pattern matching enhancement that conditionally extract data from an object if the instanceof operator was satisfied and assigns it to a variable.

The variable in this pattern matching is following a flow scope. This means that the variable is in scope if it is guaranted that it can satisfies the instanceof operator.

Code Without Pattern Matching

record Person(String firstName, String lastName) {}

Record rec = new Person("Juan", "Dela Cruz");

//Check if rec is a Person.
if (rec instanceof Person) {

    //rec can safely be casted to Person.
    var person = (Person) rec;

    System.out.println(person);
    System.out.println(person.firstName());
    System.out.println(person.lastName());
}

Notice that casting the rec to Person once the check succeded is required.

Code With Pattern Matching

record Person(String firstName, String lastName) {}

Record rec = new Person("Juan", "Dela Cruz");

//If rec is a Person extract it to a variable person.
if (rec instanceof Person person) {
    System.out.println(person);
    System.out.println(person.firstName());
    System.out.println(person.lastName());
}

Notice that casting is not required here and Person instance is extracted to person variable. Moreover, the scope of the variable is in the truth block of the if statement.

Flow Scope

Example 1

Record rec = new Person("Juan", "Dela Cruz");

if (!(rec instanceof Person person)) {
    System.out.println("In human.");
}
else {
    System.out.println(person);
    System.out.println(person.firstName());
    System.out.println(person.lastName());
}

Notice that person variable usage is on the else block of the if statement.

Example 2

Record rec = new Person("Juan", "Dela Cruz");

if (rec instanceof Person person && "JUAN DELA CRUZ".equals(String.join(person.firstName(), " ", person.lastName().toUpperCase()))) {
    System.out.println("You won a price");
}

Notice that the person variable is usable after the AND (&&) operator. This is because the and operator guarantees that the instanceof operator was satisfied before evaluating the following condition. Changing it to OR (||) operator will be an error, since the person variable is out of scope.

Practical Usage

equals implementation

import java.util.Objects;

record Person(String firstName, String lastName) {

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (null == o) return false;
        if (o instanceof Person person) {
            return Objects.equals(firstName, person.firstName()) && Objects.equals(lastName, person.lastName());
        }
        return false;
    }

}
« Older posts Newer posts »