public boolean isMessageIdRequired() {
        return false;
    }

/**
 * ****************************************************************************
 *
 *  Contributors:
 *     Dave Locke - initial API and implementation and/or initial documentation
 */
package top.fighter_lee.mqttlibs.mqttv3.internal.wire;

import java.io.IOException;
import top.fighter_lee.mqttlibs.mqttv3.MqttException;

/**
 * An on-the-wire representation of an MQTT DISCONNECT message.
 */
public class MqttDisconnect extends MqttWireMessage {

    public static final String KEY = "Disc";

    public MqttDisconnect() {
        super(MqttWireMessage.MESSAGE_TYPE_DISCONNECT);
    }

    public MqttDisconnect(byte info, byte[] variableHeader) throws IOException {
        super(MqttWireMessage.MESSAGE_TYPE_DISCONNECT);
    }

    protected byte getMessageInfo() {
        return (byte) 0;
    }

    protected byte[] getVariableHeader() throws MqttException {
        return new byte[0];
    }

    /**
     * Returns whether or not this message needs to include a message ID.
     */

    public String getKey() {
        return KEY;
    }
}


void inject(Object object, SporkInstance sporkInstance);

package spork.inject;

import spork.SporkInstance;

public interface ObjectGraph {

    /**
     * A shortcut to Spork.bind(Object, ObjectGraph).
     * This binds all known annotations for the shared SporkInstance instance including spork-inject.
     * @param object the object to bind
     */
    void inject(Object object);

    /**
     * A shortcut to spork.getBinder().bind(Object, ObjectGraph)
     * This binds all known annotations for the given SporkInstance instance including spork-inject.
     * @param object the object to bind
     */


package org.lasarobotics.vision.detection.objects;

import org.lasarobotics.vision.util.MathUtil;
import org.lasarobotics.vision.util.color.Color;
import org.lasarobotics.vision.util.color.ColorSpace;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import java.util.List;

/**
 * A detectable object
 */
public abstract class Detectable {

    /**
     * Offset a list of objects, translating them by a specific offset point
     *
     * @param detectables List of detectables
     * @param offset      Point to offset by, e.g. (1, 0) would move objects 1 px right
     * @return Modified list of detectables
     */
    public static List<? extends Detectable> offset(List<? extends Detectable> detectables, Point offset) {
        for (int i = 0; i < detectables.size(); i++) detectables.get(i).offset(offset);
        return detectables;
    }

    /**
     * Get the x-coordinate of the left side of the object
     *
     * @return Left side of the object
     */
    protected abstract double left();

    /**
     * Get the x-coordinate of the right side of the object
     *
     * @return Right side of the object
     */
    protected abstract double right();

    /**
     * Get the y-coordinate of the top side of the object
     *
     * @return Top side of the object
     */
    protected abstract double top();

    /**
     * Get the y-coordinate of the bottom side of the object
     *
     * @return Bottom side of the object
     */

    /**
     * Get the width of the object
     *
     * @return Width of the object
     */
    public abstract double width();

    /**
     * Get the height of the object
     *
     * @return Height of the object
     */
    public abstract double height();

    /**
     * Get the top-left point of the object
     *
     * @return Top-left point of the object
     */
    public Point topLeft() {
        return new Point(left(), top());
    }

    /**
     * Get the bottom right point of the object
     *
     * @return Bottom right point of the object
     */
    public Point bottomRight() {
        return new Point(right(), bottom());
    }

    /**
     * Gets the average color of the object
     *
     * @param img      The image matrix, of any color size
     * @param imgSpace The image's color space
     * @return The average color of the region
     */
    public Color averageColor(Mat img, ColorSpace imgSpace) {
        // Coerce values to stay within screen dimensions
        double leftX = MathUtil.coerce(0, img.cols() - 1, left());
        double rightX = MathUtil.coerce(0, img.cols() - 1, right());
        double topY = MathUtil.coerce(0, img.rows() - 1, top());
        double bottomY = MathUtil.coerce(0, img.rows() - 1, bottom());
        // Input points into array for calculation
        // TODO rectangular submatrix-based calculation isn't perfectly accurate when you have ellipses or weird shapes
        Mat subMat = img.submat((int) topY, (int) bottomY, (int) leftX, (int) rightX);
        // Calculate average and return new color instance
        return Color.create(Core.mean(subMat), imgSpace);
    }

    /**
     * Offset the object, translating it by a specific offset point
     *
     * @param offset Point to offset by, e.g. (1, 0) would move object 1 px right
     */
    public abstract void offset(Point offset);
}


for (int i = 0; i < detectables.size(); i++) detectables.get(i).offset(offset);

package org.lasarobotics.vision.detection.objects;

import org.lasarobotics.vision.util.MathUtil;
import org.lasarobotics.vision.util.color.Color;
import org.lasarobotics.vision.util.color.ColorSpace;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import java.util.List;

/**
 * A detectable object
 */
public abstract class Detectable {

    /**
     * Offset a list of objects, translating them by a specific offset point
     *
     * @param detectables List of detectables
     * @param offset      Point to offset by, e.g. (1, 0) would move objects 1 px right
     * @return Modified list of detectables
     */
    public static List<? extends Detectable> offset(List<? extends Detectable> detectables, Point offset) {

        return detectables;
    }

    /**
     * Get the x-coordinate of the left side of the object
     *
     * @return Left side of the object
     */
    protected abstract double left();

    /**
     * Get the x-coordinate of the right side of the object
     *
     * @return Right side of the object
     */
    protected abstract double right();

    /**
     * Get the y-coordinate of the top side of the object
     *
     * @return Top side of the object
     */
    protected abstract double top();

    /**
     * Get the y-coordinate of the bottom side of the object
     *
     * @return Bottom side of the object
     */
    protected abstract double bottom();

    /**
     * Get the width of the object
     *
     * @return Width of the object
     */
    public abstract double width();

    /**
     * Get the height of the object
     *
     * @return Height of the object
     */
    public abstract double height();

    /**
     * Get the top-left point of the object
     *
     * @return Top-left point of the object
     */
    public Point topLeft() {
        return new Point(left(), top());
    }

    /**
     * Get the bottom right point of the object
     *
     * @return Bottom right point of the object
     */
    public Point bottomRight() {
        return new Point(right(), bottom());
    }

    /**
     * Gets the average color of the object
     *
     * @param img      The image matrix, of any color size
     * @param imgSpace The image's color space
     * @return The average color of the region
     */
    public Color averageColor(Mat img, ColorSpace imgSpace) {
        // Coerce values to stay within screen dimensions
        double leftX = MathUtil.coerce(0, img.cols() - 1, left());
        double rightX = MathUtil.coerce(0, img.cols() - 1, right());
        double topY = MathUtil.coerce(0, img.rows() - 1, top());
        double bottomY = MathUtil.coerce(0, img.rows() - 1, bottom());
        // Input points into array for calculation
        // TODO rectangular submatrix-based calculation isn't perfectly accurate when you have ellipses or weird shapes
        Mat subMat = img.submat((int) topY, (int) bottomY, (int) leftX, (int) rightX);
        // Calculate average and return new color instance
        return Color.create(Core.mean(subMat), imgSpace);
    }

    /**
     * Offset the object, translating it by a specific offset point
     *
     * @param offset Point to offset by, e.g. (1, 0) would move object 1 px right
     */
    public abstract void offset(Point offset);
}


package io.vproxy.base.util;

import io.vproxy.base.util.thread.VProxyThread;
import io.vproxy.vfd.DatagramFD;
import io.vproxy.vfd.FDProvider;
import io.vproxy.vfd.IP;
import io.vproxy.vfd.IPPort;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.Set;

public class Logger {

    public static final boolean stackTraceOn;

    public static final boolean lowLevelDebugOn;

    public static final boolean lowLevelNetDebugOn;

    public static final String DEBUG_COLOR = "\033[0;36m";

    public static final String INFO_COLOR = "\033[0;32m";

    public static final String WARN_COLOR = "\033[0;33m";

    public static final String ERROR_COLOR = "\033[0;31m";

    public static final String RESET_COLOR = "\033[0m";

    private static DatagramFD logChannel;

