commit 4e0b5092e249fed9f51622b811846ba53760f31c Author: siujamo Date: Tue Jun 2 13:57:20 2026 +0800 refactor: migrate from repo onixbyte/onixbyte-toolbox to module repos diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..d01b18f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,42 @@ +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +max_line_length = 100 +tab_width = 4 + +[*.less] +indent_size = 2 + +[*.proto] +indent_size = 2 +tab_width = 2 + +[*.sass] +indent_size = 2 + +[*.scss] +indent_size = 2 + +[*.vue] +indent_size = 2 +tab_width = 2 + +[{*.bash,*.sh,*.zsh}] +indent_size = 2 +tab_width = 2 + +[{*.default,*.yaml,*.yml}] +indent_size = 2 + +[{*.har,*.jsb2,*.jsb3,*.json,*.jsonc,*.postman_collection,*.postman_collection.json,*.postman_environment,*.postman_environment.json,.babelrc,.eslintrc,.prettierrc,.stylelintrc,.ws-context,jest.config}] +indent_size = 2 + +[{*.pb,*.textproto,*.txtpb}] +indent_size = 2 +tab_width = 2 + +[{*.ps1,*.psd1,*.psm1}] +max_line_length = 115 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..79b8c8c --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + +### Gradle ### +.gradle \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b18c455 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,62 @@ +# Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our project +a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, +gender identity and expression, level of experience, nationality, personal appearance, race, +religion, or sexual identity and orientation. + +## Our Standards + +Examples of behaviour that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behaviour by participants include: + +- The use of sexualised language or imagery, and unwelcome sexual attention or advances +- Trolling, insulting, or derogatory comments +- Personal or political attacks +- Public or private harassment +- Publishing others’ private information, such as a physical or electronic address, without + explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behaviour and are +expected to take appropriate and fair corrective action in response to any instances of +unacceptable behaviour. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, +code, wiki edits, issues, and other contributions that do not align with this Code of Conduct, and +will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is +representing the project or its community. Examples of representing a project or community include +using an official project email address, posting via an official social media account, or acting as +an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or unacceptable behaviour may be reported by contacting the +project team at [opensource@onixbyte.com](mailto:opensource@onixbyte.com). All complaints will be +reviewed and investigated and will result in a response that is deemed necessary and appropriate to +the circumstances. The project team is obligated to maintain confidentiality with regard to the +reporter of an incident. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face +temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), +version 1.4, available at https://www.contributor-covenant.org/version/1/4/ + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..5ed8874 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,61 @@ +# Contributing to OnixByte Toolbox + +We appreciate your interest in contributing to our Java Enterprise Utility Library. Contributions +are welcome in various forms such as code, documentation, bug reports, and test cases. To ensure a +smooth collaboration, please follow the guidelines outlined below. + +## Getting Started + +The OnixByte Toolbox is an open-source Java library designed to ease Java enterprise +application development. It is built with Java 17, and we require contributors to use OpenJDK 17. + +## Development Setup + +There is no need for manual setup beyond ensuring you have JDK 17 and a stable internet connection. +Our project uses Gradle Wrapper for building, simplifying the setup process. + +```shell +./gradlew build +``` + +## Branching Strategy + +We follow the `git-flow` branching model. Contributors should fork this repository and create their +work on separate branches prefixed with `feature/` or `hotfix/` as appropriate. + +## Code Style + +Please adhere to the coding standards specified in our `.editorconfig` file in the root of +the repository. Consistent style helps in maintaining readability and uniformity across the codebase. + +## Commit Messages + +We require that commit messages follow this structure: + +```text +type[(scope)]: subject + +[body] + +[BREAKING CHANGE: breaking changes] +``` + +This format helps in auto-generating changelogs and understanding the purpose behind changes. + +## Submitting Contributions + +1. Fork the repository. +2. Create a branch: `git checkout -b feature/my-new-feature` or `git checkout -b hotfix/my-fix`. +3. Make your changes and commit them. +4. Push to the branch: `git push origin feature/my-new-feature`. +5. Create a Pull Request with a succinct subject and a detailed body. + +## Testing + +We encourage using JUnit Jupiter for unit and integration tests. Pull Requests with accompanying +test reports are prioritised for review and merging. + +## License + +By contributing to the OnixByte Toolbox, you agree that your contributions will be licensed under the +MIT license. If you do not agree to this, please refrain from contributing. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8c2f4a4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024-2025 OnixByte + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..72b11d8 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# Math Toolkit + +**Math Toolkit** provides some mathematical algorithms and utilities such as chained high-precision +mathematical calculator and percentile statistic algorithm. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..9a690a3 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2024-2026 OnixByte + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import java.net.URI + +plugins { + java + id("java-library") + id("maven-publish") + id("signing") +} + +val artefactVersion: String by project + +version = artefactVersion +val projectUrl: String by project +val projectGithubUrl: String by project +val licenseName: String by project +val licenseUrl: String by project + +repositories { + mavenCentral() +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + withSourcesJar() + withJavadocJar() +} + +tasks.withType { + options.encoding = "UTF-8" +} + +tasks.withType { + exclude("logback.xml") +} + +dependencies { + compileOnly(libs.slf4j) + implementation(libs.logback) + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) +} + +tasks.test { + useJUnitPlatform() +} + +publishing { + publications { + create("mathToolbox") { + groupId = group.toString() + artifactId = "math-toolbox" + version = artefactVersion + + pom { + name = "OnixByte Math Toolbox" + description = + "This module is an easy-to-use util for mathematical calculations in Java." + url = projectUrl + + licenses { + license { + name = licenseName + url = licenseUrl + } + } + + scm { + connection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git" + developerConnection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git" + url = projectGithubUrl + } + + developers { + developer { + id = "zihluwang" + name = "Zihlu Wang" + email = "real@zihluwang.me" + timezone = "Asia/Hong_Kong" + } + + developer { + id = "siujamo" + name = "Siu Jam'o" + email = "jamo.siu@gmail.com" + timezone = "Asia/Shanghai" + } + } + } + + from(components["java"]) + + signing { + setRequired(project.hasProperty("signing.keyId")) + sign(publishing.publications["mathToolbox"]) + } + } + + repositories { + maven { + name = "sonatypeNexus" + url = URI(providers.gradleProperty("repo.maven-central.host").get()) + credentials { + username = providers.gradleProperty("repo.maven-central.username").get() + password = providers.gradleProperty("repo.maven-central.password").get() + } + } + } + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..646fb18 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,27 @@ +# +# Copyright (c) 2024-2025 OnixByte +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +artefactVersion=3.3.0 +projectUrl=https://github.com/onixbyte/onixbyte-tuple +projectGithubUrl=git@github.com:onixbyte/onixbyte-tuple.git +licenseName=MIT +licenseUrl= diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..42c64d6 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,10 @@ +[versions] +slf4j = "2.0.17" +logback = "1.5.26" +junit = "5.11.4" + +[libraries] +slf4j = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" } +logback = { group = "ch.qos.logback", name = "logback-classic", version.ref = "logback" } +junit-bom = { group = "org.junit", name = "junit-bom", version.ref = "junit" } +junit-jupiter = { group = "org.junit.jupiter", name = "junit-jupiter", version.ref = "junit" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..79eb9d0 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/com/onixbyte/math/Calculator.java b/src/main/java/com/onixbyte/math/Calculator.java new file mode 100644 index 0000000..00fbd1f --- /dev/null +++ b/src/main/java/com/onixbyte/math/Calculator.java @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2024-2026 OnixByte + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.onixbyte.math; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** + * The {@code ChainedCalcUtil} class provides a convenient way to perform chained high-precision + * calculations using {@link BigDecimal}. It allows users to perform mathematical operations such + * as addition, subtraction, multiplication, and division with customisable precision and scale. + * By using this utility class, developers can achieve accurate results and avoid precision loss + * in their calculations. + *

