index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/PythonTraceback.java
package ai.timefold.jpyinterpreter.types.errors; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Traceback of a Python Error. * TODO: Implement this */ public class PythonTraceback extends AbstractPythonLikeObject { public static final PythonLikeType TRACEBACK_TYPE = new PythonLikeType("traceback", PythonTraceback.class), $TYPE = TRACEBACK_TYPE; public PythonTraceback() { super(TRACEBACK_TYPE); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/RecursionError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class RecursionError extends RuntimeError { final public static PythonLikeType RECURSION_ERROR_TYPE = new PythonLikeType("RecursionError", RecursionError.class, List.of(RUNTIME_ERROR_TYPE)), $TYPE = RECURSION_ERROR_TYPE; static { RECURSION_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new RecursionError(RECURSION_ERROR_TYPE, positionalArguments))); } public RecursionError(PythonLikeType type) { super(type); } public RecursionError(PythonLikeType type, String message) { super(type, message); } public RecursionError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/ReferenceError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class ReferenceError extends PythonBaseException { final public static PythonLikeType REFERENCE_ERROR_TYPE = new PythonLikeType("ReferenceError", ReferenceError.class, List.of(BASE_EXCEPTION_TYPE)), $TYPE = REFERENCE_ERROR_TYPE; static { REFERENCE_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new ReferenceError(REFERENCE_ERROR_TYPE, positionalArguments))); } public ReferenceError(PythonLikeType type) { super(type); } public ReferenceError(PythonLikeType type, String message) { super(type, message); } public ReferenceError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/RuntimeError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class RuntimeError extends PythonBaseException { final public static PythonLikeType RUNTIME_ERROR_TYPE = new PythonLikeType("RuntimeError", RuntimeError.class, List.of(BASE_EXCEPTION_TYPE)), $TYPE = RUNTIME_ERROR_TYPE; static { RUNTIME_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new RuntimeError(RUNTIME_ERROR_TYPE, positionalArguments))); } public RuntimeError(String message) { super(RUNTIME_ERROR_TYPE, message); } public RuntimeError(PythonLikeType type) { super(type); } public RuntimeError(PythonLikeType type, String message) { super(type, message); } public RuntimeError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/StopAsyncIteration.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; /** * Error thrown when a Python async iterator has no more values to return. */ public class StopAsyncIteration extends PythonException { public static final PythonLikeType STOP_ASYNC_ITERATION_TYPE = new PythonLikeType("StopAsyncIteration", StopAsyncIteration.class, List.of(EXCEPTION_TYPE)), $TYPE = STOP_ASYNC_ITERATION_TYPE; static { STOP_ASYNC_ITERATION_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new StopAsyncIteration(STOP_ASYNC_ITERATION_TYPE, positionalArguments))); } private final PythonLikeObject value; public StopAsyncIteration() { this(PythonNone.INSTANCE); } public StopAsyncIteration(PythonLikeObject value) { this(STOP_ASYNC_ITERATION_TYPE, List.of(value)); } public StopAsyncIteration(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); if (args.size() > 0) { value = args.get(0); } else { value = PythonNone.INSTANCE; } } public PythonLikeObject getValue() { return value; } /** * This exception acts as a signal, and should be low cost * * @return this */ @Override public synchronized Throwable fillInStackTrace() { // Do nothing return this; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/StopIteration.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; /** * Error thrown when a Python iterator has no more values to return. */ public class StopIteration extends PythonException { public static final PythonLikeType STOP_ITERATION_TYPE = new PythonLikeType("StopIteration", StopIteration.class, List.of(EXCEPTION_TYPE)), $TYPE = STOP_ITERATION_TYPE; static { STOP_ITERATION_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new StopIteration(STOP_ITERATION_TYPE, positionalArguments))); } private final PythonLikeObject value; public StopIteration() { this(PythonNone.INSTANCE); } public StopIteration(PythonLikeObject value) { this(STOP_ITERATION_TYPE, List.of(value)); } public StopIteration(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); if (args.size() > 0) { value = args.get(0); } else { value = PythonNone.INSTANCE; } } public PythonLikeObject getValue() { return value; } /** * This exception acts as a signal, and should be low cost * * @return this */ @Override public synchronized Throwable fillInStackTrace() { // Do nothing return this; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/TypeError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class TypeError extends PythonException { public final static PythonLikeType TYPE_ERROR_TYPE = new PythonLikeType("TypeError", TypeError.class, List.of(EXCEPTION_TYPE)), $TYPE = TYPE_ERROR_TYPE; static { TYPE_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new TypeError(TYPE_ERROR_TYPE, positionalArguments))); } public TypeError() { super(TYPE_ERROR_TYPE); } public TypeError(String message) { super(TYPE_ERROR_TYPE, message); } public TypeError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public TypeError(PythonLikeType type) { super(type); } public TypeError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/UnboundLocalError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class UnboundLocalError extends NameError { public final static PythonLikeType UNBOUND_LOCAL_ERROR_TYPE = new PythonLikeType("UnboundLocalError", UnboundLocalError.class, List.of(NAME_ERROR_TYPE)), $TYPE = UNBOUND_LOCAL_ERROR_TYPE; static { UNBOUND_LOCAL_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new UnboundLocalError(UNBOUND_LOCAL_ERROR_TYPE, positionalArguments))); } public UnboundLocalError() { super(UNBOUND_LOCAL_ERROR_TYPE); } public UnboundLocalError(String message) { super(UNBOUND_LOCAL_ERROR_TYPE, message); } public UnboundLocalError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public UnboundLocalError(PythonLikeType type) { super(type); } public UnboundLocalError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/ValueError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class ValueError extends PythonException { public final static PythonLikeType VALUE_ERROR_TYPE = new PythonLikeType("ValueError", ValueError.class, List.of(EXCEPTION_TYPE)), $TYPE = VALUE_ERROR_TYPE; static { VALUE_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new ValueError(VALUE_ERROR_TYPE, positionalArguments))); } public ValueError() { super(VALUE_ERROR_TYPE); } public ValueError(String message) { super(VALUE_ERROR_TYPE, message); } public ValueError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ValueError(PythonLikeType type) { super(type); } public ValueError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/arithmetic/ArithmeticError.java
package ai.timefold.jpyinterpreter.types.errors.arithmetic; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonException; /** * The base class for those built-in exceptions that are raised for various arithmetic errors */ public class ArithmeticError extends PythonException { final public static PythonLikeType ARITHMETIC_ERROR_TYPE = new PythonLikeType("ArithmeticError", ArithmeticError.class, List.of(EXCEPTION_TYPE)), $TYPE = ARITHMETIC_ERROR_TYPE; static { ARITHMETIC_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new ArithmeticError(ARITHMETIC_ERROR_TYPE, positionalArguments))); } public ArithmeticError(PythonLikeType type) { super(type); } public ArithmeticError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ArithmeticError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/arithmetic/FloatingPointError.java
package ai.timefold.jpyinterpreter.types.errors.arithmetic; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * The base class for those built-in exceptions that are raised for various arithmetic errors */ public class FloatingPointError extends ArithmeticError { final public static PythonLikeType FLOATING_POINT_ERROR_TYPE = new PythonLikeType("FloatingPointError", FloatingPointError.class, List.of(ARITHMETIC_ERROR_TYPE)), $TYPE = FLOATING_POINT_ERROR_TYPE; static { FLOATING_POINT_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new FloatingPointError(FLOATING_POINT_ERROR_TYPE, positionalArguments))); } public FloatingPointError(PythonLikeType type) { super(type); } public FloatingPointError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public FloatingPointError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/arithmetic/OverflowError.java
package ai.timefold.jpyinterpreter.types.errors.arithmetic; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * The base class for those built-in exceptions that are raised for various arithmetic errors */ public class OverflowError extends ArithmeticError { final public static PythonLikeType OVERFLOW_ERROR_TYPE = new PythonLikeType("OverflowError", OverflowError.class, List.of(ARITHMETIC_ERROR_TYPE)), $TYPE = OVERFLOW_ERROR_TYPE; static { OVERFLOW_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new OverflowError(OVERFLOW_ERROR_TYPE, positionalArguments))); } public OverflowError(PythonLikeType type) { super(type); } public OverflowError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public OverflowError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/arithmetic/ZeroDivisionError.java
package ai.timefold.jpyinterpreter.types.errors.arithmetic; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * The base class for those built-in exceptions that are raised for various arithmetic errors */ public class ZeroDivisionError extends ArithmeticError { final public static PythonLikeType ZERO_DIVISION_ERROR_TYPE = new PythonLikeType("ZeroDivisionError", ZeroDivisionError.class, List.of(ARITHMETIC_ERROR_TYPE)), $TYPE = ZERO_DIVISION_ERROR_TYPE; static { ZERO_DIVISION_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new ZeroDivisionError(ZERO_DIVISION_ERROR_TYPE, positionalArguments))); } public ZeroDivisionError(String message) { super(ZERO_DIVISION_ERROR_TYPE, message); } public ZeroDivisionError(PythonLikeType type) { super(type); } public ZeroDivisionError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ZeroDivisionError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/BlockingIOError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class BlockingIOError extends OSError { final public static PythonLikeType BLOCKING_IO_ERROR_TYPE = new PythonLikeType("BlockingIOError", BlockingIOError.class, List.of(OS_ERROR_TYPE)), $TYPE = BLOCKING_IO_ERROR_TYPE; static { BLOCKING_IO_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new BlockingIOError(BLOCKING_IO_ERROR_TYPE, positionalArguments))); } public BlockingIOError(PythonLikeType type) { super(type); } public BlockingIOError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public BlockingIOError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/ChildProcessError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class ChildProcessError extends OSError { final public static PythonLikeType CHILD_PROCESS_ERROR_TYPE = new PythonLikeType("ChildProcessError", ChildProcessError.class, List.of(OS_ERROR_TYPE)), $TYPE = CHILD_PROCESS_ERROR_TYPE; static { CHILD_PROCESS_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new ChildProcessError(CHILD_PROCESS_ERROR_TYPE, positionalArguments))); } public ChildProcessError(PythonLikeType type) { super(type); } public ChildProcessError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ChildProcessError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/EOFError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; /** * Raised when a buffer related operation cannot be performed. */ public class EOFError extends PythonBaseException { final public static PythonLikeType EOF_ERROR_TYPE = new PythonLikeType("EOFError", EOFError.class, List.of(PythonBaseException.BASE_EXCEPTION_TYPE)), $TYPE = EOF_ERROR_TYPE; static { EOF_ERROR_TYPE .setConstructor(((positionalArguments, namedArguments, callerInstance) -> new EOFError(EOF_ERROR_TYPE, positionalArguments))); } public EOFError(PythonLikeType type) { super(type); } public EOFError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public EOFError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/FileExistsError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class FileExistsError extends OSError { final public static PythonLikeType FILE_EXISTS_ERROR_TYPE = new PythonLikeType("FileExistsError", FileExistsError.class, List.of(OS_ERROR_TYPE)), $TYPE = FILE_EXISTS_ERROR_TYPE; static { FILE_EXISTS_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new FileExistsError(FILE_EXISTS_ERROR_TYPE, positionalArguments))); } public FileExistsError(PythonLikeType type) { super(type); } public FileExistsError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public FileExistsError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/FileNotFoundError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class FileNotFoundError extends OSError { final public static PythonLikeType FILE_NOT_FOUND_ERROR_TYPE = new PythonLikeType("FileNotFoundError", FileNotFoundError.class, List.of(OS_ERROR_TYPE)), $TYPE = FILE_NOT_FOUND_ERROR_TYPE; static { FILE_NOT_FOUND_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new FileNotFoundError(FILE_NOT_FOUND_ERROR_TYPE, positionalArguments))); } public FileNotFoundError(PythonLikeType type) { super(type); } public FileNotFoundError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public FileNotFoundError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/InterruptedError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class InterruptedError extends OSError { final public static PythonLikeType INTERRUPTED_ERROR_TYPE = new PythonLikeType("InterruptedError", InterruptedError.class, List.of(OS_ERROR_TYPE)), $TYPE = INTERRUPTED_ERROR_TYPE; static { INTERRUPTED_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new InterruptedError(INTERRUPTED_ERROR_TYPE, positionalArguments))); } public InterruptedError(PythonLikeType type) { super(type); } public InterruptedError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public InterruptedError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/IsADirectoryError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class IsADirectoryError extends OSError { final public static PythonLikeType IS_A_DIRECTORY_ERROR_TYPE = new PythonLikeType("IsADirectoryError", IsADirectoryError.class, List.of(OS_ERROR_TYPE)), $TYPE = IS_A_DIRECTORY_ERROR_TYPE; static { IS_A_DIRECTORY_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new IsADirectoryError(IS_A_DIRECTORY_ERROR_TYPE, positionalArguments))); } public IsADirectoryError(PythonLikeType type) { super(type); } public IsADirectoryError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public IsADirectoryError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/KeyboardInterrupt.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; /** * Raised when a buffer related operation cannot be performed. */ public class KeyboardInterrupt extends PythonBaseException { final public static PythonLikeType KEYBOARD_INTERRUPT_TYPE = new PythonLikeType("KeyboardInterrupt", KeyboardInterrupt.class, List.of(PythonBaseException.BASE_EXCEPTION_TYPE)), $TYPE = KEYBOARD_INTERRUPT_TYPE; static { KEYBOARD_INTERRUPT_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new KeyboardInterrupt(KEYBOARD_INTERRUPT_TYPE, positionalArguments))); } public KeyboardInterrupt(PythonLikeType type) { super(type); } public KeyboardInterrupt(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public KeyboardInterrupt(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/MemoryError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; /** * Raised when a buffer related operation cannot be performed. */ public class MemoryError extends PythonBaseException { final public static PythonLikeType MEMORY_ERROR_TYPE = new PythonLikeType("MemoryError", MemoryError.class, List.of(PythonBaseException.BASE_EXCEPTION_TYPE)), $TYPE = MEMORY_ERROR_TYPE; static { MEMORY_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new MemoryError(MEMORY_ERROR_TYPE, positionalArguments))); } public MemoryError(PythonLikeType type) { super(type); } public MemoryError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public MemoryError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/NotADirectoryError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class NotADirectoryError extends OSError { final public static PythonLikeType NOT_A_DIRECTORY_ERROR_TYPE = new PythonLikeType("NotADirectoryError", NotADirectoryError.class, List.of(OS_ERROR_TYPE)), $TYPE = NOT_A_DIRECTORY_ERROR_TYPE; static { NOT_A_DIRECTORY_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new NotADirectoryError(NOT_A_DIRECTORY_ERROR_TYPE, positionalArguments))); } public NotADirectoryError(PythonLikeType type) { super(type); } public NotADirectoryError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public NotADirectoryError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/OSError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; /** * Raised when a buffer related operation cannot be performed. */ public class OSError extends PythonBaseException { final public static PythonLikeType OS_ERROR_TYPE = new PythonLikeType("OSError", OSError.class, List.of(PythonBaseException.BASE_EXCEPTION_TYPE)), $TYPE = OS_ERROR_TYPE; static { OS_ERROR_TYPE .setConstructor(((positionalArguments, namedArguments, callerInstance) -> new OSError(OS_ERROR_TYPE, positionalArguments))); } public OSError(PythonLikeType type) { super(type); } public OSError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public OSError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/PermissionError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class PermissionError extends OSError { final public static PythonLikeType PERMISSION_ERROR_TYPE = new PythonLikeType("PermissionError", PermissionError.class, List.of(OS_ERROR_TYPE)), $TYPE = PERMISSION_ERROR_TYPE; static { PERMISSION_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new PermissionError(PERMISSION_ERROR_TYPE, positionalArguments))); } public PermissionError(PythonLikeType type) { super(type); } public PermissionError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public PermissionError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/ProcessLookupError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class ProcessLookupError extends OSError { final public static PythonLikeType PROCESS_LOOKUP_ERROR_TYPE = new PythonLikeType("ProcessLookupError", ProcessLookupError.class, List.of(OS_ERROR_TYPE)), $TYPE = PROCESS_LOOKUP_ERROR_TYPE; static { PROCESS_LOOKUP_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new ProcessLookupError(PROCESS_LOOKUP_ERROR_TYPE, positionalArguments))); } public ProcessLookupError(PythonLikeType type) { super(type); } public ProcessLookupError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ProcessLookupError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/SystemError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; /** * Raised when a buffer related operation cannot be performed. */ public class SystemError extends PythonBaseException { final public static PythonLikeType SYSTEM_ERROR_TYPE = new PythonLikeType("SystemError", SystemError.class, List.of(PythonBaseException.BASE_EXCEPTION_TYPE)), $TYPE = SYSTEM_ERROR_TYPE; static { SYSTEM_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new SystemError(SYSTEM_ERROR_TYPE, positionalArguments))); } public SystemError(PythonLikeType type) { super(type); } public SystemError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public SystemError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/SystemExit.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; /** * Raised when a buffer related operation cannot be performed. */ public class SystemExit extends PythonBaseException { final public static PythonLikeType SYSTEM_EXIT_TYPE = new PythonLikeType("SystemExit", SystemExit.class, List.of(PythonBaseException.BASE_EXCEPTION_TYPE)), $TYPE = SYSTEM_EXIT_TYPE; static { SYSTEM_EXIT_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new SystemExit(SYSTEM_EXIT_TYPE, positionalArguments))); } public SystemExit(PythonLikeType type) { super(type); } public SystemExit(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public SystemExit(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/TimeoutError.java
package ai.timefold.jpyinterpreter.types.errors.io; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class TimeoutError extends OSError { final public static PythonLikeType TIMEOUT_ERROR_TYPE = new PythonLikeType("TimeoutError", TimeoutError.class, List.of(OS_ERROR_TYPE)), $TYPE = TIMEOUT_ERROR_TYPE; static { TIMEOUT_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new TimeoutError(TIMEOUT_ERROR_TYPE, positionalArguments))); } public TimeoutError(PythonLikeType type) { super(type); } public TimeoutError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public TimeoutError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/connection/BrokenPipeError.java
package ai.timefold.jpyinterpreter.types.errors.io.connection; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class BrokenPipeError extends ConnectionError { final public static PythonLikeType BROKEN_PIPE_ERROR_TYPE = new PythonLikeType("BrokenPipeError", BrokenPipeError.class, List.of(CONNECTION_ERROR_TYPE)), $TYPE = BROKEN_PIPE_ERROR_TYPE; static { BROKEN_PIPE_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new BrokenPipeError(BROKEN_PIPE_ERROR_TYPE, positionalArguments))); } public BrokenPipeError(PythonLikeType type) { super(type); } public BrokenPipeError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public BrokenPipeError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/connection/ConnectionAbortedError.java
package ai.timefold.jpyinterpreter.types.errors.io.connection; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class ConnectionAbortedError extends ConnectionError { final public static PythonLikeType CONNECTION_ABORTED_ERROR_TYPE = new PythonLikeType("ConnectionAbortedError", ConnectionAbortedError.class, List.of(CONNECTION_ERROR_TYPE)), $TYPE = CONNECTION_ABORTED_ERROR_TYPE; static { CONNECTION_ABORTED_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new ConnectionAbortedError(CONNECTION_ABORTED_ERROR_TYPE, positionalArguments))); } public ConnectionAbortedError(PythonLikeType type) { super(type); } public ConnectionAbortedError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ConnectionAbortedError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/connection/ConnectionError.java
package ai.timefold.jpyinterpreter.types.errors.io.connection; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.io.OSError; /** * Raised when a buffer related operation cannot be performed. */ public class ConnectionError extends OSError { final public static PythonLikeType CONNECTION_ERROR_TYPE = new PythonLikeType("ConnectionError", ConnectionError.class, List.of(OS_ERROR_TYPE)), $TYPE = CONNECTION_ERROR_TYPE; static { CONNECTION_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new ConnectionError(CONNECTION_ERROR_TYPE, positionalArguments))); } public ConnectionError(PythonLikeType type) { super(type); } public ConnectionError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ConnectionError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/connection/ConnectionRefusedError.java
package ai.timefold.jpyinterpreter.types.errors.io.connection; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class ConnectionRefusedError extends ConnectionError { final public static PythonLikeType CONNECTION_REFUSED_ERROR_TYPE = new PythonLikeType("ConnectionRefusedError", ConnectionRefusedError.class, List.of(CONNECTION_ERROR_TYPE)), $TYPE = CONNECTION_REFUSED_ERROR_TYPE; static { CONNECTION_REFUSED_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new ConnectionRefusedError(CONNECTION_REFUSED_ERROR_TYPE, positionalArguments))); } public ConnectionRefusedError(PythonLikeType type) { super(type); } public ConnectionRefusedError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ConnectionRefusedError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/io/connection/ConnectionResetError.java
package ai.timefold.jpyinterpreter.types.errors.io.connection; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class ConnectionResetError extends ConnectionError { final public static PythonLikeType CONNECTION_RESET_ERROR_TYPE = new PythonLikeType("ConnectionResetError", ConnectionResetError.class, List.of(CONNECTION_ERROR_TYPE)), $TYPE = CONNECTION_RESET_ERROR_TYPE; static { CONNECTION_RESET_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new ConnectionResetError(CONNECTION_RESET_ERROR_TYPE, positionalArguments))); } public ConnectionResetError(PythonLikeType type) { super(type); } public ConnectionResetError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ConnectionResetError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/lookup/IndexError.java
package ai.timefold.jpyinterpreter.types.errors.lookup; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid. */ public class IndexError extends LookupError { final public static PythonLikeType INDEX_ERROR_TYPE = new PythonLikeType("IndexError", IndexError.class, List.of(LOOKUP_ERROR_TYPE)), $TYPE = INDEX_ERROR_TYPE; static { INDEX_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new IndexError(INDEX_ERROR_TYPE, positionalArguments))); } public IndexError(PythonLikeType type) { super(type); } public IndexError(String message) { super(INDEX_ERROR_TYPE, message); } public IndexError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public IndexError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/lookup/KeyError.java
package ai.timefold.jpyinterpreter.types.errors.lookup; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid. */ public class KeyError extends LookupError { final public static PythonLikeType KEY_ERROR_TYPE = new PythonLikeType("KeyError", KeyError.class, List.of(LOOKUP_ERROR_TYPE)), $TYPE = KEY_ERROR_TYPE; static { KEY_ERROR_TYPE .setConstructor(((positionalArguments, namedArguments, callerInstance) -> new KeyError(KEY_ERROR_TYPE, positionalArguments))); } public KeyError(PythonLikeType type) { super(type); } public KeyError(String message) { super(KEY_ERROR_TYPE, message); } public KeyError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public KeyError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/lookup/LookupError.java
package ai.timefold.jpyinterpreter.types.errors.lookup; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonException; /** * The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid. */ public class LookupError extends PythonException { final public static PythonLikeType LOOKUP_ERROR_TYPE = new PythonLikeType("LookupError", LookupError.class, List.of(EXCEPTION_TYPE)), $TYPE = LOOKUP_ERROR_TYPE; static { LOOKUP_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new LookupError(LOOKUP_ERROR_TYPE, positionalArguments))); } public LookupError(PythonLikeType type) { super(type); } public LookupError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public LookupError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/syntax/IndentationError.java
package ai.timefold.jpyinterpreter.types.errors.syntax; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class IndentationError extends SyntaxError { final public static PythonLikeType INDENTATION_ERROR_TYPE = new PythonLikeType("IndentationError", IndentationError.class, List.of(SYNTAX_ERROR_TYPE)), $TYPE = INDENTATION_ERROR_TYPE; static { INDENTATION_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new IndentationError(INDENTATION_ERROR_TYPE, positionalArguments))); } public IndentationError(PythonLikeType type) { super(type); } public IndentationError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public IndentationError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/syntax/SyntaxError.java
package ai.timefold.jpyinterpreter.types.errors.syntax; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonException; /** * Raised when a buffer related operation cannot be performed. */ public class SyntaxError extends PythonException { final public static PythonLikeType SYNTAX_ERROR_TYPE = new PythonLikeType("SyntaxError", SyntaxError.class, List.of(EXCEPTION_TYPE)), $TYPE = SYNTAX_ERROR_TYPE; static { SYNTAX_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new SyntaxError(SYNTAX_ERROR_TYPE, positionalArguments))); } public SyntaxError(PythonLikeType type) { super(type); } public SyntaxError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public SyntaxError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/syntax/TabError.java
package ai.timefold.jpyinterpreter.types.errors.syntax; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class TabError extends IndentationError { final public static PythonLikeType TAB_ERROR_TYPE = new PythonLikeType("TabError", TabError.class, List.of(INDENTATION_ERROR_TYPE)), $TYPE = TAB_ERROR_TYPE; static { TAB_ERROR_TYPE .setConstructor(((positionalArguments, namedArguments, callerInstance) -> new TabError(TAB_ERROR_TYPE, positionalArguments))); } public TabError(PythonLikeType type) { super(type); } public TabError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public TabError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/unicode/UnicodeDecodeError.java
package ai.timefold.jpyinterpreter.types.errors.unicode; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class UnicodeDecodeError extends UnicodeError { public final static PythonLikeType UNICODE_DECODE_ERROR_TYPE = new PythonLikeType("UnicodeDecodeError", UnicodeDecodeError.class, List.of(UNICODE_ERROR_TYPE)), $TYPE = UNICODE_DECODE_ERROR_TYPE; static { UNICODE_DECODE_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new UnicodeDecodeError(UNICODE_DECODE_ERROR_TYPE, positionalArguments))); } public UnicodeDecodeError() { super(UNICODE_DECODE_ERROR_TYPE); } public UnicodeDecodeError(String message) { super(UNICODE_DECODE_ERROR_TYPE, message); } public UnicodeDecodeError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public UnicodeDecodeError(PythonLikeType type) { super(type); } public UnicodeDecodeError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/unicode/UnicodeEncodeError.java
package ai.timefold.jpyinterpreter.types.errors.unicode; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class UnicodeEncodeError extends UnicodeError { public final static PythonLikeType UNICODE_ENCODE_ERROR_TYPE = new PythonLikeType("UnicodeEncodeError", UnicodeEncodeError.class, List.of(UNICODE_ERROR_TYPE)), $TYPE = UNICODE_ENCODE_ERROR_TYPE; static { UNICODE_ENCODE_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new UnicodeEncodeError(UNICODE_ENCODE_ERROR_TYPE, positionalArguments))); } public UnicodeEncodeError() { super(UNICODE_ENCODE_ERROR_TYPE); } public UnicodeEncodeError(String message) { super(UNICODE_ENCODE_ERROR_TYPE, message); } public UnicodeEncodeError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public UnicodeEncodeError(PythonLikeType type) { super(type); } public UnicodeEncodeError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/unicode/UnicodeError.java
package ai.timefold.jpyinterpreter.types.errors.unicode; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.ValueError; public class UnicodeError extends ValueError { public final static PythonLikeType UNICODE_ERROR_TYPE = new PythonLikeType("UnicodeError", UnicodeError.class, List.of(VALUE_ERROR_TYPE)), $TYPE = UNICODE_ERROR_TYPE; static { UNICODE_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new UnicodeError(UNICODE_ERROR_TYPE, positionalArguments))); } public UnicodeError() { super(UNICODE_ERROR_TYPE); } public UnicodeError(String message) { super(UNICODE_ERROR_TYPE, message); } public UnicodeError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public UnicodeError(PythonLikeType type) { super(type); } public UnicodeError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/unicode/UnicodeTranslateError.java
package ai.timefold.jpyinterpreter.types.errors.unicode; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class UnicodeTranslateError extends UnicodeError { public final static PythonLikeType UNICODE_TRANSLATE_ERROR_TYPE = new PythonLikeType("UnicodeTranslateError", UnicodeTranslateError.class, List.of(UNICODE_ERROR_TYPE)), $TYPE = UNICODE_TRANSLATE_ERROR_TYPE; static { UNICODE_TRANSLATE_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new UnicodeTranslateError(UNICODE_TRANSLATE_ERROR_TYPE, positionalArguments))); } public UnicodeTranslateError() { super(UNICODE_TRANSLATE_ERROR_TYPE); } public UnicodeTranslateError(String message) { super(UNICODE_TRANSLATE_ERROR_TYPE, message); } public UnicodeTranslateError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public UnicodeTranslateError(PythonLikeType type) { super(type); } public UnicodeTranslateError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/BytesWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class BytesWarning extends Warning { public final static PythonLikeType BYTES_WARNING_TYPE = new PythonLikeType("BytesWarning", BytesWarning.class, List.of(WARNING_TYPE)), $TYPE = BYTES_WARNING_TYPE; static { BYTES_WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new BytesWarning(BYTES_WARNING_TYPE, positionalArguments))); } public BytesWarning() { super(BYTES_WARNING_TYPE); } public BytesWarning(String message) { super(BYTES_WARNING_TYPE, message); } public BytesWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public BytesWarning(PythonLikeType type) { super(type); } public BytesWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/DeprecationWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class DeprecationWarning extends Warning { public final static PythonLikeType DEPRECATION_WARNING_TYPE = new PythonLikeType("DeprecationWarning", DeprecationWarning.class, List.of(WARNING_TYPE)), $TYPE = DEPRECATION_WARNING_TYPE; static { DEPRECATION_WARNING_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new DeprecationWarning(DEPRECATION_WARNING_TYPE, positionalArguments))); } public DeprecationWarning() { super(DEPRECATION_WARNING_TYPE); } public DeprecationWarning(String message) { super(DEPRECATION_WARNING_TYPE, message); } public DeprecationWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public DeprecationWarning(PythonLikeType type) { super(type); } public DeprecationWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/EncodingWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class EncodingWarning extends Warning { public final static PythonLikeType ENCODING_WARNING_TYPE = new PythonLikeType("EncodingWarning", EncodingWarning.class, List.of(WARNING_TYPE)), $TYPE = ENCODING_WARNING_TYPE; static { ENCODING_WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new EncodingWarning(ENCODING_WARNING_TYPE, positionalArguments))); } public EncodingWarning() { super(ENCODING_WARNING_TYPE); } public EncodingWarning(String message) { super(ENCODING_WARNING_TYPE, message); } public EncodingWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public EncodingWarning(PythonLikeType type) { super(type); } public EncodingWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/FutureWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class FutureWarning extends Warning { public final static PythonLikeType FUTURE_WARNING_TYPE = new PythonLikeType("FutureWarning", FutureWarning.class, List.of(WARNING_TYPE)), $TYPE = FUTURE_WARNING_TYPE; static { FUTURE_WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new FutureWarning(FUTURE_WARNING_TYPE, positionalArguments))); } public FutureWarning() { super(FUTURE_WARNING_TYPE); } public FutureWarning(String message) { super(FUTURE_WARNING_TYPE, message); } public FutureWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public FutureWarning(PythonLikeType type) { super(type); } public FutureWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/ImportWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class ImportWarning extends Warning { public final static PythonLikeType IMPORT_WARNING_TYPE = new PythonLikeType("ImportWarning", ImportWarning.class, List.of(WARNING_TYPE)), $TYPE = IMPORT_WARNING_TYPE; static { IMPORT_WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new ImportWarning(IMPORT_WARNING_TYPE, positionalArguments))); } public ImportWarning() { super(IMPORT_WARNING_TYPE); } public ImportWarning(String message) { super(IMPORT_WARNING_TYPE, message); } public ImportWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ImportWarning(PythonLikeType type) { super(type); } public ImportWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/PendingDeprecationWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class PendingDeprecationWarning extends Warning { public final static PythonLikeType PENDING_DEPRECATION_WARNING_TYPE = new PythonLikeType("PendingDeprecationWarning", PendingDeprecationWarning.class, List.of(WARNING_TYPE)), $TYPE = PENDING_DEPRECATION_WARNING_TYPE; static { PENDING_DEPRECATION_WARNING_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new PendingDeprecationWarning(PENDING_DEPRECATION_WARNING_TYPE, positionalArguments))); } public PendingDeprecationWarning() { super(PENDING_DEPRECATION_WARNING_TYPE); } public PendingDeprecationWarning(String message) { super(PENDING_DEPRECATION_WARNING_TYPE, message); } public PendingDeprecationWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public PendingDeprecationWarning(PythonLikeType type) { super(type); } public PendingDeprecationWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/ResourceWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class ResourceWarning extends Warning { public final static PythonLikeType RESOURCE_WARNING_TYPE = new PythonLikeType("ResourceWarning", ResourceWarning.class, List.of(WARNING_TYPE)), $TYPE = RESOURCE_WARNING_TYPE; static { RESOURCE_WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new ResourceWarning(RESOURCE_WARNING_TYPE, positionalArguments))); } public ResourceWarning() { super(RESOURCE_WARNING_TYPE); } public ResourceWarning(String message) { super(RESOURCE_WARNING_TYPE, message); } public ResourceWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public ResourceWarning(PythonLikeType type) { super(type); } public ResourceWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/RuntimeWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class RuntimeWarning extends Warning { public final static PythonLikeType RUNTIME_WARNING_TYPE = new PythonLikeType("RuntimeWarning", RuntimeWarning.class, List.of(WARNING_TYPE)), $TYPE = RUNTIME_WARNING_TYPE; static { RUNTIME_WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new RuntimeWarning(RUNTIME_WARNING_TYPE, positionalArguments))); } public RuntimeWarning() { super(RUNTIME_WARNING_TYPE); } public RuntimeWarning(String message) { super(RUNTIME_WARNING_TYPE, message); } public RuntimeWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public RuntimeWarning(PythonLikeType type) { super(type); } public RuntimeWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/SyntaxWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class SyntaxWarning extends Warning { public final static PythonLikeType SYNTAX_WARNING_TYPE = new PythonLikeType("SyntaxWarning", SyntaxWarning.class, List.of(WARNING_TYPE)), $TYPE = SYNTAX_WARNING_TYPE; static { SYNTAX_WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new SyntaxWarning(SYNTAX_WARNING_TYPE, positionalArguments))); } public SyntaxWarning() { super(SYNTAX_WARNING_TYPE); } public SyntaxWarning(String message) { super(SYNTAX_WARNING_TYPE, message); } public SyntaxWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public SyntaxWarning(PythonLikeType type) { super(type); } public SyntaxWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/UnicodeWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class UnicodeWarning extends Warning { public final static PythonLikeType UNICODE_WARNING_TYPE = new PythonLikeType("UnicodeWarning", UnicodeWarning.class, List.of(WARNING_TYPE)), $TYPE = UNICODE_WARNING_TYPE; static { UNICODE_WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new UnicodeWarning(UNICODE_WARNING_TYPE, positionalArguments))); } public UnicodeWarning() { super(UNICODE_WARNING_TYPE); } public UnicodeWarning(String message) { super(UNICODE_WARNING_TYPE, message); } public UnicodeWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public UnicodeWarning(PythonLikeType type) { super(type); } public UnicodeWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/UserWarning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class UserWarning extends Warning { public final static PythonLikeType USER_WARNING_TYPE = new PythonLikeType("UserWarning", UserWarning.class, List.of(WARNING_TYPE)), $TYPE = USER_WARNING_TYPE; static { USER_WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new UserWarning(USER_WARNING_TYPE, positionalArguments))); } public UserWarning() { super(USER_WARNING_TYPE); } public UserWarning(String message) { super(USER_WARNING_TYPE, message); } public UserWarning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public UserWarning(PythonLikeType type) { super(type); } public UserWarning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/warning/Warning.java
package ai.timefold.jpyinterpreter.types.errors.warning; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.PythonException; public class Warning extends PythonException { public final static PythonLikeType WARNING_TYPE = new PythonLikeType("Warning", Warning.class, List.of(PythonException.EXCEPTION_TYPE)), $TYPE = WARNING_TYPE; static { WARNING_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new Warning(WARNING_TYPE, positionalArguments))); } public Warning() { super(WARNING_TYPE); } public Warning(String message) { super(WARNING_TYPE, message); } public Warning(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public Warning(PythonLikeType type) { super(type); } public Warning(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/numeric/PythonBoolean.java
package ai.timefold.jpyinterpreter.types.numeric; import java.math.BigInteger; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import ai.timefold.jpyinterpreter.MethodDescriptor; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.GlobalBuiltins; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.ValueError; public class PythonBoolean extends PythonInteger { public final static PythonBoolean TRUE = new PythonBoolean(true); public final static PythonBoolean FALSE = new PythonBoolean(false); static { PythonOverloadImplementor.deferDispatchesFor(PythonBoolean::registerMethods); } public static PythonLikeType registerMethods() { try { BuiltinTypes.BOOLEAN_TYPE.addUnaryMethod(PythonUnaryOperator.AS_BOOLEAN, new PythonFunctionSignature(new MethodDescriptor( PythonBoolean.class.getMethod("asBoolean")), BuiltinTypes.BOOLEAN_TYPE)); BuiltinTypes.BOOLEAN_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, new PythonFunctionSignature(new MethodDescriptor( PythonBoolean.class.getMethod("asString")), BuiltinTypes.STRING_TYPE)); BuiltinTypes.BOOLEAN_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, new PythonFunctionSignature(new MethodDescriptor( PythonBoolean.class.getMethod("asString")), BuiltinTypes.STRING_TYPE)); BuiltinTypes.BOOLEAN_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> { if (namedArguments.size() > 1) { throw new ValueError("bool does not take named arguments"); } if (positionalArguments.isEmpty()) { return FALSE; } else if (positionalArguments.size() == 1) { return PythonBoolean.valueOf(PythonBoolean.isTruthful(positionalArguments.get(0))); } else { throw new ValueError("bool expects 0 or 1 arguments, got " + positionalArguments.size()); } })); GlobalBuiltins.addBuiltinConstant("True", TRUE); GlobalBuiltins.addBuiltinConstant("False", FALSE); return BuiltinTypes.BOOLEAN_TYPE; } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } private final boolean booleanValue; private PythonBoolean(boolean booleanValue) { super(BuiltinTypes.BOOLEAN_TYPE, booleanValue ? BigInteger.ONE : BigInteger.ZERO); this.booleanValue = booleanValue; } public boolean getBooleanValue() { return booleanValue; } public PythonBoolean not() { if (this == TRUE) { return FALSE; } else { return TRUE; } } public static boolean isTruthful(PythonLikeObject tested) { if (tested instanceof PythonBoolean) { return tested == TRUE; } else if (tested instanceof PythonInteger) { return ((PythonInteger) tested).asBoolean() == TRUE; } else if (tested instanceof PythonFloat) { return ((PythonFloat) tested).asBoolean() == TRUE; } else if (tested instanceof PythonNone) { return false; } else if (tested instanceof Collection) { return ((Collection<?>) tested).size() == 0; } else if (tested instanceof Map) { return ((Map<?, ?>) tested).size() == 0; } else { PythonLikeType testedType = tested.$getType(); PythonLikeFunction boolMethod = (PythonLikeFunction) testedType.$getAttributeOrNull("__bool__"); if (boolMethod != null) { return isTruthful(boolMethod.$call(List.of(tested), Map.of(), null)); } PythonLikeFunction lenMethod = (PythonLikeFunction) testedType.$getAttributeOrNull("__len__"); if (lenMethod != null) { return isTruthful(lenMethod.$call(List.of(tested), Map.of(), null)); } return true; } } public PythonBoolean asBoolean() { return this; } public static PythonBoolean valueOf(boolean result) { return (result) ? TRUE : FALSE; } @Override public PythonLikeType $getType() { return BuiltinTypes.BOOLEAN_TYPE; } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { if (this == TRUE) { return "True"; } else { return "False"; } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonBoolean that = (PythonBoolean) o; return booleanValue == that.booleanValue; } @Override public int hashCode() { return Objects.hash(booleanValue); } public PythonString asString() { return PythonString.valueOf(toString()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/numeric/PythonComplex.java
package ai.timefold.jpyinterpreter.types.numeric; import java.util.List; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonComplex extends AbstractPythonLikeObject implements PythonNumber, PlanningImmutable { final PythonNumber real; final PythonNumber imaginary; public final static PythonLikeType COMPLEX_TYPE = new PythonLikeType("complex", PythonComplex.class, List.of(NUMBER_TYPE)); static { PythonOverloadImplementor.deferDispatchesFor(PythonComplex::registerMethods); } public PythonComplex(PythonNumber real, PythonNumber imaginary) { super(COMPLEX_TYPE); this.real = real; this.imaginary = imaginary; } private static PythonLikeType registerMethods() throws NoSuchMethodException { // TODO return COMPLEX_TYPE; } public PythonComplex valueOf(PythonNumber real, PythonNumber imaginary) { return new PythonComplex(real, imaginary); } @Override public Number getValue() { return (real.getValue().doubleValue() * real.getValue().doubleValue()) + (imaginary.getValue().doubleValue() * imaginary.getValue().doubleValue()); } public PythonNumber getReal() { return real; } public PythonNumber getImaginary() { return imaginary; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/numeric/PythonDecimal.java
package ai.timefold.jpyinterpreter.types.numeric; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.util.function.BiPredicate; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.PythonClassTranslator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonDecimal extends AbstractPythonLikeObject implements PythonNumber, PlanningImmutable { public final BigDecimal value; private static final ThreadLocal<MathContext> threadMathContext = ThreadLocal.withInitial(() -> new MathContext(28, RoundingMode.HALF_EVEN)); static { PythonOverloadImplementor.deferDispatchesFor(PythonDecimal::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { BuiltinTypes.DECIMAL_TYPE.setConstructor((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.size() == 0) { return new PythonDecimal(BigDecimal.ZERO); } else if (positionalArguments.size() == 1) { return PythonDecimal.from(positionalArguments.get(0)); } else if (positionalArguments.size() == 2) { // TODO: Support context throw new ValueError("context constructor not supported"); } else { throw new TypeError("function takes at most 2 arguments, got " + positionalArguments.size()); } }); for (var method : PythonDecimal.class.getDeclaredMethods()) { if (method.getName().startsWith(PythonClassTranslator.JAVA_METHOD_PREFIX)) { BuiltinTypes.DECIMAL_TYPE.addMethod( method.getName().substring(PythonClassTranslator.JAVA_METHOD_PREFIX.length()), method); } } return BuiltinTypes.DECIMAL_TYPE; } // *************************** // Constructors // *************************** public PythonDecimal(BigDecimal value) { super(BuiltinTypes.DECIMAL_TYPE); this.value = value; } public static PythonDecimal from(PythonLikeObject value) { if (value instanceof PythonInteger integer) { return PythonDecimal.valueOf(integer); } else if (value instanceof PythonFloat pythonFloat) { return PythonDecimal.valueOf(pythonFloat); } else if (value instanceof PythonString str) { return PythonDecimal.valueOf(str); } else { throw new TypeError( "conversion from %s to Decimal is not supported".formatted(value.$getType().getTypeName())); } } public static PythonDecimal $method$from_float(PythonFloat value) { return new PythonDecimal(new BigDecimal(value.value, threadMathContext.get())); } public static PythonDecimal valueOf(PythonInteger value) { return new PythonDecimal(new BigDecimal(value.value, threadMathContext.get())); } public static PythonDecimal valueOf(PythonFloat value) { return new PythonDecimal(new BigDecimal(value.value, threadMathContext.get())); } public static PythonDecimal valueOf(PythonString value) { return valueOf(value.value); } public static PythonDecimal valueOf(String value) { return new PythonDecimal(new BigDecimal(value, threadMathContext.get())); } // *************************** // Interface methods // *************************** @Override public Number getValue() { return value; } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public PythonString $method$__repr__() { return PythonString.valueOf("Decimal('%s')".formatted(value.toPlainString())); } @Override public String toString() { return value.toPlainString(); } // Required since to_python_score expects a BigDecimal instance // (which comes from the Java *BigDecimalScore) // but the translator will automatically convert all BigDecimals // into PythonDecimal instances. // In particular, it expects a toPlainString method so it can // create a Python decimal from a BigDecimal. // The function can be called either untranslated (normally) // or translated (when used in a justification function), // hence why we define this method. public PythonString $method$toPlainString() { return PythonString.valueOf(value.toPlainString()); } public boolean equals(Object o) { if (o instanceof PythonNumber number) { return compareTo(number) == 0; } else { return false; } } @Override public int hashCode() { return $method$__hash__().value.intValue(); } @Override public PythonInteger $method$__hash__() { var scale = value.scale(); if (scale <= 0) { return PythonNumber.computeHash(new PythonInteger(value.toBigInteger()), PythonInteger.ONE); } var scaledValue = value.movePointRight(scale); return PythonNumber.computeHash(new PythonInteger(scaledValue.toBigInteger()), new PythonInteger(BigInteger.TEN.pow(scale))); } // *************************** // Unary operations // *************************** public PythonBoolean $method$__bool__() { return PythonBoolean.valueOf(value.compareTo(BigDecimal.ZERO) != 0); } public PythonInteger $method$__int__() { return PythonInteger.valueOf(value.toBigInteger()); } public PythonFloat $method$__float__() { return PythonFloat.valueOf(value.doubleValue()); } public PythonDecimal $method$__pos__() { return this; } public PythonDecimal $method$__neg__() { return new PythonDecimal(value.negate()); } public PythonDecimal $method$__abs__() { return new PythonDecimal(value.abs()); } // *************************** // Binary operations // *************************** public PythonBoolean $method$__lt__(PythonDecimal other) { return PythonBoolean.valueOf(value.compareTo(other.value) < 0); } public PythonBoolean $method$__lt__(PythonInteger other) { return $method$__lt__(PythonDecimal.valueOf(other)); } public PythonBoolean $method$__lt__(PythonFloat other) { return $method$__lt__(PythonDecimal.valueOf(other)); } public PythonBoolean $method$__le__(PythonDecimal other) { return PythonBoolean.valueOf(value.compareTo(other.value) <= 0); } public PythonBoolean $method$__le__(PythonInteger other) { return $method$__le__(PythonDecimal.valueOf(other)); } public PythonBoolean $method$__le__(PythonFloat other) { return $method$__le__(PythonDecimal.valueOf(other)); } public PythonBoolean $method$__gt__(PythonDecimal other) { return PythonBoolean.valueOf(value.compareTo(other.value) > 0); } public PythonBoolean $method$__gt__(PythonInteger other) { return $method$__gt__(PythonDecimal.valueOf(other)); } public PythonBoolean $method$__gt__(PythonFloat other) { return $method$__gt__(PythonDecimal.valueOf(other)); } public PythonBoolean $method$__ge__(PythonDecimal other) { return PythonBoolean.valueOf(value.compareTo(other.value) >= 0); } public PythonBoolean $method$__ge__(PythonInteger other) { return $method$__ge__(PythonDecimal.valueOf(other)); } public PythonBoolean $method$__ge__(PythonFloat other) { return $method$__ge__(PythonDecimal.valueOf(other)); } public PythonBoolean $method$__eq__(PythonDecimal other) { return PythonBoolean.valueOf(value.compareTo(other.value) == 0); } public PythonBoolean $method$__eq__(PythonInteger other) { return PythonBoolean.valueOf(value.compareTo(new BigDecimal(other.value)) == 0); } public PythonBoolean $method$__eq__(PythonFloat other) { return PythonBoolean.valueOf(value.compareTo(new BigDecimal(other.value)) == 0); } public PythonBoolean $method$__neq__(PythonDecimal other) { return $method$__eq__(other).not(); } public PythonBoolean $method$__neq__(PythonInteger other) { return $method$__eq__(other).not(); } public PythonBoolean $method$__neq__(PythonFloat other) { return $method$__eq__(other).not(); } public PythonDecimal $method$__add__(PythonDecimal other) { return new PythonDecimal(value.add(other.value, threadMathContext.get())); } public PythonDecimal $method$__add__(PythonInteger other) { return $method$__add__(PythonDecimal.valueOf(other)); } public PythonDecimal $method$__radd__(PythonInteger other) { return PythonDecimal.valueOf(other).$method$__add__(this); } public PythonDecimal $method$__sub__(PythonDecimal other) { return new PythonDecimal(value.subtract(other.value, threadMathContext.get())); } public PythonDecimal $method$__sub__(PythonInteger other) { return $method$__sub__(PythonDecimal.valueOf(other)); } public PythonDecimal $method$__rsub__(PythonInteger other) { return PythonDecimal.valueOf(other).$method$__sub__(this); } public PythonDecimal $method$__mul__(PythonDecimal other) { return new PythonDecimal(value.multiply(other.value, threadMathContext.get())); } public PythonDecimal $method$__mul__(PythonInteger other) { return $method$__mul__(PythonDecimal.valueOf(other)); } public PythonDecimal $method$__rmul__(PythonInteger other) { return PythonDecimal.valueOf(other).$method$__mul__(this); } public PythonDecimal $method$__truediv__(PythonDecimal other) { return new PythonDecimal(value.divide(other.value, threadMathContext.get())); } public PythonDecimal $method$__truediv__(PythonInteger other) { return $method$__truediv__(PythonDecimal.valueOf(other)); } public PythonDecimal $method$__rtruediv__(PythonInteger other) { return PythonDecimal.valueOf(other).$method$__truediv__(this); } public PythonDecimal $method$__floordiv__(PythonDecimal other) { var newSignNum = switch (value.signum() * other.value.signum()) { case -1 -> BigDecimal.ONE.negate(); case 0 -> BigDecimal.ZERO; case 1 -> BigDecimal.ONE; default -> throw new IllegalStateException("Unexpected signum (%d)." .formatted(value.signum() * other.value.signum())); }; // Need to round toward 0, but Java floors the result, so take the absolute and // multiply by the sign-num return new PythonDecimal(value.abs().divideToIntegralValue(other.value.abs()) .multiply(newSignNum, threadMathContext.get())); } public PythonDecimal $method$__floordiv__(PythonInteger other) { return $method$__floordiv__(PythonDecimal.valueOf(other)); } public PythonDecimal $method$__rfloordiv__(PythonInteger other) { return PythonDecimal.valueOf(other).$method$__floordiv__(this); } public PythonDecimal $method$__mod__(PythonDecimal other) { return new PythonDecimal( value.subtract($method$__floordiv__(other).value.multiply(other.value, threadMathContext.get()))); } public PythonDecimal $method$__mod__(PythonInteger other) { return $method$__mod__(PythonDecimal.valueOf(other)); } public PythonDecimal $method$__rmod__(PythonInteger other) { return PythonDecimal.valueOf(other).$method$__mod__(this); } public PythonDecimal $method$__pow__(PythonDecimal other) { if (other.value.stripTrailingZeros().scale() <= 0) { // other is an int return new PythonDecimal(value.pow(other.value.intValue(), threadMathContext.get())); } return new PythonDecimal(new BigDecimal(Math.pow(value.doubleValue(), other.value.doubleValue()), threadMathContext.get())); } public PythonDecimal $method$__pow__(PythonInteger other) { return $method$__pow__(PythonDecimal.valueOf(other)); } public PythonDecimal $method$__rpow__(PythonInteger other) { return PythonDecimal.valueOf(other).$method$__mod__(this); } // *************************** // Other methods // *************************** public PythonInteger $method$adjusted() { // scale is the negative exponent that the big int is multiplied by // len(unscaled) - 1 = floor(log_10(unscaled)) // floor(log_10(unscaled)) - scale = exponent in engineering notation return PythonInteger.valueOf(value.unscaledValue().toString().length() - 1 - value.scale()); } public PythonLikeTuple<PythonInteger> $method$as_integer_ratio() { var parts = value.divideAndRemainder(BigDecimal.ONE); var integralPart = parts[0]; var fractionPart = parts[1]; if (fractionPart.compareTo(BigDecimal.ZERO) == 0) { // No decimal part, as integer ratio = (self, 1) return PythonLikeTuple.fromItems(PythonInteger.valueOf(integralPart.toBigInteger()), PythonInteger.ONE); } var scale = fractionPart.scale(); var scaledDenominator = BigDecimal.ONE.movePointRight(scale).toBigInteger(); var scaledIntegralPart = integralPart.movePointRight(scale).toBigInteger(); var scaledFractionPart = fractionPart.movePointRight(scale).toBigInteger(); var scaledNumerator = scaledIntegralPart.add(scaledFractionPart); var commonFactors = scaledNumerator.gcd(scaledDenominator); var reducedNumerator = scaledNumerator.divide(commonFactors); var reducedDenominator = scaledDenominator.divide(commonFactors); return PythonLikeTuple.fromItems(PythonInteger.valueOf(reducedNumerator), PythonInteger.valueOf(reducedDenominator)); } public PythonLikeTuple<PythonLikeObject> $method$as_tuple() { // TODO: Use named tuple return PythonLikeTuple.fromItems(PythonInteger.valueOf(value.signum() >= 0 ? 0 : 1), value.unscaledValue().abs().toString() .chars() .mapToObj(digit -> PythonInteger.valueOf(digit - '0')) .collect(Collectors.toCollection(PythonLikeTuple::new)), PythonInteger.valueOf(-value.scale())); } public PythonDecimal $method$canonical() { return this; } public PythonDecimal $method$compare(PythonDecimal other) { return new PythonDecimal(BigDecimal.valueOf(value.compareTo(other.value))); } public PythonDecimal $method$compare_signal(PythonDecimal other) { return $method$compare(other); } // See https://speleotrove.com/decimal/damisc.html#refcotot public PythonDecimal $method$compare_total(PythonDecimal other) { var result = $method$compare(other); if (result.value.compareTo(BigDecimal.ZERO) != 0) { return result; } var sigNum = value.scale() - other.value.scale(); if (sigNum < 0) { return new PythonDecimal(BigDecimal.ONE); } if (sigNum > 0) { return new PythonDecimal(BigDecimal.valueOf(-1L)); } return result; // Can only reach here if result == BigDecimal.ZERO } public PythonDecimal $method$compare_total_mag(PythonDecimal other) { return new PythonDecimal(value.abs()).$method$compare_total(new PythonDecimal(other.value.abs())); } public PythonDecimal $method$conjugate() { return this; } public PythonDecimal $method$copy_abs() { return new PythonDecimal(value.abs()); } public PythonDecimal $method$copy_negate() { return new PythonDecimal(value.negate()); } public PythonDecimal $method$copy_sign(PythonDecimal other) { var signChange = value.signum() * other.value.signum(); var multiplier = switch (signChange) { case -1 -> BigDecimal.valueOf(-1); case 0, 1 -> BigDecimal.ONE; // Note: there also a -0 BigDecimal in Python. default -> throw new IllegalStateException("Unexpected signum (%d).".formatted(signChange)); }; return new PythonDecimal(value.multiply(multiplier)); } private static BigDecimal getEToPrecision(int precision) { return getESubPowerToPrecision(BigDecimal.ONE, precision); } private static BigDecimal getESubPowerToPrecision(BigDecimal value, int precision) { // Uses taylor series e^x = sum(x^n/n! for n in 0...infinity) var numerator = BigDecimal.ONE; var denominator = BigDecimal.ONE; var total = BigDecimal.ZERO; var extendedContext = new MathContext(precision + 8, RoundingMode.HALF_EVEN); for (var index = 1; index < 100; index++) { total = total.add(numerator.divide(denominator, extendedContext), extendedContext); numerator = numerator.multiply(value); denominator = denominator.multiply(BigDecimal.valueOf(index)); } return total; } private static BigDecimal getEPower(BigDecimal value, int precision) { var extendedPrecision = precision + 8; // Do e^x = e^(int(x))*e^(frac(x)) var e = getEToPrecision(extendedPrecision); var integralPart = value.toBigInteger().intValue(); var fractionPart = value.remainder(BigDecimal.ONE); return e.pow(integralPart).multiply(getESubPowerToPrecision(fractionPart, extendedPrecision), threadMathContext.get()); } public PythonDecimal $method$exp() { var precision = threadMathContext.get().getPrecision(); return new PythonDecimal(getEPower(value, precision)); } public PythonDecimal $method$fma(PythonDecimal multiplier, PythonDecimal summand) { return new PythonDecimal(this.value.multiply(multiplier.value).add(summand.value, threadMathContext.get())); } public PythonDecimal $method$fma(PythonInteger multiplier, PythonDecimal summand) { return $method$fma(PythonDecimal.valueOf(multiplier), summand); } public PythonDecimal $method$fma(PythonDecimal multiplier, PythonInteger summand) { return $method$fma(multiplier, PythonDecimal.valueOf(summand)); } public PythonDecimal $method$fma(PythonInteger multiplier, PythonInteger summand) { return $method$fma(PythonDecimal.valueOf(multiplier), PythonDecimal.valueOf(summand)); } public PythonBoolean $method$is_canonical() { return PythonBoolean.TRUE; } public PythonBoolean $method$is_finite() { // We don't support infinite or NaN Decimals return PythonBoolean.TRUE; } public PythonBoolean $method$is_infinite() { // We don't support infinite or NaN Decimals return PythonBoolean.FALSE; } public PythonBoolean $method$is_nan() { // We don't support infinite or NaN Decimals return PythonBoolean.FALSE; } public PythonBoolean $method$is_normal() { // We don't support subnormal Decimals return PythonBoolean.TRUE; } public PythonBoolean $method$is_qnan() { // We don't support infinite or NaN Decimals return PythonBoolean.FALSE; } public PythonBoolean $method$is_signed() { // Same as `isNegative()` return value.compareTo(BigDecimal.ZERO) < 0 ? PythonBoolean.TRUE : PythonBoolean.FALSE; } public PythonBoolean $method$is_snan() { // We don't support infinite or NaN Decimals return PythonBoolean.FALSE; } public PythonBoolean $method$is_subnormal() { // We don't support subnormal Decimals return PythonBoolean.FALSE; } public PythonBoolean $method$is_zero() { return value.compareTo(BigDecimal.ZERO) == 0 ? PythonBoolean.TRUE : PythonBoolean.FALSE; } public PythonDecimal $method$ln() { return new PythonDecimal(new BigDecimal( Math.log(value.doubleValue()), threadMathContext.get())); } public PythonDecimal $method$log10() { return new PythonDecimal(new BigDecimal( Math.log10(value.doubleValue()), threadMathContext.get())); } public PythonDecimal $method$logb() { // Finds the exponent b in a * 10^b, where a in [1, 10) return new PythonDecimal(BigDecimal.valueOf(value.precision() - value.scale() - 1)); } private static PythonDecimal logicalOp(BiPredicate<Boolean, Boolean> op, BigDecimal a, BigDecimal b) { if (a.scale() < 0 || b.scale() < 0) { throw new ValueError("Invalid Operation: both operands must be positive integers consisting of 1's and 0's"); } var aText = a.toPlainString(); var bText = b.toPlainString(); if (aText.length() > bText.length()) { bText = "0".repeat(aText.length() - bText.length()) + bText; } else if (aText.length() < bText.length()) { aText = "0".repeat(bText.length() - aText.length()) + aText; } var digitCount = aText.length(); var result = new StringBuilder(); for (int i = 0; i < digitCount; i++) { var aBit = switch (aText.charAt(i)) { case '0' -> false; case '1' -> true; default -> throw new ValueError(("Invalid Operation: first operand (%s) is not a positive integer " + "consisting of 1's and 0's").formatted(a)); }; var bBit = switch (bText.charAt(i)) { case '0' -> false; case '1' -> true; default -> throw new ValueError(("Invalid Operation: second operand (%s) is not a positive integer " + "consisting of 1's and 0's").formatted(b)); }; result.append(op.test(aBit, bBit) ? '1' : '0'); } return new PythonDecimal(new BigDecimal(result.toString())); } public PythonDecimal $method$logical_and(PythonDecimal other) { return logicalOp(Boolean::logicalAnd, this.value, other.value); } public PythonDecimal $method$logical_or(PythonDecimal other) { return logicalOp(Boolean::logicalOr, this.value, other.value); } public PythonDecimal $method$logical_xor(PythonDecimal other) { return logicalOp(Boolean::logicalXor, this.value, other.value); } public PythonDecimal $method$logical_invert() { return logicalOp(Boolean::logicalXor, this.value, new BigDecimal("1".repeat(threadMathContext.get().getPrecision()))); } public PythonDecimal $method$max(PythonDecimal other) { return new PythonDecimal(value.max(other.value)); } public PythonDecimal $method$max_mag(PythonDecimal other) { var result = $method$compare_total_mag(other).value.intValue(); if (result >= 0) { return this; } else { return other; } } public PythonDecimal $method$min(PythonDecimal other) { return new PythonDecimal(value.min(other.value)); } public PythonDecimal $method$min_mag(PythonDecimal other) { var result = $method$compare_total_mag(other).value.intValue(); if (result <= 0) { return this; } else { return other; } } private BigDecimal getLastPlaceUnit(MathContext mathContext) { int remainingPrecision = mathContext.getPrecision() - value.stripTrailingZeros().precision(); return BigDecimal.ONE.movePointLeft(value.scale() + remainingPrecision + 1); } public PythonDecimal $method$next_minus() { var context = new MathContext(threadMathContext.get().getPrecision(), RoundingMode.FLOOR); var lastPlaceUnit = getLastPlaceUnit(context); return new PythonDecimal(value.subtract(lastPlaceUnit, context)); } public PythonDecimal $method$next_plus() { var context = new MathContext(threadMathContext.get().getPrecision(), RoundingMode.CEILING); var lastPlaceUnit = getLastPlaceUnit(context); return new PythonDecimal(value.add(lastPlaceUnit, context)); } public PythonDecimal $method$next_toward(PythonDecimal other) { var result = $method$compare(other).value.intValue(); switch (result) { case -1 -> { return $method$next_plus(); } case 1 -> { return $method$next_minus(); } case 0 -> { return this; } default -> throw new IllegalStateException(); } } public PythonDecimal $method$normalize() { return new PythonDecimal(value.stripTrailingZeros()); } public PythonString $method$number_class() { var result = value.compareTo(BigDecimal.ZERO); if (result < 0) { return PythonString.valueOf("-Normal"); } else if (result > 0) { return PythonString.valueOf("+Normal"); } else { return PythonString.valueOf("+Zero"); } } public PythonDecimal $method$quantize(PythonDecimal other) { return new PythonDecimal(value.setScale(other.value.scale(), threadMathContext.get().getRoundingMode())); } public PythonDecimal $method$radix() { return new PythonDecimal(BigDecimal.TEN); } public PythonDecimal $method$remainder_near(PythonDecimal other) { var floorQuotient = $method$__floordiv__(other).value; var firstRemainder = new PythonDecimal(value.subtract(floorQuotient.multiply(other.value, threadMathContext.get()))); var secondRemainder = other.$method$__sub__(firstRemainder).$method$__neg__(); var comparison = firstRemainder.$method$compare_total_mag(secondRemainder).value.intValue(); return switch (comparison) { case -1 -> firstRemainder; case 1 -> secondRemainder; case 0 -> { if (floorQuotient.longValue() % 2 == 0) { yield firstRemainder; } else { yield secondRemainder; } } default -> throw new IllegalStateException(); }; } public PythonDecimal $method$rotate(PythonInteger other) { var amount = -other.value.intValue(); if (amount == 0) { return this; } var precision = threadMathContext.get().getPrecision(); if (Math.abs(amount) > precision) { throw new ValueError("other must be between -%d and %d".formatted(amount, amount)); } var digitString = value.unscaledValue().toString(); digitString = "0".repeat(precision - digitString.length()) + digitString; if (amount < 0) { // Turn a rotate right to a rotate left amount = precision + amount; } var rotatedResult = digitString.substring(precision - amount, precision) + digitString.substring(0, precision - amount); var unscaledResult = new BigInteger(rotatedResult); return new PythonDecimal(new BigDecimal(unscaledResult, value.scale())); } public PythonBoolean $method$same_quantum(PythonDecimal other) { return PythonBoolean.valueOf( value.ulp().compareTo(other.value.ulp()) == 0); } public PythonDecimal $method$scaleb(PythonInteger other) { return new PythonDecimal(value.movePointRight(other.value.intValue())); } public PythonDecimal $method$shift(PythonInteger other) { var amount = other.value.intValue(); if (amount == 0) { return this; } var precision = threadMathContext.get().getPrecision(); if (Math.abs(amount) > precision) { throw new ValueError("other must be between -%d and %d".formatted(amount, amount)); } return new PythonDecimal(value.movePointLeft(amount)); } public PythonDecimal $method$sqrt() { return new PythonDecimal(value.sqrt(threadMathContext.get())); } public PythonString $method$to_eng_string() { return new PythonString(value.toEngineeringString()); } public PythonInteger $method$to_integral() { return $method$to_integral_value(); } public PythonInteger $method$to_integral_exact() { // TODO: set signals in the context object return $method$to_integral_value(); } public PythonInteger $method$to_integral_value() { return new PythonInteger(value.divideToIntegralValue(BigDecimal.ONE, threadMathContext.get()).toBigInteger()); } public PythonInteger $method$__round__() { // Round without an argument ignores thread math context var first = value.toBigInteger(); var second = first.add(BigInteger.ONE); var firstDiff = value.subtract(new BigDecimal(first)); var secondDiff = new BigDecimal(second).subtract(value); var comparison = firstDiff.compareTo(secondDiff); return switch (comparison) { case -1 -> new PythonInteger(first); case 1 -> new PythonInteger(second); case 0 -> { if (first.intValue() % 2 == 0) { yield new PythonInteger(first); } else { yield new PythonInteger(second); } } default -> throw new IllegalStateException(); }; } public PythonLikeObject $method$__round__(PythonLikeObject maybePrecision) { if (maybePrecision instanceof PythonNone) { return $method$__round__(); } if (!(maybePrecision instanceof PythonInteger precision)) { throw new ValueError("ndigits must be an integer"); } // Round with an argument uses thread math context var integralPart = value.toBigInteger(); return new PythonDecimal(value.round(new MathContext( integralPart.toString().length() + precision.value.intValue(), threadMathContext.get().getRoundingMode()))); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/numeric/PythonFloat.java
package ai.timefold.jpyinterpreter.types.numeric; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.Coercible; import ai.timefold.jpyinterpreter.types.NotImplemented; import ai.timefold.jpyinterpreter.types.PythonLikeComparable; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.arithmetic.ZeroDivisionError; import ai.timefold.jpyinterpreter.util.DefaultFormatSpec; import ai.timefold.jpyinterpreter.util.StringFormatter; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonFloat extends AbstractPythonLikeObject implements PythonNumber, PlanningImmutable, Coercible { public final double value; static { PythonOverloadImplementor.deferDispatchesFor(PythonFloat::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { PythonLikeComparable.setup(BuiltinTypes.FLOAT_TYPE); // Constructor BuiltinTypes.FLOAT_TYPE.setConstructor((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.isEmpty()) { return new PythonFloat(0.0); } else if (positionalArguments.size() == 1) { return PythonFloat.from(positionalArguments.get(0)); } else { throw new ValueError("float takes 0 or 1 arguments, got " + positionalArguments.size()); } }); // Unary BuiltinTypes.FLOAT_TYPE.addUnaryMethod(PythonUnaryOperator.AS_BOOLEAN, PythonFloat.class.getMethod("asBoolean")); BuiltinTypes.FLOAT_TYPE.addUnaryMethod(PythonUnaryOperator.AS_INT, PythonFloat.class.getMethod("asInteger")); BuiltinTypes.FLOAT_TYPE.addUnaryMethod(PythonUnaryOperator.POSITIVE, PythonFloat.class.getMethod("asFloat")); BuiltinTypes.FLOAT_TYPE.addUnaryMethod(PythonUnaryOperator.NEGATIVE, PythonFloat.class.getMethod("negative")); BuiltinTypes.FLOAT_TYPE.addUnaryMethod(PythonUnaryOperator.ABS, PythonFloat.class.getMethod("abs")); BuiltinTypes.FLOAT_TYPE.addUnaryMethod(PythonUnaryOperator.HASH, PythonFloat.class.getMethod("$method$__hash__")); // Binary BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.ADD, PythonFloat.class.getMethod("add", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.ADD, PythonFloat.class.getMethod("add", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.ADD, PythonFloat.class.getMethod("add", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonFloat.class.getMethod("subtract", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonFloat.class.getMethod("subtract", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonFloat.class.getMethod("subtract", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonFloat.class.getMethod("multiply", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonFloat.class.getMethod("multiply", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonFloat.class.getMethod("multiply", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.TRUE_DIVIDE, PythonFloat.class.getMethod("trueDivide", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.TRUE_DIVIDE, PythonFloat.class.getMethod("trueDivide", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.TRUE_DIVIDE, PythonFloat.class.getMethod("trueDivide", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.FLOOR_DIVIDE, PythonFloat.class.getMethod("floorDivide", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.FLOOR_DIVIDE, PythonFloat.class.getMethod("floorDivide", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.FLOOR_DIVIDE, PythonFloat.class.getMethod("floorDivide", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.DIVMOD, PythonFloat.class.getMethod("divmod", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.DIVMOD, PythonFloat.class.getMethod("divmod", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.DIVMOD, PythonFloat.class.getMethod("divmod", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MODULO, PythonFloat.class.getMethod("modulo", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MODULO, PythonFloat.class.getMethod("modulo", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MODULO, PythonFloat.class.getMethod("modulo", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.POWER, PythonFloat.class.getMethod("power", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.POWER, PythonFloat.class.getMethod("power", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.POWER, PythonFloat.class.getMethod("power", PythonFloat.class)); // Comparisons BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.EQUAL, PythonFloat.class.getMethod("pythonEquals", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.EQUAL, PythonFloat.class.getMethod("pythonEquals", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.EQUAL, PythonFloat.class.getMethod("pythonEquals", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.NOT_EQUAL, PythonFloat.class.getMethod("notEqual", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.NOT_EQUAL, PythonFloat.class.getMethod("notEqual", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.NOT_EQUAL, PythonFloat.class.getMethod("notEqual", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonFloat.class.getMethod("lessThan", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonFloat.class.getMethod("lessThan", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonFloat.class.getMethod("lessThan", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonFloat.class.getMethod("lessThanOrEqual", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonFloat.class.getMethod("lessThanOrEqual", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonFloat.class.getMethod("lessThanOrEqual", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonFloat.class.getMethod("greaterThan", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonFloat.class.getMethod("greaterThan", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonFloat.class.getMethod("greaterThan", PythonFloat.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonFloat.class.getMethod("greaterThanOrEqual", PythonLikeObject.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonFloat.class.getMethod("greaterThanOrEqual", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonFloat.class.getMethod("greaterThanOrEqual", PythonFloat.class)); // Other BuiltinTypes.FLOAT_TYPE.addMethod("__round__", PythonFloat.class.getMethod("round")); BuiltinTypes.FLOAT_TYPE.addMethod("__round__", PythonFloat.class.getMethod("round", PythonInteger.class)); BuiltinTypes.FLOAT_TYPE.addBinaryMethod(PythonBinaryOperator.FORMAT, PythonFloat.class.getMethod("$method$__format__")); BuiltinTypes.FLOAT_TYPE.addBinaryMethod(PythonBinaryOperator.FORMAT, PythonFloat.class.getMethod("$method$__format__", PythonLikeObject.class)); return BuiltinTypes.FLOAT_TYPE; } public PythonFloat(double value) { super(BuiltinTypes.FLOAT_TYPE); this.value = value; } public static PythonFloat from(PythonLikeObject value) { if (value instanceof PythonInteger integer) { return integer.asFloat(); } else if (value instanceof PythonFloat) { return (PythonFloat) value; } else if (value instanceof PythonString str) { try { var literal = switch (str.value.toLowerCase()) { case "nan", "+nan" -> "+NaN"; case "-nan" -> "-NaN"; case "inf", "+inf", "infinity" -> "+Infinity"; case "-inf", "-infinity" -> "-Infinity"; default -> str.value; }; return new PythonFloat(Double.parseDouble(literal)); } catch (NumberFormatException e) { throw new ValueError("invalid literal for float(): %s".formatted(value)); } } else { PythonLikeType valueType = value.$getType(); PythonLikeFunction asFloatFunction = (PythonLikeFunction) (valueType.$getAttributeOrError("__float__")); return (PythonFloat) asFloatFunction.$call(List.of(value), Map.of(), null); } } @Override public Number getValue() { return value; } public PythonLikeTuple asFraction() { final BigInteger FIVE = BigInteger.valueOf(5L); BigDecimal bigDecimal = new BigDecimal(value); BigInteger numerator = bigDecimal.movePointRight(bigDecimal.scale()).toBigIntegerExact(); BigInteger denominator; if (bigDecimal.scale() < 0) { denominator = BigInteger.ONE; numerator = numerator.multiply(BigInteger.TEN.pow(-bigDecimal.scale())); } else { denominator = BigInteger.TEN.pow(bigDecimal.scale()); } // denominator is a multiple of 10, thus only have 5 and 2 as prime factors while (denominator.remainder(BigInteger.TWO).equals(BigInteger.ZERO) && numerator.remainder(BigInteger.TWO).equals(BigInteger.ZERO)) { denominator = denominator.shiftRight(1); numerator = numerator.shiftRight(1); } while (denominator.remainder(FIVE).equals(BigInteger.ZERO) && numerator.remainder(FIVE).equals(BigInteger.ZERO)) { denominator = denominator.divide(FIVE); numerator = numerator.divide(FIVE); } return PythonLikeTuple.fromItems(PythonInteger.valueOf(numerator), PythonInteger.valueOf(denominator)); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { return Double.toString(value); } @Override public boolean equals(Object o) { if (o instanceof Number number) { return number.doubleValue() == value; } else if (o instanceof PythonNumber number) { return compareTo(number) == 0; } else { return false; } } @Override public int hashCode() { return $method$__hash__().value.intValue(); } @Override public PythonInteger $method$__hash__() { if (Double.isNaN(value)) { return PythonInteger.valueOf(hashCode()); } else if (Double.isInfinite(value)) { if (value > 0) { return INFINITY_HASH_VALUE; } else { return INFINITY_HASH_VALUE.negative(); } } PythonLikeTuple fractionTuple = asFraction(); return PythonNumber.computeHash((PythonInteger) fractionTuple.get(0), (PythonInteger) fractionTuple.get(1)); } public static PythonFloat valueOf(float value) { return new PythonFloat(value); } public static PythonFloat valueOf(double value) { return new PythonFloat(value); } public PythonBoolean asBoolean() { return value == 0.0 ? PythonBoolean.FALSE : PythonBoolean.TRUE; } public PythonInteger asInteger() { return new PythonInteger((long) Math.floor(value)); } public PythonFloat asFloat() { return this; } public PythonFloat negative() { return new PythonFloat(-value); } public PythonFloat abs() { return new PythonFloat(Math.abs(value)); } public PythonLikeObject add(PythonLikeObject other) { if (other instanceof PythonInteger) { return add((PythonInteger) other); } else if (other instanceof PythonFloat) { return add((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonFloat add(PythonInteger other) { return new PythonFloat(value + other.value.doubleValue()); } public PythonFloat add(PythonFloat other) { return new PythonFloat(value + other.value); } public PythonLikeObject subtract(PythonLikeObject other) { if (other instanceof PythonInteger) { return subtract((PythonInteger) other); } else if (other instanceof PythonFloat) { return subtract((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonFloat subtract(PythonInteger other) { return new PythonFloat(value - other.value.doubleValue()); } public PythonFloat subtract(PythonFloat other) { return new PythonFloat(value - other.value); } public PythonLikeObject multiply(PythonLikeObject other) { if (other instanceof PythonInteger) { return multiply((PythonInteger) other); } else if (other instanceof PythonFloat) { return multiply((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonFloat multiply(PythonInteger other) { return new PythonFloat(value * other.value.doubleValue()); } public PythonFloat multiply(PythonFloat other) { return new PythonFloat(value * other.value); } public PythonLikeObject trueDivide(PythonLikeObject other) { if (other instanceof PythonInteger) { return trueDivide((PythonInteger) other); } else if (other instanceof PythonFloat) { return trueDivide((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonFloat trueDivide(PythonInteger other) { if (other.value.equals(BigInteger.ZERO)) { throw new ZeroDivisionError("float division"); } return new PythonFloat(value / other.value.doubleValue()); } public PythonFloat trueDivide(PythonFloat other) { if (other.value == 0) { throw new ZeroDivisionError("float division"); } return new PythonFloat(value / other.value); } public PythonLikeObject floorDivide(PythonLikeObject other) { if (other instanceof PythonInteger) { return floorDivide((PythonInteger) other); } else if (other instanceof PythonFloat) { return floorDivide((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonFloat floorDivide(PythonInteger other) { if (other.value.equals(BigInteger.ZERO)) { throw new ZeroDivisionError("float division"); } return new PythonFloat(new BigDecimal(value) .divideToIntegralValue(new BigDecimal(other.value)) .doubleValue()); } public PythonFloat floorDivide(PythonFloat other) { if (other.value == 0) { throw new ZeroDivisionError("float division"); } return PythonFloat.valueOf(Math.floor(value / other.value)); } public PythonFloat ceilDivide(PythonInteger other) { if (other.value.equals(BigInteger.ZERO)) { throw new ZeroDivisionError("float division"); } return new PythonFloat(new BigDecimal(value) .divide(new BigDecimal(other.value), RoundingMode.CEILING) .doubleValue()); } public PythonFloat ceilDivide(PythonFloat other) { if (other.value == 0) { throw new ZeroDivisionError("float division"); } return PythonFloat.valueOf(Math.ceil(value / other.value)); } public PythonLikeObject modulo(PythonLikeObject other) { if (other instanceof PythonInteger) { return modulo((PythonInteger) other); } else if (other instanceof PythonFloat) { return modulo((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonFloat modulo(PythonInteger other) { int remainderSign = other.compareTo(PythonInteger.ZERO); if (remainderSign == 0) { throw new ZeroDivisionError("float modulo"); } else if (remainderSign > 0) { double remainder = value % other.value.doubleValue(); if (remainder < 0) { remainder = remainder + other.value.doubleValue(); } return new PythonFloat(remainder); } else { double remainder = value % other.value.doubleValue(); if (remainder > 0) { remainder = remainder + other.value.doubleValue(); } return new PythonFloat(remainder); } } public PythonFloat modulo(PythonFloat other) { if (other.value == 0) { throw new ZeroDivisionError("float modulo"); } else if (other.value > 0) { double remainder = value % other.value; if (remainder < 0) { remainder = remainder + other.value; } return new PythonFloat(remainder); } else { double remainder = value % other.value; if (remainder > 0) { remainder = remainder + other.value; } return new PythonFloat(remainder); } } public PythonLikeObject divmod(PythonLikeObject other) { if (other instanceof PythonInteger) { return divmod((PythonInteger) other); } else if (other instanceof PythonFloat) { return divmod((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeTuple divmod(PythonInteger other) { PythonFloat quotient; if (value < 0 == other.value.compareTo(BigInteger.ZERO) < 0) { // Same sign, use floor division quotient = floorDivide(other); } else { // Different sign, use ceil division quotient = ceilDivide(other); } PythonInteger.valueOf(Math.round(value / other.value.doubleValue())); double remainder = value % other.value.doubleValue(); // Python remainder has sign of divisor if (other.value.compareTo(BigInteger.ZERO) < 0) { if (remainder > 0) { quotient = quotient.subtract(PythonInteger.ONE); remainder = remainder + other.value.doubleValue(); } } else { if (remainder < 0) { quotient = quotient.subtract(PythonInteger.ONE); remainder = remainder + other.value.doubleValue(); } } return PythonLikeTuple.fromItems(quotient, new PythonFloat(remainder)); } public PythonLikeTuple divmod(PythonFloat other) { PythonFloat quotient; if (value < 0 == other.value < 0) { // Same sign, use floor division quotient = floorDivide(other); } else { // Different sign, use ceil division quotient = ceilDivide(other); } double remainder = value % other.value; // Python remainder has sign of divisor if (other.value < 0) { if (remainder > 0) { quotient = quotient.subtract(PythonInteger.ONE); remainder = remainder + other.value; } } else { if (remainder < 0) { quotient = quotient.subtract(PythonInteger.ONE); remainder = remainder + other.value; } } return PythonLikeTuple.fromItems(quotient, new PythonFloat(remainder)); } public PythonInteger round() { if (value % 1.0 == 0.5) { long floor = (long) Math.floor(value); if (floor % 2 == 0) { return PythonInteger.valueOf(floor); } else { return PythonInteger.valueOf(floor + 1); } } return PythonInteger.valueOf(Math.round(value)); } public PythonNumber round(PythonInteger digitsAfterDecimal) { if (digitsAfterDecimal.equals(PythonInteger.ZERO)) { return round(); } BigDecimal asDecimal = new BigDecimal(value); return new PythonFloat( asDecimal.setScale(digitsAfterDecimal.value.intValueExact(), RoundingMode.HALF_EVEN).doubleValue()); } public PythonLikeObject power(PythonLikeObject other) { if (other instanceof PythonInteger) { return power((PythonInteger) other); } else if (other instanceof PythonFloat) { return power((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonFloat power(PythonInteger other) { return new PythonFloat(Math.pow(value, other.value.doubleValue())); } public PythonFloat power(PythonFloat other) { return new PythonFloat(Math.pow(value, other.value)); } public PythonLikeObject pythonEquals(PythonLikeObject other) { if (other instanceof PythonInteger) { return pythonEquals((PythonInteger) other); } else if (other instanceof PythonFloat) { return pythonEquals((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject notEqual(PythonLikeObject other) { if (other instanceof PythonInteger) { return notEqual((PythonInteger) other); } else if (other instanceof PythonFloat) { return notEqual((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject lessThan(PythonLikeObject other) { if (other instanceof PythonInteger) { return lessThan((PythonInteger) other); } else if (other instanceof PythonFloat) { return lessThan((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject greaterThan(PythonLikeObject other) { if (other instanceof PythonInteger) { return greaterThan((PythonInteger) other); } else if (other instanceof PythonFloat) { return greaterThan((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject lessThanOrEqual(PythonLikeObject other) { if (other instanceof PythonInteger) { return lessThanOrEqual((PythonInteger) other); } else if (other instanceof PythonFloat) { return lessThanOrEqual((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject greaterThanOrEqual(PythonLikeObject other) { if (other instanceof PythonInteger) { return greaterThanOrEqual((PythonInteger) other); } else if (other instanceof PythonFloat) { return greaterThanOrEqual((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonBoolean pythonEquals(PythonInteger other) { return PythonBoolean.valueOf(value == other.value.doubleValue()); } public PythonBoolean notEqual(PythonInteger other) { return PythonBoolean.valueOf(value != other.value.doubleValue()); } public PythonBoolean lessThan(PythonInteger other) { return PythonBoolean.valueOf(value < other.value.doubleValue()); } public PythonBoolean lessThanOrEqual(PythonInteger other) { return PythonBoolean.valueOf(value <= other.value.doubleValue()); } public PythonBoolean greaterThan(PythonInteger other) { return PythonBoolean.valueOf(value > other.value.doubleValue()); } public PythonBoolean greaterThanOrEqual(PythonInteger other) { return PythonBoolean.valueOf(value >= other.value.doubleValue()); } public PythonBoolean pythonEquals(PythonFloat other) { return PythonBoolean.valueOf(value == other.value); } public PythonBoolean notEqual(PythonFloat other) { return PythonBoolean.valueOf(value != other.value); } public PythonBoolean lessThan(PythonFloat other) { return PythonBoolean.valueOf(value < other.value); } public PythonBoolean lessThanOrEqual(PythonFloat other) { return PythonBoolean.valueOf(value <= other.value); } public PythonBoolean greaterThan(PythonFloat other) { return PythonBoolean.valueOf(value > other.value); } public PythonBoolean greaterThanOrEqual(PythonFloat other) { return PythonBoolean.valueOf(value >= other.value); } public PythonString format() { return PythonString.valueOf(Double.toString(value)); } private DecimalFormat getNumberFormat(DefaultFormatSpec formatSpec) { DecimalFormat numberFormat = new DecimalFormat(); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); boolean isUppercase = false; switch (formatSpec.conversionType.orElse(DefaultFormatSpec.ConversionType.LOWERCASE_GENERAL)) { case UPPERCASE_GENERAL: case UPPERCASE_SCIENTIFIC_NOTATION: case UPPERCASE_FIXED_POINT: isUppercase = true; break; } if (isUppercase) { symbols.setExponentSeparator("E"); symbols.setInfinity("INF"); symbols.setNaN("NAN"); } else { symbols.setExponentSeparator("e"); symbols.setInfinity("inf"); symbols.setNaN("nan"); } if (formatSpec.groupingOption.isPresent()) { switch (formatSpec.groupingOption.get()) { case COMMA: symbols.setGroupingSeparator(','); break; case UNDERSCORE: symbols.setGroupingSeparator('_'); break; } } if (formatSpec.conversionType.orElse(null) == DefaultFormatSpec.ConversionType.LOCALE_SENSITIVE) { symbols.setGroupingSeparator(DecimalFormatSymbols.getInstance().getGroupingSeparator()); } numberFormat.setDecimalFormatSymbols(symbols); switch (formatSpec.conversionType.orElse(DefaultFormatSpec.ConversionType.LOWERCASE_GENERAL)) { case LOWERCASE_SCIENTIFIC_NOTATION: case UPPERCASE_SCIENTIFIC_NOTATION: numberFormat.applyPattern("0." + "#".repeat(formatSpec.getPrecisionOrDefault()) + "E00"); break; case LOWERCASE_FIXED_POINT: case UPPERCASE_FIXED_POINT: if (formatSpec.groupingOption.isPresent()) { numberFormat.applyPattern("#,##0." + "0".repeat(formatSpec.getPrecisionOrDefault())); } else { numberFormat.applyPattern("0." + "0".repeat(formatSpec.getPrecisionOrDefault())); } break; case LOCALE_SENSITIVE: case LOWERCASE_GENERAL: case UPPERCASE_GENERAL: BigDecimal asBigDecimal = new BigDecimal(value); // total digits - digits to the right of the decimal point int exponent; if (asBigDecimal.precision() == asBigDecimal.scale() + 1) { exponent = -asBigDecimal.scale(); } else { exponent = asBigDecimal.precision() - asBigDecimal.scale() - 1; } if (-4 < exponent || exponent >= formatSpec.getPrecisionOrDefault()) { if (formatSpec.conversionType.isEmpty()) { numberFormat.applyPattern("0.0" + "#".repeat(formatSpec.getPrecisionOrDefault() - 1) + "E00"); } else { numberFormat.applyPattern("0." + "#".repeat(formatSpec.getPrecisionOrDefault()) + "E00"); } } else { if (formatSpec.groupingOption.isPresent() || formatSpec.conversionType.orElse(null) == DefaultFormatSpec.ConversionType.LOCALE_SENSITIVE) { if (formatSpec.conversionType.isEmpty()) { numberFormat.applyPattern("#,##0.0" + "#".repeat(formatSpec.getPrecisionOrDefault() - 1)); } else { numberFormat.applyPattern("#,##0." + "#".repeat(formatSpec.getPrecisionOrDefault())); } } else { if (formatSpec.conversionType.isEmpty()) { numberFormat.applyPattern("0.0" + "#".repeat(formatSpec.getPrecisionOrDefault() - 1)); } else { numberFormat.applyPattern("0." + "#".repeat(formatSpec.getPrecisionOrDefault())); } } } case PERCENTAGE: if (formatSpec.groupingOption.isPresent()) { numberFormat.applyPattern("#,##0." + "0".repeat(formatSpec.getPrecisionOrDefault()) + "%"); } else { numberFormat.applyPattern("0." + "0".repeat(formatSpec.getPrecisionOrDefault()) + "%"); } break; default: throw new ValueError("Invalid conversion for float type: " + formatSpec.conversionType); } switch (formatSpec.signOption.orElse(DefaultFormatSpec.SignOption.ONLY_NEGATIVE_NUMBERS)) { case ALWAYS_SIGN: numberFormat.setPositivePrefix("+"); numberFormat.setNegativePrefix("-"); break; case ONLY_NEGATIVE_NUMBERS: numberFormat.setPositivePrefix(""); numberFormat.setNegativePrefix("-"); break; case SPACE_FOR_POSITIVE_NUMBERS: numberFormat.setPositivePrefix(" "); numberFormat.setNegativePrefix("-"); break; } numberFormat.setRoundingMode(RoundingMode.HALF_EVEN); numberFormat.setDecimalSeparatorAlwaysShown(formatSpec.useAlternateForm); return numberFormat; } public PythonString $method$__format__(PythonLikeObject specObject) { PythonString spec; if (specObject == PythonNone.INSTANCE) { spec = PythonString.EMPTY; } else if (specObject instanceof PythonString) { spec = (PythonString) specObject; } else { throw new TypeError("__format__ argument 0 has incorrect type (expecting str or None)"); } DefaultFormatSpec formatSpec = DefaultFormatSpec.fromSpec(spec); StringBuilder out = new StringBuilder(); NumberFormat numberFormat = getNumberFormat(formatSpec); out.append(numberFormat.format(value)); StringFormatter.align(out, formatSpec, DefaultFormatSpec.AlignmentOption.RIGHT_ALIGN); return PythonString.valueOf(out.toString()); } @Override public <T> T coerce(Class<T> targetType) { if (targetType.equals(PythonInteger.class)) { return (T) PythonInteger.valueOf((long) value); } return null; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/numeric/PythonInteger.java
package ai.timefold.jpyinterpreter.types.numeric; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.Coercible; import ai.timefold.jpyinterpreter.types.NotImplemented; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.arithmetic.ZeroDivisionError; import ai.timefold.jpyinterpreter.util.DefaultFormatSpec; import ai.timefold.jpyinterpreter.util.StringFormatter; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonInteger extends AbstractPythonLikeObject implements PythonNumber, PlanningImmutable, Coercible { private static final BigInteger MIN_BYTE = BigInteger.valueOf(0); private static final BigInteger MAX_BYTE = BigInteger.valueOf(255); public final BigInteger value; public final static PythonInteger ZERO = new PythonInteger(BigInteger.ZERO); public final static PythonInteger ONE = new PythonInteger(BigInteger.ONE); public final static PythonInteger TWO = new PythonInteger(BigInteger.TWO); static { PythonOverloadImplementor.deferDispatchesFor(PythonInteger::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Constructor BuiltinTypes.INT_TYPE.setConstructor((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.isEmpty()) { return PythonInteger.valueOf(0); } else if (positionalArguments.size() == 1) { return PythonInteger.from(positionalArguments.get(0)); } else if (positionalArguments.size() == 2) { return PythonInteger.fromUsingBase(positionalArguments.get(0), positionalArguments.get(1)); } else { throw new TypeError("int takes at most 2 arguments, got " + positionalArguments.size()); } }); // Unary BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.AS_BOOLEAN, PythonInteger.class.getMethod("asBoolean")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.AS_INT, PythonInteger.class.getMethod("asInteger")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.AS_FLOAT, PythonInteger.class.getMethod("asFloat")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.AS_INDEX, PythonInteger.class.getMethod("asInteger")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.POSITIVE, PythonInteger.class.getMethod("asInteger")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.NEGATIVE, PythonInteger.class.getMethod("negative")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.INVERT, PythonInteger.class.getMethod("invert")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.ABS, PythonInteger.class.getMethod("abs")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, PythonInteger.class.getMethod("asString")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, PythonInteger.class.getMethod("asString")); BuiltinTypes.INT_TYPE.addUnaryMethod(PythonUnaryOperator.HASH, PythonInteger.class.getMethod("$method$__hash__")); // Binary BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.ADD, PythonInteger.class.getMethod("add", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.ADD, PythonInteger.class.getMethod("add", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.ADD, PythonInteger.class.getMethod("add", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonInteger.class.getMethod("subtract", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonInteger.class.getMethod("subtract", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonInteger.class.getMethod("subtract", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonInteger.class.getMethod("multiply", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonInteger.class.getMethod("multiply", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonInteger.class.getMethod("multiply", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.TRUE_DIVIDE, PythonInteger.class.getMethod("trueDivide", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.TRUE_DIVIDE, PythonInteger.class.getMethod("trueDivide", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.TRUE_DIVIDE, PythonInteger.class.getMethod("trueDivide", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.FLOOR_DIVIDE, PythonInteger.class.getMethod("floorDivide", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.FLOOR_DIVIDE, PythonInteger.class.getMethod("floorDivide", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.FLOOR_DIVIDE, PythonInteger.class.getMethod("floorDivide", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.DIVMOD, PythonInteger.class.getMethod("divmod", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.DIVMOD, PythonInteger.class.getMethod("divmod", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MODULO, PythonInteger.class.getMethod("modulo", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MODULO, PythonInteger.class.getMethod("modulo", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.MODULO, PythonInteger.class.getMethod("modulo", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.POWER, PythonInteger.class.getMethod("power", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.POWER, PythonInteger.class.getMethod("power", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.POWER, PythonInteger.class.getMethod("power", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LSHIFT, PythonInteger.class.getMethod("shiftLeft", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LSHIFT, PythonInteger.class.getMethod("shiftLeft", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.RSHIFT, PythonInteger.class.getMethod("shiftRight", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.RSHIFT, PythonInteger.class.getMethod("shiftRight", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.AND, PythonInteger.class.getMethod("bitwiseAnd", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.AND, PythonInteger.class.getMethod("bitwiseAnd", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.OR, PythonInteger.class.getMethod("bitwiseOr", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.OR, PythonInteger.class.getMethod("bitwiseOr", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.XOR, PythonInteger.class.getMethod("bitwiseXor", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.XOR, PythonInteger.class.getMethod("bitwiseXor", PythonInteger.class)); // Ternary BuiltinTypes.INT_TYPE.addBinaryMethod(PythonBinaryOperator.POWER, PythonInteger.class.getMethod("power", PythonInteger.class, PythonInteger.class)); // Comparisons BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.EQUAL, PythonInteger.class.getMethod("pythonEquals", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.EQUAL, PythonInteger.class.getMethod("pythonEquals", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.EQUAL, PythonInteger.class.getMethod("pythonEquals", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.NOT_EQUAL, PythonInteger.class.getMethod("notEqual", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.NOT_EQUAL, PythonInteger.class.getMethod("notEqual", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.NOT_EQUAL, PythonInteger.class.getMethod("notEqual", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonInteger.class.getMethod("lessThan", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonInteger.class.getMethod("lessThan", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonInteger.class.getMethod("lessThan", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonInteger.class.getMethod("lessThanOrEqual", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonInteger.class.getMethod("lessThanOrEqual", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonInteger.class.getMethod("lessThanOrEqual", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonInteger.class.getMethod("greaterThan", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonInteger.class.getMethod("greaterThan", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonInteger.class.getMethod("greaterThan", PythonFloat.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonInteger.class.getMethod("greaterThanOrEqual", PythonLikeObject.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonInteger.class.getMethod("greaterThanOrEqual", PythonInteger.class)); BuiltinTypes.INT_TYPE.addLeftBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonInteger.class.getMethod("greaterThanOrEqual", PythonFloat.class)); // Other BuiltinTypes.INT_TYPE.addMethod("__round__", PythonInteger.class.getMethod("round")); BuiltinTypes.INT_TYPE.addMethod("__round__", PythonInteger.class.getMethod("round", PythonInteger.class)); BuiltinTypes.INT_TYPE.addBinaryMethod(PythonBinaryOperator.FORMAT, PythonInteger.class.getMethod("$method$__format__")); BuiltinTypes.INT_TYPE.addBinaryMethod(PythonBinaryOperator.FORMAT, PythonInteger.class.getMethod("$method$__format__", PythonLikeObject.class)); return BuiltinTypes.INT_TYPE; } public PythonInteger(PythonLikeType type) { super(type); this.value = BigInteger.ZERO; } public PythonInteger(PythonLikeType type, BigInteger value) { super(type); this.value = value; } public PythonInteger(long value) { this(BigInteger.valueOf(value)); } public PythonInteger(BigInteger value) { super(BuiltinTypes.INT_TYPE); this.value = value; } private static PythonInteger from(PythonLikeObject value) { if (value instanceof PythonInteger integer) { return integer; } else if (value instanceof PythonFloat pythonFloat) { return pythonFloat.asInteger(); } else if (value instanceof PythonString str) { try { return new PythonInteger(new BigInteger(str.value)); } catch (NumberFormatException e) { throw new ValueError("invalid literal for int() with base 10: %s".formatted(value)); } } else { PythonLikeType valueType = value.$getType(); PythonLikeFunction asIntFunction = (PythonLikeFunction) (valueType.$getAttributeOrError("__int__")); return (PythonInteger) asIntFunction.$call(List.of(value), Map.of(), null); } } private static PythonInteger fromUsingBase(PythonLikeObject value, PythonLikeObject base) { if (value instanceof PythonString str && base instanceof PythonInteger baseInt) { try { return new PythonInteger(new BigInteger(str.value, baseInt.value.intValue())); } catch (NumberFormatException e) { throw new ValueError( "invalid literal for int() with base %d: %s".formatted(baseInt.value.intValue(), value)); } } else { PythonLikeType valueType = value.$getType(); PythonLikeFunction asIntFunction = (PythonLikeFunction) (valueType.$getAttributeOrError("__int__")); return (PythonInteger) asIntFunction.$call(List.of(value, base), Map.of(), null); } } @Override public Number getValue() { return value; } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { return value.toString(); } public byte asByte() { if (value.compareTo(MIN_BYTE) < 0 || value.compareTo(MAX_BYTE) > 0) { throw new ValueError(value + " cannot represent a byte because it outside the range [0, 255]."); } return value.byteValue(); } @Override public boolean equals(Object o) { if (o instanceof Number number) { return value.equals(BigInteger.valueOf(number.longValue())); } else if (o instanceof PythonNumber number) { return compareTo(number) == 0; } else { return false; } } @Override public int hashCode() { return $method$__hash__().value.intValue(); } public PythonInteger $method$__hash__() { return PythonNumber.computeHash(this, ONE); } public static PythonInteger valueOf(byte value) { return new PythonInteger(value); } public static PythonInteger valueOf(short value) { return new PythonInteger(value); } public static PythonInteger valueOf(int value) { return new PythonInteger(value); } public static PythonInteger valueOf(long value) { return new PythonInteger(value); } public static PythonInteger valueOf(BigInteger value) { return new PythonInteger(value); } public PythonBoolean asBoolean() { return value.signum() == 0 ? PythonBoolean.FALSE : PythonBoolean.TRUE; } public PythonInteger asInteger() { return this; } public PythonFloat asFloat() { return new PythonFloat(value.doubleValue()); } public PythonInteger negative() { return new PythonInteger(value.negate()); } public PythonInteger invert() { return new PythonInteger(value.add(BigInteger.ONE).negate()); } public PythonInteger abs() { return new PythonInteger(value.abs()); } public PythonLikeObject add(PythonLikeObject other) { if (other instanceof PythonInteger) { return add((PythonInteger) other); } else if (other instanceof PythonFloat) { return add((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger add(PythonInteger other) { return new PythonInteger(value.add(other.value)); } public PythonFloat add(PythonFloat other) { return new PythonFloat(value.doubleValue() + other.value); } public PythonLikeObject subtract(PythonLikeObject other) { if (other instanceof PythonInteger) { return subtract((PythonInteger) other); } else if (other instanceof PythonFloat) { return subtract((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger subtract(PythonInteger other) { return new PythonInteger(value.subtract(other.value)); } public PythonFloat subtract(PythonFloat other) { return new PythonFloat(value.doubleValue() - other.value); } public PythonLikeObject multiply(PythonLikeObject other) { if (other instanceof PythonInteger) { return multiply((PythonInteger) other); } else if (other instanceof PythonFloat) { return multiply((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger multiply(PythonInteger other) { return new PythonInteger(value.multiply(other.value)); } public PythonFloat multiply(PythonFloat other) { return new PythonFloat(value.doubleValue() * other.value); } public PythonLikeObject trueDivide(PythonLikeObject other) { if (other instanceof PythonInteger) { return trueDivide((PythonInteger) other); } else if (other instanceof PythonFloat) { return trueDivide((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonFloat trueDivide(PythonInteger other) { if (other.value.equals(BigInteger.ZERO)) { throw new ZeroDivisionError("integer division or modulo by zero"); } return new PythonFloat(value.doubleValue() / other.value.doubleValue()); } public PythonFloat trueDivide(PythonFloat other) { if (other.value == 0.0) { throw new ZeroDivisionError("integer division or modulo by zero"); } return new PythonFloat(value.doubleValue() / other.value); } public PythonLikeObject floorDivide(PythonLikeObject other) { if (other instanceof PythonInteger) { return floorDivide((PythonInteger) other); } else if (other instanceof PythonFloat) { return floorDivide((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger floorDivide(PythonInteger other) { if (other.value.equals(BigInteger.ZERO)) { throw new ZeroDivisionError("integer division or modulo by zero"); } return new PythonInteger(value.divide(other.value)); } public PythonFloat floorDivide(PythonFloat other) { if (other.value == 0.0) { throw new ZeroDivisionError("integer division or modulo by zero"); } return PythonFloat.valueOf(new BigDecimal(value) .divideToIntegralValue(BigDecimal.valueOf(other.value)) .doubleValue()); } public PythonFloat ceilDivide(PythonFloat other) { if (other.value == 0.0) { throw new ZeroDivisionError("integer division or modulo by zero"); } return PythonFloat.valueOf(new BigDecimal(value) .divide(BigDecimal.valueOf(other.value), RoundingMode.CEILING) .doubleValue()); } public PythonLikeObject modulo(PythonLikeObject other) { if (other instanceof PythonInteger) { return modulo((PythonInteger) other); } else if (other instanceof PythonFloat) { return modulo((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger modulo(PythonInteger other) { int remainderSign = other.compareTo(ZERO); if (remainderSign == 0) { throw new ZeroDivisionError("integer division or modulo by zero"); } else if (remainderSign > 0) { BigInteger remainder = value.remainder(other.value); if (remainder.compareTo(BigInteger.ZERO) < 0) { remainder = other.value.add(remainder); } return new PythonInteger(remainder); } else { BigInteger remainder = value.remainder(other.value); if (remainder.compareTo(BigInteger.ZERO) > 0) { remainder = other.value.add(remainder); } return new PythonInteger(remainder); } } public PythonFloat modulo(PythonFloat other) { int remainderSign = other.compareTo(ZERO); double doubleValue = value.doubleValue(); if (remainderSign == 0) { throw new ZeroDivisionError("integer division or modulo by zero"); } else if (remainderSign > 0) { double remainder = doubleValue % other.value; if (remainder < 0) { remainder = remainder + other.value; } return new PythonFloat(remainder); } else { double remainder = doubleValue % other.value; if (remainder > 0) { remainder = remainder + other.value; } return new PythonFloat(remainder); } } public PythonLikeTuple divmod(PythonInteger other) { BigInteger[] result = value.divideAndRemainder(other.value); // Python remainder has sign of divisor if (other.value.compareTo(BigInteger.ZERO) < 0) { if (result[1].compareTo(BigInteger.ZERO) > 0) { result[0] = result[0].subtract(BigInteger.ONE); result[1] = result[1].add(other.value); } } else { if (result[1].compareTo(BigInteger.ZERO) < 0) { result[0] = result[0].subtract(BigInteger.ONE); result[1] = result[1].add(other.value); } } return PythonLikeTuple.fromItems(PythonInteger.valueOf(result[0]), PythonInteger.valueOf(result[1])); } public PythonLikeTuple divmod(PythonFloat other) { PythonFloat quotient; if (value.compareTo(BigInteger.ZERO) < 0 == other.value < 0) { // Same sign, use floor division quotient = floorDivide(other); } else { // Different sign, use ceil division quotient = ceilDivide(other); } double remainder = value.doubleValue() % other.value; // Python remainder has sign of divisor if (other.value < 0) { if (remainder > 0) { quotient = quotient.subtract(PythonInteger.ONE); remainder = remainder + other.value; } } else { if (remainder < 0) { quotient = quotient.subtract(PythonInteger.ONE); remainder = remainder + other.value; } } return PythonLikeTuple.fromItems(quotient, new PythonFloat(remainder)); } public PythonInteger round() { return this; } public PythonInteger round(PythonInteger digitsAfterDecimal) { if (digitsAfterDecimal.compareTo(PythonInteger.ZERO) >= 0) { return this; } BigInteger powerOfTen = BigInteger.TEN.pow(-digitsAfterDecimal.value.intValueExact()); BigInteger halfPowerOfTen = powerOfTen.shiftRight(1); BigInteger remainder = value.mod(powerOfTen); BigInteger previous = value.subtract(remainder); BigInteger next = value.add(powerOfTen.subtract(remainder)); if (remainder.equals(halfPowerOfTen)) { if (previous.divide(powerOfTen).mod(BigInteger.TWO).equals(BigInteger.ZERO)) { // previous even return PythonInteger.valueOf(previous); } else { // next even return PythonInteger.valueOf(next); } } else if (remainder.compareTo(halfPowerOfTen) < 0) { // previous closer return PythonInteger.valueOf(previous); } else { // next closer return PythonInteger.valueOf(next); } } public PythonLikeObject power(PythonLikeObject other) { if (other instanceof PythonInteger) { return power((PythonInteger) other); } else if (other instanceof PythonFloat) { return power((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonNumber power(PythonInteger other) { if (other.value.signum() >= 0) { return new PythonInteger(value.pow(other.value.intValueExact())); } return new PythonFloat(Math.pow(value.doubleValue(), other.value.doubleValue())); } public PythonInteger power(PythonInteger exponent, PythonInteger modulus) { return PythonInteger.valueOf(value.modPow(exponent.value, modulus.value)); } public PythonFloat power(PythonFloat other) { return new PythonFloat(Math.pow(value.doubleValue(), other.value)); } public PythonLikeObject shiftLeft(PythonLikeObject other) { if (other instanceof PythonInteger) { return shiftLeft((PythonInteger) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger shiftLeft(PythonInteger other) { return new PythonInteger(value.shiftLeft(other.value.intValueExact())); } public PythonLikeObject shiftRight(PythonLikeObject other) { if (other instanceof PythonInteger) { return shiftRight((PythonInteger) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger shiftRight(PythonInteger other) { return new PythonInteger(value.shiftRight(other.value.intValueExact())); } public PythonLikeObject bitwiseAnd(PythonLikeObject other) { if (other instanceof PythonInteger) { return bitwiseAnd((PythonInteger) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger bitwiseAnd(PythonInteger other) { return new PythonInteger(value.and(other.value)); } public PythonLikeObject bitwiseOr(PythonLikeObject other) { if (other instanceof PythonInteger) { return bitwiseOr((PythonInteger) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger bitwiseOr(PythonInteger other) { return new PythonInteger(value.or(other.value)); } public PythonLikeObject bitwiseXor(PythonLikeObject other) { if (other instanceof PythonInteger) { return bitwiseXor((PythonInteger) other); } else { return NotImplemented.INSTANCE; } } public PythonInteger bitwiseXor(PythonInteger other) { return new PythonInteger(value.xor(other.value)); } public PythonLikeObject pythonEquals(PythonLikeObject other) { if (other instanceof PythonInteger) { return pythonEquals((PythonInteger) other); } else if (other instanceof PythonFloat) { return pythonEquals((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject notEqual(PythonLikeObject other) { if (other instanceof PythonInteger) { return notEqual((PythonInteger) other); } else if (other instanceof PythonFloat) { return notEqual((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject lessThan(PythonLikeObject other) { if (other instanceof PythonInteger) { return lessThan((PythonInteger) other); } else if (other instanceof PythonFloat) { return lessThan((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject lessThanOrEqual(PythonLikeObject other) { if (other instanceof PythonInteger) { return lessThanOrEqual((PythonInteger) other); } else if (other instanceof PythonFloat) { return lessThanOrEqual((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject greaterThan(PythonLikeObject other) { if (other instanceof PythonInteger) { return greaterThan((PythonInteger) other); } else if (other instanceof PythonFloat) { return greaterThan((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonLikeObject greaterThanOrEqual(PythonLikeObject other) { if (other instanceof PythonInteger) { return greaterThanOrEqual((PythonInteger) other); } else if (other instanceof PythonFloat) { return greaterThanOrEqual((PythonFloat) other); } else { return NotImplemented.INSTANCE; } } public PythonBoolean pythonEquals(PythonInteger other) { return PythonBoolean.valueOf(value.compareTo(other.value) == 0); } public PythonBoolean notEqual(PythonInteger other) { return PythonBoolean.valueOf(value.compareTo(other.value) != 0); } public PythonBoolean lessThan(PythonInteger other) { return PythonBoolean.valueOf(value.compareTo(other.value) < 0); } public PythonBoolean lessThanOrEqual(PythonInteger other) { return PythonBoolean.valueOf(value.compareTo(other.value) <= 0); } public PythonBoolean greaterThan(PythonInteger other) { return PythonBoolean.valueOf(value.compareTo(other.value) > 0); } public PythonBoolean greaterThanOrEqual(PythonInteger other) { return PythonBoolean.valueOf(value.compareTo(other.value) >= 0); } public PythonBoolean pythonEquals(PythonFloat other) { return PythonBoolean.valueOf(value.doubleValue() == other.value); } public PythonBoolean notEqual(PythonFloat other) { return PythonBoolean.valueOf(value.doubleValue() != other.value); } public PythonBoolean lessThan(PythonFloat other) { return PythonBoolean.valueOf(value.doubleValue() < other.value); } public PythonBoolean lessThanOrEqual(PythonFloat other) { return PythonBoolean.valueOf(value.doubleValue() <= other.value); } public PythonBoolean greaterThan(PythonFloat other) { return PythonBoolean.valueOf(value.doubleValue() > other.value); } public PythonBoolean greaterThanOrEqual(PythonFloat other) { return PythonBoolean.valueOf(value.doubleValue() >= other.value); } public PythonString asString() { return PythonString.valueOf(value.toString()); } public PythonString $method$__format__() { return PythonString.valueOf(value.toString()); } public PythonString $method$__format__(PythonLikeObject specObject) { PythonString spec; if (specObject == PythonNone.INSTANCE) { spec = PythonString.EMPTY; } else if (specObject instanceof PythonString) { spec = (PythonString) specObject; } else { throw new TypeError("__format__ argument 0 has incorrect type (expecting str or None)"); } DefaultFormatSpec formatSpec = DefaultFormatSpec.fromSpec(spec); StringBuilder out = new StringBuilder(); String alternateFormPrefix = null; int groupSize; if (formatSpec.precision.isPresent()) { throw new ValueError("Precision not allowed in integer format specifier"); } switch (formatSpec.conversionType.orElse(DefaultFormatSpec.ConversionType.DECIMAL)) { case BINARY: alternateFormPrefix = "0b"; groupSize = 4; out.append(value.toString(2)); break; case OCTAL: alternateFormPrefix = "0o"; groupSize = 4; out.append(value.toString(8)); break; case DECIMAL: out.append(value.toString(10)); groupSize = 3; break; case LOWERCASE_HEX: alternateFormPrefix = "0x"; groupSize = 4; out.append(value.toString(16)); break; case UPPERCASE_HEX: alternateFormPrefix = "0X"; groupSize = 4; out.append(value.toString(16).toUpperCase()); break; case CHARACTER: groupSize = -1; out.appendCodePoint(value.intValueExact()); break; case LOCALE_SENSITIVE: groupSize = -1; NumberFormat.getIntegerInstance().format(value); break; default: throw new ValueError("Invalid format spec for int: " + spec); } StringFormatter.addGroupings(out, formatSpec, groupSize); switch (formatSpec.signOption.orElse(DefaultFormatSpec.SignOption.ONLY_NEGATIVE_NUMBERS)) { case ALWAYS_SIGN: if (out.charAt(0) != '-') { out.insert(0, '+'); } break; case ONLY_NEGATIVE_NUMBERS: break; case SPACE_FOR_POSITIVE_NUMBERS: if (out.charAt(0) != '-') { out.insert(0, ' '); } break; default: throw new IllegalStateException("Unhandled case: " + formatSpec.signOption); } if (formatSpec.useAlternateForm && alternateFormPrefix != null) { StringFormatter.alignWithPrefixRespectingSign(out, alternateFormPrefix, formatSpec, DefaultFormatSpec.AlignmentOption.RIGHT_ALIGN); } else { StringFormatter.align(out, formatSpec, DefaultFormatSpec.AlignmentOption.RIGHT_ALIGN); } return PythonString.valueOf(out.toString()); } @Override public <T> T coerce(Class<T> targetType) { if (targetType.equals(PythonFloat.class)) { return (T) PythonFloat.valueOf(value.doubleValue()); } return null; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/numeric/PythonNumber.java
package ai.timefold.jpyinterpreter.types.numeric; import java.math.BigDecimal; import java.math.BigInteger; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeComparable; import ai.timefold.jpyinterpreter.types.PythonLikeType; public interface PythonNumber extends PythonLikeComparable<PythonNumber>, PythonLikeObject { PythonLikeType NUMBER_TYPE = new PythonLikeType("number", PythonNumber.class); PythonInteger MODULUS = PythonInteger.valueOf((1L << 61) - 1); PythonInteger INFINITY_HASH_VALUE = PythonInteger.valueOf(314159); Number getValue(); @Override default int compareTo(PythonNumber pythonNumber) { Number value = getValue(); Number otherValue = pythonNumber.getValue(); if (value instanceof BigInteger self) { if (otherValue instanceof BigInteger other) { return self.compareTo(other); } else if (otherValue instanceof BigDecimal other) { return new BigDecimal(self).compareTo(other); } } if (value instanceof BigDecimal self) { if (otherValue instanceof BigDecimal other) { return self.compareTo(other); } else if (otherValue instanceof BigInteger other) { return self.compareTo(new BigDecimal(other)); } } // If comparing against a float, convert both arguments to float return Double.compare(value.doubleValue(), otherValue.doubleValue()); } static PythonInteger computeHash(PythonInteger numerator, PythonInteger denominator) { PythonInteger P = MODULUS; // Remove common factors of P. (Unnecessary if m and n already coprime.) while (numerator.modulo(P).equals(PythonInteger.ZERO) && denominator.modulo(P).equals(PythonInteger.ZERO)) { numerator = numerator.floorDivide(P); denominator = denominator.floorDivide(P); } PythonInteger hash_value; if (denominator.modulo(P).equals(PythonInteger.ZERO)) { hash_value = INFINITY_HASH_VALUE; } else { // Fermat's Little Theorem: pow(n, P-1, P) is 1, so // pow(n, P-2, P) gives the inverse of n modulo P. hash_value = (numerator.abs().modulo(P)).multiply(denominator.power(P.subtract(PythonInteger.TWO), P)).modulo(P); } if (numerator.lessThan(PythonInteger.ZERO).getBooleanValue()) { hash_value = hash_value.negative(); } if (hash_value.equals(PythonInteger.valueOf(-1))) { hash_value = PythonInteger.valueOf(-2); } return hash_value; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/wrappers/CPythonType.java
package ai.timefold.jpyinterpreter.types.wrappers; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.CPythonBackedPythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; public class CPythonType extends PythonLikeType { private static final Map<Number, CPythonType> cpythonTypeMap = new HashMap<>(); private final OpaquePythonReference pythonReference; private final Map<String, PythonLikeObject> cachedAttributeMap; private static String getTypeName(OpaquePythonReference pythonReference) { return ((PythonString) CPythonBackedPythonInterpreter .lookupAttributeOnPythonReference(pythonReference, "__name__")) .getValue(); } public static CPythonType lookupTypeOfPythonObject(OpaquePythonReference reference) { OpaquePythonReference type = CPythonBackedPythonInterpreter.getPythonReferenceType(reference); return cpythonTypeMap.computeIfAbsent(CPythonBackedPythonInterpreter.getPythonReferenceId(type), key -> new CPythonType(type)); } public static CPythonType getType(OpaquePythonReference typeReference) { return cpythonTypeMap.computeIfAbsent(CPythonBackedPythonInterpreter.getPythonReferenceId(typeReference), key -> new CPythonType(typeReference)); } private CPythonType(OpaquePythonReference pythonReference) { super(getTypeName(pythonReference), PythonObjectWrapper.class); this.pythonReference = pythonReference; this.cachedAttributeMap = new HashMap<>(); } @Override public PythonLikeObject $getAttributeOrNull(String attributeName) { switch (attributeName) { case "__eq__": return cachedAttributeMap.computeIfAbsent(attributeName, key -> { PythonLikeObject equals = CPythonBackedPythonInterpreter.lookupAttributeOnPythonReference(pythonReference, attributeName); if (equals instanceof PythonLikeFunction) { final PythonLikeFunction function = (PythonLikeFunction) equals; return (PythonLikeFunction) (pos, named, callerInstance) -> { PythonLikeObject result = function.$call(pos, named, null); if (result instanceof PythonBoolean) { return result; } else { return PythonBoolean.valueOf(pos.get(0) == pos.get(1)); } }; } else { return equals; } }); case "__ne__": return cachedAttributeMap.computeIfAbsent(attributeName, key -> { PythonLikeObject notEquals = CPythonBackedPythonInterpreter.lookupAttributeOnPythonReference(pythonReference, attributeName); if (notEquals instanceof PythonLikeFunction) { final PythonLikeFunction function = (PythonLikeFunction) notEquals; return (PythonLikeFunction) (pos, named, callerInstance) -> { PythonLikeObject result = function.$call(pos, named, null); if (result instanceof PythonBoolean) { return result; } else { return PythonBoolean.valueOf(pos.get(0) != pos.get(1)); } }; } else { return notEquals; } }); case "__hash__": return cachedAttributeMap.computeIfAbsent(attributeName, key -> { PythonLikeObject hash = CPythonBackedPythonInterpreter.lookupAttributeOnPythonReference(pythonReference, attributeName); if (hash instanceof PythonLikeFunction) { final PythonLikeFunction function = (PythonLikeFunction) hash; return (PythonLikeFunction) (pos, named, callerInstance) -> { PythonLikeObject result = function.$call(pos, named, null); if (result instanceof PythonInteger) { return result; } else { return PythonInteger.valueOf(System.identityHashCode(pos.get(0))); } }; } else { return hash; } }); default: return cachedAttributeMap.computeIfAbsent(attributeName, key -> CPythonBackedPythonInterpreter.lookupAttributeOnPythonReference(pythonReference, attributeName)); } } @Override public void $setAttribute(String attributeName, PythonLikeObject value) { cachedAttributeMap.put(attributeName, value); CPythonBackedPythonInterpreter.setAttributeOnPythonReference(pythonReference, null, attributeName, value); } @Override public void $deleteAttribute(String attributeName) { cachedAttributeMap.remove(attributeName); CPythonBackedPythonInterpreter.deleteAttributeOnPythonReference(pythonReference, attributeName); } @Override public PythonLikeType $getType() { return BuiltinTypes.TYPE_TYPE; } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { return CPythonBackedPythonInterpreter.callPythonReference(pythonReference, positionalArguments, namedArguments); } public OpaquePythonReference getPythonReference() { return pythonReference; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/wrappers/JavaMethodReference.java
package ai.timefold.jpyinterpreter.types.wrappers; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; public class JavaMethodReference implements PythonLikeFunction { private final Method method; private final Map<String, Integer> parameterNameToIndexMap; public JavaMethodReference(Method method, Map<String, Integer> parameterNameToIndexMap) { this.method = method; this.parameterNameToIndexMap = parameterNameToIndexMap; } public Method getMethod() { return method; } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { Object self; Object[] args; if (Modifier.isStatic(method.getModifiers())) { self = null; args = unwrapPrimitiveArguments(positionalArguments, namedArguments); } else { self = positionalArguments.get(0); if (self instanceof JavaObjectWrapper) { // unwrap wrapped Java Objects self = ((JavaObjectWrapper) self).getWrappedObject(); } args = unwrapPrimitiveArguments(positionalArguments.subList(1, positionalArguments.size()), namedArguments); } try { return JavaPythonTypeConversionImplementor.wrapJavaObject(method.invoke(self, args)); } catch (IllegalAccessException e) { throw new IllegalStateException("Method (" + method + ") is not accessible.", e); } catch (InvocationTargetException e) { throw (RuntimeException) e.getCause(); } } private Object[] unwrapPrimitiveArguments(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments) { namedArguments = (namedArguments != null) ? namedArguments : Map.of(); Object[] out = new Object[method.getParameterCount()]; Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < positionalArguments.size(); i++) { PythonLikeObject argument = positionalArguments.get(i); out[i] = JavaPythonTypeConversionImplementor.convertPythonObjectToJavaType(parameterTypes[i], argument); } for (PythonString key : namedArguments.keySet()) { int index = parameterNameToIndexMap.get(key.value); PythonLikeObject argument = namedArguments.get(key); out[index] = JavaPythonTypeConversionImplementor.convertPythonObjectToJavaType(parameterTypes[index], argument); } return out; } @Override public PythonLikeType $getType() { if (Modifier.isStatic(method.getModifiers())) { return BuiltinTypes.STATIC_FUNCTION_TYPE; } else { return BuiltinTypes.FUNCTION_TYPE; } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/wrappers/JavaObjectWrapper.java
package ai.timefold.jpyinterpreter.types.wrappers; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.AttributeError; import ai.timefold.jpyinterpreter.types.errors.RuntimeError; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; public class JavaObjectWrapper implements PythonLikeObject, Iterable<JavaObjectWrapper>, Comparable<JavaObjectWrapper> { final static Map<Class<?>, PythonLikeType> classToPythonTypeMap = new HashMap<>(); final static Map<Class<?>, Map<String, Field>> classToAttributeNameToMemberListMap = new HashMap<>(); private final PythonLikeType type; private final Object wrappedObject; private final Class<?> objectClass; private final Map<String, Field> attributeNameToMemberListMap; private final Map<Object, PythonLikeObject> convertedObjectMap; private static Map<String, Field> getAllFields(Class<?> baseClass) { return getAllDeclaredMembers(baseClass) .stream() .filter(member -> member instanceof Field && !Modifier.isStatic(member.getModifiers())) .collect(Collectors.toMap(Member::getName, member -> (Field) member, (oldMember, newMember) -> { if (oldMember.getDeclaringClass().isAssignableFrom(newMember.getDeclaringClass())) { return newMember; } else { return oldMember; } })); } private static List<Member> getAllDeclaredMembers(Class<?> baseClass) { Class<?> clazz = baseClass; List<Member> members = new ArrayList<>(); members.addAll(Arrays.asList(clazz.getFields())); members.addAll(Arrays.asList(clazz.getMethods())); return members; } private Method getGetterMethod(Field field) { String getterName; if (objectClass.isRecord()) { getterName = field.getName(); } else { String propertyName = field.getName(); String capitalizedName = propertyName.isEmpty() ? "" : propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); getterName = (field.getType().equals(boolean.class) ? "is" : "get") + capitalizedName; } PythonLikeObject object = type.$getAttributeOrNull(getterName); if (object instanceof JavaMethodReference methodReference) { return methodReference.getMethod(); } if (object instanceof MultiDispatchJavaMethodReference multiDispatchJavaMethodReference) { return multiDispatchJavaMethodReference.getNoArgsMethod(); } throw new AttributeError("Cannot get attribute (%s) on class (%s)." .formatted(field.getName(), type)); } private Method getSetterMethod(Field field) { String propertyName = field.getName(); String capitalizedName = propertyName.isEmpty() ? "" : propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); String setterName = "set" + capitalizedName; PythonLikeObject object = type.$getAttributeOrNull(setterName); if (object instanceof JavaMethodReference methodReference) { return methodReference.getMethod(); } throw new AttributeError("Cannot set attribute (%s) on class (%s)." .formatted(field.getName(), type)); } public JavaObjectWrapper(Object wrappedObject) { this(wrappedObject, new IdentityHashMap<>()); } public JavaObjectWrapper(Object wrappedObject, Map<Object, PythonLikeObject> convertedObjectMap) { convertedObjectMap.put(wrappedObject, this); this.wrappedObject = wrappedObject; this.objectClass = wrappedObject.getClass(); this.convertedObjectMap = convertedObjectMap; this.attributeNameToMemberListMap = classToAttributeNameToMemberListMap.computeIfAbsent(objectClass, JavaObjectWrapper::getAllFields); this.type = getPythonTypeForClass(objectClass, convertedObjectMap); } public static PythonLikeType getPythonTypeForClass(Class<?> objectClass) { return getPythonTypeForClass(objectClass, new IdentityHashMap<>()); } public static PythonLikeType getPythonTypeForClass(Class<?> objectClass, Map<Object, PythonLikeObject> convertedObjectMap) { if (classToPythonTypeMap.containsKey(objectClass)) { return classToPythonTypeMap.get(objectClass); } PythonLikeType out = generatePythonTypeForClass(objectClass, convertedObjectMap); classToPythonTypeMap.put(objectClass, out); return out; } private static boolean isInaccessible(Member member) { return isInaccessible(member.getDeclaringClass()); } private static boolean isInaccessible(Class<?> clazz) { for (Class<?> declaringClass = clazz; declaringClass != null; declaringClass = declaringClass.getDeclaringClass()) { if (!Modifier.isPublic(declaringClass.getModifiers())) { return true; } } return false; } private static Method findMethodInInterfaces(Class<?> declaringClass, Method method) { Queue<Class<?>> toVisit = new ArrayDeque<>(); while (declaringClass != null) { toVisit.addAll(List.of(declaringClass.getInterfaces())); declaringClass = declaringClass.getSuperclass(); } Set<Class<?>> visited = new HashSet<>(); while (!toVisit.isEmpty()) { Class<?> interfaceClass = toVisit.poll(); if (visited.contains(interfaceClass)) { continue; } visited.add(interfaceClass); toVisit.addAll(Arrays.asList(interfaceClass.getInterfaces())); if (isInaccessible(interfaceClass)) { continue; } try { return interfaceClass.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException e) { // Intentionally empty, need to search other interfaces } } return null; } private static void addMemberToPythonType(PythonLikeType type, Member member, Map<Object, PythonLikeObject> convertedObjectMap) { if (member instanceof Method method) { if (isInaccessible(member)) { method = findMethodInInterfaces(method.getDeclaringClass(), method); if (method == null) { return; } } // For certain Collection/List/Map methods, also add their corresponding dunder methods, // so a[x], x in a, len(a) will work. switch (method.getName()) { case "size" -> { if (Collection.class.isAssignableFrom(method.getDeclaringClass())) { type.__dir__.put(PythonUnaryOperator.LENGTH.getDunderMethod(), new JavaMethodReference(method, Map.of())); } } case "contains" -> { if (Collection.class.isAssignableFrom(method.getDeclaringClass())) { type.__dir__.put(PythonBinaryOperator.CONTAINS.getDunderMethod(), new JavaMethodReference(method, Map.of())); } } case "get" -> { type.__dir__.put(PythonBinaryOperator.GET_ITEM.getDunderMethod(), new JavaMethodReference(method, Map.of())); } } ((MultiDispatchJavaMethodReference) type.__dir__.computeIfAbsent(method.getName(), (name) -> new MultiDispatchJavaMethodReference())).addMethod(method); } else { if (isInaccessible(member)) { return; } Field field = (Field) member; if (Modifier.isPublic(field.getModifiers())) { try { type.__dir__.put(field.getName(), JavaPythonTypeConversionImplementor.wrapJavaObject(field.get(null), convertedObjectMap)); } catch (IllegalAccessException e) { throw (RuntimeError) new RuntimeError("Cannot get attribute (%s) on type (%s)." .formatted(field.getName(), type.getTypeName())).initCause(e); } } } } private static PythonLikeType generatePythonTypeForClass(Class<?> objectClass, Map<Object, PythonLikeObject> convertedObjectMap) { var out = new PythonLikeType(objectClass.getName(), JavaObjectWrapper.class, objectClass); getAllDeclaredMembers(objectClass) .stream() .filter(member -> Modifier.isStatic(member.getModifiers()) || member instanceof Method) .forEach(member -> addMemberToPythonType(out, member, convertedObjectMap)); return out; } public Object getWrappedObject() { return wrappedObject; } @Override public PythonLikeObject $getAttributeOrNull(String attributeName) { Field field = attributeNameToMemberListMap.get(attributeName); if (field == null) { return null; } Object result; try { if (Modifier.isPublic(field.getModifiers())) { result = field.get(wrappedObject); } else { Method getterMethod = getGetterMethod(field); result = getterMethod.invoke(wrappedObject); } return JavaPythonTypeConversionImplementor.wrapJavaObject(result, convertedObjectMap); } catch (InvocationTargetException | IllegalAccessException e) { throw (RuntimeError) new RuntimeError("Cannot get attribute (%s) on object (%s)." .formatted(attributeName, this)).initCause(e); } } @Override public void $setAttribute(String attributeName, PythonLikeObject value) { Field field = attributeNameToMemberListMap.get(attributeName); if (field == null) { throw new AttributeError("(%s) object does not have attribute (%s)." .formatted(type, attributeName)); } try { Object javaObject = JavaPythonTypeConversionImplementor.convertPythonObjectToJavaType(field.getType(), value); if (Modifier.isPublic(field.getModifiers())) { field.set(wrappedObject, javaObject); } else { Method setterMethod = getSetterMethod(field); setterMethod.invoke(wrappedObject, javaObject); } } catch (InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } } @Override public void $deleteAttribute(String attributeName) { throw new IllegalArgumentException("Cannot delete attributes on type '" + objectClass + "'"); } @Override public PythonLikeType $getType() { return type; } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public int compareTo(JavaObjectWrapper javaObjectWrapper) { if (!(wrappedObject instanceof Comparable comparable)) { throw new IllegalStateException("Class (%s) does not implement (%s).".formatted(objectClass, Comparable.class)); } return comparable.compareTo(javaObjectWrapper.wrappedObject); } @Override public Iterator<JavaObjectWrapper> iterator() { if (!(wrappedObject instanceof Iterable<?> iterable)) { throw new IllegalStateException("Class (%s) does not implement (%s).".formatted(objectClass, Iterable.class)); } return new WrappingJavaObjectIterator(iterable.iterator()); } @Override public String toString() { return wrappedObject.toString(); } @Override public boolean equals(Object o) { if (o instanceof JavaObjectWrapper other) { return wrappedObject.equals(other.wrappedObject); } return wrappedObject.equals(o); } @Override public int hashCode() { return wrappedObject.hashCode(); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(hashCode()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/wrappers/MultiDispatchJavaMethodReference.java
package ai.timefold.jpyinterpreter.types.wrappers; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.TypeError; public class MultiDispatchJavaMethodReference implements PythonLikeFunction { private final List<Method> methodList; public MultiDispatchJavaMethodReference() { this.methodList = new ArrayList<>(); } public void addMethod(Method method) { methodList.add(method); } public Method getNoArgsMethod() { for (Method method : methodList) { if (method.getParameterCount() == 0) { return method; } } throw new TypeError(); } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { Object self; Object[] args; for (Method method : methodList) { if (Modifier.isStatic(method.getModifiers())) { if (method.getParameterCount() != positionalArguments.size()) { continue; } self = null; try { args = unwrapPrimitiveArguments(method, positionalArguments); } catch (TypeError e) { continue; } } else { if (method.getParameterCount() + 1 != positionalArguments.size()) { continue; } self = positionalArguments.get(0); if (self instanceof JavaObjectWrapper) { // unwrap wrapped Java Objects self = ((JavaObjectWrapper) self).getWrappedObject(); } try { args = unwrapPrimitiveArguments(method, positionalArguments.subList(1, positionalArguments.size())); } catch (TypeError e) { continue; } } try { return JavaPythonTypeConversionImplementor.wrapJavaObject(method.invoke(self, args)); } catch (IllegalAccessException e) { throw new IllegalStateException("Method (" + method + ") is not accessible.", e); } catch (InvocationTargetException e) { throw (RuntimeException) e.getCause(); } } throw new TypeError("No method with matching signature found for %s in method list %s.".formatted(positionalArguments, methodList)); } private Object[] unwrapPrimitiveArguments(Method method, List<PythonLikeObject> positionalArguments) { Object[] out = new Object[method.getParameterCount()]; Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < positionalArguments.size(); i++) { PythonLikeObject argument = positionalArguments.get(i); out[i] = JavaPythonTypeConversionImplementor.convertPythonObjectToJavaType(parameterTypes[i], argument); } return out; } @Override public PythonLikeType $getType() { if (Modifier.isStatic(methodList.get(0).getModifiers())) { return BuiltinTypes.STATIC_FUNCTION_TYPE; } else { return BuiltinTypes.FUNCTION_TYPE; } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/wrappers/OpaqueJavaReference.java
package ai.timefold.jpyinterpreter.types.wrappers; import ai.timefold.jpyinterpreter.PythonLikeObject; /** * An interface used to indicate a Java Object * should not be interacted with directly and should * be proxied (even if it implements {@link PythonLikeObject}). */ public interface OpaqueJavaReference { /** * Creates a proxy of the OpaqueJavaReference, which * can be interacted with directly. */ PythonLikeObject proxy(); }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/wrappers/OpaquePythonReference.java
package ai.timefold.jpyinterpreter.types.wrappers; /** * An OpaquePythonReference represents an * arbitrary Python Object. No methods * should ever be called on it, including * hashCode and equals. To operate on * the Object, pass it to a Python function. */ public interface OpaquePythonReference { // intentionally empty }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/wrappers/PythonLikeFunctionWrapper.java
package ai.timefold.jpyinterpreter.types.wrappers; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; /** * A class used as a delegator to another PythonLikeFunction. * Used to handle recursion correctly when translating functions. */ public final class PythonLikeFunctionWrapper implements PythonLikeFunction { PythonLikeFunction wrapped; public PythonLikeFunctionWrapper() { this.wrapped = null; } public PythonLikeFunction getWrapped() { return wrapped; } public void setWrapped(PythonLikeFunction wrapped) { this.wrapped = wrapped; } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { return wrapped.$call(positionalArguments, namedArguments, callerInstance); } public PythonLikeObject $getAttributeOrNull(String attributeName) { return wrapped.$getAttributeOrNull(attributeName); } public PythonLikeObject $getAttributeOrError(String attributeName) { return wrapped.$getAttributeOrError(attributeName); } public void $setAttribute(String attributeName, PythonLikeObject value) { wrapped.$setAttribute(attributeName, value); } public void $deleteAttribute(String attributeName) { wrapped.$deleteAttribute(attributeName); } public PythonLikeType $getType() { return wrapped.$getType(); } public PythonLikeObject $method$__getattribute__(PythonString pythonName) { return wrapped.$method$__getattribute__(pythonName); } public PythonLikeObject $method$__setattr__(PythonString pythonName, PythonLikeObject value) { return wrapped.$method$__setattr__(pythonName, value); } public PythonLikeObject $method$__delattr__(PythonString pythonName) { return wrapped.$method$__delattr__(pythonName); } public PythonLikeObject $method$__eq__(PythonLikeObject other) { return wrapped.$method$__eq__(other); } public PythonLikeObject $method$__ne__(PythonLikeObject other) { return wrapped.$method$__ne__(other); } public PythonString $method$__str__() { return wrapped.$method$__str__(); } public PythonLikeObject $method$__repr__() { return wrapped.$method$__repr__(); } public PythonLikeObject $method$__format__() { return wrapped.$method$__format__(); } public PythonLikeObject $method$__format__(PythonLikeObject formatString) { return wrapped.$method$__format__(formatString); } public PythonLikeObject $method$__hash__() { return wrapped.$method$__hash__(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/wrappers/PythonObjectWrapper.java
package ai.timefold.jpyinterpreter.types.wrappers; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.CPythonBackedPythonInterpreter; import ai.timefold.jpyinterpreter.PythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.CPythonBackedPythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonIterator; import ai.timefold.jpyinterpreter.types.errors.NotImplementedError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; public class PythonObjectWrapper extends CPythonBackedPythonLikeObject implements PythonLikeObject, PythonLikeFunction, PythonIterator<PythonLikeObject>, Comparable<PythonObjectWrapper> { private final static PythonLikeType PYTHON_REFERENCE_TYPE = new PythonLikeType("python-reference", PythonObjectWrapper.class), $TYPE = PYTHON_REFERENCE_TYPE; private final Map<String, PythonLikeObject> cachedAttributeMap; private PythonLikeObject cachedNext = null; public PythonObjectWrapper(OpaquePythonReference pythonReference) { super(PythonInterpreter.DEFAULT, CPythonType.lookupTypeOfPythonObject(pythonReference), pythonReference); cachedAttributeMap = new HashMap<>(); } public OpaquePythonReference getWrappedObject() { return $cpythonReference; } @Override public PythonLikeObject $getAttributeOrNull(String attributeName) { return cachedAttributeMap.computeIfAbsent(attributeName, key -> CPythonBackedPythonInterpreter.lookupAttributeOnPythonReference($cpythonReference, attributeName, $instanceMap)); } @Override public void $setAttribute(String attributeName, PythonLikeObject value) { cachedAttributeMap.put(attributeName, value); CPythonBackedPythonInterpreter.setAttributeOnPythonReference($cpythonReference, null, attributeName, value); } @Override public void $deleteAttribute(String attributeName) { cachedAttributeMap.remove(attributeName); CPythonBackedPythonInterpreter.deleteAttributeOnPythonReference($cpythonReference, attributeName); } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { return CPythonBackedPythonInterpreter.callPythonReference($cpythonReference, positionalArguments, namedArguments); } @Override public int compareTo(PythonObjectWrapper other) { if (equals(other)) { return 0; } PythonLikeFunction lessThan = (PythonLikeFunction) $getType().$getAttributeOrError("__lt__"); PythonLikeObject result = lessThan.$call(List.of(this, other), Map.of(), null); if (result instanceof PythonBoolean) { if (((PythonBoolean) result).getBooleanValue()) { return -1; } else { return 1; } } else { throw new NotImplementedError("Cannot compare " + this.$getType().getTypeName() + " with " + other.$getType().getTypeName()); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PythonObjectWrapper other)) { return false; } Object maybeEquals = $getType().$getAttributeOrNull("__eq__"); if (!(maybeEquals instanceof PythonLikeFunction equals)) { return super.equals(o); } PythonLikeObject result = equals.$call(List.of(this, other), Map.of(), null); if (result instanceof PythonBoolean) { return ((PythonBoolean) result).getBooleanValue(); } return false; } @Override public int hashCode() { Object maybeHash = $getType().$getAttributeOrNull("__hash__"); if (!(maybeHash instanceof PythonLikeFunction hash)) { return super.hashCode(); } PythonLikeObject result = hash.$call(List.of(this), Map.of(), null); if (result instanceof PythonInteger) { return ((PythonInteger) result).value.hashCode(); } else { return System.identityHashCode(this); } } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(hashCode()); } @Override public String toString() { Object maybeStr = $getType().$getAttributeOrNull("__str__"); if (!(maybeStr instanceof PythonLikeFunction)) { return super.toString(); } PythonLikeFunction str = (PythonLikeFunction) maybeStr; PythonLikeObject result = str.$call(List.of(this), Map.of(), null); return result.toString(); } @Override public PythonLikeObject nextPythonItem() { if (cachedNext != null) { var out = cachedNext; cachedNext = null; return out; } return UnaryDunderBuiltin.NEXT.invoke(this); } @Override public PythonIterator<PythonLikeObject> getIterator() { return (PythonIterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(this); } @Override public boolean hasNext() { if (cachedNext != null) { return true; } try { cachedNext = nextPythonItem(); return true; } catch (Exception e) { return false; } } @Override public PythonLikeObject next() { return nextPythonItem(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/wrappers/WrappingJavaObjectIterator.java
package ai.timefold.jpyinterpreter.types.wrappers; import java.util.Iterator; record WrappingJavaObjectIterator(Iterator<?> delegate) implements Iterator<JavaObjectWrapper> { @Override public boolean hasNext() { return delegate.hasNext(); } @Override public JavaObjectWrapper next() { return new JavaObjectWrapper(delegate.next()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/ByteCharSequence.java
package ai.timefold.jpyinterpreter.util; public final class ByteCharSequence implements CharSequence { private final byte[] data; private final int inclusiveStartIndex; private final int exclusiveEndIndex; public ByteCharSequence(byte[] data) { this.data = data; this.inclusiveStartIndex = 0; this.exclusiveEndIndex = data.length; } public ByteCharSequence(byte[] data, int inclusiveStartIndex, int exclusiveEndIndex) { this.data = data; this.inclusiveStartIndex = inclusiveStartIndex; this.exclusiveEndIndex = exclusiveEndIndex; } @Override public int length() { return exclusiveEndIndex - inclusiveStartIndex; } @Override public char charAt(int i) { return (char) (data[inclusiveStartIndex + i] & 0xFF); } @Override public ByteCharSequence subSequence(int from, int to) { return new ByteCharSequence(data, inclusiveStartIndex + from, inclusiveStartIndex + to); } @Override public String toString() { char[] chars = new char[length()]; for (int i = 0; i < length(); i++) { chars[i] = charAt(i); } return String.valueOf(chars); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/ConcurrentWeakIdentityHashMap.java
package ai.timefold.jpyinterpreter.util; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Source: <a href= * "https://github.com/spring-projects/spring-loaded/blob/be39be1624c50b83741c0add3213ff02d23c6fd5/springloaded/src/main/java/org/springsource/loaded/support/ConcurrentWeakIdentityHashMap.java">Spring * Loaded ConcurrentWeakIdentityHashMap</a> */ public class ConcurrentWeakIdentityHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> { private final ConcurrentMap<Key<K>, V> map; private final ReferenceQueue<K> queue = new ReferenceQueue<>(); private transient Set<Map.Entry<K, V>> entry; public ConcurrentWeakIdentityHashMap(int initialCapacity) { this.map = new ConcurrentHashMap<>(initialCapacity); } public ConcurrentWeakIdentityHashMap() { this.map = new ConcurrentHashMap<>(); } @Override public V get(Object key) { purgeKeys(); return map.get(new Key<>(key, null)); } @Override public V put(K key, V value) { purgeKeys(); return map.put(new Key<>(key, queue), value); } @Override public int size() { purgeKeys(); return map.size(); } private void purgeKeys() { Reference<? extends K> reference; while ((reference = queue.poll()) != null) { map.remove(reference); } } @Override public Set<Map.Entry<K, V>> entrySet() { Set<Map.Entry<K, V>> entrySet; return ((entrySet = this.entry) == null) ? entry = new EntrySet() : entrySet; } @Override public V putIfAbsent(K key, V value) { purgeKeys(); return map.putIfAbsent(new Key<>(key, queue), value); } @Override public V remove(Object key) { return map.remove(new Key<>(key, null)); } @Override public boolean remove(Object key, Object value) { purgeKeys(); return map.remove(new Key<>(key, null), value); } @Override public boolean replace(K key, V oldValue, V newValue) { purgeKeys(); return map.replace(new Key<>(key, null), oldValue, newValue); } @Override public V replace(K key, V value) { purgeKeys(); return map.replace(new Key<>(key, null), value); } @Override public boolean containsKey(Object key) { purgeKeys(); return map.containsKey(new Key<>(key, null)); } @Override public void clear() { while (queue.poll() != null) ; map.clear(); } @Override public boolean containsValue(Object value) { purgeKeys(); return map.containsValue(value); } private static class Key<T> extends WeakReference<T> { private final int hash; Key(T t, ReferenceQueue<T> queue) { super(t, queue); if (t == null) { throw new NullPointerException(); } else { hash = System.identityHashCode(t); } } @Override public boolean equals(Object o) { return this == o || o instanceof Key<?> other && other.get() == get(); } @Override public int hashCode() { return hash; } } private class Iter implements Iterator<Map.Entry<K, V>> { private final Iterator<Map.Entry<Key<K>, V>> it; private Map.Entry<K, V> nextValue; Iter(Iterator<Map.Entry<Key<K>, V>> it) { this.it = it; } @Override public boolean hasNext() { if (nextValue != null) { return true; } while (it.hasNext()) { Map.Entry<Key<K>, V> entry = it.next(); K key = entry.getKey().get(); if (key != null) { nextValue = new Entry(key, entry.getValue()); return true; } else { it.remove(); } } return false; } @Override public Map.Entry<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } Map.Entry<K, V> entry = nextValue; nextValue = null; return entry; } @Override public void remove() { it.remove(); nextValue = null; } } private class EntrySet extends AbstractSet<Map.Entry<K, V>> { @Override public Iterator<Map.Entry<K, V>> iterator() { return new Iter(map.entrySet().iterator()); } @Override public int size() { return ConcurrentWeakIdentityHashMap.this.size(); } @Override public void clear() { ConcurrentWeakIdentityHashMap.this.clear(); } @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry<?, ?> e)) { return false; } return ConcurrentWeakIdentityHashMap.this.get(e.getKey()) == e.getValue(); } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry<?, ?> e)) { return false; } return ConcurrentWeakIdentityHashMap.this.remove(e.getKey(), e.getValue()); } } private class Entry extends AbstractMap.SimpleEntry<K, V> { Entry(K key, V value) { super(key, value); } @Override public V setValue(V value) { ConcurrentWeakIdentityHashMap.this.put(getKey(), value); return super.setValue(value); } @Override public boolean equals(Object obj) { if (obj instanceof Map.Entry<?, ?> e) { return getKey() == e.getKey() && getValue() == e.getValue(); } return false; } @Override public int hashCode() { return System.identityHashCode(getKey()) ^ System.identityHashCode(getValue()); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/CopyOnWriteMap.java
package ai.timefold.jpyinterpreter.util; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; public class CopyOnWriteMap<Key_, Value_> implements Map<Key_, Value_> { private final Map<Key_, Value_> immutableMap; private Optional<Map<Key_, Value_>> modifiedMap; public CopyOnWriteMap(Map<Key_, Value_> immutableMap) { this.immutableMap = immutableMap; this.modifiedMap = Optional.empty(); } // Read Operations @Override public int size() { return modifiedMap.map(Map::size).orElseGet(immutableMap::size); } @Override public boolean isEmpty() { return modifiedMap.map(Map::isEmpty).orElseGet(immutableMap::isEmpty); } @Override public boolean containsKey(Object o) { return modifiedMap.map(map -> map.containsKey(o)).orElseGet(() -> immutableMap.containsKey(o)); } @Override public boolean containsValue(Object o) { return modifiedMap.map(map -> map.containsValue(o)).orElseGet(() -> immutableMap.containsValue(o)); } @Override public Value_ get(Object o) { return modifiedMap.map(map -> map.get(o)).orElseGet(() -> immutableMap.get(o)); } @Override public Set<Key_> keySet() { return modifiedMap.map(Map::keySet).orElseGet(immutableMap::keySet); } @Override public Collection<Value_> values() { return modifiedMap.map(Map::values).orElseGet(immutableMap::values); } @Override public Set<Entry<Key_, Value_>> entrySet() { return modifiedMap.map(Map::entrySet).orElseGet(immutableMap::entrySet); } // Write Operations @Override public Value_ put(Key_ key, Value_ value) { if (modifiedMap.isEmpty()) { modifiedMap = Optional.of(new HashMap<>(immutableMap)); } return modifiedMap.get().put(key, value); } @Override public Value_ remove(Object o) { if (modifiedMap.isEmpty()) { modifiedMap = Optional.of(new HashMap<>(immutableMap)); } return modifiedMap.get().remove(o); } @Override public void putAll(Map<? extends Key_, ? extends Value_> map) { if (modifiedMap.isEmpty()) { modifiedMap = Optional.of(new HashMap<>(immutableMap)); } modifiedMap.get().putAll(map); } @Override public void clear() { if (modifiedMap.isEmpty()) { modifiedMap = Optional.of(new HashMap<>(immutableMap)); } modifiedMap.get().clear(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/DefaultFormatSpec.java
package ai.timefold.jpyinterpreter.util; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.ValueError; public class DefaultFormatSpec { final static String FILL = "(?<fill>.)?"; final static String ALIGN = "(?:" + FILL + "(?<align>[<>=^]))?"; final static String SIGN = "(?<sign>[+\\- ])?"; final static String ALTERNATE_FORM = "(?<alternateForm>#)?"; final static String SIGN_AWARE_ZERO_FILL = "(?<signAwareZeroFill>0)?"; final static String WIDTH = "(?<width>\\d+)?"; final static String GROUPING_OPTION = "(?<groupingOption>[_,])?"; final static String PRECISION = "(?:\\.(?<precision>\\d+))?"; final static String TYPE = "(?<type>[bcdeEfFgGnosxX%])?"; final static String DEFAULT_FORMAT_SPEC = ALIGN + SIGN + ALTERNATE_FORM + SIGN_AWARE_ZERO_FILL + WIDTH + GROUPING_OPTION + PRECISION + TYPE; final static Pattern DEFAULT_FORMAT_SPEC_PATTERN = Pattern.compile(DEFAULT_FORMAT_SPEC); /** * The character to use for padding */ public final String fillCharacter; /** * If true, modify the displayed output for some {@link ConversionType} */ public final boolean useAlternateForm; /** * How padding should be applied to fill width */ public final Optional<AlignmentOption> alignment; public final Optional<SignOption> signOption; /** * The minimum space the output should satisfy */ public final Optional<Integer> width; /** * What to use for the thousands' seperator */ public final Optional<GroupingOption> groupingOption; /** * How many significant digits for floating point numbers. For strings, the * maximum space the output should satisfy. Not allowed for int types. */ public final Optional<Integer> precision; /** * How the value should be displayed */ public final Optional<ConversionType> conversionType; private DefaultFormatSpec(String fillCharacter, boolean useAlternateForm, Optional<AlignmentOption> alignment, Optional<SignOption> signOption, Optional<Integer> width, Optional<GroupingOption> groupingOption, Optional<Integer> precision, Optional<ConversionType> conversionType) { this.fillCharacter = fillCharacter; this.useAlternateForm = useAlternateForm; this.alignment = alignment; this.signOption = signOption; this.width = width; this.groupingOption = groupingOption; this.precision = precision; this.conversionType = conversionType; } public static DefaultFormatSpec fromSpec(PythonString formatSpec) { Matcher matcher = DEFAULT_FORMAT_SPEC_PATTERN.matcher(formatSpec.value); if (!matcher.matches()) { throw new ValueError("Invalid format spec: " + formatSpec.value); } Optional<String> signAwareZeroFill = Optional.ofNullable(matcher.group("signAwareZeroFill")); return new DefaultFormatSpec( Optional.ofNullable(matcher.group("fill")).or(() -> signAwareZeroFill).orElse(" "), Optional.ofNullable(matcher.group("alternateForm")).isPresent(), Optional.ofNullable(matcher.group("align")).map(AlignmentOption::fromString) .or(() -> signAwareZeroFill.map(ignored -> AlignmentOption.RESPECT_SIGN_RIGHT_ALIGN)), Optional.ofNullable(matcher.group("sign")).map(SignOption::fromString), Optional.ofNullable(matcher.group("width")).map(Integer::parseInt), Optional.ofNullable(matcher.group("groupingOption")).map(GroupingOption::fromString), Optional.ofNullable(matcher.group("precision")).map(Integer::parseInt), Optional.ofNullable(matcher.group("type")).map(ConversionType::fromString)); } /** * For use by {@link PythonString}, where since Python 3.10, 0 before width do not affect default alignment * of strings. */ public static DefaultFormatSpec fromStringSpec(PythonString formatSpec) { Matcher matcher = DEFAULT_FORMAT_SPEC_PATTERN.matcher(formatSpec.value); if (!matcher.matches()) { throw new ValueError("Invalid format spec: " + formatSpec.value); } Optional<String> signAwareZeroFill = Optional.ofNullable(matcher.group("signAwareZeroFill")); return new DefaultFormatSpec( Optional.ofNullable(matcher.group("fill")).or(() -> signAwareZeroFill).orElse(" "), Optional.ofNullable(matcher.group("alternateForm")).isPresent(), Optional.ofNullable(matcher.group("align")).map(AlignmentOption::fromString), Optional.ofNullable(matcher.group("sign")).map(SignOption::fromString), Optional.ofNullable(matcher.group("width")).map(Integer::parseInt), Optional.ofNullable(matcher.group("groupingOption")).map(GroupingOption::fromString), Optional.ofNullable(matcher.group("precision")).map(Integer::parseInt), Optional.ofNullable(matcher.group("type")).map(ConversionType::fromString)); } public int getPrecisionOrDefault() { return precision.orElse(6); } public enum AlignmentOption { /** * Forces the field to be left-aligned within the available space (this is the default for most objects). */ LEFT_ALIGN("<"), /** * Forces the field to be right-aligned within the available space (this is the default for numbers). */ RIGHT_ALIGN(">"), /** * Forces the padding to be placed after the sign (if any) but before the digits. * This is used for printing fields in the form ‘+000000120’. * This alignment option is only valid for numeric types. * It becomes the default for numbers when ‘0’ immediately precedes the field width. */ RESPECT_SIGN_RIGHT_ALIGN("="), /** * Forces the field to be centered within the available space. */ CENTER_ALIGN("^"); final String matchCharacter; AlignmentOption(String matchCharacter) { this.matchCharacter = matchCharacter; } public static AlignmentOption fromString(String text) { for (AlignmentOption alignmentOption : AlignmentOption.values()) { if (alignmentOption.matchCharacter.equals(text)) { return alignmentOption; } } throw new IllegalArgumentException("\"" + text + "\" does not match any alignment option"); } } public enum SignOption { ALWAYS_SIGN("+"), ONLY_NEGATIVE_NUMBERS("-"), SPACE_FOR_POSITIVE_NUMBERS(" "); final String matchCharacter; SignOption(String matchCharacter) { this.matchCharacter = matchCharacter; } public static SignOption fromString(String text) { for (SignOption signOption : SignOption.values()) { if (signOption.matchCharacter.equals(text)) { return signOption; } } throw new IllegalArgumentException("\"" + text + "\" does not match any sign option"); } } public enum GroupingOption { /** * Signals the use of a comma for the thousands' separator. */ COMMA(","), /** * Signals the use of an underscore for the thousands' separator. */ UNDERSCORE("_"); final String matchCharacter; GroupingOption(String matchCharacter) { this.matchCharacter = matchCharacter; } public static GroupingOption fromString(String text) { for (GroupingOption groupingOption : GroupingOption.values()) { if (groupingOption.matchCharacter.equals(text)) { return groupingOption; } } throw new IllegalArgumentException("\"" + text + "\" does not match any grouping option"); } } public enum ConversionType { // String /** * (string) String format. This is the default type for strings and may be omitted. */ STRING("s"), // Integer /** * (int) Binary format. Outputs the number in base 2. */ BINARY("b"), /** * (int) Character. Converts the integer to the corresponding unicode character before printing. */ CHARACTER("c"), /** * (int) Decimal Integer. Outputs the number in base 10. */ DECIMAL("d"), /** * (int) Octal format. Outputs the number in base 8. */ OCTAL("o"), /** * (int) Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. */ LOWERCASE_HEX("x"), /** * (int) Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. * In case '#' is specified, the prefix '0x' will be upper-cased to '0X' as well. */ UPPERCASE_HEX("X"), // Float /** * (float) Scientific notation. For a given precision p, * formats the number in scientific notation with the letter ‘e’ separating the coefficient from the exponent. * The coefficient has one digit before and p digits after the decimal point, for a total of p + 1 significant digits. * With no precision given, uses a precision of 6 digits after the decimal point for float, * and shows all coefficient digits for Decimal. If no digits follow the decimal point, * the decimal point is also removed unless the # option is used. */ LOWERCASE_SCIENTIFIC_NOTATION("e"), /** * (float) Same as {@link #LOWERCASE_SCIENTIFIC_NOTATION} except it uses an upper case ‘E’ as the separator character. */ UPPERCASE_SCIENTIFIC_NOTATION("E"), /** * (float) Fixed-point notation. For a given precision p, formats the number as a decimal number * with exactly p digits following the decimal point. With no precision given, * uses a precision of 6 digits after the decimal point for float, and uses a precision large enough to show * all coefficient digits for Decimal. If no digits follow the decimal point, the decimal point is also removed * unless the # option is used. */ LOWERCASE_FIXED_POINT("f"), /** * (float) Same as {@link #LOWERCASE_FIXED_POINT} but converts "nan" to "NAN" and "inf" to "INF" */ UPPERCASE_FIXED_POINT("F"), /** * (float) General format. For a given precision p >= 1, this rounds the number to p significant digits and then * formats the result in either fixed-point format or in scientific notation, depending on its magnitude. * A precision of 0 is treated as equivalent to a precision of 1. * * The precise rules are as follows: * suppose that the result formatted with presentation type {@link #LOWERCASE_SCIENTIFIC_NOTATION} * and precision p-1 would have exponent exp. * Then, if m &le; exp &lt; p, where m is -4 for floats and -6 for Decimals, * the number is formatted with presentation type 'f'and precision p-1-exp. * Otherwise, the number is formatted with presentation type 'e' and precision p-1. * In both cases insignificant trailing zeros are removed from the significand, * and the decimal point is also removed if there are no remaining digits following it, * unless the '#' option is used. * * With no precision given, uses a precision of 6 significant digits for float. * For Decimal, the coefficient of the result is formed from the coefficient digits of the value; * scientific notation is used for values smaller than 1e-6 in absolute value and values where * the place value of the least significant digit is larger than 1, and fixed-point notation is used otherwise. * * Positive and negative infinity, positive and negative zero, and nans, are formatted as * inf, -inf, 0, -0 and nan respectively, regardless of the precision. */ LOWERCASE_GENERAL("g"), /** * (float) Same as {@link #LOWERCASE_GENERAL}, except switches to {#UPPERCASE_SCIENTIFIC_NOTATION} if the number gets * too large. * The representations of infinity and NaN are uppercased, too. */ UPPERCASE_GENERAL("G"), /** * (int, float) Locale sensitive number output. For integers, same as {@link #DECIMAL} but it will use the * current locale's number seperator. For floats, same as {@link #LOWERCASE_GENERAL}, * except that when fixed-point notation is used to format the result, * it always includes at least one digit past the decimal point. * The precision used is as large as needed to represent the given value faithfully. */ LOCALE_SENSITIVE("n"), /** * (float) Percentage. Multiplies the number by 100 and displays in {@link #LOWERCASE_FIXED_POINT} format, * followed by a percent sign. */ PERCENTAGE("%"); final String matchCharacter; ConversionType(String matchCharacter) { this.matchCharacter = matchCharacter; } public static ConversionType fromString(String text) { for (ConversionType conversionType : ConversionType.values()) { if (conversionType.matchCharacter.equals(text)) { return conversionType; } } throw new IllegalArgumentException("\"" + text + "\" does not match any conversion type"); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/HandlerSorterAdapter.java
package ai.timefold.jpyinterpreter.util; import java.util.Collections; import java.util.Comparator; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TryCatchBlockNode; // Taken from https://gist.github.com/sampsyo/281277 /** * Sorts the exception handlers in a method innermost-to-outermost. This * allows the programmer to add handlers without worrying about ordering them * correctly with respect to existing, in-code handlers. * * Behavior is only defined for properly-nested handlers. If any "try" blocks * overlap (something that isn't possible in Java code) then this may not * do what you want. */ public class HandlerSorterAdapter extends MethodNode { private final MethodVisitor mv; public HandlerSorterAdapter( final MethodVisitor mv, final int api, final int access, final String name, final String desc, final String signature, final String[] exceptions) { super(api, access, name, desc, signature, exceptions); this.mv = mv; } public void visitEnd() { TryCatchBlockLengthComparator comp = new TryCatchBlockLengthComparator(this); Collections.sort(tryCatchBlocks, comp); if (mv != null) { accept(mv); } } /** * Compares TryCatchBlockNodes by the length of their "try" block. */ static class TryCatchBlockLengthComparator implements Comparator { private final MethodNode meth; public TryCatchBlockLengthComparator(MethodNode meth) { this.meth = meth; } public int compare(Object o1, Object o2) { int len1 = blockLength((TryCatchBlockNode) o1); int len2 = blockLength((TryCatchBlockNode) o2); return len1 - len2; } private int blockLength(TryCatchBlockNode block) { int startidx = meth.instructions.indexOf(block.start); int endidx = meth.instructions.indexOf(block.end); return endidx - startidx; } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/IteratorUtils.java
package ai.timefold.jpyinterpreter.util; import java.util.Iterator; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonLikeObject; public class IteratorUtils { public static <Mapped_> Iterator<PythonLikeObject> iteratorMap(final Iterator<Mapped_> source, final Function<Mapped_, PythonLikeObject> mapFunction) { return new Iterator<PythonLikeObject>() { @Override public boolean hasNext() { return source.hasNext(); } @Override public PythonLikeObject next() { return mapFunction.apply(source.next()); } }; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/JavaIdentifierUtils.java
package ai.timefold.jpyinterpreter.util; import java.util.Set; public class JavaIdentifierUtils { private static final Set<String> JAVA_KEYWORD_SET = Set.of( "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", "while"); private JavaIdentifierUtils() { } public static String sanitizeClassName(String pythonClassName) { StringBuilder builder = new StringBuilder(); pythonClassName.chars().forEachOrdered(character -> { if (character != '.' && !Character.isJavaIdentifierPart(character)) { String replacement = "$_" + character + "_$"; builder.append(replacement); } else { builder.appendCodePoint(character); } }); String out = builder.toString(); if (JAVA_KEYWORD_SET.contains(out)) { return "$" + out; } else { return out; } } public static String sanitizeFieldName(String pythonFieldName) { StringBuilder builder = new StringBuilder(); pythonFieldName.chars().forEachOrdered(character -> { if (!Character.isJavaIdentifierPart(character)) { String replacement = "$_" + character + "_$"; builder.append(replacement); } else { builder.appendCodePoint(character); } }); String out = builder.toString(); if (JAVA_KEYWORD_SET.contains(out)) { return "$" + out; } else if (pythonFieldName.isEmpty()) { return "$$"; } else if (Character.isDigit(pythonFieldName.charAt(0))) { return "$" + out; } else { return out; } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/JavaPythonClassWriter.java
package ai.timefold.jpyinterpreter.util; import java.util.Objects; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Type; /** * A ClassWriter with a custom getCommonSuperClass, preventing * TypeNotPresent errors when computing frames. */ public class JavaPythonClassWriter extends ClassWriter { public JavaPythonClassWriter(int flags) { super(flags); } @Override protected String getCommonSuperClass(String type1, String type2) { if (Objects.equals(type1, type2)) { return type1; } try { return super.getCommonSuperClass(type1, type2); } catch (TypeNotPresentException e) { return Type.getInternalName(Object.class); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/JavaStringMapMirror.java
package ai.timefold.jpyinterpreter.util; import java.util.Collection; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonString; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; public class JavaStringMapMirror implements OrderedMap<PythonLikeObject, PythonLikeObject> { final Map<String, PythonLikeObject> delegate; public JavaStringMapMirror(Map<String, PythonLikeObject> delegate) { this.delegate = delegate; } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean containsKey(Object o) { return o instanceof PythonString && delegate.containsKey(((PythonString) o).value); } @Override public boolean containsValue(Object o) { return delegate.containsValue(o); } @Override public PythonLikeObject get(Object o) { if (o instanceof PythonString) { return delegate.get(((PythonString) o).value); } return null; } @Override public PythonLikeObject put(PythonLikeObject key, PythonLikeObject value) { if (key instanceof PythonString) { return delegate.put(((PythonString) key).value, value); } else { throw new IllegalArgumentException(); } } @Override public PythonLikeObject remove(Object o) { if (o instanceof PythonString) { return delegate.remove(((PythonString) o).value); } return delegate.remove(o); } @Override public void putAll(Map<? extends PythonLikeObject, ? extends PythonLikeObject> map) { map.forEach(this::put); } @Override public void clear() { delegate.clear(); } @Override public Set<PythonLikeObject> keySet() { return delegate.keySet().stream().map(PythonString::valueOf).collect(Collectors.toSet()); } @Override public Collection<PythonLikeObject> values() { return delegate.values(); } @Override public Set<Entry<PythonLikeObject, PythonLikeObject>> entrySet() { return delegate.entrySet().stream().map(entry -> new Entry<PythonLikeObject, PythonLikeObject>() { @Override public PythonLikeObject getKey() { return PythonString.valueOf(entry.getKey()); } @Override public PythonLikeObject getValue() { return entry.getValue(); } @Override public PythonLikeObject setValue(PythonLikeObject o) { return entry.setValue(o); } }).collect(Collectors.toSet()); } @Override public OrderedMapIterator<PythonLikeObject, PythonLikeObject> mapIterator() { throw new UnsupportedOperationException("mapIterator is not supported"); } @Override public PythonLikeObject firstKey() { if (delegate.isEmpty()) { throw new NoSuchElementException("Map is empty"); } return PythonString.valueOf(delegate.keySet().iterator().next()); } @Override public PythonLikeObject lastKey() { if (delegate.isEmpty()) { throw new NoSuchElementException("Map is empty"); } String lastKey = null; for (String key : delegate.keySet()) { lastKey = key; } return PythonString.valueOf(lastKey); } @Override public PythonLikeObject nextKey(PythonLikeObject object) { boolean returnNextKey = false; for (String key : delegate.keySet()) { if (key.equals(object.toString())) { returnNextKey = true; } if (returnNextKey) { return PythonString.valueOf(key); } } return null; } @Override public PythonLikeObject previousKey(PythonLikeObject object) { String previousKey = null; for (String key : delegate.keySet()) { if (key.equals(object.toString())) { return PythonString.valueOf(previousKey); } previousKey = key; } return null; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/JumpUtils.java
package ai.timefold.jpyinterpreter.util; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; public final class JumpUtils { private JumpUtils() { } public static int getInstructionIndexForByteOffset(int byteOffset, PythonVersion pythonVersion) { return byteOffset >> 1; } private static int parseArgRepr(PythonBytecodeInstruction instruction) { return Integer.parseInt(instruction.argRepr().substring(3)) / 2; } public static int getAbsoluteTarget(PythonBytecodeInstruction instruction, PythonVersion pythonVersion) { if (pythonVersion.isBefore(PythonVersion.PYTHON_3_12)) { return instruction.arg(); } else { return parseArgRepr(instruction); } } public static int getRelativeTarget(PythonBytecodeInstruction instruction, PythonVersion pythonVersion) { if (pythonVersion.isBefore(PythonVersion.PYTHON_3_12)) { return instruction.offset() + instruction.arg() + 1; } else { return parseArgRepr(instruction); } } public static int getBackwardRelativeTarget(PythonBytecodeInstruction instruction, PythonVersion pythonVersion) { if (pythonVersion.isBefore(PythonVersion.PYTHON_3_12)) { return instruction.offset() - instruction.arg() + 1; } else { return parseArgRepr(instruction); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/MethodVisitorAdapters.java
package ai.timefold.jpyinterpreter.util; import java.lang.reflect.Modifier; import java.util.HashMap; import ai.timefold.jpyinterpreter.MethodDescriptor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.util.CheckMethodAdapter; public class MethodVisitorAdapters { public static MethodVisitor adapt(MethodVisitor methodVisitor, MethodDescriptor method) { return adapt(methodVisitor, method.getMethodName(), method.getMethodDescriptor()); } public static MethodVisitor adapt(MethodVisitor methodVisitor, String name, String descriptor) { CheckMethodAdapter out = new CheckMethodAdapter(Modifier.PUBLIC, name, descriptor, new HandlerSorterAdapter(methodVisitor, Opcodes.ASM9, Modifier.PUBLIC, name, descriptor, null, null), new HashMap<>()); out.version = Opcodes.V11; return out; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/OverrideMethod.java
package ai.timefold.jpyinterpreter.util; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Marks a generated method as an override implementation. * Needed since {@link Override} is not retained at runtime. */ @Retention(RetentionPolicy.RUNTIME) public @interface OverrideMethod { }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/PythonGlobalsBackedMap.java
package ai.timefold.jpyinterpreter.util; import java.util.HashMap; import ai.timefold.jpyinterpreter.PythonLikeObject; public class PythonGlobalsBackedMap extends HashMap<String, PythonLikeObject> { private final long pythonGlobalsId; public PythonGlobalsBackedMap(long pythonGlobalsId) { this.pythonGlobalsId = pythonGlobalsId; } public long getPythonGlobalsId() { return pythonGlobalsId; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/StringFormatter.java
package ai.timefold.jpyinterpreter.util; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.builtins.BinaryDunderBuiltin; import ai.timefold.jpyinterpreter.builtins.GlobalBuiltins; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.PythonByteArray; import ai.timefold.jpyinterpreter.types.PythonBytes; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.lookup.KeyError; import ai.timefold.jpyinterpreter.types.numeric.PythonFloat; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; public class StringFormatter { final static String IDENTIFIER = "(?:(?:\\p{javaUnicodeIdentifierStart}|_)\\p{javaUnicodeIdentifierPart}*)"; final static String ARG_NAME = "(?<argName>" + IDENTIFIER + "|\\d+)?"; final static String ATTRIBUTE_NAME = IDENTIFIER; final static String ELEMENT_INDEX = "[^]]+"; final static String ITEM_NAME = "(?:(?:\\." + ATTRIBUTE_NAME + ")|(?:\\[" + ELEMENT_INDEX + "\\]))"; final static String FIELD_NAME = "(?<fieldName>" + ARG_NAME + "(" + ITEM_NAME + ")*)?"; final static String CONVERSION = "(?:!(?<conversion>[rsa]))?"; final static String FORMAT_SPEC = "(?::(?<formatSpec>[^{}]*))?"; final static Pattern REPLACEMENT_FIELD_PATTERN = Pattern.compile("\\{" + FIELD_NAME + CONVERSION + FORMAT_SPEC + "}|(?<literal>\\{\\{|}})"); final static Pattern INDEX_CHAIN_PART_PATTERN = Pattern.compile(ITEM_NAME); /** * Pattern that matches conversion specifiers for the "%" operator. See * <a href="https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting"> * Python printf-style String Formatting documentation</a> for details. */ private final static Pattern PRINTF_FORMAT_REGEX = Pattern.compile("%(?:(?<key>\\([^()]+\\))?" + "(?<flags>[#0\\-+ ]*)?" + "(?<minWidth>\\*|\\d+)?" + "(?<precision>\\.(?:\\*|\\d+))?" + "[hlL]?" + // ignored length modifier "(?<type>[diouxXeEfFgGcrsa%])|.*)"); private enum PrintfConversionType { SIGNED_INTEGER_DECIMAL("d", "i", "u"), SIGNED_INTEGER_OCTAL("o"), SIGNED_HEXADECIMAL_LOWERCASE("x"), SIGNED_HEXADECIMAL_UPPERCASE("X"), FLOATING_POINT_EXPONENTIAL_LOWERCASE("e"), FLOATING_POINT_EXPONENTIAL_UPPERCASE("E"), FLOATING_POINT_DECIMAL("f", "F"), FLOATING_POINT_DECIMAL_OR_EXPONENTIAL_LOWERCASE("g"), FLOATING_POINT_DECIMAL_OR_EXPONENTIAL_UPPERCASE("G"), SINGLE_CHARACTER("c"), REPR_STRING("r"), STR_STRING("s"), ASCII_STRING("a"), LITERAL_PERCENT("%"); final String[] matchedCharacters; PrintfConversionType(String... matchedCharacters) { this.matchedCharacters = matchedCharacters; } public static PrintfConversionType getConversionType(Matcher matcher) { String conversion = matcher.group("type"); if (conversion == null) { throw new ValueError("Invalid specifier at position " + matcher.start() + " in string "); } for (PrintfConversionType conversionType : PrintfConversionType.values()) { for (String matchedCharacter : conversionType.matchedCharacters) { if (matchedCharacter.equals(conversion)) { return conversionType; } } } throw new IllegalStateException("Conversion (" + conversion + ") does not match any defined conversions"); } } public enum PrintfStringType { STRING, BYTES } public static String printfInterpolate(CharSequence value, List<PythonLikeObject> tuple, PrintfStringType stringType) { Matcher matcher = PRINTF_FORMAT_REGEX.matcher(value); StringBuilder out = new StringBuilder(); int start = 0; int currentElement = 0; while (matcher.find()) { out.append(value, start, matcher.start()); start = matcher.end(); String key = matcher.group("key"); if (key != null) { throw new TypeError("format requires a mapping"); } String flags = matcher.group("flags"); String minWidth = matcher.group("minWidth"); String precisionString = matcher.group("precision"); PrintfConversionType conversionType = PrintfConversionType.getConversionType(matcher); if (conversionType != PrintfConversionType.LITERAL_PERCENT) { if (tuple.size() <= currentElement) { throw new TypeError("not enough arguments for format string"); } PythonLikeObject toConvert = tuple.get(currentElement); currentElement++; if ("*".equals(minWidth)) { if (tuple.size() <= currentElement) { throw new TypeError("not enough arguments for format string"); } minWidth = ((PythonString) UnaryDunderBuiltin.STR.invoke(tuple.get(currentElement))).value; currentElement++; } if ("*".equals(precisionString)) { if (tuple.size() <= currentElement) { throw new TypeError("not enough arguments for format string"); } precisionString = ((PythonString) UnaryDunderBuiltin.STR.invoke(tuple.get(currentElement))).value; currentElement++; } Optional<Integer> maybePrecision, maybeWidth; if (precisionString != null) { maybePrecision = Optional.of(Integer.parseInt(precisionString.substring(1))); } else { maybePrecision = Optional.empty(); } if (minWidth != null) { maybeWidth = Optional.of(Integer.parseInt(minWidth)); } else { maybeWidth = Optional.empty(); } out.append(performInterpolateConversion(flags, maybeWidth, maybePrecision, conversionType, toConvert, stringType)); } else { out.append("%"); } } out.append(value.subSequence(start, value.length())); return out.toString(); } public static String printfInterpolate(CharSequence value, PythonLikeDict dict, PrintfStringType stringType) { Matcher matcher = PRINTF_FORMAT_REGEX.matcher(value); StringBuilder out = new StringBuilder(); int start = 0; while (matcher.find()) { out.append(value, start, matcher.start()); start = matcher.end(); PrintfConversionType conversionType = PrintfConversionType.getConversionType(matcher); if (conversionType != PrintfConversionType.LITERAL_PERCENT) { String key = matcher.group("key"); if (key == null) { throw new ValueError( "When a dict is used for the interpolation operator, all conversions must have parenthesised keys"); } key = key.substring(1, key.length() - 1); String flags = matcher.group("flags"); String minWidth = matcher.group("minWidth"); String precisionString = matcher.group("precision"); if ("*".equals(minWidth)) { throw new ValueError( "* cannot be used for minimum field width when a dict is used for the interpolation operator"); } if ("*".equals(precisionString)) { throw new ValueError("* cannot be used for precision when a dict is used for the interpolation operator"); } PythonLikeObject toConvert; if (stringType == PrintfStringType.STRING) { toConvert = dict.getItemOrError(PythonString.valueOf(key)); } else { toConvert = dict.getItemOrError(PythonString.valueOf(key).asAsciiBytes()); } Optional<Integer> maybePrecision, maybeWidth; if (precisionString != null) { maybePrecision = Optional.of(Integer.parseInt(precisionString.substring(1))); } else { maybePrecision = Optional.empty(); } if (minWidth != null) { maybeWidth = Optional.of(Integer.parseInt(minWidth)); } else { maybeWidth = Optional.empty(); } out.append(performInterpolateConversion(flags, maybeWidth, maybePrecision, conversionType, toConvert, stringType)); } else { out.append("%"); } } out.append(value.subSequence(start, value.length())); return out.toString(); } private static BigDecimal getBigDecimalWithPrecision(BigDecimal number, Optional<Integer> precision) { int currentScale = number.scale(); int currentPrecision = number.precision(); int precisionDelta = precision.orElse(6) - currentPrecision; return number.setScale(currentScale + precisionDelta, RoundingMode.HALF_EVEN); } private static String getUppercaseEngineeringString(BigDecimal number, Optional<Integer> precision) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(out); printStream.printf("%1." + (precision.orElse(6) - 1) + "E", number); return out.toString(); } private static String performInterpolateConversion(String flags, Optional<Integer> maybeWidth, Optional<Integer> maybePrecision, PrintfConversionType conversionType, PythonLikeObject toConvert, PrintfStringType stringType) { boolean useAlternateForm = flags.contains("#"); boolean isZeroPadded = flags.contains("0"); boolean isLeftAdjusted = flags.contains("-"); if (isLeftAdjusted) { isZeroPadded = false; } boolean putSpaceBeforePositiveNumber = flags.contains(" "); boolean putSignBeforeConversion = flags.contains("+"); if (putSignBeforeConversion) { putSpaceBeforePositiveNumber = false; } String result; switch (conversionType) { case SIGNED_INTEGER_DECIMAL: { if (toConvert instanceof PythonFloat) { toConvert = ((PythonFloat) toConvert).asInteger(); } if (!(toConvert instanceof PythonInteger)) { throw new TypeError("%d format: a real number is required, not " + toConvert.$getType().getTypeName()); } result = ((PythonInteger) toConvert).value.toString(10); break; } case SIGNED_INTEGER_OCTAL: { if (toConvert instanceof PythonFloat) { toConvert = ((PythonFloat) toConvert).asInteger(); } if (!(toConvert instanceof PythonInteger)) { throw new TypeError("%o format: a real number is required, not " + toConvert.$getType().getTypeName()); } result = ((PythonInteger) toConvert).value.toString(8); if (useAlternateForm) { result = (result.startsWith("-")) ? "-0o" + result.substring(1) : "0o" + result; } break; } case SIGNED_HEXADECIMAL_LOWERCASE: { if (toConvert instanceof PythonFloat) { toConvert = ((PythonFloat) toConvert).asInteger(); } if (!(toConvert instanceof PythonInteger)) { throw new TypeError("%x format: a real number is required, not " + toConvert.$getType().getTypeName()); } result = ((PythonInteger) toConvert).value.toString(16); if (useAlternateForm) { result = (result.startsWith("-")) ? "-0x" + result.substring(1) : "0x" + result; } break; } case SIGNED_HEXADECIMAL_UPPERCASE: { if (toConvert instanceof PythonFloat) { toConvert = ((PythonFloat) toConvert).asInteger(); } if (!(toConvert instanceof PythonInteger)) { throw new TypeError("%X format: a real number is required, not " + toConvert.$getType().getTypeName()); } result = ((PythonInteger) toConvert).value.toString(16).toUpperCase(); if (useAlternateForm) { result = (result.startsWith("-")) ? "-0X" + result.substring(1) : "0X" + result; } break; } case FLOATING_POINT_EXPONENTIAL_LOWERCASE: { if (toConvert instanceof PythonInteger) { toConvert = ((PythonInteger) toConvert).asFloat(); } if (!(toConvert instanceof PythonFloat)) { throw new TypeError("%e format: a real number is required, not " + toConvert.$getType().getTypeName()); } BigDecimal value = BigDecimal.valueOf(((PythonFloat) toConvert).value); result = getUppercaseEngineeringString(value, maybePrecision.map(precision -> precision + 1) .or(() -> Optional.of(7))).toLowerCase(); if (useAlternateForm && !result.contains(".")) { result = result + ".0"; } break; } case FLOATING_POINT_EXPONENTIAL_UPPERCASE: { if (toConvert instanceof PythonInteger) { toConvert = ((PythonInteger) toConvert).asFloat(); } if (!(toConvert instanceof PythonFloat)) { throw new TypeError("%E format: a real number is required, not " + toConvert.$getType().getTypeName()); } BigDecimal value = BigDecimal.valueOf(((PythonFloat) toConvert).value); result = getUppercaseEngineeringString(value, maybePrecision.map(precision -> precision + 1) .or(() -> Optional.of(7))); if (useAlternateForm && !result.contains(".")) { result = result + ".0"; } break; } case FLOATING_POINT_DECIMAL: { if (toConvert instanceof PythonInteger) { toConvert = ((PythonInteger) toConvert).asFloat(); } if (!(toConvert instanceof PythonFloat)) { throw new TypeError("%f format: a real number is required, not " + toConvert.$getType().getTypeName()); } BigDecimal value = BigDecimal.valueOf(((PythonFloat) toConvert).value); BigDecimal valueWithPrecision = value.setScale(maybePrecision.orElse(6), RoundingMode.HALF_EVEN); result = valueWithPrecision.toPlainString(); if (useAlternateForm && !result.contains(".")) { result = result + ".0"; } break; } case FLOATING_POINT_DECIMAL_OR_EXPONENTIAL_LOWERCASE: { if (toConvert instanceof PythonInteger) { toConvert = ((PythonInteger) toConvert).asFloat(); } if (!(toConvert instanceof PythonFloat)) { throw new TypeError("%g format: a real number is required, not " + toConvert.$getType().getTypeName()); } BigDecimal value = BigDecimal.valueOf(((PythonFloat) toConvert).value); BigDecimal valueWithPrecision; if (value.scale() > 4 || value.precision() >= maybePrecision.orElse(6)) { valueWithPrecision = getBigDecimalWithPrecision(value, maybePrecision); result = getUppercaseEngineeringString(valueWithPrecision, maybePrecision).toLowerCase(); } else { valueWithPrecision = value.setScale(maybePrecision.orElse(6), RoundingMode.HALF_EVEN); result = valueWithPrecision.toPlainString(); } if (result.length() >= 3 && result.charAt(result.length() - 3) == 'e') { result = result.substring(0, result.length() - 1) + "0" + result.charAt(result.length() - 1); } break; } case FLOATING_POINT_DECIMAL_OR_EXPONENTIAL_UPPERCASE: { if (toConvert instanceof PythonInteger) { toConvert = ((PythonInteger) toConvert).asFloat(); } if (!(toConvert instanceof PythonFloat)) { throw new TypeError("%G format: a real number is required, not " + toConvert.$getType().getTypeName()); } BigDecimal value = BigDecimal.valueOf(((PythonFloat) toConvert).value); BigDecimal valueWithPrecision; if (value.scale() > 4 || value.precision() >= maybePrecision.orElse(6)) { valueWithPrecision = getBigDecimalWithPrecision(value, maybePrecision); result = getUppercaseEngineeringString(valueWithPrecision, maybePrecision); } else { valueWithPrecision = value.setScale(maybePrecision.orElse(6), RoundingMode.HALF_EVEN); result = valueWithPrecision.toPlainString(); } break; } case SINGLE_CHARACTER: { if (stringType == PrintfStringType.STRING) { if (toConvert instanceof PythonString) { PythonString convertedCharacter = (PythonString) toConvert; if (convertedCharacter.value.length() != 1) { throw new ValueError("c specifier can only take an integer or single character string"); } result = convertedCharacter.value; } else { result = Character.toString(((PythonInteger) toConvert).value.intValueExact()); } } else { if (toConvert instanceof PythonBytes) { PythonBytes convertedCharacter = (PythonBytes) toConvert; if (convertedCharacter.value.length != 1) { throw new ValueError("c specifier can only take an integer or single character string"); } result = convertedCharacter.asCharSequence().toString(); } else if (toConvert instanceof PythonByteArray) { PythonByteArray convertedCharacter = (PythonByteArray) toConvert; if (convertedCharacter.valueBuffer.limit() != 1) { throw new ValueError("c specifier can only take an integer or single character string"); } result = convertedCharacter.asCharSequence().toString(); } else { result = Character.toString(((PythonInteger) toConvert).value.intValueExact()); } } break; } case REPR_STRING: { result = ((PythonString) UnaryDunderBuiltin.REPRESENTATION.invoke(toConvert)).value; break; } case STR_STRING: { if (stringType == PrintfStringType.STRING) { result = ((PythonString) UnaryDunderBuiltin.STR.invoke(toConvert)).value; } else { if (toConvert instanceof PythonBytes) { result = ((PythonBytes) toConvert).asCharSequence().toString(); } else if (toConvert instanceof PythonByteArray) { result = ((PythonByteArray) toConvert).asCharSequence().toString(); } else { result = ((PythonString) UnaryDunderBuiltin.STR.invoke(toConvert)).value; } } break; } case ASCII_STRING: { result = GlobalBuiltins.ascii(List.of(toConvert), Map.of(), null).value; break; } case LITERAL_PERCENT: { result = "%"; break; } default: throw new IllegalStateException("Unhandled case: " + conversionType); } if (putSignBeforeConversion && !(result.startsWith("+") || result.startsWith("-"))) { result = "+" + result; } if (putSpaceBeforePositiveNumber && !(result.startsWith("-"))) { result = " " + result; } if (maybeWidth.isPresent() && maybeWidth.get() > result.length()) { int padding = maybeWidth.get() - result.length(); if (isZeroPadded) { if (result.startsWith("+") || result.startsWith("-")) { result = result.charAt(0) + "0".repeat(padding) + result.substring(1); } else { result = "0".repeat(padding) + result; } } else if (isLeftAdjusted) { result = result + " ".repeat(padding); } } return result; } public static String format(String text, List<PythonLikeObject> positionalArguments, Map<? extends PythonLikeObject, PythonLikeObject> namedArguments) { Matcher matcher = REPLACEMENT_FIELD_PATTERN.matcher(text); StringBuilder out = new StringBuilder(); int start = 0; int implicitField = 0; while (matcher.find()) { out.append(text, start, matcher.start()); start = matcher.end(); String literal = matcher.group("literal"); if (literal != null) { switch (literal) { case "{{": out.append("{"); continue; case "}}": out.append("}"); continue; default: throw new IllegalStateException("Unhandled literal: " + literal); } } String argName = matcher.group("argName"); PythonLikeObject toConvert; if (positionalArguments != null) { if (argName == null) { if (implicitField >= positionalArguments.size()) { throw new ValueError( "(" + implicitField + ") is larger than sequence length (" + positionalArguments.size() + ")"); } toConvert = positionalArguments.get(implicitField); implicitField++; } else { try { int argumentIndex = Integer.parseInt(argName); if (argumentIndex >= positionalArguments.size()) { throw new ValueError("(" + implicitField + ") is larger than sequence length (" + positionalArguments.size() + ")"); } toConvert = positionalArguments.get(argumentIndex); } catch (NumberFormatException e) { if (namedArguments == null) { throw new ValueError("(" + argName + ") cannot be used to index a sequence"); } else { toConvert = namedArguments.get(PythonString.valueOf(argName)); } } } } else { toConvert = namedArguments.get(PythonString.valueOf(argName)); } if (toConvert == null) { throw new KeyError(argName); } toConvert = getFinalObjectInChain(toConvert, matcher.group("fieldName")); String conversion = matcher.group("conversion"); if (conversion != null) { switch (conversion) { case "s": toConvert = UnaryDunderBuiltin.STR.invoke(toConvert); break; case "r": toConvert = UnaryDunderBuiltin.REPRESENTATION.invoke(toConvert); break; case "a": toConvert = GlobalBuiltins.ascii(List.of(toConvert), Map.of(), null); break; } } String formatSpec = Objects.requireNonNullElse(matcher.group("formatSpec"), ""); out.append(BinaryDunderBuiltin.FORMAT.invoke(toConvert, PythonString.valueOf(formatSpec))); } out.append(text.substring(start)); return out.toString(); } private static PythonLikeObject getFinalObjectInChain(PythonLikeObject chainStart, String chain) { if (chain == null) { return chainStart; } PythonLikeObject current = chainStart; Matcher matcher = INDEX_CHAIN_PART_PATTERN.matcher(chain); while (matcher.find()) { String result = matcher.group(); if (result.startsWith(".")) { String attributeName = result.substring(1); current = BinaryDunderBuiltin.GET_ATTRIBUTE.invoke(current, PythonString.valueOf(attributeName)); } else { String index = result.substring(1, result.length() - 1); try { int intIndex = Integer.parseInt(index); current = BinaryDunderBuiltin.GET_ITEM.invoke(current, PythonInteger.valueOf(intIndex)); } catch (NumberFormatException e) { current = BinaryDunderBuiltin.GET_ITEM.invoke(current, PythonString.valueOf(index)); } } } return current; } public static void addGroupings(StringBuilder out, DefaultFormatSpec formatSpec, int groupSize) { if (formatSpec.groupingOption.isEmpty()) { return; } if (groupSize <= 0) { throw new ValueError( "Invalid format spec: grouping option now allowed for conversion type " + formatSpec.conversionType); } int decimalSeperator = out.indexOf("."); char seperator; switch (formatSpec.groupingOption.get()) { case COMMA: seperator = ','; break; case UNDERSCORE: seperator = '_'; break; default: throw new IllegalStateException("Unhandled case: " + formatSpec.groupingOption.get()); } int index; if (decimalSeperator != -1) { index = decimalSeperator - 1; } else { index = out.length() - 1; } int groupIndex = 0; while (index >= 0 && out.charAt(index) != '-') { groupIndex++; if (groupIndex == groupSize) { out.insert(index, seperator); groupIndex = 0; } index--; } } public static void align(StringBuilder out, DefaultFormatSpec formatSpec, DefaultFormatSpec.AlignmentOption defaultAlignment) { if (formatSpec.width.isPresent()) { switch (formatSpec.alignment.orElse(defaultAlignment)) { case LEFT_ALIGN: leftAlign(out, formatSpec.fillCharacter, formatSpec.width.get()); break; case RIGHT_ALIGN: rightAlign(out, formatSpec.fillCharacter, formatSpec.width.get()); break; case RESPECT_SIGN_RIGHT_ALIGN: respectSignRightAlign(out, formatSpec.fillCharacter, formatSpec.width.get()); break; case CENTER_ALIGN: center(out, formatSpec.fillCharacter, formatSpec.width.get()); break; } } } public static void alignWithPrefixRespectingSign(StringBuilder out, String prefix, DefaultFormatSpec formatSpec, DefaultFormatSpec.AlignmentOption defaultAlignment) { int insertPosition = (out.charAt(0) == '+' || out.charAt(0) == '-' || out.charAt(0) == ' ') ? 1 : 0; if (formatSpec.width.isPresent()) { switch (formatSpec.alignment.orElse(defaultAlignment)) { case LEFT_ALIGN: out.insert(insertPosition, prefix); leftAlign(out, formatSpec.fillCharacter, formatSpec.width.get()); break; case RIGHT_ALIGN: out.insert(insertPosition, prefix); rightAlign(out, formatSpec.fillCharacter, formatSpec.width.get()); break; case RESPECT_SIGN_RIGHT_ALIGN: respectSignRightAlign(out, formatSpec.fillCharacter, formatSpec.width.get()); out.insert(insertPosition, prefix); break; case CENTER_ALIGN: out.insert(insertPosition, prefix); center(out, formatSpec.fillCharacter, formatSpec.width.get()); break; } } else { out.insert(insertPosition, prefix); } } public static void leftAlign(StringBuilder builder, String fillCharAsString, int width) { if (width <= builder.length()) { return; } int rightPadding = width - builder.length(); builder.append(fillCharAsString.repeat(rightPadding)); } public static void rightAlign(StringBuilder builder, String fillCharAsString, int width) { if (width <= builder.length()) { return; } int leftPadding = width - builder.length(); builder.insert(0, fillCharAsString.repeat(leftPadding)); } public static void respectSignRightAlign(StringBuilder builder, String fillCharAsString, int width) { if (width <= builder.length()) { return; } int leftPadding = width - builder.length(); if (builder.length() >= 1 && (builder.charAt(0) == '+' || builder.charAt(0) == '-' || builder.charAt(0) == ' ')) { builder.insert(1, fillCharAsString.repeat(leftPadding)); } else { builder.insert(0, fillCharAsString.repeat(leftPadding)); } } public static void center(StringBuilder builder, String fillCharAsString, int width) { if (width <= builder.length()) { return; } int extraWidth = width - builder.length(); int rightPadding = extraWidth / 2; // left padding get extra character if extraWidth is odd int leftPadding = rightPadding + (extraWidth & 1); // x & 1 == x % 2 builder.insert(0, fillCharAsString.repeat(leftPadding)) .append(fillCharAsString.repeat(rightPadding)); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/TracebackUtils.java
package ai.timefold.jpyinterpreter.util; import java.io.PrintWriter; import java.io.StringWriter; public class TracebackUtils { private TracebackUtils() { } public static String getTraceback(Throwable t) { var output = new StringWriter(); PrintWriter printWriter = new PrintWriter(output); t.printStackTrace(printWriter); return output.toString(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/arguments/ArgumentKind.java
package ai.timefold.jpyinterpreter.util.arguments; public enum ArgumentKind { POSITIONAL_AND_KEYWORD(true, true), POSITIONAL_ONLY(true, false), KEYWORD_ONLY(false, true), VARARGS(false, false); final boolean allowPositional; final boolean allowKeyword; ArgumentKind(boolean allowPositional, boolean allowKeyword) { this.allowPositional = allowPositional; this.allowKeyword = allowKeyword; } public boolean isAllowPositional() { return allowPositional; } public boolean isAllowKeyword() { return allowKeyword; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/util/arguments/ArgumentSpec.java
package ai.timefold.jpyinterpreter.util.arguments; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import ai.timefold.jpyinterpreter.MethodDescriptor; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public final class ArgumentSpec<Out_> { private static List<ArgumentSpec<?>> ARGUMENT_SPECS = new ArrayList<>(); private final String functionReturnTypeName; private final String functionName; private final List<String> argumentNameList; private final List<String> argumentTypeNameList; private final List<ArgumentKind> argumentKindList; private final List<Object> argumentDefaultList; private final BitSet nullableArgumentSet; private final Optional<Integer> extraPositionalsArgumentIndex; private final Optional<Integer> extraKeywordsArgumentIndex; private final int numberOfPositionalArguments; private final int requiredPositionalArguments; private Class<?> functionReturnType = null; private List<Class> argumentTypeList = null; private ArgumentSpec(String functionName, String functionReturnTypeName) { this.functionReturnTypeName = functionReturnTypeName; this.functionName = functionName + "()"; requiredPositionalArguments = 0; numberOfPositionalArguments = 0; argumentNameList = Collections.emptyList(); argumentTypeNameList = Collections.emptyList(); argumentKindList = Collections.emptyList(); argumentDefaultList = Collections.emptyList(); extraPositionalsArgumentIndex = Optional.empty(); extraKeywordsArgumentIndex = Optional.empty(); nullableArgumentSet = new BitSet(); } private ArgumentSpec(String argumentName, String argumentTypeName, ArgumentKind argumentKind, Object defaultValue, Optional<Integer> extraPositionalsArgumentIndex, Optional<Integer> extraKeywordsArgumentIndex, boolean allowNull, ArgumentSpec<Out_> previousSpec) { functionName = previousSpec.functionName; functionReturnTypeName = previousSpec.functionReturnTypeName; if (previousSpec.numberOfPositionalArguments < previousSpec.getTotalArgumentCount()) { numberOfPositionalArguments = previousSpec.numberOfPositionalArguments; } else { if (argumentKind.allowPositional) { numberOfPositionalArguments = previousSpec.getTotalArgumentCount() + 1; } else { numberOfPositionalArguments = previousSpec.getTotalArgumentCount(); } } if (argumentKind == ArgumentKind.POSITIONAL_ONLY) { if (previousSpec.requiredPositionalArguments != previousSpec.getTotalArgumentCount()) { throw new IllegalArgumentException("All required positional arguments must come before all other arguments"); } else { requiredPositionalArguments = previousSpec.getTotalArgumentCount() + 1; } } else { requiredPositionalArguments = previousSpec.requiredPositionalArguments; } argumentNameList = new ArrayList<>(previousSpec.argumentNameList.size() + 1); argumentTypeNameList = new ArrayList<>(previousSpec.argumentTypeNameList.size() + 1); argumentKindList = new ArrayList<>(previousSpec.argumentKindList.size() + 1); argumentDefaultList = new ArrayList<>(previousSpec.argumentDefaultList.size() + 1); argumentNameList.addAll(previousSpec.argumentNameList); argumentNameList.add(argumentName); argumentTypeNameList.addAll(previousSpec.argumentTypeNameList); argumentTypeNameList.add(argumentTypeName); argumentKindList.addAll(previousSpec.argumentKindList); argumentKindList.add(argumentKind); argumentDefaultList.addAll(previousSpec.argumentDefaultList); argumentDefaultList.add(defaultValue); if (extraPositionalsArgumentIndex.isPresent() && previousSpec.extraPositionalsArgumentIndex.isPresent()) { throw new IllegalArgumentException("Multiple positional vararg arguments"); } if (previousSpec.extraPositionalsArgumentIndex.isPresent()) { extraPositionalsArgumentIndex = previousSpec.extraPositionalsArgumentIndex; } if (extraKeywordsArgumentIndex.isPresent() && previousSpec.extraKeywordsArgumentIndex.isPresent()) { throw new IllegalArgumentException("Multiple keyword vararg arguments"); } if (previousSpec.extraKeywordsArgumentIndex.isPresent()) { extraKeywordsArgumentIndex = previousSpec.extraKeywordsArgumentIndex; } this.extraPositionalsArgumentIndex = extraPositionalsArgumentIndex; this.extraKeywordsArgumentIndex = extraKeywordsArgumentIndex; this.nullableArgumentSet = (BitSet) previousSpec.nullableArgumentSet.clone(); if (allowNull) { nullableArgumentSet.set(argumentNameList.size() - 1); } } public static <T extends PythonLikeObject> ArgumentSpec<T> forFunctionReturning(String functionName, String outClass) { return new ArgumentSpec<>(functionName, outClass); } public int getTotalArgumentCount() { return argumentNameList.size(); } public int getAllowPositionalArgumentCount() { return numberOfPositionalArguments; } public boolean hasExtraPositionalArgumentsCapture() { return extraPositionalsArgumentIndex.isPresent(); } public boolean hasExtraKeywordArgumentsCapture() { return extraKeywordsArgumentIndex.isPresent(); } public String getArgumentTypeInternalName(int argumentIndex) { return argumentTypeNameList.get(argumentIndex).replace('.', '/'); } public ArgumentKind getArgumentKind(int argumentIndex) { return argumentKindList.get(argumentIndex); } /** * Returns the index of an argument with the given name. Returns -1 if no argument has the given name. * * @param argumentName The name of the argument. * @return the index of an argument with the given name, or -1 if no argument has that name */ public int getArgumentIndex(String argumentName) { return argumentNameList.indexOf(argumentName); } public boolean isArgumentNullable(int argumentIndex) { return nullableArgumentSet.get(argumentIndex); } public Optional<Integer> getExtraPositionalsArgumentIndex() { return extraPositionalsArgumentIndex; } public Optional<Integer> getExtraKeywordsArgumentIndex() { return extraKeywordsArgumentIndex; } public Collection<Integer> getUnspecifiedArgumentSet(int positionalArguments, List<String> keywordArgumentNameList) { int specArgumentCount = getTotalArgumentCount(); if (hasExtraPositionalArgumentsCapture()) { specArgumentCount--; } if (hasExtraKeywordArgumentsCapture()) { specArgumentCount--; } return IntStream.range(positionalArguments, specArgumentCount) .filter(index -> !keywordArgumentNameList.contains(argumentNameList.get(index))) .boxed() .collect(Collectors.toList()); } public static ArgumentSpec<?> getArgumentSpec(int argumentSpecIndex) { return ARGUMENT_SPECS.get(argumentSpecIndex); } public void loadArgumentSpec(MethodVisitor methodVisitor) { int index = ARGUMENT_SPECS.size(); ARGUMENT_SPECS.add(this); methodVisitor.visitLdcInsn(index); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(ArgumentSpec.class), "getArgumentSpec", Type.getMethodDescriptor(Type.getType(ArgumentSpec.class), Type.INT_TYPE), false); } private void computeArgumentTypeList() { if (argumentTypeList == null) { try { functionReturnType = BuiltinTypes.asmClassLoader.loadClass(functionReturnTypeName.replace('/', '.')); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } argumentTypeList = argumentTypeNameList.stream() .map(className -> { try { return (Class) BuiltinTypes.asmClassLoader.loadClass(className.replace('/', '.')); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }) .toList(); } } public List<PythonLikeObject> extractArgumentList(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> keywordArguments) { computeArgumentTypeList(); List<PythonLikeObject> out = new ArrayList<>(argumentNameList.size()); if (positionalArguments.size() > numberOfPositionalArguments && extraPositionalsArgumentIndex.isEmpty()) { throw new TypeError(functionName + " takes " + numberOfPositionalArguments + " positional arguments but " + positionalArguments.size() + " were given"); } if (positionalArguments.size() < requiredPositionalArguments) { int missing = (requiredPositionalArguments - positionalArguments.size()); String argumentString = (missing == 1) ? "argument" : "arguments"; List<String> missingArgumentNames = argumentNameList.subList(argumentNameList.size() - missing, argumentNameList.size()); throw new TypeError(functionName + " missing " + (requiredPositionalArguments - positionalArguments.size()) + " required positional " + argumentString + ": '" + String.join("', ", missingArgumentNames) + "'"); } int numberOfSetArguments = Math.min(numberOfPositionalArguments, positionalArguments.size()); out.addAll(positionalArguments.subList(0, numberOfSetArguments)); for (int i = numberOfSetArguments; i < argumentNameList.size(); i++) { out.add(null); } int remaining = argumentNameList.size() - numberOfSetArguments; PythonLikeDict extraKeywordArguments = null; if (extraPositionalsArgumentIndex.isPresent()) { remaining--; out.set(extraPositionalsArgumentIndex.get(), PythonLikeTuple .fromList(positionalArguments.subList(numberOfSetArguments, positionalArguments.size()))); } if (extraKeywordsArgumentIndex.isPresent()) { remaining--; extraKeywordArguments = new PythonLikeDict(); out.set(extraKeywordsArgumentIndex.get(), extraKeywordArguments); } for (Map.Entry<PythonString, PythonLikeObject> keywordArgument : keywordArguments.entrySet()) { PythonString argumentName = keywordArgument.getKey(); int position = argumentNameList.indexOf(argumentName.value); if (position == -1) { if (extraKeywordsArgumentIndex.isPresent()) { extraKeywordArguments.put(argumentName, keywordArgument.getValue()); continue; } else { throw new TypeError(functionName + " got an unexpected keyword argument " + argumentName.repr().value); } } if (out.get(position) != null) { throw new TypeError(functionName + " got multiple values for argument " + argumentName.repr().value); } if (!argumentKindList.get(position).allowKeyword) { throw new TypeError(functionName + " got some positional-only arguments passed as keyword arguments: " + argumentName.repr().value); } remaining--; out.set(position, keywordArgument.getValue()); } if (remaining > 0) { List<Integer> missing = new ArrayList<>(remaining); for (int i = 0; i < out.size(); i++) { if (out.get(i) == null) { if (argumentDefaultList.get(i) != null || nullableArgumentSet.get(i)) { out.set(i, (PythonLikeObject) argumentDefaultList.get(i)); remaining--; } else { missing.add(i); } } } if (remaining > 0) { if (missing.stream().anyMatch(index -> argumentKindList.get(index).allowPositional)) { List<String> missingAllowsPositional = new ArrayList<>(remaining); for (int index : missing) { if (argumentKindList.get(index).allowPositional) { missingAllowsPositional.add(argumentNameList.get(index)); } } String argumentString = (missingAllowsPositional.size() == 1) ? "argument" : "arguments"; throw new TypeError(functionName + " missing " + remaining + " required positional " + argumentString + ": '" + String.join("', ", missingAllowsPositional) + "'"); } else { List<String> missingKeywordOnly = new ArrayList<>(remaining); for (int index : missing) { missingKeywordOnly.add(argumentNameList.get(index)); } String argumentString = (missingKeywordOnly.size() == 1) ? "argument" : "arguments"; throw new TypeError(functionName + " missing " + remaining + " required keyword-only " + argumentString + ": '" + String.join("', ", missingKeywordOnly) + "'"); } } } for (int i = 0; i < argumentNameList.size(); i++) { if ((out.get(i) == null && !nullableArgumentSet.get(i)) || (out.get(i) != null && !argumentTypeList.get(i).isInstance(out.get(i)))) { throw new TypeError(functionName + "'s argument '" + argumentNameList.get(i) + "' has incorrect type: " + "'" + argumentNameList.get(i) + "' must be a " + JavaPythonTypeConversionImplementor.getPythonLikeType(argumentTypeList.get(i)) + " (got " + ((out.get(i) != null) ? JavaPythonTypeConversionImplementor.getPythonLikeType(out.get(i).getClass()) : "NULL") + " instead)"); } } return out; } public boolean verifyMatchesCallSignature(int positionalArgumentCount, List<String> keywordArgumentNameList, List<PythonLikeType> callStackTypeList) { computeArgumentTypeList(); Set<Integer> missingValue = getRequiredArgumentIndexSet(); for (int keywordIndex = 0; keywordIndex < keywordArgumentNameList.size(); keywordIndex++) { String keyword = keywordArgumentNameList.get(keywordIndex); PythonLikeType stackType = callStackTypeList.get(positionalArgumentCount + keywordIndex); int index = argumentNameList.indexOf(keyword); if (index == -1 && extraKeywordsArgumentIndex.isEmpty()) { return false; } if (index != -1 && index < positionalArgumentCount) { return false; } else { try { if (!argumentTypeList.get(index).isAssignableFrom(stackType.getJavaClass())) { return false; } } catch (ClassNotFoundException e) { // Assume if the type is not found, it assignable } missingValue.remove(index); } } if (positionalArgumentCount < requiredPositionalArguments || positionalArgumentCount > getTotalArgumentCount()) { return false; } for (int i = 0; i < positionalArgumentCount; i++) { missingValue.remove(i); try { if (!argumentTypeList.get(i).isAssignableFrom(callStackTypeList.get(i).getJavaClass())) { return false; } } catch (ClassNotFoundException e) { // Assume if the type is not found, it assignable } } if (!missingValue.isEmpty()) { return false; } if (extraPositionalsArgumentIndex.isEmpty() && extraKeywordsArgumentIndex.isEmpty()) { // no *vargs or **kwargs return positionalArgumentCount <= numberOfPositionalArguments && positionalArgumentCount + keywordArgumentNameList.size() <= argumentNameList.size(); } else if (extraPositionalsArgumentIndex.isPresent() && extraKeywordsArgumentIndex.isEmpty()) { // *vargs only return true; } else if (extraPositionalsArgumentIndex.isEmpty()) { // **kwargs only return positionalArgumentCount < numberOfPositionalArguments; } else { // *vargs and **kwargs return true; } } private Set<Integer> getRequiredArgumentIndexSet() { Set<Integer> out = new HashSet<>(); for (int i = 0; i < argumentNameList.size(); i++) { if (argumentKindList.get(i) == ArgumentKind.VARARGS) { continue; } if (argumentDefaultList.get(i) != null || nullableArgumentSet.get(i)) { continue; } out.add(i); } return out; } private <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addArgument(String argumentName, String argumentTypeName, ArgumentKind argumentKind, ArgumentType_ defaultValue, Optional<Integer> extraPositionalsArgumentIndex, Optional<Integer> extraKeywordsArgumentIndex, boolean allowNull) { return new ArgumentSpec<>(argumentName, argumentTypeName, argumentKind, defaultValue, extraPositionalsArgumentIndex, extraKeywordsArgumentIndex, allowNull, this); } public <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addArgument(String argumentName, String argumentTypeName) { return addArgument(argumentName, argumentTypeName, ArgumentKind.POSITIONAL_AND_KEYWORD, null, Optional.empty(), Optional.empty(), false); } public <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addPositionalOnlyArgument(String argumentName, String argumentTypeName) { return addArgument(argumentName, argumentTypeName, ArgumentKind.POSITIONAL_ONLY, null, Optional.empty(), Optional.empty(), false); } public <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addKeywordOnlyArgument(String argumentName, String argumentTypeName) { return addArgument(argumentName, argumentTypeName, ArgumentKind.KEYWORD_ONLY, null, Optional.empty(), Optional.empty(), false); } public <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addArgument(String argumentName, String argumentTypeName, ArgumentType_ defaultValue) { return addArgument(argumentName, argumentTypeName, ArgumentKind.POSITIONAL_AND_KEYWORD, defaultValue, Optional.empty(), Optional.empty(), false); } public <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addPositionalOnlyArgument(String argumentName, String argumentTypeName, ArgumentType_ defaultValue) { return addArgument(argumentName, argumentTypeName, ArgumentKind.POSITIONAL_ONLY, defaultValue, Optional.empty(), Optional.empty(), false); } public <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addKeywordOnlyArgument(String argumentName, String argumentTypeName, ArgumentType_ defaultValue) { return addArgument(argumentName, argumentTypeName, ArgumentKind.KEYWORD_ONLY, defaultValue, Optional.empty(), Optional.empty(), false); } public <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addNullableArgument(String argumentName, String argumentTypeName) { return addArgument(argumentName, argumentTypeName, ArgumentKind.POSITIONAL_AND_KEYWORD, null, Optional.empty(), Optional.empty(), true); } public <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addNullablePositionalOnlyArgument(String argumentName, String argumentTypeName) { return addArgument(argumentName, argumentTypeName, ArgumentKind.POSITIONAL_ONLY, null, Optional.empty(), Optional.empty(), true); } public <ArgumentType_ extends PythonLikeObject> ArgumentSpec<Out_> addNullableKeywordOnlyArgument(String argumentName, String argumentTypeName) { return addArgument(argumentName, argumentTypeName, ArgumentKind.KEYWORD_ONLY, null, Optional.empty(), Optional.empty(), true); } public ArgumentSpec<Out_> addExtraPositionalVarArgument(String argumentName) { return addArgument(argumentName, PythonLikeTuple.class.getName(), ArgumentKind.VARARGS, null, Optional.of(getTotalArgumentCount()), Optional.empty(), false); } public ArgumentSpec<Out_> addExtraKeywordVarArgument(String argumentName) { return addArgument(argumentName, PythonLikeDict.class.getName(), ArgumentKind.VARARGS, null, Optional.empty(), Optional.of(getTotalArgumentCount()), false); } public PythonFunctionSignature asPythonFunctionSignature(Method method) { verifyMethodMatchesSpec(method); return getPythonFunctionSignatureForMethodDescriptor(new MethodDescriptor(method), method.getReturnType()); } public PythonFunctionSignature asStaticPythonFunctionSignature(Method method) { verifyMethodMatchesSpec(method); return getPythonFunctionSignatureForMethodDescriptor(new MethodDescriptor(method, MethodDescriptor.MethodType.STATIC), method.getReturnType()); } public PythonFunctionSignature asClassPythonFunctionSignature(Method method) { verifyMethodMatchesSpec(method); return getPythonFunctionSignatureForMethodDescriptor(new MethodDescriptor(method, MethodDescriptor.MethodType.CLASS), method.getReturnType()); } public PythonFunctionSignature asPythonFunctionSignature(String internalClassName, String methodName, String methodDescriptor) { MethodDescriptor method = new MethodDescriptor(internalClassName, MethodDescriptor.MethodType.VIRTUAL, methodName, methodDescriptor); try { return getPythonFunctionSignatureForMethodDescriptor(method, BuiltinTypes.asmClassLoader.loadClass( method.getReturnType().getClassName().replace('/', '.'))); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public PythonFunctionSignature asStaticPythonFunctionSignature(String internalClassName, String methodName, String methodDescriptor) { MethodDescriptor method = new MethodDescriptor(internalClassName, MethodDescriptor.MethodType.STATIC, methodName, methodDescriptor); try { return getPythonFunctionSignatureForMethodDescriptor(method, BuiltinTypes.asmClassLoader.loadClass( method.getReturnType().getClassName().replace('/', '.'))); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public PythonFunctionSignature asClassPythonFunctionSignature(String internalClassName, String methodName, String methodDescriptor) { MethodDescriptor method = new MethodDescriptor(internalClassName, MethodDescriptor.MethodType.CLASS, methodName, methodDescriptor); try { return getPythonFunctionSignatureForMethodDescriptor(method, BuiltinTypes.asmClassLoader.loadClass( method.getReturnType().getClassName().replace('/', '.'))); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } private void verifyMethodMatchesSpec(Method method) { computeArgumentTypeList(); if (!functionReturnType.isAssignableFrom(method.getReturnType())) { throw new IllegalArgumentException("Method (" + method + ") does not match the given spec (" + this + "): its return type (" + method.getReturnType() + ") is not " + "assignable to the spec return type (" + functionReturnTypeName + ")."); } if (method.getParameterCount() != argumentNameList.size()) { throw new IllegalArgumentException("Method (" + method + ") does not match the given spec (" + this + "): they have different parameter counts."); } for (int i = 0; i < method.getParameterCount(); i++) { if (!method.getParameterTypes()[i].isAssignableFrom(argumentTypeList.get(i))) { throw new IllegalArgumentException("Method (" + method + ") does not match the given spec (" + this + "): its " + i + " parameter (" + method.getParameters()[i].toString() + ") cannot " + " be assigned from the spec " + i + " parameter (" + argumentTypeList.get(i) + " " + argumentNameList.get(i) + ")."); } } } @SuppressWarnings("unchecked") private PythonFunctionSignature getPythonFunctionSignatureForMethodDescriptor(MethodDescriptor methodDescriptor, Class<?> javaReturnType) { computeArgumentTypeList(); int firstDefault = 0; while (firstDefault < argumentDefaultList.size() && argumentDefaultList.get(firstDefault) == null && !nullableArgumentSet.get(firstDefault)) { firstDefault++; } List<PythonLikeObject> defaultParameterValueList; if (firstDefault != argumentDefaultList.size()) { defaultParameterValueList = (List<PythonLikeObject>) (List<?>) argumentDefaultList.subList(firstDefault, argumentDefaultList.size()); } else { defaultParameterValueList = Collections.emptyList(); } List<PythonLikeType> parameterTypeList = argumentTypeList.stream() .map(JavaPythonTypeConversionImplementor::getPythonLikeType) .collect(Collectors.toList()); PythonLikeType returnType = JavaPythonTypeConversionImplementor.getPythonLikeType(javaReturnType); Map<String, Integer> keywordArgumentToIndexMap = new HashMap<>(); for (int i = 0; i < argumentNameList.size(); i++) { if (argumentKindList.get(i).allowKeyword) { keywordArgumentToIndexMap.put(argumentNameList.get(i), i); } } return new PythonFunctionSignature(methodDescriptor, defaultParameterValueList, keywordArgumentToIndexMap, returnType, parameterTypeList, extraPositionalsArgumentIndex, extraKeywordsArgumentIndex, this); } public Object getDefaultValue(int defaultIndex) { return argumentDefaultList.get(defaultIndex); } @Override public String toString() { StringBuilder out = new StringBuilder("ArgumentSpec("); out.append("name=").append(functionName) .append(", returnType=").append(functionReturnTypeName) .append(", arguments=["); for (int i = 0; i < argumentNameList.size(); i++) { out.append(argumentTypeNameList.get(i)); out.append(" "); out.append(argumentNameList.get(i)); if (nullableArgumentSet.get(i)) { out.append(" (nullable)"); } if (argumentDefaultList.get(i) != null) { out.append(" (default: "); out.append(argumentDefaultList.get(i)); out.append(")"); } if (argumentKindList.get(i) != ArgumentKind.POSITIONAL_AND_KEYWORD) { if (extraPositionalsArgumentIndex.isPresent() && extraPositionalsArgumentIndex.get() == i) { out.append(" (vargs)"); } else if (extraKeywordsArgumentIndex.isPresent() && extraKeywordsArgumentIndex.get() == i) { out.append(" (kwargs)"); } else { out.append(" ("); out.append(argumentKindList.get(i)); out.append(")"); } } if (i != argumentNameList.size() - 1) { out.append(", "); } } out.append("])"); return out.toString(); } }
0
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it/TimefoldSolverController.java
package ai.timefold.solver.spring.boot.it; import ai.timefold.solver.core.api.solver.SolverFactory; import ai.timefold.solver.spring.boot.it.domain.IntegrationTestSolution; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/integration-test") public class TimefoldSolverController { private final SolverFactory<IntegrationTestSolution> solverFactory; public TimefoldSolverController(SolverFactory<IntegrationTestSolution> solverFactory) { this.solverFactory = solverFactory; } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public IntegrationTestSolution solve(@RequestBody IntegrationTestSolution problem) { return solverFactory.buildSolver().solve(problem); } }
0
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it/TimefoldSolverSpringBootApp.java
package ai.timefold.solver.spring.boot.it; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TimefoldSolverSpringBootApp { public static void main(String[] args) { SpringApplication.run(TimefoldSolverSpringBootApp.class, args); } }
0
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it/domain/IntegrationTestEntity.java
package ai.timefold.solver.spring.boot.it.domain; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.lookup.PlanningId; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; @PlanningEntity public class IntegrationTestEntity { @PlanningId private String id; @PlanningVariable private IntegrationTestValue value; public IntegrationTestEntity() { } public IntegrationTestEntity(String id) { this.id = id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public IntegrationTestValue getValue() { return value; } public void setValue(IntegrationTestValue value) { this.value = value; } }
0
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it/domain/IntegrationTestSolution.java
package ai.timefold.solver.spring.boot.it.domain; import java.util.List; import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty; import ai.timefold.solver.core.api.domain.solution.PlanningScore; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty; import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore; @PlanningSolution public class IntegrationTestSolution { @PlanningEntityCollectionProperty private List<IntegrationTestEntity> entityList; @ValueRangeProvider @ProblemFactCollectionProperty private List<IntegrationTestValue> valueList; @PlanningScore private SimpleScore score; public IntegrationTestSolution() { } public IntegrationTestSolution(List<IntegrationTestEntity> entityList, List<IntegrationTestValue> valueList) { this.entityList = entityList; this.valueList = valueList; } public List<IntegrationTestEntity> getEntityList() { return entityList; } public void setEntityList(List<IntegrationTestEntity> entityList) { this.entityList = entityList; } public List<IntegrationTestValue> getValueList() { return valueList; } public void setValueList(List<IntegrationTestValue> valueList) { this.valueList = valueList; } public SimpleScore getScore() { return score; } public void setScore(SimpleScore score) { this.score = score; } }
0
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it/domain/IntegrationTestValue.java
package ai.timefold.solver.spring.boot.it.domain; public record IntegrationTestValue(String id) { }
0
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it
java-sources/ai/timefold/solver/spring-boot-integration-test/1.26.1/ai/timefold/solver/spring/boot/it/solver/IntegrationTestConstraintProvider.java
package ai.timefold.solver.spring.boot.it.solver; import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.api.score.stream.ConstraintFactory; import ai.timefold.solver.core.api.score.stream.ConstraintProvider; import ai.timefold.solver.spring.boot.it.domain.IntegrationTestEntity; import org.jspecify.annotations.NonNull; public class IntegrationTestConstraintProvider implements ConstraintProvider { @Override public Constraint @NonNull [] defineConstraints(@NonNull ConstraintFactory constraintFactory) { return new Constraint[] { constraintFactory.forEach(IntegrationTestEntity.class) .filter(entity -> !entity.getId().equals(entity.getValue().id())) .penalize(SimpleScore.ONE) .asConstraint("Entity id do not match value id") }; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/api/PlannerBenchmark.java
package ai.timefold.solver.benchmark.api; import java.io.File; import org.jspecify.annotations.NonNull; /** * A planner benchmark that runs a number of single benchmarks. * <p> * Build by a {@link PlannerBenchmarkFactory}. */ public interface PlannerBenchmark { /** * Run all the single benchmarks and create an overview report. * * @return the directory in which the benchmark results are stored */ @NonNull File benchmark(); /** * Run all the single benchmarks, create an overview report * and show it in the default browser. * * @return the directory in which the benchmark results are stored */ @NonNull File benchmarkAndShowReportInBrowser(); }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/api/PlannerBenchmarkException.java
package ai.timefold.solver.benchmark.api; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; /** * If at least one of the {@link SingleBenchmarkResult}s of a {@link PlannerBenchmark} fail, * the {@link PlannerBenchmark} throws this exception * after all {@link SingleBenchmarkResult}s are finished and the benchmark report has been written. */ public class PlannerBenchmarkException extends RuntimeException { public PlannerBenchmarkException(@NonNull String message, @Nullable Throwable cause) { super(message, cause); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/api/PlannerBenchmarkFactory.java
package ai.timefold.solver.benchmark.api; import java.io.File; import java.util.List; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig; import ai.timefold.solver.benchmark.impl.DefaultPlannerBenchmarkFactory; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.config.solver.SolverConfig; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; /** * Builds {@link PlannerBenchmark} instances. * <p> * Supports tweaking the configuration programmatically before a {@link PlannerBenchmark} instance is build. */ public abstract class PlannerBenchmarkFactory { // ************************************************************************ // Static creation methods: SolverConfig XML // ************************************************************************ /** * Reads an XML solver configuration from the classpath * and uses that {@link SolverConfig} to build a {@link PlannerBenchmarkConfig} * that in turn is used to build a {@link PlannerBenchmarkFactory}. * The XML root element must be {@code <solver>}. * <p> * To read an XML benchmark configuration instead, use {@link #createFromXmlResource(String)}. * * @param solverConfigResource a classpath resource as defined by {@link ClassLoader#getResource(String)} */ public static @NonNull PlannerBenchmarkFactory createFromSolverConfigXmlResource(@NonNull String solverConfigResource) { SolverConfig solverConfig = SolverConfig.createFromXmlResource(solverConfigResource); PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromSolverConfigXmlResource(String)}. * * @param solverConfigResource a classpath resource * as defined by {@link ClassLoader#getResource(String)}. * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkFactory createFromSolverConfigXmlResource(@NonNull String solverConfigResource, @Nullable ClassLoader classLoader) { SolverConfig solverConfig = SolverConfig.createFromXmlResource(solverConfigResource, classLoader); PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromSolverConfigXmlResource(String)}. * * @param solverConfigResource a classpath resource * as defined by {@link ClassLoader#getResource(String)} */ public static @NonNull PlannerBenchmarkFactory createFromSolverConfigXmlResource(@NonNull String solverConfigResource, @NonNull File benchmarkDirectory) { SolverConfig solverConfig = SolverConfig.createFromXmlResource(solverConfigResource); PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig, benchmarkDirectory); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromSolverConfigXmlResource(String)}. * * @param solverConfigResource a classpath resource * as defined by {@link ClassLoader#getResource(String)} * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkFactory createFromSolverConfigXmlResource(@NonNull String solverConfigResource, @NonNull File benchmarkDirectory, @Nullable ClassLoader classLoader) { SolverConfig solverConfig = SolverConfig.createFromXmlResource(solverConfigResource, classLoader); PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig, benchmarkDirectory); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } // ************************************************************************ // Static creation methods: XML // ************************************************************************ /** * Reads an XML benchmark configuration from the classpath * and uses that {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}. * The XML root element must be {@code <plannerBenchmark>}. * <p> * To read an XML solver configuration instead, use {@link #createFromSolverConfigXmlResource(String)}. * * @param benchmarkConfigResource a classpath resource * as defined by {@link ClassLoader#getResource(String)} */ public static @NonNull PlannerBenchmarkFactory createFromXmlResource(@NonNull String benchmarkConfigResource) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource(benchmarkConfigResource); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromXmlResource(String)}. * * @param benchmarkConfigResource a classpath resource * as defined by {@link ClassLoader#getResource(String)} * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkFactory createFromXmlResource(@NonNull String benchmarkConfigResource, @Nullable ClassLoader classLoader) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource(benchmarkConfigResource, classLoader); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * Reads an XML benchmark configuration from the file system * and uses that {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}. * <p> * Warning: this leads to platform dependent code, * it's recommend to use {@link #createFromXmlResource(String)} instead. * */ public static @NonNull PlannerBenchmarkFactory createFromXmlFile(@NonNull File benchmarkConfigFile) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromXmlFile(benchmarkConfigFile); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromXmlFile(File)}. * * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkFactory createFromXmlFile(@NonNull File benchmarkConfigFile, @Nullable ClassLoader classLoader) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromXmlFile(benchmarkConfigFile, classLoader); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } // ************************************************************************ // Static creation methods: Freemarker XML // ************************************************************************ /** * Reads a Freemarker template from the classpath that generates an XML benchmark configuration * and uses that {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}. * The generated XML root element must be {@code <plannerBenchmark>}. * * @param templateResource a classpath resource as defined by {@link ClassLoader#getResource(String)} * @see #createFromFreemarkerXmlResource(String) */ public static @NonNull PlannerBenchmarkFactory createFromFreemarkerXmlResource(@NonNull String templateResource) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromFreemarkerXmlResource(String)}. * * @param templateResource a classpath resource as defined by {@link ClassLoader#getResource(String)} * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkFactory createFromFreemarkerXmlResource(@NonNull String templateResource, @Nullable ClassLoader classLoader) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource, classLoader); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromFreemarkerXmlResource(String)}. * * @param templateResource a classpath resource as defined by {@link ClassLoader#getResource(String)} */ public static @NonNull PlannerBenchmarkFactory createFromFreemarkerXmlResource(@NonNull String templateResource, @Nullable Object model) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource, model); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromFreemarkerXmlResource(String)}. * * @param templateResource a classpath resource as defined by {@link ClassLoader#getResource(String)} * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkFactory createFromFreemarkerXmlResource(@NonNull String templateResource, @Nullable Object model, @Nullable ClassLoader classLoader) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource, model, classLoader); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * Reads a Freemarker template rom the file system that generates an XML benchmark configuration * and uses that {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}. * The generated XML root element must be {@code <plannerBenchmark>}. * <p> * Warning: this leads to platform dependent code, * it's recommend to use {@link #createFromFreemarkerXmlResource(String)} instead. */ public static @NonNull PlannerBenchmarkFactory createFromFreemarkerXmlFile(@NonNull File templateFile) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(templateFile); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromFreemarkerXmlFile(File)}. * * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkFactory createFromFreemarkerXmlFile(@NonNull File templateFile, @Nullable ClassLoader classLoader) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(templateFile, classLoader); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromFreemarkerXmlFile(File)}. */ public static @NonNull PlannerBenchmarkFactory createFromFreemarkerXmlFile(@NonNull File templateFile, @Nullable Object model) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(templateFile, model); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } /** * As defined by {@link #createFromFreemarkerXmlFile(File)}. * * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkFactory createFromFreemarkerXmlFile(@NonNull File templateFile, @Nullable Object model, @Nullable ClassLoader classLoader) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(templateFile, model, classLoader); return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } // ************************************************************************ // Static creation methods: PlannerBenchmarkConfig and SolverConfig // ************************************************************************ /** * Uses a {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}. * If you don't need to manipulate the {@link PlannerBenchmarkConfig} programmatically, * use {@link #createFromXmlResource(String)} instead. */ public static @NonNull PlannerBenchmarkFactory create(@NonNull PlannerBenchmarkConfig benchmarkConfig) { return new DefaultPlannerBenchmarkFactory(benchmarkConfig); } public static @NonNull PlannerBenchmarkFactory createFromSolverConfig(@NonNull SolverConfig solverConfig) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig); return create(benchmarkConfig); } public static @NonNull PlannerBenchmarkFactory createFromSolverConfig(@NonNull SolverConfig solverConfig, @NonNull File benchmarkDirectory) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig, benchmarkDirectory); return create(benchmarkConfig); } // ************************************************************************ // Interface methods // ************************************************************************ /** * Creates a new {@link PlannerBenchmark} instance. */ public abstract @NonNull PlannerBenchmark buildPlannerBenchmark(); /** * Creates a new {@link PlannerBenchmark} instance for datasets that are already in memory. * * @param problemList can be empty * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public <Solution_> @NonNull PlannerBenchmark buildPlannerBenchmark(@NonNull List<@NonNull Solution_> problemList) { return buildPlannerBenchmark(problemList.toArray()); } /** * Creates a new {@link PlannerBenchmark} instance for datasets that are already in memory. * * @param problems can be none * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public abstract <Solution_> @NonNull PlannerBenchmark buildPlannerBenchmark(@NonNull Solution_ @NonNull... problems); }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/api/package-info.java
/** * The public API of Timefold Benchmark. * <p> * All classes in this namespace are backwards compatible in future releases (especially minor and hotfix releases). * If a major version number changes, a few specific classes might not be backwards compatible, in which case * <a href="https://docs.timefold.ai/timefold-solver/latest/upgrading-timefold-solver/upgrade-to-latest-version">the upgrade * recipe</a> * will clearly document those cases. */ package ai.timefold.solver.benchmark.api;
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/PlannerBenchmarkConfig.java
package ai.timefold.solver.benchmark.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadFactory; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlTransient; import jakarta.xml.bind.annotation.XmlType; import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory; import ai.timefold.solver.benchmark.config.blueprint.SolverBenchmarkBluePrintConfig; import ai.timefold.solver.benchmark.config.report.BenchmarkReportConfig; import ai.timefold.solver.benchmark.impl.io.PlannerBenchmarkConfigIO; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.core.config.solver.SolverConfig; import ai.timefold.solver.core.impl.io.jaxb.TimefoldXmlSerializationException; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; /** * To read it from XML, use {@link #createFromXmlResource(String)}. * To build a {@link PlannerBenchmarkFactory} with it, use {@link PlannerBenchmarkFactory#create(PlannerBenchmarkConfig)}. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = PlannerBenchmarkConfig.XML_ELEMENT_NAME) @XmlType(propOrder = { "name", "benchmarkDirectory", "threadFactoryClass", "parallelBenchmarkCount", "warmUpMillisecondsSpentLimit", "warmUpSecondsSpentLimit", "warmUpMinutesSpentLimit", "warmUpHoursSpentLimit", "warmUpDaysSpentLimit", "benchmarkReportConfig", "inheritedSolverBenchmarkConfig", "solverBenchmarkBluePrintConfigList", "solverBenchmarkConfigList" }) public class PlannerBenchmarkConfig { public static final String SOLVER_NAMESPACE_PREFIX = "solver"; public static final String XML_ELEMENT_NAME = "plannerBenchmark"; public static final String XML_NAMESPACE = "https://timefold.ai/xsd/benchmark"; // ************************************************************************ // Static creation methods: SolverConfig // ************************************************************************ public static @NonNull PlannerBenchmarkConfig createFromSolverConfig(@NonNull SolverConfig solverConfig) { return createFromSolverConfig(solverConfig, new File("local/benchmarkReport")); } public static @NonNull PlannerBenchmarkConfig createFromSolverConfig(@NonNull SolverConfig solverConfig, @NonNull File benchmarkDirectory) { PlannerBenchmarkConfig plannerBenchmarkConfig = new PlannerBenchmarkConfig(); plannerBenchmarkConfig.setBenchmarkDirectory(benchmarkDirectory); SolverBenchmarkConfig solverBenchmarkConfig = new SolverBenchmarkConfig(); // Defensive copy of solverConfig solverBenchmarkConfig.setSolverConfig(new SolverConfig(solverConfig)); plannerBenchmarkConfig.setInheritedSolverBenchmarkConfig(solverBenchmarkConfig); plannerBenchmarkConfig.setSolverBenchmarkConfigList(Collections.singletonList(new SolverBenchmarkConfig())); return plannerBenchmarkConfig; } // ************************************************************************ // Static creation methods: XML // ************************************************************************ /** * Reads an XML benchmark configuration from the classpath. * * @param benchmarkConfigResource a classpath resource * as defined by {@link ClassLoader#getResource(String)} */ public static @NonNull PlannerBenchmarkConfig createFromXmlResource(@NonNull String benchmarkConfigResource) { return createFromXmlResource(benchmarkConfigResource, null); } /** * As defined by {@link #createFromXmlResource(String)}. * * @param benchmarkConfigResource a classpath resource * as defined by {@link ClassLoader#getResource(String)} * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromXmlResource(@NonNull String benchmarkConfigResource, @Nullable ClassLoader classLoader) { ClassLoader actualClassLoader = classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader(); try (InputStream in = actualClassLoader.getResourceAsStream(benchmarkConfigResource)) { if (in == null) { String errorMessage = "The benchmarkConfigResource (" + benchmarkConfigResource + ") does not exist as a classpath resource in the classLoader (" + actualClassLoader + ")."; if (benchmarkConfigResource.startsWith("/")) { errorMessage += "\nA classpath resource should not start with a slash (/)." + " A benchmarkConfigResource adheres to ClassLoader.getResource(String)." + " Maybe remove the leading slash from the benchmarkConfigResource."; } throw new IllegalArgumentException(errorMessage); } return createFromXmlInputStream(in, classLoader); } catch (TimefoldXmlSerializationException e) { throw new IllegalArgumentException("Unmarshalling of benchmarkConfigResource (" + benchmarkConfigResource + ") fails.", e); } catch (IOException e) { throw new IllegalArgumentException("Reading the benchmarkConfigResource (" + benchmarkConfigResource + ") fails.", e); } } /** * Reads an XML benchmark configuration from the file system. * <p> * Warning: this leads to platform dependent code, * it's recommend to use {@link #createFromXmlResource(String)} instead. */ public static @NonNull PlannerBenchmarkConfig createFromXmlFile(@NonNull File benchmarkConfigFile) { return createFromXmlFile(benchmarkConfigFile, null); } /** * As defined by {@link #createFromXmlFile(File)}. * * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromXmlFile(@NonNull File benchmarkConfigFile, @Nullable ClassLoader classLoader) { try (InputStream in = new FileInputStream(benchmarkConfigFile)) { return createFromXmlInputStream(in, classLoader); } catch (TimefoldXmlSerializationException e) { throw new IllegalArgumentException("Unmarshalling the benchmarkConfigFile (" + benchmarkConfigFile + ") fails.", e); } catch (FileNotFoundException e) { throw new IllegalArgumentException("The benchmarkConfigFile (" + benchmarkConfigFile + ") was not found.", e); } catch (IOException e) { throw new IllegalArgumentException("Reading the benchmarkConfigFile (" + benchmarkConfigFile + ") fails.", e); } } /** * @param in gets closed */ public static @NonNull PlannerBenchmarkConfig createFromXmlInputStream(@NonNull InputStream in) { return createFromXmlInputStream(in, null); } /** * @param in gets closed * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromXmlInputStream(@NonNull InputStream in, @Nullable ClassLoader classLoader) { try (Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) { return createFromXmlReader(reader, classLoader); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("This vm does not support the charset (" + StandardCharsets.UTF_8 + ").", e); } catch (IOException e) { throw new IllegalArgumentException("Reading fails.", e); } } /** * @param reader gets closed */ public static @NonNull PlannerBenchmarkConfig createFromXmlReader(@NonNull Reader reader) { return createFromXmlReader(reader, null); } /** * @param reader gets closed * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromXmlReader(@NonNull Reader reader, @Nullable ClassLoader classLoader) { PlannerBenchmarkConfigIO xmlIO = new PlannerBenchmarkConfigIO(); Object benchmarkConfigObject = xmlIO.read(reader); if (!(benchmarkConfigObject instanceof PlannerBenchmarkConfig)) { throw new IllegalArgumentException("The " + PlannerBenchmarkConfig.class.getSimpleName() + "'s XML root element resolves to a different type (" + (benchmarkConfigObject == null ? null : benchmarkConfigObject.getClass().getSimpleName()) + ")." + (benchmarkConfigObject instanceof SolverConfig ? "\nMaybe use " + PlannerBenchmarkFactory.class.getSimpleName() + ".createFromSolverConfigXmlResource() instead." : "")); } PlannerBenchmarkConfig benchmarkConfig = (PlannerBenchmarkConfig) benchmarkConfigObject; benchmarkConfig.setClassLoader(classLoader); return benchmarkConfig; } // ************************************************************************ // Static creation methods: Freemarker XML // ************************************************************************ /** * Reads a Freemarker XML benchmark configuration from the classpath. * * @param templateResource a classpath resource as defined by {@link ClassLoader#getResource(String)} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlResource(@NonNull String templateResource) { return createFromFreemarkerXmlResource(templateResource, null); } /** * As defined by {@link #createFromFreemarkerXmlResource(String)}. * * @param templateResource a classpath resource as defined by {@link ClassLoader#getResource(String)} * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlResource(@NonNull String templateResource, @Nullable ClassLoader classLoader) { return createFromFreemarkerXmlResource(templateResource, null, classLoader); } /** * As defined by {@link #createFromFreemarkerXmlResource(String)}. * * @param templateResource a classpath resource as defined by {@link ClassLoader#getResource(String)} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlResource(@NonNull String templateResource, @Nullable Object model) { return createFromFreemarkerXmlResource(templateResource, model, null); } /** * As defined by {@link #createFromFreemarkerXmlResource(String)}. * * @param templateResource a classpath resource as defined by {@link ClassLoader#getResource(String)} * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlResource(@NonNull String templateResource, @Nullable Object model, @Nullable ClassLoader classLoader) { ClassLoader actualClassLoader = classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader(); try (InputStream templateIn = actualClassLoader.getResourceAsStream(templateResource)) { if (templateIn == null) { String errorMessage = "The templateResource (" + templateResource + ") does not exist as a classpath resource in the classLoader (" + actualClassLoader + ")."; if (templateResource.startsWith("/")) { errorMessage += "\nA classpath resource should not start with a slash (/)." + " A templateResource adheres to ClassLoader.getResource(String)." + " Maybe remove the leading slash from the templateResource."; } throw new IllegalArgumentException(errorMessage); } return createFromFreemarkerXmlInputStream(templateIn, model, classLoader); } catch (IOException e) { throw new IllegalArgumentException("Reading the templateResource (" + templateResource + ") fails.", e); } } /** * Reads a Freemarker XML benchmark configuration from the file system. * <p> * Warning: this leads to platform dependent code, * it's recommend to use {@link #createFromFreemarkerXmlResource(String)} instead. */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlFile(@NonNull File templateFile) { return createFromFreemarkerXmlFile(templateFile, null); } /** * As defined by {@link #createFromFreemarkerXmlFile(File)}. * * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlFile(@NonNull File templateFile, @Nullable ClassLoader classLoader) { return createFromFreemarkerXmlFile(templateFile, null, classLoader); } /** * As defined by {@link #createFromFreemarkerXmlFile(File)}. */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlFile(@NonNull File templateFile, @Nullable Object model) { return createFromFreemarkerXmlFile(templateFile, model, null); } /** * As defined by {@link #createFromFreemarkerXmlFile(File)}. * * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlFile(@NonNull File templateFile, @Nullable Object model, @Nullable ClassLoader classLoader) { try (FileInputStream templateIn = new FileInputStream(templateFile)) { return createFromFreemarkerXmlInputStream(templateIn, model, classLoader); } catch (FileNotFoundException e) { throw new IllegalArgumentException("The templateFile (" + templateFile + ") was not found.", e); } catch (IOException e) { throw new IllegalArgumentException("Reading the templateFile (" + templateFile + ") fails.", e); } } /** * @param templateIn gets closed */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlInputStream(@NonNull InputStream templateIn) { return createFromFreemarkerXmlInputStream(templateIn, null); } /** * As defined by {@link #createFromFreemarkerXmlInputStream(InputStream)}. * * @param templateIn gets closed * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlInputStream(@NonNull InputStream templateIn, @Nullable ClassLoader classLoader) { return createFromFreemarkerXmlInputStream(templateIn, null, classLoader); } /** * As defined by {@link #createFromFreemarkerXmlInputStream(InputStream)}. * * @param templateIn gets closed */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlInputStream(@NonNull InputStream templateIn, @Nullable Object model) { return createFromFreemarkerXmlInputStream(templateIn, model, null); } /** * As defined by {@link #createFromFreemarkerXmlInputStream(InputStream)}. * * @param templateIn gets closed * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlInputStream(@NonNull InputStream templateIn, @Nullable Object model, @Nullable ClassLoader classLoader) { try (Reader reader = new InputStreamReader(templateIn, StandardCharsets.UTF_8)) { return createFromFreemarkerXmlReader(reader, model, classLoader); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("This vm does not support the charset (" + StandardCharsets.UTF_8 + ").", e); } catch (IOException e) { throw new IllegalArgumentException("Reading fails.", e); } } /** * @param templateReader gets closed */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlReader(@NonNull Reader templateReader) { return createFromFreemarkerXmlReader(templateReader, null); } /** * As defined by {@link #createFromFreemarkerXmlReader(Reader)}. * * @param templateReader gets closed * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlReader(@NonNull Reader templateReader, @Nullable ClassLoader classLoader) { return createFromFreemarkerXmlReader(templateReader, null, classLoader); } /** * As defined by {@link #createFromFreemarkerXmlReader(Reader)}. * * @param templateReader gets closed */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlReader(@NonNull Reader templateReader, @Nullable Object model) { return createFromFreemarkerXmlReader(templateReader, model, null); } /** * As defined by {@link #createFromFreemarkerXmlReader(Reader)}. * * @param templateReader gets closed * @param classLoader the {@link ClassLoader} to use for loading all resources and {@link Class}es, * null to use the default {@link ClassLoader} */ public static @NonNull PlannerBenchmarkConfig createFromFreemarkerXmlReader(@NonNull Reader templateReader, @Nullable Object model, @Nullable ClassLoader classLoader) { Configuration freemarkerConfiguration = BenchmarkReport.createFreeMarkerConfiguration(); freemarkerConfiguration.setNumberFormat("computer"); freemarkerConfiguration.setDateFormat("yyyy-mm-dd"); freemarkerConfiguration.setDateTimeFormat("yyyy-mm-dd HH:mm:ss.SSS z"); freemarkerConfiguration.setTimeFormat("HH:mm:ss.SSS"); String xmlContent; try (StringWriter xmlContentWriter = new StringWriter()) { Template template = new Template("benchmarkTemplate.ftl", templateReader, freemarkerConfiguration, freemarkerConfiguration.getDefaultEncoding()); template.process(model, xmlContentWriter); xmlContent = xmlContentWriter.toString(); } catch (TemplateException | IOException e) { throw new IllegalArgumentException("Can not process the Freemarker template into xmlContentWriter.", e); } try (StringReader configReader = new StringReader(xmlContent)) { return createFromXmlReader(configReader, classLoader); } } // ************************************************************************ // Fields // ************************************************************************ public static final String PARALLEL_BENCHMARK_COUNT_AUTO = "AUTO"; @XmlTransient private ClassLoader classLoader = null; private String name = null; private File benchmarkDirectory = null; private Class<? extends ThreadFactory> threadFactoryClass = null; private String parallelBenchmarkCount = null; private Long warmUpMillisecondsSpentLimit = null; private Long warmUpSecondsSpentLimit = null; private Long warmUpMinutesSpentLimit = null; private Long warmUpHoursSpentLimit = null; private Long warmUpDaysSpentLimit = null; @XmlElement(name = "benchmarkReport") private BenchmarkReportConfig benchmarkReportConfig = null; @XmlElement(name = "inheritedSolverBenchmark") private SolverBenchmarkConfig inheritedSolverBenchmarkConfig = null; @XmlElement(name = "solverBenchmarkBluePrint") private List<SolverBenchmarkBluePrintConfig> solverBenchmarkBluePrintConfigList = null; @XmlElement(name = "solverBenchmark") private List<SolverBenchmarkConfig> solverBenchmarkConfigList = null; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ /** * Create an empty benchmark config. */ public PlannerBenchmarkConfig() { } public PlannerBenchmarkConfig(@Nullable ClassLoader classLoader) { this.classLoader = classLoader; } public @Nullable ClassLoader getClassLoader() { return classLoader; } public void setClassLoader(@Nullable ClassLoader classLoader) { this.classLoader = classLoader; } public @Nullable String getName() { return name; } public void setName(@Nullable String name) { this.name = name; } public @Nullable File getBenchmarkDirectory() { return benchmarkDirectory; } public void setBenchmarkDirectory(@Nullable File benchmarkDirectory) { this.benchmarkDirectory = benchmarkDirectory; } public @Nullable Class<? extends ThreadFactory> getThreadFactoryClass() { return threadFactoryClass; } public void setThreadFactoryClass(@Nullable Class<? extends ThreadFactory> threadFactoryClass) { this.threadFactoryClass = threadFactoryClass; } /** * Using multiple parallel benchmarks can decrease the reliability of the results. * <p> * If there aren't enough processors available, it will be decreased. * * @return null, a number or {@value #PARALLEL_BENCHMARK_COUNT_AUTO}. */ public @Nullable String getParallelBenchmarkCount() { return parallelBenchmarkCount; } public void setParallelBenchmarkCount(@Nullable String parallelBenchmarkCount) { this.parallelBenchmarkCount = parallelBenchmarkCount; } public @Nullable Long getWarmUpMillisecondsSpentLimit() { return warmUpMillisecondsSpentLimit; } public void setWarmUpMillisecondsSpentLimit(@Nullable Long warmUpMillisecondsSpentLimit) { this.warmUpMillisecondsSpentLimit = warmUpMillisecondsSpentLimit; } public @Nullable Long getWarmUpSecondsSpentLimit() { return warmUpSecondsSpentLimit; } public void setWarmUpSecondsSpentLimit(@Nullable Long warmUpSecondsSpentLimit) { this.warmUpSecondsSpentLimit = warmUpSecondsSpentLimit; } public @Nullable Long getWarmUpMinutesSpentLimit() { return warmUpMinutesSpentLimit; } public void setWarmUpMinutesSpentLimit(@Nullable Long warmUpMinutesSpentLimit) { this.warmUpMinutesSpentLimit = warmUpMinutesSpentLimit; } public @Nullable Long getWarmUpHoursSpentLimit() { return warmUpHoursSpentLimit; } public void setWarmUpHoursSpentLimit(@Nullable Long warmUpHoursSpentLimit) { this.warmUpHoursSpentLimit = warmUpHoursSpentLimit; } public @Nullable Long getWarmUpDaysSpentLimit() { return warmUpDaysSpentLimit; } public void setWarmUpDaysSpentLimit(@Nullable Long warmUpDaysSpentLimit) { this.warmUpDaysSpentLimit = warmUpDaysSpentLimit; } public @Nullable BenchmarkReportConfig getBenchmarkReportConfig() { return benchmarkReportConfig; } public void setBenchmarkReportConfig(@Nullable BenchmarkReportConfig benchmarkReportConfig) { this.benchmarkReportConfig = benchmarkReportConfig; } public @Nullable SolverBenchmarkConfig getInheritedSolverBenchmarkConfig() { return inheritedSolverBenchmarkConfig; } public void setInheritedSolverBenchmarkConfig(@Nullable SolverBenchmarkConfig inheritedSolverBenchmarkConfig) { this.inheritedSolverBenchmarkConfig = inheritedSolverBenchmarkConfig; } public @Nullable List<@NonNull SolverBenchmarkBluePrintConfig> getSolverBenchmarkBluePrintConfigList() { return solverBenchmarkBluePrintConfigList; } public void setSolverBenchmarkBluePrintConfigList( @Nullable List<@NonNull SolverBenchmarkBluePrintConfig> solverBenchmarkBluePrintConfigList) { this.solverBenchmarkBluePrintConfigList = solverBenchmarkBluePrintConfigList; } public @Nullable List<@NonNull SolverBenchmarkConfig> getSolverBenchmarkConfigList() { return solverBenchmarkConfigList; } public void setSolverBenchmarkConfigList(@Nullable List<@NonNull SolverBenchmarkConfig> solverBenchmarkConfigList) { this.solverBenchmarkConfigList = solverBenchmarkConfigList; } // ************************************************************************ // With methods // ************************************************************************ public @NonNull PlannerBenchmarkConfig withClassLoader(@NonNull ClassLoader classLoader) { this.setClassLoader(classLoader); return this; } public @NonNull PlannerBenchmarkConfig withName(@NonNull String name) { this.setName(name); return this; } public @NonNull PlannerBenchmarkConfig withBenchmarkDirectory(@NonNull File benchmarkDirectory) { this.setBenchmarkDirectory(benchmarkDirectory); return this; } public @NonNull PlannerBenchmarkConfig withThreadFactoryClass(@NonNull Class<? extends ThreadFactory> threadFactoryClass) { this.setThreadFactoryClass(threadFactoryClass); return this; } public @NonNull PlannerBenchmarkConfig withParallelBenchmarkCount(@NonNull String parallelBenchmarkCount) { this.setParallelBenchmarkCount(parallelBenchmarkCount); return this; } public @NonNull PlannerBenchmarkConfig withWarmUpMillisecondsSpentLimit(@NonNull Long warmUpMillisecondsSpentLimit) { this.setWarmUpMillisecondsSpentLimit(warmUpMillisecondsSpentLimit); return this; } public @NonNull PlannerBenchmarkConfig withWarmUpSecondsSpentLimit(@NonNull Long warmUpSecondsSpentLimit) { this.setWarmUpSecondsSpentLimit(warmUpSecondsSpentLimit); return this; } public @NonNull PlannerBenchmarkConfig withWarmUpMinutesSpentLimit(@NonNull Long warmUpMinutesSpentLimit) { this.setWarmUpMinutesSpentLimit(warmUpMinutesSpentLimit); return this; } public @NonNull PlannerBenchmarkConfig withWarmUpHoursSpentLimit(@NonNull Long warmUpHoursSpentLimit) { this.setWarmUpHoursSpentLimit(warmUpHoursSpentLimit); return this; } public @NonNull PlannerBenchmarkConfig withWarmUpDaysSpentLimit(@NonNull Long warmUpDaysSpentLimit) { this.setWarmUpDaysSpentLimit(warmUpDaysSpentLimit); return this; } public @NonNull PlannerBenchmarkConfig withBenchmarkReportConfig(@NonNull BenchmarkReportConfig benchmarkReportConfig) { this.setBenchmarkReportConfig(benchmarkReportConfig); return this; } public @NonNull PlannerBenchmarkConfig withInheritedSolverBenchmarkConfig(@NonNull SolverBenchmarkConfig inheritedSolverBenchmarkConfig) { this.setInheritedSolverBenchmarkConfig(inheritedSolverBenchmarkConfig); return this; } public @NonNull PlannerBenchmarkConfig withSolverBenchmarkBluePrintConfigList( @NonNull List<@NonNull SolverBenchmarkBluePrintConfig> solverBenchmarkBluePrintConfigList) { this.setSolverBenchmarkBluePrintConfigList(solverBenchmarkBluePrintConfigList); return this; } public @NonNull PlannerBenchmarkConfig withSolverBenchmarkBluePrintConfigs( @NonNull SolverBenchmarkBluePrintConfig... solverBenchmarkBluePrintConfigs) { this.setSolverBenchmarkBluePrintConfigList(List.of(solverBenchmarkBluePrintConfigs)); return this; } public @NonNull PlannerBenchmarkConfig withSolverBenchmarkConfigList(@NonNull List<@NonNull SolverBenchmarkConfig> solverBenchmarkConfigList) { this.setSolverBenchmarkConfigList(solverBenchmarkConfigList); return this; } public @NonNull PlannerBenchmarkConfig withSolverBenchmarkConfigs(@NonNull SolverBenchmarkConfig... solverBenchmarkConfigs) { this.setSolverBenchmarkConfigList(List.of(solverBenchmarkConfigs)); return this; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/ProblemBenchmarksConfig.java
package ai.timefold.solver.benchmark.config; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.config.statistic.SingleStatisticType; import ai.timefold.solver.core.config.AbstractConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; @XmlType(propOrder = { "solutionFileIOClass", "writeOutputSolutionEnabled", "inputSolutionFileList", "problemStatisticEnabled", "problemStatisticTypeList", "singleStatisticTypeList" }) public class ProblemBenchmarksConfig extends AbstractConfig<ProblemBenchmarksConfig> { private Class<? extends SolutionFileIO<?>> solutionFileIOClass = null; private Boolean writeOutputSolutionEnabled = null; @XmlElement(name = "inputSolutionFile") private List<File> inputSolutionFileList = null; private Boolean problemStatisticEnabled = null; @XmlElement(name = "problemStatisticType") private List<ProblemStatisticType> problemStatisticTypeList = null; @XmlElement(name = "singleStatisticType") private List<SingleStatisticType> singleStatisticTypeList = null; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ public @Nullable Class<? extends SolutionFileIO<?>> getSolutionFileIOClass() { return solutionFileIOClass; } public void setSolutionFileIOClass(@Nullable Class<? extends SolutionFileIO<?>> solutionFileIOClass) { this.solutionFileIOClass = solutionFileIOClass; } public @Nullable Boolean getWriteOutputSolutionEnabled() { return writeOutputSolutionEnabled; } public void setWriteOutputSolutionEnabled(@Nullable Boolean writeOutputSolutionEnabled) { this.writeOutputSolutionEnabled = writeOutputSolutionEnabled; } public @Nullable List<@NonNull File> getInputSolutionFileList() { return inputSolutionFileList; } public void setInputSolutionFileList(@Nullable List<@NonNull File> inputSolutionFileList) { this.inputSolutionFileList = inputSolutionFileList; } public @Nullable Boolean getProblemStatisticEnabled() { return problemStatisticEnabled; } public void setProblemStatisticEnabled(@Nullable Boolean problemStatisticEnabled) { this.problemStatisticEnabled = problemStatisticEnabled; } public @Nullable List<@NonNull ProblemStatisticType> getProblemStatisticTypeList() { return problemStatisticTypeList; } public void setProblemStatisticTypeList(@Nullable List<@NonNull ProblemStatisticType> problemStatisticTypeList) { this.problemStatisticTypeList = problemStatisticTypeList; } public @Nullable List<@NonNull SingleStatisticType> getSingleStatisticTypeList() { return singleStatisticTypeList; } public void setSingleStatisticTypeList(@Nullable List<@NonNull SingleStatisticType> singleStatisticTypeList) { this.singleStatisticTypeList = singleStatisticTypeList; } // ************************************************************************ // With methods // ************************************************************************ public @NonNull ProblemBenchmarksConfig withSolutionFileIOClass(@NonNull Class<? extends SolutionFileIO<?>> solutionFileIOClass) { this.setSolutionFileIOClass(solutionFileIOClass); return this; } public @NonNull ProblemBenchmarksConfig withWriteOutputSolutionEnabled(@NonNull Boolean writeOutputSolutionEnabled) { this.setWriteOutputSolutionEnabled(writeOutputSolutionEnabled); return this; } public @NonNull ProblemBenchmarksConfig withInputSolutionFileList(@NonNull List<@NonNull File> inputSolutionFileList) { this.setInputSolutionFileList(inputSolutionFileList); return this; } public @NonNull ProblemBenchmarksConfig withInputSolutionFiles(@NonNull File... inputSolutionFiles) { this.setInputSolutionFileList(List.of(inputSolutionFiles)); return this; } public @NonNull ProblemBenchmarksConfig withProblemStatisticsEnabled(@NonNull Boolean problemStatisticEnabled) { this.setProblemStatisticEnabled(problemStatisticEnabled); return this; } public @NonNull ProblemBenchmarksConfig withProblemStatisticTypeList(@NonNull List<@NonNull ProblemStatisticType> problemStatisticTypeList) { this.setProblemStatisticTypeList(problemStatisticTypeList); return this; } public @NonNull ProblemBenchmarksConfig withProblemStatisticTypes(@NonNull ProblemStatisticType... problemStatisticTypes) { this.setProblemStatisticTypeList(List.of(problemStatisticTypes)); return this; } public @NonNull ProblemBenchmarksConfig withSingleStatisticTypeList(@NonNull List<@NonNull SingleStatisticType> singleStatisticTypeList) { this.setSingleStatisticTypeList(singleStatisticTypeList); return this; } public @NonNull ProblemBenchmarksConfig withSingleStatisticTypes(@NonNull SingleStatisticType... singleStatisticTypes) { this.setSingleStatisticTypeList(List.of(singleStatisticTypes)); return this; } // ************************************************************************ // Complex methods // ************************************************************************ /** * Return the problem statistic type list, or a list containing default metrics if problemStatisticEnabled * is not false. If problemStatisticEnabled is false, an empty list is returned. */ public @NonNull List<@NonNull ProblemStatisticType> determineProblemStatisticTypeList() { if (problemStatisticEnabled != null && !problemStatisticEnabled) { return Collections.emptyList(); } if (problemStatisticTypeList == null || problemStatisticTypeList.isEmpty()) { return ProblemStatisticType.defaultList(); } return problemStatisticTypeList; } /** * Return the single statistic type list, or an empty list if it is null */ public @NonNull List<@NonNull SingleStatisticType> determineSingleStatisticTypeList() { return Objects.requireNonNullElse(singleStatisticTypeList, Collections.emptyList()); } @Override public @NonNull ProblemBenchmarksConfig inherit(@NonNull ProblemBenchmarksConfig inheritedConfig) { solutionFileIOClass = ConfigUtils.inheritOverwritableProperty(solutionFileIOClass, inheritedConfig.getSolutionFileIOClass()); writeOutputSolutionEnabled = ConfigUtils.inheritOverwritableProperty(writeOutputSolutionEnabled, inheritedConfig.getWriteOutputSolutionEnabled()); inputSolutionFileList = ConfigUtils.inheritMergeableListProperty(inputSolutionFileList, inheritedConfig.getInputSolutionFileList()); problemStatisticEnabled = ConfigUtils.inheritOverwritableProperty(problemStatisticEnabled, inheritedConfig.getProblemStatisticEnabled()); problemStatisticTypeList = ConfigUtils.inheritUniqueMergeableListProperty(problemStatisticTypeList, inheritedConfig.getProblemStatisticTypeList()); singleStatisticTypeList = ConfigUtils.inheritUniqueMergeableListProperty(singleStatisticTypeList, inheritedConfig.getSingleStatisticTypeList()); return this; } @Override public @NonNull ProblemBenchmarksConfig copyConfig() { return new ProblemBenchmarksConfig().inherit(this); } @Override public void visitReferencedClasses(@NonNull Consumer<Class<?>> classVisitor) { classVisitor.accept(solutionFileIOClass); } }