    static {
        {
            String debug = Utils.getSystemProperty("debug");
            lowLevelDebugOn = !"off".equals(debug);
        }
        {
            String debug = System.getProperty("javax.net.debug");
            lowLevelNetDebugOn = "all".equals(debug) || "vproxy".equals(debug);
        }
        {
            if (lowLevelDebugOn && Utils.assertOn()) {
                stackTraceOn = true;
            } else {
                String stackTrace = Utils.getSystemProperty("stacktrace", "off");
                stackTraceOn = !"off".equals(stackTrace);
            }
        }
    }

    public static boolean debugOn() {
        return lowLevelDebugOn || lowLevelNetDebugOn;
    }

    private Logger() {
    }

    private static String fillToTen(int n) {
        return (n < 10 ? "0" : "") + n;
    }

    private static String fillToHundred(int n) {
        return (n < 10 ? "00" : (n < 100 ? "0" : "")) + n;
    }

    @SuppressWarnings("deprecation")
    private static String current() {
        long cur = FDProvider.get().currentTimeMillis();
        Date d = new Date(cur);
        return "[" + (d.getYear() + 1900) + "-" + fillToTen(d.getMonth() + 1) + "-" + fillToTen(d.getDate()) + " " + fillToTen(d.getHours()) + ":" + fillToTen(d.getMinutes()) + ":" + fillToTen(d.getSeconds()) + "." + fillToHundred((int) (cur % 1000)) + "] ";
    }

    private static StackTraceElement getFirstElementOutOfLoggerLib() {
        var arr = Thread.currentThread().getStackTrace();
        boolean intoLoggerLib = false;
        for (StackTraceElement e : arr) {
            if (e.getClassName().matches(".*Logger\\b.*")) {
                intoLoggerLib = true;
            } else {
                if (intoLoggerLib) {
                    // out of logger lib now
                    return e;
                }
            }
        }
        // should not reach here, however return the last element if it really happens
        return arr[arr.length - 1];
    }

    private static final Set<String> ADD_DEBUG_INFO_CLASS_PREFIX = Set.of("io.vproxy.vswitch.");

    // some message for debugging this project
    // use assert to print this log
    // e.g. assert Logger.lowLevelDebug("i will not be here in production environment")
    public static boolean lowLevelDebug(String msg) {
        if (!lowLevelDebugOn)
            return true;
        return debugLog(msg);
    }

    public static boolean lowLevelNetDebug(String msg) {
        if (!lowLevelNetDebugOn || !lowLevelDebugOn)
            return true;
        return debugLog(msg);
    }

    private static boolean debugLog(String msg) {
        String threadName = Thread.currentThread().getName();
        StackTraceElement elem = getFirstElementOutOfLoggerLib();
        System.out.println(DEBUG_COLOR + current() + threadName + " - " + elem.getClassName() + "#" + elem.getMethodName() + "(" + elem.getLineNumber() + ") - " + RESET_COLOR + getDebugInfo(elem) + msg);
        return true;
    }

    private static String getDebugInfo(StackTraceElement elem) {
        String clsName = elem.getClassName();
        boolean addDebugInfo = false;
        for (String cls : ADD_DEBUG_INFO_CLASS_PREFIX) {
            if (clsName.startsWith(cls)) {
                addDebugInfo = true;
                break;
            }
        }
        if (addDebugInfo) {
            String debugInfo = VProxyThread.current().debugInfo;
            return debugInfo + " - ";
        }
        return "";
    }

    private static void privateErr(String err) {
        String threadName = Thread.currentThread().getName();
        StackTraceElement elem = getFirstElementOutOfLoggerLib();
        System.out.println(ERROR_COLOR + current() + threadName + " - " + elem.getClassName() + "#" + elem.getMethodName() + "(" + elem.getLineNumber() + ") - " + RESET_COLOR + err);
    }

    private static void privatePrintStackTrace(Throwable t) {
        if (stackTraceOn || !(t instanceof Exception) || (t instanceof RuntimeException)) {
            // always print runtime exceptions and errors
            t.printStackTrace(System.out);
        } else {
            StringBuilder sb = new StringBuilder();
            formatExceptionStackTrace(t, sb);
            System.out.println(sb);
        }
    }

    private static void formatExceptionStackTrace(Throwable t, StringBuilder sb) {
        String msg = t.getMessage();
        if (msg == null || msg.isBlank()) {
            sb.append(t.getClass().getName());
        } else {
            sb.append(t.getClass().getName()).append(": ").append(msg.trim());
        }
        if (t.getCause() != null) {
            sb.append(" <= ");
            formatExceptionStackTrace(t.getCause(), sb);
        }
    }

    // unexpected errors, or situation should happen
    public static void fatal(LogType logType, String err) {
        privateErr(logType + " - " + err);
    }

    public static void fatal(LogType logType, String err, Throwable ex) {
        privateErr(logType + " - " + err);
        privatePrintStackTrace(ex);
    }

    // expected errors, but not normal condition
    public static void error(LogType logType, String err) {
        privateErr(logType + " - " + err);
    }

    public static void error(LogType logType, String err, Throwable ex) {
        privateErr(logType + " - " + err);
        privatePrintStackTrace(ex);
    }

    // expected errors, maybe user misuse, and we can recover
    public static void warn(LogType logType, String err) {
        System.out.println(WARN_COLOR + current() + logType + " - " + RESET_COLOR + err);
    }

    public static void warn(LogType logType, String err, Throwable t) {
        System.out.println(WARN_COLOR + current() + logType + " - " + RESET_COLOR + err);
        privatePrintStackTrace(t);
    }

    // expected condition
    public static void info(LogType logType, String msg) {
        System.out.println(INFO_COLOR + current() + logType + " - " + RESET_COLOR + msg);
    }

    public static void trace(LogType logType, String msg) {
        System.out.println(DEBUG_COLOR + current() + logType + " - " + RESET_COLOR + msg);
    }

    public static void shouldNotHappen(String msg) {
        fatal(LogType.UNEXPECTED, "should not happen - " + msg);
    }

    public static void alert(String msg) {
        info(LogType.ALERT, msg);
    }

    public static void access(String msg) {
        info(LogType.ACCESS, msg);
    }

    public static void probe(String msg) {
        String threadName = Thread.currentThread().getName();
        String log = DEBUG_COLOR + current() + threadName + " " + LogType.PROBE + " - " + RESET_COLOR + msg + "\r\n";
        DatagramFD chnl = getLogChannel();
        try {
            chnl.send(ByteBuffer.wrap(log.getBytes()), getLogAddress());
        } catch (IOException e) {
            Logger.shouldNotHappen("sending log message failed", e);
        }
    }

    private static DatagramFD getLogChannel() {
        if (logChannel == null) {
            try {
                logChannel = FDProvider.get().openDatagramFD();
                logChannel.configureBlocking(false);
            } catch (IOException e) {
                shouldNotHappen("open datagram channel as log channel failed", e);
                if (logChannel != null) {
                    try {
                        logChannel.close();
                    } catch (IOException ignore) {
                    }
                }
                logChannel = null;
                throw new RuntimeException(e);
            }
        }
        if (!logChannel.isOpen()) {
            try {
                logChannel.close();
            } catch (IOException ignore) {
            }
            logChannel = null;
            return getLogChannel();
        }
        return logChannel;
    }

    private static IPPort getLogAddress() {
        return new IPPort(IP.from(new byte[] { 127, 0, 0, 1 }), 23456);
    }

    public static void shouldNotHappen(String msg, Throwable err) {
        fatal(LogType.UNEXPECTED, "should not happen - " + msg, err);
    }

    public static boolean printStackTrace(Throwable t) {
        // do not use privatePrintStackTrace, always print here
        t.printStackTrace(System.out);
        return true;
    }

    public static boolean lowLevelNetDebugPrintBytes(byte[] array) {
        if (lowLevelNetDebugOn) {
            printBytes(array);
        }
        return true;
    }

    public static boolean lowLevelNetDebugPrintBytes(byte[] array, int off, int end) {
        if (lowLevelNetDebugOn) {
            printBytes(array, off, end);
        }
        return true;
    }

    public static void printBytes(byte[] array) {
        printBytes(array, 0, array.length);
    }