+ * Usage: + *

+ *  // Perform addition: 3 + 4
+ *  BigDecimal result1 = Calculator.startWith(3)
+ *                                      .add(4)
+ *                                      .getValue();
+ *
+ *  // Perform subtraction: 4 - 2
+ *  BigDecimal result2 = Calculator.startWith(4)
+ *                                      .subtract(2)
+ *                                      .getValue();
+ *
+ *  // Perform multiplication: 3 * 6
+ *  BigDecimal result3 = Calculator.startWith(3)
+ *                                      .multiply(6)
+ *                                      .getValue();
+ *
+ *  // Perform division: 6 ÷ 2
+ *  BigDecimal result4 = Calculator.startWith(6)
+ *                                      .divide(2)
+ *                                      .getValue();
+ *
+ *  // Perform division with specified scale: 13 ÷ 7 with a scale of 2
+ *  BigDecimal result5 = Calculator.startWith(13)
+ *                                      .divideWithScale(7, 2)
+ *                                      .getValue();
+ *
+ *  // Get int, long, or double results
+ *  int intResult = Calculator.startWith(3)
+ *                                .add(4)
+ *                                .getInteger();
+ *
+ *  long longResult = Calculator.startWith(4)
+ *                                  .subtract(2)
+ *                                  .getLong();
+ *
+ *  double doubleResult = Calculator.startWith(6)
+ *                                      .divide(2)
+ *                                      .getDouble();
+ *
+ *  // Get BigDecimal result with specified scale
+ *  BigDecimal result6 = Calculator.startWith(13)
+ *                                      .divide(7)
+ *                                      .getValue(2);
+ *  
+ * The above expressions perform various mathematical calculations using the + * {@code ChainedCalcUtil} class. + *