    public static void printBytes(byte[] array, int off, int end) {
        {
            byte[] tmp = Utils.allocateByteArray(end - off);
            System.arraycopy(array, off, tmp, 0, end - off);
            array = tmp;
        }
        final int bytesPerLine = 36;
        int lastLine = array.length % bytesPerLine;
        if (lastLine == 0) {
            lastLine = bytesPerLine;
        }
        int lines = array.length / bytesPerLine + (lastLine != bytesPerLine ? 1 : 0);
        byte[][] linesArray = new byte[lines][];
        for (int i = 0; i < linesArray.length - 1; ++i) {
            linesArray[i] = Utils.allocateByteArray(bytesPerLine);
        }
        linesArray[linesArray.length - 1] = Utils.allocateByteArray(lastLine);
        for (int i = 0; i < array.length; ++i) {
            int idx0 = i / bytesPerLine;
            int idx1 = i % bytesPerLine;
            linesArray[idx0][idx1] = array[i];
        }
        for (int idx = 0; idx < linesArray.length; idx++) {
            byte[] line = linesArray[idx];
            System.out.print(Utils.bytesToHex(line));
            System.out.print("    ");
            if (idx == linesArray.length - 1) {
                for (int i = 0; i < 2 * (bytesPerLine - lastLine); ++i) {
                    System.out.print(" ");
                }
            }
            char[] cs = new char[line.length];

            System.out.println(new String(cs));
        }
    }

    public static char toPrintableChar(byte bb) {
        int b = bb;
        if (b < 0) {
            b += 256;
        }
        if (b < 32 || b > 126) {
            return '.';
        } else {
            return (char) b;
        }
    }
}


try {
            chnl.send(ByteBuffer.wrap(log.getBytes()), getLogAddress());
        } catch (IOException e) {
            Logger.shouldNotHappen("sending log message failed", e);
        }

package io.vproxy.base.util;

import io.vproxy.base.util.thread.VProxyThread;
import io.vproxy.vfd.DatagramFD;
import io.vproxy.vfd.FDProvider;
import io.vproxy.vfd.IP;
import io.vproxy.vfd.IPPort;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.Set;

public class Logger {

    public static final boolean stackTraceOn;

    public static final boolean lowLevelDebugOn;

    public static final boolean lowLevelNetDebugOn;

    public static final String DEBUG_COLOR = "\033[0;36m";

    public static final String INFO_COLOR = "\033[0;32m";

    public static final String WARN_COLOR = "\033[0;33m";

    public static final String ERROR_COLOR = "\033[0;31m";

    public static final String RESET_COLOR = "\033[0m";

    private static DatagramFD logChannel;

    static {
        {
            String debug = Utils.getSystemProperty("debug");
            lowLevelDebugOn = !"off".equals(debug);
        }
        {
            String debug = System.getProperty("javax.net.debug");
            lowLevelNetDebugOn = "all".equals(debug) || "vproxy".equals(debug);
        }
        {
            if (lowLevelDebugOn && Utils.assertOn()) {
                stackTraceOn = true;
            } else {
                String stackTrace = Utils.getSystemProperty("stacktrace", "off");
                stackTraceOn = !"off".equals(stackTrace);
            }
        }
    }

    public static boolean debugOn() {
        return lowLevelDebugOn || lowLevelNetDebugOn;
    }

    private Logger() {
    }

    private static String fillToTen(int n) {
        return (n < 10 ? "0" : "") + n;
    }

    private static String fillToHundred(int n) {
        return (n < 10 ? "00" : (n < 100 ? "0" : "")) + n;
    }

    @SuppressWarnings("deprecation")
    private static String current() {
        long cur = FDProvider.get().currentTimeMillis();
        Date d = new Date(cur);
        return "[" + (d.getYear() + 1900) + "-" + fillToTen(d.getMonth() + 1) + "-" + fillToTen(d.getDate()) + " " + fillToTen(d.getHours()) + ":" + fillToTen(d.getMinutes()) + ":" + fillToTen(d.getSeconds()) + "." + fillToHundred((int) (cur % 1000)) + "] ";
    }

    private static StackTraceElement getFirstElementOutOfLoggerLib() {
        var arr = Thread.currentThread().getStackTrace();
        boolean intoLoggerLib = false;
        for (StackTraceElement e : arr) {
            if (e.getClassName().matches(".*Logger\\b.*")) {
                intoLoggerLib = true;
            } else {
                if (intoLoggerLib) {
                    // out of logger lib now
                    return e;
                }
            }
        }
        // should not reach here, however return the last element if it really happens
        return arr[arr.length - 1];
    }

    private static final Set<String> ADD_DEBUG_INFO_CLASS_PREFIX = Set.of("io.vproxy.vswitch.");

    // some message for debugging this project
    // use assert to print this log
    // e.g. assert Logger.lowLevelDebug("i will not be here in production environment")
    public static boolean lowLevelDebug(String msg) {
        if (!lowLevelDebugOn)
            return true;
        return debugLog(msg);
    }

    public static boolean lowLevelNetDebug(String msg) {
        if (!lowLevelNetDebugOn || !lowLevelDebugOn)
            return true;
        return debugLog(msg);
    }

    private static boolean debugLog(String msg) {
        String threadName = Thread.currentThread().getName();
        StackTraceElement elem = getFirstElementOutOfLoggerLib();
        System.out.println(DEBUG_COLOR + current() + threadName + " - " + elem.getClassName() + "#" + elem.getMethodName() + "(" + elem.getLineNumber() + ") - " + RESET_COLOR + getDebugInfo(elem) + msg);
        return true;
    }

    private static String getDebugInfo(StackTraceElement elem) {
        String clsName = elem.getClassName();
        boolean addDebugInfo = false;
        for (String cls : ADD_DEBUG_INFO_CLASS_PREFIX) {
            if (clsName.startsWith(cls)) {
                addDebugInfo = true;
                break;
            }
        }
        if (addDebugInfo) {
            String debugInfo = VProxyThread.current().debugInfo;
            return debugInfo + " - ";
        }
        return "";
    }

    private static void privateErr(String err) {
        String threadName = Thread.currentThread().getName();
        StackTraceElement elem = getFirstElementOutOfLoggerLib();
        System.out.println(ERROR_COLOR + current() + threadName + " - " + elem.getClassName() + "#" + elem.getMethodName() + "(" + elem.getLineNumber() + ") - " + RESET_COLOR + err);
    }

    private static void privatePrintStackTrace(Throwable t) {
        if (stackTraceOn || !(t instanceof Exception) || (t instanceof RuntimeException)) {
            // always print runtime exceptions and errors
            t.printStackTrace(System.out);
        } else {
            StringBuilder sb = new StringBuilder();
            formatExceptionStackTrace(t, sb);
            System.out.println(sb);
        }
    }

    private static void formatExceptionStackTrace(Throwable t, StringBuilder sb) {
        String msg = t.getMessage();
        if (msg == null || msg.isBlank()) {
            sb.append(t.getClass().getName());
        } else {
            sb.append(t.getClass().getName()).append(": ").append(msg.trim());
        }
        if (t.getCause() != null) {
            sb.append(" <= ");
            formatExceptionStackTrace(t.getCause(), sb);
        }
    }

    // unexpected errors, or situation should happen
    public static void fatal(LogType logType, String err) {
        privateErr(logType + " - " + err);
    }

    public static void fatal(LogType logType, String err, Throwable ex) {
        privateErr(logType + " - " + err);
        privatePrintStackTrace(ex);
    }

    // expected errors, but not normal condition
    public static void error(LogType logType, String err) {
        privateErr(logType + " - " + err);
    }

    public static void error(LogType logType, String err, Throwable ex) {
        privateErr(logType + " - " + err);
        privatePrintStackTrace(ex);
    }

    // expected errors, maybe user misuse, and we can recover
    public static void warn(LogType logType, String err) {
        System.out.println(WARN_COLOR + current() + logType + " - " + RESET_COLOR + err);
    }

    public static void warn(LogType logType, String err, Throwable t) {
        System.out.println(WARN_COLOR + current() + logType + " - " + RESET_COLOR + err);
        privatePrintStackTrace(t);
    }

    // expected condition
    public static void info(LogType logType, String msg) {
        System.out.println(INFO_COLOR + current() + logType + " - " + RESET_COLOR + msg);
    }

    public static void trace(LogType logType, String msg) {
        System.out.println(DEBUG_COLOR + current() + logType + " - " + RESET_COLOR + msg);
    }

    public static void shouldNotHappen(String msg) {
        fatal(LogType.UNEXPECTED, "should not happen - " + msg);
    }

    public static void alert(String msg) {
        info(LogType.ALERT, msg);
    }

    public static void access(String msg) {
        info(LogType.ACCESS, msg);
    }

    public static void probe(String msg) {
        String threadName = Thread.currentThread().getName();
        String log = DEBUG_COLOR + current() + threadName + " " + LogType.PROBE + " - " + RESET_COLOR + msg + "\r\n";
        DatagramFD chnl = getLogChannel();

    }

    private static DatagramFD getLogChannel() {
        if (logChannel == null) {
            try {
                logChannel = FDProvider.get().openDatagramFD();
                logChannel.configureBlocking(false);
            } catch (IOException e) {
                shouldNotHappen("open datagram channel as log channel failed", e);
                if (logChannel != null) {
                    try {
                        logChannel.close();
                    } catch (IOException ignore) {
                    }
                }
                logChannel = null;
                throw new RuntimeException(e);
            }
        }
        if (!logChannel.isOpen()) {
            try {
                logChannel.close();
            } catch (IOException ignore) {
            }
            logChannel = null;
            return getLogChannel();
        }
        return logChannel;
    }

    private static IPPort getLogAddress() {
        return new IPPort(IP.from(new byte[] { 127, 0, 0, 1 }), 23456);
    }

    public static void shouldNotHappen(String msg, Throwable err) {
        fatal(LogType.UNEXPECTED, "should not happen - " + msg, err);
    }

    public static boolean printStackTrace(Throwable t) {
        // do not use privatePrintStackTrace, always print here
        t.printStackTrace(System.out);
        return true;
    }

    public static boolean lowLevelNetDebugPrintBytes(byte[] array) {
        if (lowLevelNetDebugOn) {
            printBytes(array);
        }
        return true;
    }

    public static boolean lowLevelNetDebugPrintBytes(byte[] array, int off, int end) {
        if (lowLevelNetDebugOn) {
            printBytes(array, off, end);
        }
        return true;
    }

    public static void printBytes(byte[] array) {
        printBytes(array, 0, array.length);
    }

    public static void printBytes(byte[] array, int off, int end) {
        {
            byte[] tmp = Utils.allocateByteArray(end - off);
            System.arraycopy(array, off, tmp, 0, end - off);
            array = tmp;
        }
        final int bytesPerLine = 36;
        int lastLine = array.length % bytesPerLine;
        if (lastLine == 0) {
            lastLine = bytesPerLine;
        }
        int lines = array.length / bytesPerLine + (lastLine != bytesPerLine ? 1 : 0);
        byte[][] linesArray = new byte[lines][];
        for (int i = 0; i < linesArray.length - 1; ++i) {
            linesArray[i] = Utils.allocateByteArray(bytesPerLine);
        }
        linesArray[linesArray.length - 1] = Utils.allocateByteArray(lastLine);
        for (int i = 0; i < array.length; ++i) {
            int idx0 = i / bytesPerLine;
            int idx1 = i % bytesPerLine;
            linesArray[idx0][idx1] = array[i];
        }
        for (int idx = 0; idx < linesArray.length; idx++) {
            byte[] line = linesArray[idx];
            System.out.print(Utils.bytesToHex(line));
            System.out.print("    ");
            if (idx == linesArray.length - 1) {
                for (int i = 0; i < 2 * (bytesPerLine - lastLine); ++i) {
                    System.out.print(" ");
                }
            }
            char[] cs = new char[line.length];
            for (int i = 0; i < line.length; ++i) {
                int b = line[i];
                if (b < 0) {
                    b += 256;
                }
                if (b < 32 || b > 126) {
                    cs[i] = '.';
                } else {
                    cs[i] = (char) b;
                }
            }
            System.out.println(new String(cs));
        }
    }

    public static char toPrintableChar(byte bb) {
        int b = bb;
        if (b < 0) {
            b += 256;
        }
        if (b < 32 || b > 126) {
            return '.';
        } else {
            return (char) b;
        }
    }
}


public static Camera getCameraInstance() {
        Camera c = null;
        try {
            // attempt to get a Camera instance
            c = Camera.open();
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            Log.e("ch.getCI", "Failed to get camera!", e);
        }
        // returns null if camera is unavailable
        return c;
    }

package org.durka.hallmonitor;

import java.util.List;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.media.CameraProfile;
import android.util.Log;

public class CameraHelper {

    public static final int MEDIA_TYPE_IMAGE = 1;

    public static final String KEY_PICTURE_SIZE = "pref_camera_picturesize_key";

    /**
     * A safe way to get an instance of the Camera object.
     */

    public static void initialCameraPictureSize(Context context, Parameters parameters) {
        // When launching the camera app first time, we will set the picture
        // size to the first one in the list defined in "arrays.xml" and is also
        // supported by the driver.
        List<Size> supported = parameters.getSupportedPictureSizes();
        if (supported == null)
            return;
        for (String candidate : context.getResources().getStringArray(R.array.pref_camera_picturesize_entryvalues)) {
            if (setCameraPictureSize(candidate, supported, parameters)) {
                return;
            }
        }
        Log.e("ch.initCPS", "No supported picture size found");
    }

    public static boolean setCameraPictureSize(String candidate, List<Size> supported, Parameters parameters) {
        int index = candidate.indexOf('x');
        if (index == -1)
            return false;
        int width = Integer.parseInt(candidate.substring(0, index));
        int height = Integer.parseInt(candidate.substring(index + 1));
        for (Size size : supported) {
            if (size.width == width && size.height == height) {
                parameters.setPictureSize(width, height);
                return true;
            }
        }
        return false;
    }

    public static void updateCameraParametersPreference(Context ctx, Camera cam) {
        // get Camera parameters
        Camera.Parameters params = cam.getParameters();
        List<String> focusModes = params.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
            // set the focus mode
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        }
        // set the camera picture size
        initialCameraPictureSize(ctx, params);
        // Set JPEG quality.
        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(0, CameraProfile.QUALITY_HIGH);
        params.setJpegQuality(jpegQuality);
        List<String> flashModes = params.getSupportedFlashModes();
        if (flashModes.contains(Camera.Parameters.FLASH_MODE_AUTO)) {
            // set the focus mode
            params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
        }
        List<String> whiteBalanceModes = params.getSupportedWhiteBalance();
        if (whiteBalanceModes.contains(Camera.Parameters.WHITE_BALANCE_AUTO)) {
            // set the focus mode
            params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
        }
        // set Camera parameters
        cam.setParameters(params);
    }
}


try {
            // attempt to get a Camera instance
            c = Camera.open();
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            Log.e("ch.getCI", "Failed to get camera!", e);
        }

package org.durka.hallmonitor;

import java.util.List;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.media.CameraProfile;
import android.util.Log;

public class CameraHelper {

    public static final int MEDIA_TYPE_IMAGE = 1;

    public static final String KEY_PICTURE_SIZE = "pref_camera_picturesize_key";

    /**
     * A safe way to get an instance of the Camera object.
     */
    public static Camera getCameraInstance() {
        Camera c = null;

        // returns null if camera is unavailable
        return c;
    }

    public static void initialCameraPictureSize(Context context, Parameters parameters) {
        // When launching the camera app first time, we will set the picture
        // size to the first one in the list defined in "arrays.xml" and is also
        // supported by the driver.
        List<Size> supported = parameters.getSupportedPictureSizes();
        if (supported == null)
            return;
        for (String candidate : context.getResources().getStringArray(R.array.pref_camera_picturesize_entryvalues)) {
            if (setCameraPictureSize(candidate, supported, parameters)) {
                return;
            }
        }
        Log.e("ch.initCPS", "No supported picture size found");
    }

    public static boolean setCameraPictureSize(String candidate, List<Size> supported, Parameters parameters) {
        int index = candidate.indexOf('x');
        if (index == -1)
            return false;
        int width = Integer.parseInt(candidate.substring(0, index));
        int height = Integer.parseInt(candidate.substring(index + 1));
        for (Size size : supported) {
            if (size.width == width && size.height == height) {
                parameters.setPictureSize(width, height);
                return true;
            }
        }
        return false;
    }

    public static void updateCameraParametersPreference(Context ctx, Camera cam) {
        // get Camera parameters
        Camera.Parameters params = cam.getParameters();
        List<String> focusModes = params.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
            // set the focus mode
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        }
        // set the camera picture size
        initialCameraPictureSize(ctx, params);
        // Set JPEG quality.
        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(0, CameraProfile.QUALITY_HIGH);
        params.setJpegQuality(jpegQuality);
        List<String> flashModes = params.getSupportedFlashModes();
        if (flashModes.contains(Camera.Parameters.FLASH_MODE_AUTO)) {
            // set the focus mode
            params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
        }
        List<String> whiteBalanceModes = params.getSupportedWhiteBalance();
        if (whiteBalanceModes.contains(Camera.Parameters.WHITE_BALANCE_AUTO)) {
            // set the focus mode
            params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
        }
        // set Camera parameters
        cam.setParameters(params);
    }
}