+ * Note: + * The {@code ChainedCalcUtil} class internally uses {@link BigDecimal} to handle high-precision + * calculations. It is important to note that {@link BigDecimal} operations can be memory-intensive + * and may have performance implications for extremely large numbers or complex calculations. + * + * @author sunzsh + * @version 3.3.0 + * @see BigDecimal + * @since 1.0.0 + */ +public final class Calculator { + + /** + * Creates a {@code ChainedCalcUtil} instance with the specified initial value. + * + * @param value the initial value for the calculation + */ + private Calculator(Number value) { + this.value = convertBigDecimal(value, null); + } + + /** + * Starts a chained calculation with the specified initial value. + * + * @param value the initial value for the calculation + * @return a {@code ChainedCalcUtil} instance for performing chained calculations + */ + public static Calculator startWith(Number value) { + return new Calculator(value); + } + + /** + * Adds the specified value to the current value. + * + * @param other the value to be added + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator add(Number other) { + return operator(BigDecimal::add, other); + } + + /** + * Adds the specified value to the current value with a specified scale before the operation. + * + * @param other the value to be added + * @param beforeOperateScale the scale to be applied before the operation + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator add(Number other, Integer beforeOperateScale) { + return operator(BigDecimal::add, other, beforeOperateScale); + } + + /** + * Subtracts the specified value from the current value. + * + * @param other the value to be subtracted + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator subtract(Number other) { + return operator(BigDecimal::subtract, other); + } + + /** + * Subtracts the specified value from the current value with a specified scale before + * the operation. + * + * @param other the value to be subtracted + * @param beforeOperateScale the scale to be applied before the operation + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator subtract(Number other, Integer beforeOperateScale) { + return operator(BigDecimal::subtract, other, beforeOperateScale); + } + + /** + * Multiplies the current value by the specified value. + * + * @param other the value to be multiplied by + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator multiply(Number other) { + return operator(BigDecimal::multiply, other); + } + + /** + * Multiplies the current value by the specified value with a specified scale before + * the operation. + * + * @param other the value to be multiplied by + * @param beforeOperateScale the scale to be applied before the operation + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator multiply(Number other, Integer beforeOperateScale) { + return operator(BigDecimal::multiply, other, beforeOperateScale); + } + + /** + * Divides the current value by the specified value. + * + * @param other the value to divide by + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator divide(Number other) { + return operator(BigDecimal::divide, other); + } + + /** + * Divides the current value by the specified value with a specified scale before the operation. + * + * @param other the value to divide by + * @param beforeOperateScale the scale to be applied before the operation + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator divide(Number other, Integer beforeOperateScale) { + return operator(BigDecimal::divide, other, beforeOperateScale); + } + + /** + * Divides the current value by the specified value with a specified scale. + * + * @param other the value to divide by + * @param scale the scale for the result + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator divideWithScale(Number other, Integer scale) { + return baseOperator(otherValue -> + this.value.divide(otherValue, scale, RoundingMode.HALF_UP), other, null); + } + + /** + * Divides the current value by the specified value with a specified scale and a scale applied + * before the operation. + * + * @param other the value to divide by + * @param scale the scale for the result + * @param beforeOperateScale the scale to be applied before the operation + * @return a {@code ChainedCalcUtil} instance with the updated value + */ + public Calculator divideWithScale(Number other, Integer scale, Integer beforeOperateScale) { + return baseOperator((otherValue) -> + this.value.divide(otherValue, scale, RoundingMode.HALF_UP), + other, beforeOperateScale); + } + + /** + * Returns the current value as a {@link BigDecimal} with the specified scale. + * + * @param scale the scale for the result + * @return the current value as a {@link BigDecimal} with the specified scale + */ + public BigDecimal getValue(int scale) { + return value.setScale(scale, RoundingMode.HALF_UP); + } + + /** + * Returns the current value as a {@link BigDecimal}. + * + * @return the current value as a {@link BigDecimal} + */ + public BigDecimal getValue() { + return value; + } + + /** + * Returns the current value as a {@link Double}. + * + * @return the current value as a {@link Double} + */ + public double getDouble() { + return getValue().doubleValue(); + } + + /** + * Returns the current value as a {@link Double} with the specified scale. + * + * @param scale the scale for the result + * @return the current value as a {@link Double} with the specified scale + */ + public double getDouble(int scale) { + return getValue(scale).doubleValue(); + } + + /** + * Returns the current value as a {@link Long}. + * + * @return the current value as a {@link Long} + */ + public long getLong() { + return getValue().longValue(); + } + + /** + * Returns the current value as an {@link Integer}. + * + * @return the current value as an {@link Integer} + */ + public int getInteger() { + return getValue().intValue(); + } + + /** + * Applies the specified operator function to the current value and another value. + * + * @param operator the operator function to apply + * @param otherValue the value to apply the operator with + * @return a ChainedCalcUtil instance with the updated value + */ + private Calculator operator( + BiFunction operator, + Object otherValue + ) { + return operator(operator, otherValue, 9); + } + + /** + * Applies the specified operator function to the current value and another value with a + * specified scale before the operation. + * + * @param operator the operator function to apply + * @param other the value to apply the operator with + * @param beforeOperateScale the scale to be applied before the operation, + * or null if not applicable + * @return a ChainedCalcUtil instance with the updated value + */ + private Calculator operator( + BiFunction operator, + Object other, + Integer beforeOperateScale + ) { + return baseOperator( + (otherValue) -> operator.apply(this.value, otherValue), + other, + beforeOperateScale + ); + } + + /** + * Applies the specified operator function to the current value and another + * value. + * + * @param operatorFunction the operator function to apply + * @param anotherValue the value to apply the operator with + * @param beforeOperateScale the scale to be applied before the operation, + * or null if not applicable + * @return a ChainedCalcUtil instance with the updated value + */ + private synchronized Calculator baseOperator( + Function operatorFunction, + Object anotherValue, + Integer beforeOperateScale + ) { + if (Objects.isNull(anotherValue)) { + return this; + } + if (anotherValue instanceof Calculator) { + this.value = operatorFunction.apply(((Calculator) anotherValue).getValue()); + return this; + } + this.value = operatorFunction.apply(convertBigDecimal(anotherValue, beforeOperateScale)); + return this; + } + + /** + * Converts the specified value to a {@link BigDecimal}. + * + * @param value the value to convert + * @param scale the scale to apply to the resulting BigDecimal, or null if not applicable + * @return the converted BigDecimal value + */ + private BigDecimal convertBigDecimal(Object value, Integer scale) { + if (Objects.isNull(value)) { + return BigDecimal.ZERO; + } + BigDecimal res; + if (value instanceof Number num) { + res = BigDecimal.valueOf(num.doubleValue()); + } else { + try { + res = new BigDecimal(value.toString()); + } catch (NumberFormatException ignored) { + return BigDecimal.ZERO; + } + } + + if (Objects.nonNull(scale)) { + return res.setScale(scale, RoundingMode.HALF_UP); + } + return res; + } + + /** + * Final result. + */ + private BigDecimal value; + +} diff --git a/src/main/java/com/onixbyte/math/PercentileCalculator.java b/src/main/java/com/onixbyte/math/PercentileCalculator.java new file mode 100644 index 0000000..f5208f7 --- /dev/null +++ b/src/main/java/com/onixbyte/math/PercentileCalculator.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2024-2026 OnixByte + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.onixbyte.math; + +import com.onixbyte.math.model.QuartileBounds; + +import java.util.List; + +/** + * A utility class that provides methods for calculating percentiles and interquartile range (IQR) + * bounds for a dataset. + *

+ * This class contains static methods to: + *

    + *
  • + * Calculate a specified percentile from a list of double values using linear interpolation. + *
  • + *
  • + * Calculate interquartile bounds (Q1, Q3) and the corresponding lower and upper bounds, + * which can be used to identify outliers in the dataset. + *
  • + *
+ *

+ * This class is final, meaning it cannot be subclassed, and it only contains static methods, + * so instances of the class cannot be created. + *

Example usage:

+ *
{@code
+ * List data = Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0);
+ * Double percentileValue = PercentileCalculator.calculatePercentile(data, 50.0);  // Calculates median
+ * QuartileBounds bounds = PercentileCalculator.calculatePercentileBounds(data);   // Calculates IQR bounds
+ * }
+ * + * @author zihluwang + * @version 3.0.0 + * @since 1.6.5 + */ +public final class PercentileCalculator { + + /** + * Private constructor to prevent instantiation of this utility class. + */ + private PercentileCalculator() { + } + + /** + * Calculates the specified percentile from a list of values. + *

+ * This method takes a list of double values and calculates the given percentile using linear + * interpolation between the two closest ranks. The list is first sorted in ascending order, + * and the specified percentile is then calculated. + * + * @param values a list of {@code Double} values from which the percentile is calculated. + * @param percentile a {@code Double} representing the percentile to be calculated (e.g., 50.0 + * for the median) + * @return a {@code Double} value representing the calculated percentile + */ + public static Double calculatePercentile(List values, Double percentile) { + if (values.isEmpty()) { + throw new IllegalArgumentException("Unable to sort an empty list."); + } + var sorted = values.stream().sorted().toList(); + + var rank = percentile / 100. * (sorted.size() - 1); + var lowerIndex = (int) Math.floor(rank); + var upperIndex = (int) Math.ceil(rank); + var weight = rank - lowerIndex; + + return sorted.get(lowerIndex) * (1 - weight) + sorted.get(upperIndex) * weight; + } + + /** + * Calculates the interquartile range (IQR) and the corresponding lower and upper bounds + * based on the first (Q1) and third (Q3) quartiles of a dataset. + *

+ * This method takes a list of double values, calculates the first quartile (Q1), + * the third quartile (Q3), and the interquartile range (IQR). Using the IQR, it computes + * the lower and upper bounds, which can be used to detect outliers in the dataset. + * The lower bound is defined as {@code Q1 - 1.5 * IQR}, and the upper bound is defined as + * {@code Q3 + 1.5 * IQR}. + * + * @param data a list of {@code Double} values for which the quartile bounds will be calculated + * @return a {@code QuartileBounds} object containing the calculated lower and upper bounds + */ + public static QuartileBounds calculatePercentileBounds(List data) { + var sorted = data.stream().sorted().toList(); + var q1 = calculatePercentile(sorted, 25.); + var q3 = calculatePercentile(sorted, 75.); + + var iqr = q3 - q1; + + var lowerBound = q1 - 1.5 * iqr; + var upperBound = q3 + 1.5 * iqr; + + return QuartileBounds.builder() + .upperBound(upperBound) + .lowerBound(lowerBound) + .build(); + } + +} diff --git a/src/main/java/com/onixbyte/math/model/QuartileBounds.java b/src/main/java/com/onixbyte/math/model/QuartileBounds.java new file mode 100644 index 0000000..84f359e --- /dev/null +++ b/src/main/java/com/onixbyte/math/model/QuartileBounds.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2024-2026 OnixByte + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.onixbyte.math.model; + +/** + * A record representing the quartile bounds of a dataset. + *

+ * This class encapsulates the lower and upper bounds of a dataset, which are typically used for + * detecting outliers in the data. The bounds are calculated based on the interquartile range (IQR) + * of the dataset. Values below the lower bound or above the upper bound may be considered outliers. + *

+ * Quartile bounds consist of: + *

    + *
  • + * {@code lowerBound} - The lower bound of the dataset, typically {@code Q1 - 1.5 * IQR}. + *
  • + *
  • + * {@code upperBound} - The upper bound of the dataset, typically {@code Q3 + 1.5 * IQR}. + *
  • + *
+ *

+ * Example usage: + *

{@code
+ * QuartileBounds bounds = QuartileBounds.builder()
+ *      .lowerBound(1.5)
+ *      .upperBound(7.5)
+ *      .build();
+ * }
+ * + * @param upperBound the upper bound of the dataset + * @param lowerBound the lower bound of the dataset + * @author zihluwang + * @version 3.0.0 + * @since 1.6.5 + */ +public record QuartileBounds( + Double upperBound, + Double lowerBound +) { + + /** + * Creates a new {@link Builder} instance for building a {@code QuartileBounds} object. + *

+ * The {@link Builder} pattern is used to construct the {@code QuartileBounds} object with + * optional values for the upper and lower bounds. + *

+ * + * @return a new instance of the {@link Builder} class + */ + public static Builder builder() { + return new Builder(); + } + + /** + * A builder class for constructing instances of the {@code QuartileBounds} record. + *

+ * The {@link Builder} pattern allows for the step-by-step construction of a + * {@code QuartileBounds} object, providing a flexible way to set values for the lower and + * upper bounds. Once the builder has the required values, the {@link #build()} method creates + * and returns a new {@code QuartileBounds} object. + *

+ *

+ * Example usage: + *

+     * {@code
+     * QuartileBounds bounds = QuartileBounds.builder()
+     *     .lowerBound(1.5)
+     *     .upperBound(7.5)
+     *     .build();
+     * }
+     * 
+ */ + public static class Builder { + private Double upperBound; + private Double lowerBound; + + /** + * Private constructor to prevent instantiation of this utility class. + */ + private Builder() { + } + + /** + * Sets the upper bound for the {@code QuartileBounds}. + * + * @param upperBound the upper bound of the dataset + * @return the current {@code Builder} instance, for method chaining + */ + public Builder upperBound(Double upperBound) { + this.upperBound = upperBound; + return this; + } + + /** + * Sets the lower bound for the {@code QuartileBounds}. + * + * @param lowerBound the lower bound of the dataset + * @return the current {@code Builder} instance, for method chaining + */ + public Builder lowerBound(Double lowerBound) { + this.lowerBound = lowerBound; + return this; + } + + /** + * Builds and returns a new {@code QuartileBounds} instance with the specified upper and + * lower bounds. + * + * @return a new {@code QuartileBounds} object containing the specified bounds + */ + public QuartileBounds build() { + return new QuartileBounds(upperBound, lowerBound); + } + } + +} diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..85b705f --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + ${COLOURFUL_OUTPUT} + + + + + +