public void addAll(Collection<T> c) {
        for (T element : c) {
            add(element);
        }
    }

/*
 *
 *
 *  The Covered Software is Terracotta Core.
 *
 *  The Initial Developer of the Covered Software is
 *  Terracotta, Inc., a Software AG company
 *
 */
package com.tc.util;

import java.util.Collection;
import java.util.NoSuchElementException;

/**
 * This singly linked list was written for performance reason. In addition to being a regular linked list, it has the
 * ability to merge other linked lists into this list without traversing through the entire list.

 *

 * Only the basic necessary methods are implemented as of now. But I can see this list implement the List interface
 * someday.
 */
public class MergableLinkedList<T> {

    private int size = 0;

    private MergableLinkedList.Node<T> head;

    private MergableLinkedList.Node<T> tail;

    /**
     * Adds the collection to the end of the list(ServerTransaction) txnQ.removeFirst()
     */

    /**
     * This is the reason this class exists. This is an optimized way to add all the elements in List m to the front of
     * this List. At the end of this call the List m is cleared.
     */
    public void mergeToFront(MergableLinkedList<T> m) {
        if (m.isEmpty()) {
            // Nothing to merge
            return;
        }
        m.tail.next = head;
        head = m.head;
        if (tail == null) {
            tail = m.tail;
        }
        size += m.size();
        m.clear();
    }

    public void clear() {
        head = tail = null;
        size = 0;
    }

    public int size() {
        return size;
    }

    public T removeFirst() {
        if (head == null) {
            throw new NoSuchElementException();
        }
        T toReturn = head.data;
        if (head == tail) {
            // Only one element in the list
            head = tail = null;
        } else {
            head = head.next;
        }
        size--;
        return toReturn;
    }

    public boolean isEmpty() {
        return (size == 0);
    }

    /**
     * Adds to the end of the list
     */
    public void add(T t) {
        MergableLinkedList.Node<T> n = new Node<T>(t);
        if (head == null) {
            // first node
            head = n;
        } else {
            tail.next = n;
        }
        tail = n;
        size++;
    }

    private static final class Node<T> {

        private MergableLinkedList.Node<T> next;

        private final T data;

        public Node(T data) {
            this.data = data;
        }
    }
}


try {
            withdrawBalanceContract = this.contract.unpack(WithdrawBalanceContract.class);
        } catch (InvalidProtocolBufferException e) {
            logger.debug(e.getMessage(), e);
            throw new ContractValidateException(e.getMessage());
        }

/*
 * GSC (Global Social Chain), a blockchain fit for mass adoption and
 * a sustainable token economy model, is the decentralized global social
 * chain with highly secure, low latency, and near-zero fee transactional system.
 *
 */
package org.gsc.core.operator;

import static org.gsc.core.operator.OperatorConstant.ACCOUNT_EXCEPTION_STR;
import com.google.common.math.LongMath;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.Arrays;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.gsc.utils.StringUtil;
import org.gsc.core.Wallet;
import org.gsc.core.wrapper.AccountWrapper;
import org.gsc.core.wrapper.TransactionResultWrapper;
import org.gsc.config.args.Args;
import org.gsc.db.Manager;
import org.gsc.core.exception.ContractExeException;
import org.gsc.core.exception.ContractValidateException;
import org.gsc.protos.Contract.WithdrawBalanceContract;
import org.gsc.protos.Protocol.Transaction.Result.code;

@Slf4j(topic = "operator")
public class WithdrawBalanceOperator extends AbstractOperator {

    WithdrawBalanceOperator(Any contract, Manager dbManager) {
        super(contract, dbManager);
    }

    @Override
    public boolean execute(TransactionResultWrapper ret) throws ContractExeException {
        long fee = calcFee();
        final WithdrawBalanceContract withdrawBalanceContract;
        try {
            withdrawBalanceContract = contract.unpack(WithdrawBalanceContract.class);
        } catch (InvalidProtocolBufferException e) {
            logger.debug(e.getMessage(), e);
            ret.setStatus(fee, code.FAILED);
            throw new ContractExeException(e.getMessage());
        }
        AccountWrapper accountWrapper = (Objects.isNull(getDeposit())) ? dbManager.getAccountStore().get(withdrawBalanceContract.getOwnerAddress().toByteArray()) : getDeposit().getAccount(withdrawBalanceContract.getOwnerAddress().toByteArray());
        long oldBalance = accountWrapper.getBalance();
        long allowance = accountWrapper.getAllowance();
        long now = dbManager.getHeadBlockTimeStamp();
        accountWrapper.setInstance(accountWrapper.getInstance().toBuilder().setBalance(oldBalance + allowance).setAllowance(0L).setLatestWithdrawTime(now).build());
        if (Objects.isNull(getDeposit())) {
            dbManager.getAccountStore().put(accountWrapper.createDbKey(), accountWrapper);
        } else {
            // cache
            deposit.putAccountValue(accountWrapper.createDbKey(), accountWrapper);
        }
        ret.setWithdrawAmount(allowance);
        ret.setStatus(fee, code.SUCESS);
        return true;
    }

    @Override
    public boolean validate() throws ContractValidateException {
        if (this.contract == null) {
            throw new ContractValidateException("No contract!");
        }
        if (dbManager == null && (getDeposit() == null || getDeposit().getDbManager() == null)) {
            throw new ContractValidateException("No dbManager!");
        }
        if (!this.contract.is(WithdrawBalanceContract.class)) {
            throw new ContractValidateException("contract type error,expected type [WithdrawBalanceContract],real type[" + contract.getClass() + "]");
        }
        final WithdrawBalanceContract withdrawBalanceContract;

        byte[] ownerAddress = withdrawBalanceContract.getOwnerAddress().toByteArray();
        if (!Wallet.addressValid(ownerAddress)) {
            throw new ContractValidateException("Invalid address");
        }
        AccountWrapper accountWrapper = Objects.isNull(getDeposit()) ? dbManager.getAccountStore().get(ownerAddress) : getDeposit().getAccount(ownerAddress);
        if (accountWrapper == null) {
            String readableOwnerAddress = StringUtil.createReadableString(ownerAddress);
            throw new ContractValidateException(ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] not exists");
        }
        String readableOwnerAddress = StringUtil.createReadableString(ownerAddress);
        if (!dbManager.getWitnessStore().has(ownerAddress)) {
            throw new ContractValidateException(ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] is not a witnessAccount");
        }
        boolean isGP = Args.getInstance().getGenesisBlock().getWitnesses().stream().anyMatch(witness -> Arrays.equals(ownerAddress, witness.getAddress()));
        if (isGP) {
            throw new ContractValidateException(ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] is a guard representative and is not allowed to withdraw Balance");
        }
        long latestWithdrawTime = accountWrapper.getLatestWithdrawTime();
        long now = dbManager.getHeadBlockTimeStamp();
        long witnessAllowanceFrozenTime = Objects.isNull(getDeposit()) ? dbManager.getDynamicPropertiesStore().getWitnessAllowanceFrozenTime() * 86_400_000L : getDeposit().getWitnessAllowanceFrozenTime() * 86_400_000L;
        if (now - latestWithdrawTime < witnessAllowanceFrozenTime) {
            throw new ContractValidateException("The last withdraw time is " + latestWithdrawTime + ",less than 24 hours");
        }
        if (accountWrapper.getAllowance() <= 0) {
            throw new ContractValidateException("witnessAccount does not have any allowance");
        }
        try {
            LongMath.checkedAdd(accountWrapper.getBalance(), accountWrapper.getAllowance());
        } catch (ArithmeticException e) {
            logger.debug(e.getMessage(), e);
            throw new ContractValidateException(e.getMessage());
        }
        return true;
    }

    @Override
    public ByteString getOwnerAddress() throws InvalidProtocolBufferException {
        return contract.unpack(WithdrawBalanceContract.class).getOwnerAddress();
    }

    @Override
    public long calcFee() {
        return 0;
    }
}


try {
            FileInputStream file = new FileInputStream(filename);
            ObjectInputStream out = new ObjectInputStream(file);
            // deserialization of the object (String)
            // will be written to STDOUT
            name = (String) out.readObject();
            System.out.println(name);
            out.close();
            file.close();
        } catch (Exception e) {
            System.out.printf("Exception: %s\n", e.toString());
        }

// run using: java <program>
import java.io.*;

public class Userial {

    public static void main(String[] args) {
        String name;
        String filename = "file.bin";


for (int i = 0; i < curColumns.size(); i++) {
                curColumns.set(i, idMap.get(curColumns.get(i)));
            }

package cn.edu.ruc.iir.rainbow.layout.algorithm.impl.ord;

import cn.edu.ruc.iir.rainbow.common.util.ConfigFactory;
import cn.edu.ruc.iir.rainbow.common.util.LogFactory;
import cn.edu.ruc.iir.rainbow.layout.algorithm.Algorithm;
import cn.edu.ruc.iir.rainbow.layout.domian.Column;
import cn.edu.ruc.iir.rainbow.layout.domian.Query;
import org.apache.commons.logging.Log;
import java.util.*;

/**
 * Created by hank on 2015/04/27
 * Updated by hank on 2016/10/12 and 2017/4/5 to use the new Algorithm interface.
 * The simulated annealing column order algorithm.
 */
public class Scoa extends Algorithm {

    protected Random rand = new Random(System.nanoTime());

    protected double coolingRate = 0.003;

    protected volatile double temperature = 100000;

    protected volatile long iterations = 0;

    protected Log log = LogFactory.Instance().getLog();

    protected double currentEnergy = 0;

    // currently this candidate queue is not used, we do not control the sequence of
    // neighbours to be accepted when there are multiple concurrent threads running this algorithm.
    private List<NeighbourState> candidateQueue = new ArrayList<>();

    private class NeighbourState {

        private List<Column> columnOrder = null;

        private double energy = 0.0;

        public NeighbourState(List<Column> columnOrder, double energy) {
            this.columnOrder = columnOrder;
            this.energy = energy;
        }

        public List<Column> ColumnOrder() {
            return columnOrder;
        }

        public double Energy() {
            return energy;
        }
    }

    public Scoa() {
    }

    protected void setTemperature(double temperature) {
        this.temperature = temperature;
    }

    protected void setCoolingRate(double coolingRate) {
        this.coolingRate = coolingRate;
    }

    protected double getTemperature() {
        return temperature *= (1 - coolingRate);
    }

    @Override
    public boolean isMultiThreaded() {
        return true;
    }

    public long getIterations() {
        return iterations;
    }

    @Override
    public void setup() {
        super.setColumnOrder(super.getSchema());
        String strCoolingRate = ConfigFactory.Instance().getProperty("scoa.cooling_rate");
        String strInitTemp = ConfigFactory.Instance().getProperty("scoa.init.temperature");
        if (strCoolingRate != null) {
            this.coolingRate = Double.parseDouble(strCoolingRate);
        }
        if (strInitTemp != null) {
            this.temperature = Double.parseDouble(strInitTemp);
        }
    }

    @Override
    public void cleanup() {
        log.info("total iterations: " + this.iterations + "");
    }

    /**
     * get the neighbour of the current column order
     * @return
     */
    protected List<Column> getNeighbour() {
        super.getColumnOrderLock().lock();
        List<Column> neighbour;
        try {
            neighbour = new ArrayList<Column>(super.getColumnOrder());
        } finally {
            super.getColumnOrderLock().unlock();
        }
        int i = rand.nextInt(neighbour.size());
        int j = i;
        while (j == i) {
            j = rand.nextInt(neighbour.size());
        }
        Column c = neighbour.get(i);
        neighbour.set(i, neighbour.get(j));
        neighbour.set(j, c);
        rand.setSeed(System.nanoTime());
        return neighbour;
    }

    /**
     * decide if accept the neighbour.
     * @param neighbour
     * @param neighbourEnergy
     * @return
     */
    protected boolean accept(List<Column> neighbour, double neighbourEnergy) {
        super.getColumnOrderLock().lock();
        try {
            double temperature = this.getTemperature();
            if (this.probability(currentEnergy, neighbourEnergy, temperature) > Math.random()) {
                List<Column> old = super.getColumnOrder();
                super.setColumnOrder(neighbour);
                old.clear();
                currentEnergy = neighbourEnergy;
                return true;
            }
            return false;
        } finally {
            super.getColumnOrderLock().unlock();
        }
    }

    protected double probability(double e, double e1, double temperature) {
        if (e1 < e) {
            return 1;
        } else {
            return Math.exp((e - e1) / temperature);
        }
    }

    /**
     * This function is faster than calculating the seek cost of a neighbour column ordering from getWorkloadSeekCoost
     * @param neighbor
     * @return
     */
    protected double getNeighbourSeekCost(List<Column> neighbor) {
        // new a comparator, this is the way in java7. in java8, we can use Comparator.<Integer>naturalOrder() instead.
        Comparator<Integer> naturalOrder = new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        };
        // make a prefix summation array
        List<Double> sum = new ArrayList<Double>();
        for (int i = 0; i < neighbor.size(); i++) {
            if (i == 0) {
                sum.add(0.0);
            } else {
                sum.add(sum.get(i - 1) + neighbor.get(i - 1).getSize());
            }
        }
        // mark a map from column id to neighbor index
        Map<Integer, Integer> idMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < neighbor.size(); i++) {
            idMap.put(neighbor.get(i).getId(), i);
        }
        // calculate cost
        double workloadSeekCost = 0;
        for (Query query : super.getWorkload()) {
            // curColumns is the index of each column in the neighbour ordering.
            List<Integer> curColumns = new ArrayList<>(query.getColumnIds());

            curColumns.sort(naturalOrder);
            double queryCost = 0;
            double lastPos = 0;
            for (int i = 0; i < curColumns.size(); i++) {
                // id is the index of the column in neighbour
                int id = curColumns.get(i);
                if (lastPos != 0) {
                    queryCost += this.getSeekCostFunction().calculate(sum.get(id) - lastPos);
                }
                lastPos = sum.get(id) + neighbor.get(id).getSize();
            }
            workloadSeekCost += query.getWeight() * queryCost;
        }
        return workloadSeekCost;
    }

    @Override
    public void runAlgorithm() {
        long startSeconds = System.currentTimeMillis() / 1000;
        this.currentEnergy = super.getCurrentWorkloadSeekCost();
        double neighbourEnergy = 0;
        // System.out.println("Initial energy of scoa is : " + this.currentEnergy);
        for (long currentSeconds = System.currentTimeMillis() / 1000; (currentSeconds - startSeconds) < super.getComputationBudget(); currentSeconds = System.currentTimeMillis() / 1000, ++this.iterations) {
            List<Column> neighbour = this.getNeighbour();
            neighbourEnergy = this.getNeighbourSeekCost(neighbour);
            this.accept(neighbour, neighbourEnergy);
        }
    }
}


while (j == i) {
            j = rand.nextInt(neighbour.size());
        }

package cn.edu.ruc.iir.rainbow.layout.algorithm.impl.ord;

import cn.edu.ruc.iir.rainbow.common.util.ConfigFactory;
import cn.edu.ruc.iir.rainbow.common.util.LogFactory;
import cn.edu.ruc.iir.rainbow.layout.algorithm.Algorithm;
import cn.edu.ruc.iir.rainbow.layout.domian.Column;
import cn.edu.ruc.iir.rainbow.layout.domian.Query;
import org.apache.commons.logging.Log;
import java.util.*;

/**
 * Created by hank on 2015/04/27
 * Updated by hank on 2016/10/12 and 2017/4/5 to use the new Algorithm interface.
 * The simulated annealing column order algorithm.
 */
public class Scoa extends Algorithm {

    protected Random rand = new Random(System.nanoTime());

    protected double coolingRate = 0.003;

    protected volatile double temperature = 100000;

    protected volatile long iterations = 0;

    protected Log log = LogFactory.Instance().getLog();

    protected double currentEnergy = 0;

    // currently this candidate queue is not used, we do not control the sequence of
    // neighbours to be accepted when there are multiple concurrent threads running this algorithm.
    private List<NeighbourState> candidateQueue = new ArrayList<>();

    private class NeighbourState {

        private List<Column> columnOrder = null;

        private double energy = 0.0;

        public NeighbourState(List<Column> columnOrder, double energy) {
            this.columnOrder = columnOrder;
            this.energy = energy;
        }

        public List<Column> ColumnOrder() {
            return columnOrder;
        }

        public double Energy() {
            return energy;
        }
    }

    public Scoa() {
    }

    protected void setTemperature(double temperature) {
        this.temperature = temperature;
    }

    protected void setCoolingRate(double coolingRate) {
        this.coolingRate = coolingRate;
    }

    protected double getTemperature() {
        return temperature *= (1 - coolingRate);
    }

    @Override
    public boolean isMultiThreaded() {
        return true;
    }

    public long getIterations() {
        return iterations;
    }

    @Override
    public void setup() {
        super.setColumnOrder(super.getSchema());
        String strCoolingRate = ConfigFactory.Instance().getProperty("scoa.cooling_rate");
        String strInitTemp = ConfigFactory.Instance().getProperty("scoa.init.temperature");
        if (strCoolingRate != null) {
            this.coolingRate = Double.parseDouble(strCoolingRate);
        }
        if (strInitTemp != null) {
            this.temperature = Double.parseDouble(strInitTemp);
        }
    }

    @Override
    public void cleanup() {
        log.info("total iterations: " + this.iterations + "");
    }

    /**
     * get the neighbour of the current column order
     * @return
     */
    protected List<Column> getNeighbour() {
        super.getColumnOrderLock().lock();
        List<Column> neighbour;
        try {
            neighbour = new ArrayList<Column>(super.getColumnOrder());
        } finally {
            super.getColumnOrderLock().unlock();
        }
        int i = rand.nextInt(neighbour.size());
        int j = i;

        Column c = neighbour.get(i);
        neighbour.set(i, neighbour.get(j));
        neighbour.set(j, c);
        rand.setSeed(System.nanoTime());
        return neighbour;
    }

    /**
     * decide if accept the neighbour.
     * @param neighbour
     * @param neighbourEnergy
     * @return
     */
    protected boolean accept(List<Column> neighbour, double neighbourEnergy) {
        super.getColumnOrderLock().lock();
        try {
            double temperature = this.getTemperature();
            if (this.probability(currentEnergy, neighbourEnergy, temperature) > Math.random()) {
                List<Column> old = super.getColumnOrder();
                super.setColumnOrder(neighbour);
                old.clear();
                currentEnergy = neighbourEnergy;
                return true;
            }
            return false;
        } finally {
            super.getColumnOrderLock().unlock();
        }
    }

    protected double probability(double e, double e1, double temperature) {
        if (e1 < e) {
            return 1;
        } else {
            return Math.exp((e - e1) / temperature);
        }
    }

    /**
     * This function is faster than calculating the seek cost of a neighbour column ordering from getWorkloadSeekCoost
     * @param neighbor
     * @return
     */
    protected double getNeighbourSeekCost(List<Column> neighbor) {
        // new a comparator, this is the way in java7. in java8, we can use Comparator.<Integer>naturalOrder() instead.
        Comparator<Integer> naturalOrder = new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        };
        // make a prefix summation array
        List<Double> sum = new ArrayList<Double>();
        for (int i = 0; i < neighbor.size(); i++) {
            if (i == 0) {
                sum.add(0.0);
            } else {
                sum.add(sum.get(i - 1) + neighbor.get(i - 1).getSize());
            }
        }
        // mark a map from column id to neighbor index
        Map<Integer, Integer> idMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < neighbor.size(); i++) {
            idMap.put(neighbor.get(i).getId(), i);
        }
        // calculate cost
        double workloadSeekCost = 0;
        for (Query query : super.getWorkload()) {
            // curColumns is the index of each column in the neighbour ordering.
            List<Integer> curColumns = new ArrayList<>(query.getColumnIds());
            for (int i = 0; i < curColumns.size(); i++) {
                curColumns.set(i, idMap.get(curColumns.get(i)));
            }
            curColumns.sort(naturalOrder);
            double queryCost = 0;
            double lastPos = 0;
            for (int i = 0; i < curColumns.size(); i++) {
                // id is the index of the column in neighbour
                int id = curColumns.get(i);
                if (lastPos != 0) {
                    queryCost += this.getSeekCostFunction().calculate(sum.get(id) - lastPos);
                }
                lastPos = sum.get(id) + neighbor.get(id).getSize();
            }
            workloadSeekCost += query.getWeight() * queryCost;
        }
        return workloadSeekCost;
    }

    @Override
    public void runAlgorithm() {
        long startSeconds = System.currentTimeMillis() / 1000;
        this.currentEnergy = super.getCurrentWorkloadSeekCost();
        double neighbourEnergy = 0;
        // System.out.println("Initial energy of scoa is : " + this.currentEnergy);
        for (long currentSeconds = System.currentTimeMillis() / 1000; (currentSeconds - startSeconds) < super.getComputationBudget(); currentSeconds = System.currentTimeMillis() / 1000, ++this.iterations) {
            List<Column> neighbour = this.getNeighbour();
            neighbourEnergy = this.getNeighbourSeekCost(neighbour);
            this.accept(neighbour, neighbourEnergy);
        }
    }
}


try {
            double temperature = this.getTemperature();
            if (this.probability(currentEnergy, neighbourEnergy, temperature) > Math.random()) {
                List<Column> old = super.getColumnOrder();
                super.setColumnOrder(neighbour);
                old.clear();
                currentEnergy = neighbourEnergy;
                return true;
            }
            return false;
        } finally {
            super.getColumnOrderLock().unlock();
        }

package cn.edu.ruc.iir.rainbow.layout.algorithm.impl.ord;

import cn.edu.ruc.iir.rainbow.common.util.ConfigFactory;
import cn.edu.ruc.iir.rainbow.common.util.LogFactory;
import cn.edu.ruc.iir.rainbow.layout.algorithm.Algorithm;
import cn.edu.ruc.iir.rainbow.layout.domian.Column;
import cn.edu.ruc.iir.rainbow.layout.domian.Query;
import org.apache.commons.logging.Log;
import java.util.*;

/**
 * Created by hank on 2015/04/27
 * Updated by hank on 2016/10/12 and 2017/4/5 to use the new Algorithm interface.
 * The simulated annealing column order algorithm.
 */
public class Scoa extends Algorithm {

    protected Random rand = new Random(System.nanoTime());

    protected double coolingRate = 0.003;

    protected volatile double temperature = 100000;

    protected volatile long iterations = 0;

    protected Log log = LogFactory.Instance().getLog();

    protected double currentEnergy = 0;

    // currently this candidate queue is not used, we do not control the sequence of
    // neighbours to be accepted when there are multiple concurrent threads running this algorithm.
    private List<NeighbourState> candidateQueue = new ArrayList<>();

    private class NeighbourState {

        private List<Column> columnOrder = null;

        private double energy = 0.0;

        public NeighbourState(List<Column> columnOrder, double energy) {
            this.columnOrder = columnOrder;
            this.energy = energy;
        }

        public List<Column> ColumnOrder() {
            return columnOrder;
        }

        public double Energy() {
            return energy;
        }
    }

    public Scoa() {
    }

    protected void setTemperature(double temperature) {
        this.temperature = temperature;
    }

    protected void setCoolingRate(double coolingRate) {
        this.coolingRate = coolingRate;
    }

    protected double getTemperature() {
        return temperature *= (1 - coolingRate);
    }

    @Override
    public boolean isMultiThreaded() {
        return true;
    }

    public long getIterations() {
        return iterations;
    }

    @Override
    public void setup() {
        super.setColumnOrder(super.getSchema());
        String strCoolingRate = ConfigFactory.Instance().getProperty("scoa.cooling_rate");
        String strInitTemp = ConfigFactory.Instance().getProperty("scoa.init.temperature");
        if (strCoolingRate != null) {
            this.coolingRate = Double.parseDouble(strCoolingRate);
        }
        if (strInitTemp != null) {
            this.temperature = Double.parseDouble(strInitTemp);
        }
    }

    @Override
    public void cleanup() {
        log.info("total iterations: " + this.iterations + "");
    }

    /**
     * get the neighbour of the current column order
     * @return
     */
    protected List<Column> getNeighbour() {
        super.getColumnOrderLock().lock();
        List<Column> neighbour;
        try {
            neighbour = new ArrayList<Column>(super.getColumnOrder());
        } finally {
            super.getColumnOrderLock().unlock();
        }
        int i = rand.nextInt(neighbour.size());
        int j = i;
        while (j == i) {
            j = rand.nextInt(neighbour.size());
        }
        Column c = neighbour.get(i);
        neighbour.set(i, neighbour.get(j));
        neighbour.set(j, c);
        rand.setSeed(System.nanoTime());
        return neighbour;
    }

    /**
     * decide if accept the neighbour.
     * @param neighbour
     * @param neighbourEnergy
     * @return
     */
    protected boolean accept(List<Column> neighbour, double neighbourEnergy) {
        super.getColumnOrderLock().lock();

    }

    protected double probability(double e, double e1, double temperature) {
        if (e1 < e) {
            return 1;
        } else {
            return Math.exp((e - e1) / temperature);
        }
    }

    /**
     * This function is faster than calculating the seek cost of a neighbour column ordering from getWorkloadSeekCoost
     * @param neighbor
     * @return
     */
    protected double getNeighbourSeekCost(List<Column> neighbor) {
        // new a comparator, this is the way in java7. in java8, we can use Comparator.<Integer>naturalOrder() instead.
        Comparator<Integer> naturalOrder = new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        };
        // make a prefix summation array
        List<Double> sum = new ArrayList<Double>();
        for (int i = 0; i < neighbor.size(); i++) {
            if (i == 0) {
                sum.add(0.0);
            } else {
                sum.add(sum.get(i - 1) + neighbor.get(i - 1).getSize());
            }
        }
        // mark a map from column id to neighbor index
        Map<Integer, Integer> idMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < neighbor.size(); i++) {
            idMap.put(neighbor.get(i).getId(), i);
        }
        // calculate cost
        double workloadSeekCost = 0;
        for (Query query : super.getWorkload()) {
            // curColumns is the index of each column in the neighbour ordering.
            List<Integer> curColumns = new ArrayList<>(query.getColumnIds());
            for (int i = 0; i < curColumns.size(); i++) {
                curColumns.set(i, idMap.get(curColumns.get(i)));
            }
            curColumns.sort(naturalOrder);
            double queryCost = 0;
            double lastPos = 0;
            for (int i = 0; i < curColumns.size(); i++) {
                // id is the index of the column in neighbour
                int id = curColumns.get(i);
                if (lastPos != 0) {
                    queryCost += this.getSeekCostFunction().calculate(sum.get(id) - lastPos);
                }
                lastPos = sum.get(id) + neighbor.get(id).getSize();
            }
            workloadSeekCost += query.getWeight() * queryCost;
        }
        return workloadSeekCost;
    }

    @Override
    public void runAlgorithm() {
        long startSeconds = System.currentTimeMillis() / 1000;
        this.currentEnergy = super.getCurrentWorkloadSeekCost();
        double neighbourEnergy = 0;
        // System.out.println("Initial energy of scoa is : " + this.currentEnergy);
        for (long currentSeconds = System.currentTimeMillis() / 1000; (currentSeconds - startSeconds) < super.getComputationBudget(); currentSeconds = System.currentTimeMillis() / 1000, ++this.iterations) {
            List<Column> neighbour = this.getNeighbour();
            neighbourEnergy = this.getNeighbourSeekCost(neighbour);
            this.accept(neighbour, neighbourEnergy);
        }
    }
}


protected POInfo initPO(Properties ctx) {
        POInfo poi = POInfo.getPOInfo(ctx, Table_ID, get_TrxName());
        return poi;
    }

/**
 * ***************************************************************************
 *  Product: iDempiere ERP & CRM Smart Business Solution                       *
 *  For the text or an alternative of this public license, you may reach us    *
 *  ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA        *
 *  or via example@nnthink.com or http://example.com           *
 * ***************************************************************************
 */
/**
 * Generated Model - DO NOT CHANGE
 */
package org.compiere.model;

import java.sql.ResultSet;
import java.util.Properties;

/**
 * Generated Model for C_Charge_Acct
 *  @author iDempiere (generated)
 *  @version Development 9.0 - $Id$
 */
@org.adempiere.base.Model(table = "C_Charge_Acct")
public class X_C_Charge_Acct extends PO implements I_C_Charge_Acct, I_Persistent {

    private static final long serialVersionUID = 20210917L;

    /**
     * Standard Constructor
     */
    public X_C_Charge_Acct(Properties ctx, int C_Charge_Acct_ID, String trxName) {
        super(ctx, C_Charge_Acct_ID, trxName);
    }

    /**
     * Load Constructor
     */
    public X_C_Charge_Acct(Properties ctx, ResultSet rs, String trxName) {
        super(ctx, rs, trxName);
    }

    protected int get_AccessLevel() {
        return accessLevel.intValue();
    }

    /**
     * Load Meta Data
     */

    public String toString() {
        StringBuilder sb = new StringBuilder("X_C_Charge_Acct[").append(get_ID()).append("]");
        return sb.toString();
    }

    public org.compiere.model.I_C_AcctSchema getC_AcctSchema() throws RuntimeException {
        return (org.compiere.model.I_C_AcctSchema) MTable.get(getCtx(), org.compiere.model.I_C_AcctSchema.Table_ID).getPO(getC_AcctSchema_ID(), get_TrxName());
    }

    /**
     *  Set Accounting Schema.
     * 		@param C_AcctSchema_ID
     * 		Rules for accounting
     */
    public void setC_AcctSchema_ID(int C_AcctSchema_ID) {
        if (C_AcctSchema_ID < 1)
            set_ValueNoCheck(COLUMNNAME_C_AcctSchema_ID, null);
        else
            set_ValueNoCheck(COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID));
    }

    /**
     *  Get Accounting Schema.
     * 		@return Rules for accounting
     */
    public int getC_AcctSchema_ID() {
        Integer ii = (Integer) get_Value(COLUMNNAME_C_AcctSchema_ID);
        if (ii == null)
            return 0;
        return ii.intValue();
    }

    /**
     *  Set C_Charge_Acct_UU.
     * 		@param C_Charge_Acct_UU C_Charge_Acct_UU
     */
    public void setC_Charge_Acct_UU(String C_Charge_Acct_UU) {
        set_Value(COLUMNNAME_C_Charge_Acct_UU, C_Charge_Acct_UU);
    }

    /**
     *  Get C_Charge_Acct_UU.
     * 		@return C_Charge_Acct_UU
     */
    public String getC_Charge_Acct_UU() {
        return (String) get_Value(COLUMNNAME_C_Charge_Acct_UU);
    }

    public org.compiere.model.I_C_Charge getC_Charge() throws RuntimeException {
        return (org.compiere.model.I_C_Charge) MTable.get(getCtx(), org.compiere.model.I_C_Charge.Table_ID).getPO(getC_Charge_ID(), get_TrxName());
    }

    /**
     *  Set Charge.
     * 		@param C_Charge_ID
     * 		Additional document charges
     */
    public void setC_Charge_ID(int C_Charge_ID) {
        if (C_Charge_ID < 1)
            set_ValueNoCheck(COLUMNNAME_C_Charge_ID, null);
        else
            set_ValueNoCheck(COLUMNNAME_C_Charge_ID, Integer.valueOf(C_Charge_ID));
    }

    /**
     *  Get Charge.
     * 		@return Additional document charges
     */
    public int getC_Charge_ID() {
        Integer ii = (Integer) get_Value(COLUMNNAME_C_Charge_ID);
        if (ii == null)
            return 0;
        return ii.intValue();
    }

    public I_C_ValidCombination getCh_Expense_A() throws RuntimeException {
        return (I_C_ValidCombination) MTable.get(getCtx(), I_C_ValidCombination.Table_ID).getPO(getCh_Expense_Acct(), get_TrxName());
    }

    /**
     *  Set Charge Account.
     * 		@param Ch_Expense_Acct
     * 		Charge Account
     */
    public void setCh_Expense_Acct(int Ch_Expense_Acct) {
        set_Value(COLUMNNAME_Ch_Expense_Acct, Integer.valueOf(Ch_Expense_Acct));
    }

    /**
     *  Get Charge Account.
     * 		@return Charge Account
     */
    public int getCh_Expense_Acct() {
        Integer ii = (Integer) get_Value(COLUMNNAME_Ch_Expense_Acct);
        if (ii == null)
            return 0;
        return ii.intValue();
    }
}